How to merge two descending singly linkedlist into one ascending linkedlist using Recursion without any helper method?

Compilation Error
The first problem is to solve the compiling error.
Just follow the interface:
    public Node<Integer> mergeAscend(Node<Integer> a, Node<Integer> b)

Warnings and Code convention
You should add the type information to the store_next_a_node variable (and store_next_b_node). Additionally, in Java naming conversion, variable names use camel case. Therefore, I suggest substitute:
            Node store_next_a_node = a.next;
           ...
            Node store_next_b_node = b.next;

By...
            Node<Integer> nextNode = a.next;

Simple "Test Case"
The code bellow is just an example and not a full automated test (for more information, look for Java automated tests. eg: junit tutorial).But it is enough to  give us some hints what is going on. For example, we can see the original code does not solve the problem. Let us write a simple test case:
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] a = { 6, 4, 2 };
        Node<Integer> h1 = new Node<>(8, null);
        Node<Integer> previous = h1;
        for (int value : a) {
            Node<Integer> node = new Node<>(value, null);
            previous.next = node;
            previous = node;
        }

        int[] b = { 7, 5, 3, 1 };
        Node<Integer> h2 = new Node<>(9, null);
        previous = h2;
        for (int value : b) {
            Node<Integer> node = new Node<>(value, null);
            previous.next = node;
            previous = node;
        }
        solution.mergeAscend(h1, h2);
        Node<Integer> iterator = solution.dummy;
        while (iterator != null) {
            System.out.println(iterator.value);
            iterator = iterator.next;
        }
    }

The expected output would be the numbers printed in ascending order as the exercise suggests.
NullPointerException
With the test case, we can execute the code and and we will get a null pointer exception during the execution:
Exception in thread "main" java.lang.NullPointerException
    at Solution.mergeAscend(Solution.java:13)
    at Solution.mergeAscend(Solution.java:19)
    at Solution.mergeAscend(Solution.java:24)
    at Solution.mergeAscend(Solution.java:19)
    at Solution.mergeAscend(Solution.java:24)
    at Solution.mergeAscend(Solution.java:19)
    at Solution.mergeAscend(Solution.java:24)
    at Solution.mergeAscend(Solution.java:19)
    at Solution.mergeAscend(Solution.java:24)
    at Solution.main(Solution.java:50)

Bug
If you look the code, the following statement is suspicious:
if((a!=null&&b==null)||a.value>=b.value)

What if a is null and b is not null? First condition is false and Java interpreter will try to evaluate the second condition. Unfortunately, a.value will throw a NullPointerException.
Next Step: How to fix it ?
Clean Code makes our life easier
Let's make the code cleaner . In our case, we want to preserve the original code ideas and just simplifying what is possible. Hopefully we will remove the conditions that make the code to fail.
Remove unnecessary else-statement
First, after the base case, we don't need a else-statement. Change..
        if (a == null && b == null) {//base case
            return null;
        }
        else {
        ...
        }

to
        if (a == null && b == null) {//base case
            return null;
        }
        ...

Nullability test only once
Second, remove the complication of testing a nullability all the time.
Just add the following check after the base case.
        if (a == null)
            return mergeAscend(b, a);

With that, now we know that a is the longest list and we don't need to check again and again that condition.
So, your second "if-statement" can be change from
        if ( (a!=null && b==null) || a.value >= b.value)

to:
        if (b == null || a.value >= b.value) // insert "b" after dummy

Remove unnecessary if-statement
After that, we might think about it... we don't need the third "if-statement". Just remove it.
 else if((a==null&&b!=null)||a.value<b.value){
     ...
 }

To...
 else {
      ...
  }

Congrats, your code now works!
    public Node<Integer> mergeAscend(Node<Integer> a, Node<Integer> b) {
        if (a == null && b == null) {//base case
            return null;
        }
        if (a == null)
            return mergeAscend(b, a);
        if (b == null || a.value >= b.value) {// insert "a" after dummy
            //store the next node of current a, before pointing a.next to dummy.next;
            Node<Integer> nextNode = a.next;
            //insert Node "a" between dummy and dummy.next
            a.next = dummy.next;
            dummy.next = a;
            mergeAscend(nextNode, b);
        } else {
            Node<Integer> nextNode = b.next;
            b.next = dummy.next;
            dummy.next = b;
            mergeAscend(a, nextNode);
        }
        return dummy.next;
    }

Test it!
PS: Another Minor Thing - Comment misleading
Your code comments are misleading. In the second if-statement, if the statement evaluate the expression as true, code below add a between dummy and dummy.next.
change
// insert "b" after dummy

To
// insert "a" after dummy

PS2: Symmetric symplification
Evaluating the code again, we might found the code is a little redundant. It means, part of the code is doing exactly the same thing, but the variable names are just swapped. In that case, we can simplify it further.
    public Node<Integer> mergeAscend(Node<Integer> a, Node<Integer> b) {
        if (a == null && b == null) {//base case
            return dummy.next;
        }
        if (a == null || (b != null && a.value < b.value)) { // symmetric case
            return mergeAscend(b, a);
        }
        //store the next node of current a, before pointing a.next to dummy.next;
        //insert Node "a" between dummy and dummy.next
        Node<Integer> nextNode = a.next;
        a.next = dummy.next;
        dummy.next = a;
        return mergeAscend(nextNode, b);
    }


Replacing strings of blanks by tabs and blanks to achieve same spacing

I don't think a proper getline() function should return an int, whether it's based on the attempted read (a boolean) or something else.

I believe you're trying to imitate fgets(), which instead returns a char* (the extracted file line) if the read was successful or NULL if it failed.  A proper I/O function should set an error flag upon a failed read attempt, and this is not done by returning an int.  Plus, there will be issues if the caller of your function expects a string or a failbit, which should be the case if the caller expects proper feedback.

Unless fgets() really doesn't satisfy your needs here, I'd recommend using that or another library function that handles this properly.  Recreating an I/O function can cause problems if not written carefully, and even then you shouldn't be doing that.


When running your program with the Go race detector, it found no race conditions. That's good!

Given this, I would consider your "execution scheduling" valid.

  Is it appropriate to use defined-size channels here?

Sure. In this case you make the buffer large enough such that it will not be blocked. You can read more about the difference between buffered and unbuffered channels here.

Benchmark through testing

  Is there a better/more effective way to achieve this task?

For benchmarking, it is recommended to use the utilities provided by the testing package.

A lot of this code is boilerplate benchmarking code. With the testing package you can be more confident in the accuracy of your benchmarks, especially since you're using goroutines.

(I will leave switching to the testing package for you.)

Performance bias

sites[site]+pages[page]

Adding strings through the + operator is slow. This could bias your results (ie if you have lots of very long strings), but that also depends on how many sites and pages you test with.

Without knowledge of your full usage, it's hard to tell.

Accuracy

time.Since(begin).Nanoseconds() / 1000000 // convert to milliseconds

I would instead use .Seconds(). Any variation on the scale of milliseconds would be meaningless. From testing with one site and two pages, I received response times of 10288 (10s) and 8128 ms (8s) and an end time of 30073 ms (30s).

Rather than converting to int64 I would keep the type as float64.

String formatting

With the details above:

fmt.Println("End.")
fmt.Println(fmt.Sprintf("%d ms", time.Since(begin).Nanoseconds()/1000000))

Should instead be converted to:

fmt.Printf("End.\nTotal time: %.0fs\n", time.Since(begin).Seconds())

And

fmt.Printf("Url : %v\nResponse Time : %d ms\n\n", benchmark.url, benchmark.time)

Should instead be:

fmt.Printf("Url: %s\nResponse Time: %.0fs\n\n", benchmark.url,
    benchmark.time)

(Notice I use %s rather than %v.)

Variable naming

Variables can have shorter names, especially in shorter functions where their purpose is clear.

totalExecTimeChan becomes timeChan
totalExecTime becomes time
BenchmarkTry becomes tries

I would argue that the names tc and t would be equally fine for the first two.

Capitalization matters in Go. The variable BenchmarkTry and the type PageBenchmark would be exported. In this case it does not make a difference, but for larger programs and packages it would be important.

Miscellaneous

This cast is not needed.

totalExecTime := int64(0)

With the switch to float64, it can instead be:

totalExecTime := 0.0

Some of your comments extend beyond the 80-character column. It is useful to stay within 80 characters when viewing things split across your screen. Instead, move comments to the line before the code. (Some of these comments are superfluous, but you're learning so that's okay.)
Store len(sites)*len(pages) in a constant, rather than recomputing it each time.

Conclusion

Here is the code I ended up with:

package main

import (
    "fmt"
    "net/http"
    "time"
)

const tries = 1000

type pageBenchmark struct {
    url  string
    time float64
}

func execBenchmark(url string, benchmarks chan pageBenchmark) {
    // prevent blocking goroutine
    timeChan := make(chan float64, tries)
    time := 0.0

    // start all requests
    for i := 0; i < tries; i++ {
        go execHTTPRequest(url, timeChan)
    }

    // catch new values from execHTTPRequest()
    for i := 0; i < tries; i++ {
        // wait to get value from goroutine
        time += <-timeChan
    }

    benchmarks <- pageBenchmark{url, time / tries}
}

// exec HTTP request and attach exec time to channel
func execHTTPRequest(url string, timeChan chan float64) {
    begin := time.Now()
    _, _ = http.Get(url)
    timeChan <- time.Since(begin).Seconds()
}

func main() {
    sites := [...]string{
        // sites
    }

    pages := [...]string{
        // pages
    }

    const length = len(sites) * len(pages)

    // set size to prevent blocked goroutine
    benchmarks := make(chan pageBenchmark, length)

    begin := time.Now()

    fmt.Println("Beginning!\n")

    // start all the goroutines
    for site := range sites {
        for page := range pages {
            go execBenchmark(sites[site]+pages[page], benchmarks)
        }
    }

    // catch and print benchmarks
    for i := 0; i < length; i++ {
        b := <-benchmarks
        fmt.Printf("Url: %s\nResponse Time: %.0fs\n\n", b.url, b.time)
    }

    // print total execution time
    fmt.Printf("End.\nTotal time: %.0fs\n", time.Since(begin).Seconds())
}

Hope this helps!


if(set.isEmpty()){
            return ret;
        }

This is unnecessary. If the set is empty, the iterator will return false to the first hasNext(), and you'll go straight to the final return ret;.

Other than that, it seems like a simple, obviously correct, approach.

However, it is quite inefficient.

        Iterator<E> it = set.iterator();
        while(it.hasNext()){
            Set<E> tmp = new HashSet<E>(set);   //create a copy of current set
            tmp.remove(it.next());              //remove current element from copy set
            ret.add(tmp);                       //add the remaining set to result
            ret.addAll(findPowerSet(tmp));      //recursively find subsets of copy set
        }
        return ret;
    }

Suppose that we call it with a set of \$n\$ elements. The outermost call produces a set of \$2^n\$ subsets by taking the union of \$n\$ subresults, each of \$2^{n-1}\$ elements. So the outermost call discards as duplicates \$(n-2)2^{n-1}\$ subsets. But, of course, each of those recursive calls discarded \$(n-3)2^{n-2}\$ subsets from their subresults, etc.

This is why the typical simple implementation is to build up from the empty set.

An advanced implementation, which isn't always better but can reduce copying in some use cases, is to write a custom iterator which uses a Gray code to add or remove precisely one element in each call to next().


I suspect that you should read the matrices from files only once and store them in a two-dimensional integer array. Once you have that, it is trivial to verify whether the squares are magic.

I had in mind something like this:

private static int[][] loadFile(File file) {
     // Do file I/O for loading the square
     return square;
}

private static int getRowMagic(int[][] square, int row) {
    int sum = 0;

    for (int column = 0; column < square.length; ++column) {
        sum += square[row][column];
    }

    return sum;
}

private static int getColumnMagic(int[][] square, int column) {
    int sum = 0;

    for (int row = 0; row < square.length; ++row) {
        sum += square[row][column];
    }

    return sum;
}

private static int getDescendingDiagonalMagic(int[][] square) {
    int sum = 0;

    for (int i = 0; i < square.length; ++i) {
        sum += square[i][i];
    }

    return sum;
}

private static getAscendingDiagonalIsMagic(int[][] square) {
    int sum = 0;

    for (int i = 0; i < square.length; ++i) {
        sum += square[square.length - 1 - i][i];
    }

    return sum;
}

public static boolean isMagicSquare(int[][] square) {
    int sum = getRowMagic(square, 0);

    for (int i = 0; i < square.length; ++i) {
        if (sum != getRowMagic(square, i) || sum != getColumnMagic(square, i)) {
            return false;
        }
    }

    return getAscendingDiagonalMagic(square) == sum &&
           getDescendingDiagonalMagic(square) == sum;
}

Hope that helps.


Lazy lists with transformations, using generators & iterators

I can not find fault with your code apart from the use of class of which i am not a fan.

So I will just present an alternative syntax that gives a little extra encapsulated protection. Its usage is slightly different. List is instantiated via a factory and closure holds the generator list. I also freeze each instance of List to further protect the state.

It also does not have to mess about with const list = this which from your side-note comment is a bit of an annoyance.

const lazyList = (() => {

    const range = (start, end) => List(function* () {
       while(start <= end) { yield start++ }
    });
    function List(source) {
        var list;
        if (typeof source === "function") { list = source }
        else { list = function* () { yield* source } }

        return Object.freeze({
            filter(pred){
                return List(function* () {
                    for (const item of list()) { pred(item) ? yield item : 0 }
                });
            },
            map(map) {
                return List(function* () {
                    for (const item of list()) { yield map(item) }
                });
            },
            take(count) {
                return List(function* () {
                    for (const item of list()) {
                        if (count--) { yield item }
                        else { break }
                    }
                });
            },
            toArray() { return [...list()] },
            *[Symbol.iterator] () { yield* list() }
        });
    }
    return Object.freeze({range, List});

})();


NullGuard for throwing more informative exceptions

Using a NullReferenceException for this seems wrong since no null reference has been dereferenced - it's capturing expressions which return null when they are not expected to. An InvalidOperationException might fit better (since you are performing an operation on an object which is in an invalid state) or even your own InvalidNullReturnException.
You can greatly simplify your message generation with:

var message = expr.Body.ToString();

This dumps the passed in expression as a string and you don't have to try and handle all kinds different expressions yourself.
Overall I would probably opt for aspect oriented programming (AOP) instead of littering my code with these NullGuard calls. There are a whole number of AOP frameworks around which usually work by using attributes you can decorate your methods and properties with. Based on these attributes arbitrary code can be injected - in your case you could inject the null checking and throwing code. This seems a much less intrusive way of achieving this kind of functionality greatly enhancing readability.


Nice program, so only some tips:

First of all, you comments are very useful for you as a beginner but without them your code is much nicer:

class coinflipsimulator(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.coin = QLabel(self)
        self.coin.setPixmap(QPixmap('coin_' + str(randint(1, 2)) + '.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        self.coin.move(0.5, 0.5)

        self.btn = QPushButton('Flip', self)
        self.btn.setFont(QFont('SansSerif', 20))
        self.btn.setToolTip('Click to Flip Coin')
        QToolTip.setFont(QFont('SansSerif', 10))
        self.btn.clicked.connect(self.flipcoin)
        self.btn.resize(166, 43)
        self.btn.move(-2, 161)

        self.setGeometry(1427, 30, 162, 201)
        self.setFixedSize(self.size())
        self.setWindowTitle('Coin Flip Simulator')
        self.setWindowIcon(QIcon('icon.png'))
        self.show()

    def flipcoin(self):
        self.coin.setPixmap(QPixmap('coin_flipping_animation.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        QApplication.processEvents()
        sleep(0.5)
        self.coin.setPixmap(QPixmap('coin_' + str(randint(1, 2)) + '.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))
        QApplication.processEvents()

if __name__ == '__main__':

    app = QApplication(argv)
    ex = coinflipsimulator()
    ex.show()
    exit(app.exec_())

Follow the DRY principle (Don't Repeat Yourself). In your code is 2 times the same statement

self.coin.setPixmap(QPixmap('coin_' + str(randint(1, 2)) + '.png').scaled(162, 302, Qt.KeepAspectRatio, Qt.FastTransformation))

In them you repeatedly construct one of two picture names:

coin_1.png
coin_2.png

Why not create a list or a tuple of them, e. g.

COINS = ('coin1.png', 'coin_2.png')

(note the use of uppercase letters for its name as a signal that it will not change) and instead of the

randint(1, 2)

use

choice(COINS)

Or - even better - create the list or tuple of 2 QPixmap objects and apply the choice() function on it?

Hard-coded file names (as the 2 mentioned above) are spread in your code so it will be more difficult to search for them in the case for the need of change them.

What about give all of them (together with other constants) appropriate names near the start of your, e. g.

ICON = 'icon.png'
SLEEP_TIME = .5

and then use those names?

You may even create constants for parameter lists of functions / methods - as you use the same again and again - and then use them, e. g.

SCALED_PARMS = 162, 302, Qt.KeepAspectRatio, Qt.FastTransformation

and then use them in the form

.scaled(*SCALED_PARMS)     # This is only the part of your command

(note the asterisk (*) in front of them for unpacking the ones).


Is there any faster way instead of using preg_match in the following code?

First of all, put up a timer so you know if things get better.

You're repeating '/' . preg_quote($search) . '/i'for each book. You should create the search string only once or else you are wasting time:

<?php
$books  = simplexml_load_file('planet.xml');
$search = '2004';
$regex = '/' . preg_quote($search) . '/i';
foreach ($books->entry as $entry) {
    if (preg_match($regex, $entry->date_iso)) {
        echo $entry->dc_date;
    }
}
?>

If you are only looking for 2004 or similar you might analyze if simpler functions would be faster e.g. strpos.

Also the /i modifier might be unnecessary.


I notice a query on one of your urls. I suggest you use jQuery's $.param to construct the query cleanly.

For your first loop, you could use reduce instead of forEach to generate your hash. Additionally, you might want kill NaN early. You don't want to be carrying NaN in any data structure, otherwise you'll get some unexpected NaN in your code.

var dataHash = data.reduce(function(hash, item) {
  var value = +item.value
  hash[item.label] = isNaN(value) ? null : value;
  return hash;
}, {});

geojson.features.forEach(function(item) {
  item.properties.incidents = dataHash[item.properties._feature_id];
});

As for efficiency, I guess that's about it. You don't want to be nesting a lookup inside the other loop. Two separate loops is better then one nested inside another.


First of all I'd like to say that you did not provide guidelines, so I'm not completely sure what is required and what not.

ClassRoom

I would rename this to Course, since it's not really related to the room where it takes place. A course probably has a instance variable that identifies the location of the course "Building A4.4" for instance. It indeed holds a vector of students, a name. But I wouldn't store a class average, instead provide a method for calculating that getCourseAverage() for example. Perhaps also store the Teacher object that gives this course.

Teachers

Your Teacher class seems not logically constructed, it is a person.
If I were you I would create a Person class and inherit your Teacher and Student class from it. A Person has a firstname, lastname , age. Probably they both have an id value. You can even go a step further and make a Employee class, that has Person as base class and of which Teacher inherits.

Instead of string ClassRoom, I would use composition and have it contain a list of Course object (courses that are given by that teacher).

Constructors

Instead of using

 a.Firstname = "John";
 a.Surname = "Doe";
 a.IDNumber = "8123295073081";
 a.Age = 30;

create a constructor like: CreateStudent(name, surname, id, age);
This is more concise and reads easier.

You might take a look into using an abstract factory pattern in order to create your student/teacher objects.

Style

Normally one does not start member variables with a upper case. perhaps take a look at this

apart from that you seem to do pretty well, style wise. But I'm not a C++ expert, I'm certain other can help you further with this.


Class CatalogWalker can walk thru a list of catalogs, calculate and report some statistics

Docstrings

I'm not a big fan of the empty-docstring fakeout """ """. It would be really useful to see some actual documentation of what this is for and how to use it.

Names

You have a lot of underscores. Per the style guide:

  Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.

Given that you use the unmangled names as properties, this is clearly not the case; you should use a single underscore to indicate private by convention.

I certainly wouldn't prepend an underscore on local names (e.g. _result), as they can't be accessed from outside the method anyway.

You have a few too-short names, too; p? d? ns? n? Your code would be much more readable with more meaningful names.

Strings

I would have written e.g.

_result = "\rcataloges:" + repr(catalogs_cntr).rjust(8)

as

result = '\rcataloges:{!r:>8}'.format(catalogs_cntr)

and I definitely wouldn't mix and match; why:

_result += "\tspeed: %12.3f"%speed + " files/s"

rather than

_result += "\tspeed: %12.3f files/s" % speed

You could also consider building a list of elements, then joining them together; this makes it easier to add, rearrange and remove fields or change the separator:

result = []
result.append("cataloges:{!r:>8}".format(catalogs_cntr))
result.append("files:{!r:>13}".format(files_ctnr))
result.append("speed: {:12.3f} files/s".format(speed))
result = '\r' + '\t'.join(result)

Code

You have lines that are too long - you should limit to 80 characters. You can reduce this using Python's continuation, e.g.

self.__reporter.report(self.__catalogs_cntr, self.__files_cntr, self.__speed)

becomes

self.__reporter.report(self.__catalogs_cntr,
                       self.__files_cntr,
                       self.__speed)

This is particularly odd-looking:

for p,d,ns in walk(catalog):
    _ = d;

The semi-colon ; is redundant, and you won't see it very often in Python code (except where trying to fit multiple statements on one line, which is rarely the right choice). If you aren't going to use d, don't assign it at all, and note the whitespace after commas:

for p, _, ns in walk(catalog):


Cumulative counts of items in a Pandas dataframe

You can group by the name and then append an increasing number to it:

import pandas as pd

def add_count(x):
    return x + ([""] + list(map(str, range(1, len(x)))))

df = pd.DataFrame(['vegetable', 'fruit', 'meat', 'dairy', 'meat', 'fruit', 'fruit'],
                  columns=["name"])
x = df.groupby("name", as_index=False)["name"].apply(add_count)
df["name2"] = x.reset_index(level=0, drop=True)
print(df)
#         name       name2
# 0  vegetable   vegetable
# 1      fruit       fruit
# 2       meat        meat
# 3      dairy       dairy
# 4       meat       meat1
# 5      fruit      fruit1
# 6      fruit      fruit2

This avoids manually iterating over rows or columns, something that is usually a good thing when dealing with pandas dataframes.


I'd say it's pretty much by-the-book already, but you could use the catch block to set the default:

error: function(err){
  var errorMessage;
  try {
    errorMessage = JSON.parse(err.responseText).messages.messages[0].description;
  } catch(exception) {
    errorMessage = AJAX_ERROR;
  }
  displayError(errorMessage);
}

Or, you can use the full try...catch...finally formulation, if you want:

error: function(err){
  var errorMessage;
  try {
    errorMessage = JSON.parse(err.responseText).messages.messages[0].description;
  } catch(exception) {
    errorMessage = AJAX_ERROR;
  } finally {
    displayError(errorMessage);
  }
}

Or you can try getting the custom error message, and only defaulting at the last moment:

error: function(err){
  var errorMessage;
  try {
    errorMessage = JSON.parse(err.responseText).messages.messages[0].description;
  } catch(exception) {
    // ignored
  }
  displayError(errorMessage || AJAX_ERROR);
}

The possible advantage of this, is that if the server for any reason sends a blank (false'y) error message the above will still default to the generic error message, even though no exceptions were thrown.

In any event the overall approach seems OK to me. There's not really a cleaner way of getting the server's error message, since you have to parse the JSON and dig deep into the structure. Either thing may throw exceptions, so try...catch is the simplest way of handling that. At minimum you need the try..catch for JSON.parse anyway, so you might as well use it for both things.


Do I need Generics for these node and tree classes?

I think that you have confused yourself with your code, and the way that data structures are intended to be implemented.

What you have done that is unconventional, and causing the confusion, is that you have exposed the Node class as a public class, and you have a constructor that takes Nodes as input.

Node is normally an implementation detail of a data astructure (your KDTree) that is transparent to others. Consider Java's LinkedList, that has Node instances, but you never see those Node instances, just like ArrayList has an internal array, etc.

Your KDTree should contain the Node class as an inner (nested) private class, and the users of your KDTree should never be able to see/access those nodes. Your KDTree class should abstact that interaction away.

The constructor for your KDTree should be able to construct off the base values of the node, or be an empty constructor, and have an add method that takes the base values.

Consider something that looks like:

public static class KDTree {

    private static class Node{
        int id;
        public double x;
        public double y;
        public Node leftChild;
        public  Node rightChild;

        Node(int id, double x, double y){
            this.id = id;
            this.x = x;
            this.y = y;
            leftChild = null;
            rightChild = null;
        }
    }

    private Node root = null;

    public KDTree(){
        // empty constructor
    }

    public boolean add(int id, double x, double y) {
        Node toadd = new Node(id, x, y);

        .... add toadd to hierarchy....

    }

    public boolean contains(int x, int y) {
        .....
    }

}

Note, the Node is private, and not visible outside the KDTree class.

It is possible that you need some other form of data structure to represent the actual data in the Node, like a Point class, and, your Node could have a reference to a Point instance. Point strikes me as being a data structure you need anyway, and probably already have.

Note that your x and y values are doubles, and any time I see == comparisons with doubles, I caution people that it is not as reliable as you would expect:

if (t.x == root.x && t.y == root.y)

Be careful there, it's possible that t.x and root.x are very, very, very close to each other, but not quite the same, due to some rounding value in a calculation, or something at the 15th decimal place, or something.


Allocation of raw memory
Rather than using operator new you could use std::get_temporary_buffer<T>(n). This allocates contiguous "correctly aligned" storage for enough memory to store approx n objects of type T (its non binding contract read documents).
Constructor
It may be more efficient to use normal constructor than the copy constructor. You should also provide the move constructor.
T* operator()(T&& x);
T* operator()(T const &x);
template<typename... Args>
T* operator()(Args... args);

Destructor
Yes you can optimize the destructor if Ts destructor is guranteed to do nothing.
template<typename T>
struct SimpleDestructableTrivialy
{
    static constexpr bool value = std::is_trivially_destructible<T>::value;
};
template<typename T, bool = SimpleDestructableTrivialy<T>::value>
class SimpleDestroy
{
    public:
        void destroyElements(T* p, std::size_t T_per_page);
};
template<typename T>
class SimpleDestroy<T, true>
{
    public:
        void destroyElements(T* p, std::size_t T_per_page) {}
};
template<typename T>
class SimpleDestroy<T, false>
{
    public:
        void destroyElements(T* p, std::size_t T_per_page)
        {
            for (size_t pos = T_per_page; pos > 0; --pos)
                p[pos - 1].~T();
        }
};


Finding if value exists in any column recursively

This site is more about the readability and structure of code rather than actual correctness. I will comment on that and maybe a more readable program will help you find any potential errors?

I would recommend that you:

Extract complex if statements to their own methods describing the test
Use the new style java iteration instead of the old for loop
Reduce the block nesting level by returning early when you know you have a negative match
Use good naming for all variables. In this case the variable i desperately needs a better name!

This should produce (sans renaming of i) code that look something like this: (not compiled or tested in any way :))

private static boolean anyCellHasValue(CommonRowType row, int i) {
    if (isNonEmptyCellType(row, i)) {
        return true;
    }

    if (!hasChildren(row)) {
        return false;
    }

    for (CommonRowType childRow : row.getChildren().getRowData()) {
        if (anyCellHasValue(childRow, i)) {
            return true;
        }
    }

    return false;
}

private static boolean isNonEmptyCellType(CommonRowType row, int i) {
    CustomCellType cell = (CustomCellType)row.getCustomRow().getCell().get(i);
    return !CELL_EMPTY.equals(cell.getType()));
}

private static boolean hasChildren(CommonRowType row) {
    return row.getChildren() != null
            && row.getChildren().getRowData() != null
            && !row.getChildren().getRowData().isEmpty();
}


Perhaps change the HTML:

Navitem:

The content

jQuery

$('.navItem').on('click',function(){
   $('.content-wrap').hide();
   $('#content-wrap'+$(this).data('content-id')).fadeIn(1000);
});


Confirming the presence/create directories

Quite a few things wrong with your PHPDoc. I'm actually learning quite a bit myself. Doccomments require two asterisks to begin, not one, no matter what language you are using. One asterisk just defines a multi-line comment. Your IDE will skip over this, essentially making these useless as doccomments. The underscore before param, the "yields" operator ->, and your return syntax all cause my IDE to ignore this comment because it is in the wrong syntax. The multi-return sequences are best done using the bitwise OR operator separating the types, but you can also use a "mixed" type to accomplish the same thing.

/** Check Directories
  * etc...
  * @param string $whereAmI Script location
  * @return bool|string String on success, FALSE on failure
//OR
  * @return mixed String on success, FALSE on failure
  */

Be careful with "clever" variables. For a few seconds there I was quite confused about your $whereAmI variable, thinking that last letter was an "L" and not an "I". I'm a bit slow sometimes and I was sitting there scratching my head trying to figure out what an "aml" was (in case you're curious, my best guess was animal). I would stick with simple variable names, such as $location or $position. Additionally, pick a style and be consistent. I see both camelCase AND under_score variables. One or the other, not both. You can do one for functions and the other for variables, if you wish. I've seen that done frequently enough that I wouldn't comment on it, but switching between the styles on the same datatype is just confusing.

Internal comments, especially ones that explain what is already in the doccomments, are just noise. Anyone reading this function will know that $status is important, and once they reach the end of the function they will know its also returned. If, like me, you skip to the bottom of the function to see what it returns and then work backwards from there, then you will already know that it is returned. Same for the rest of these comments. The only time I use internal comments is for explaining confusing lines, such as REGEX, compact(), extract(), or, in your case, that exec().

Alright, lets move on to actual code.

Why did you bother setting an initial value to $status, your very next line of code overwrites that value no matter what. Let the if/else statements assign it for you. Or lose the else and use that as the default value.

Avoid using "not" ! unless you have to. In this instance you have an if/else statement. Switch them around and remove the "not". In the above scenario you would keep the "not".

if( is_dir( $whereAmI . '/' . $backup_path ) ) {
    $status TRUE;
} else {

Explaining Not:

If you are doing a single if statement, then the not is fine and necessary. Though this could be argued that the empty() function should be used, either is fine, but I find the "not" syntax preferrable in this case.

if( ! $var ) {//fine
//OR
if( empty( $var ) ) {//also fine, though less preferrable IMO

If you are using an if/else statement, as I demonstrated in initial answer, the not is implied by else and should be removed for clarity as well as efficiency.

if( $var ) {
} else {//not implied here
}

This helps with clarity because the "not" operator ! is not always immediately noticeable, depending on how you space your statements (which is one of the reasons my statements are so spacious). This helps with efficiency because typically your "not" clause holds the least amount of coding and might even contain an early escape, resulting in the else syntax not even being necessary which meaning less indentation and increased clarity.

if( $var ) {
    return FALSE;
}
//contents of else

The only time to compare a value explicitly to a boolean is when doing a type comparison. Such as an integer "0" to a boolean "FALSE", or string "FALSE" to FALSE. And the above rules hold true for this as well.

if( $var !== FALSE ) {
//OR
if( $var === FALSE ) {
} else {
}
//OR
if( $var === FALSE ) {
    return FALSE;
}
//contents of else

End of Explanation

You mentioned security; You should be careful of functions such as exec(). Functions, by definition, are public. So, this script is public, therefore you can not guarantee the validity of those parameters being passed to it, or rather, you aren't validating them. This is a potential security issue, but only if you plan on using this in a public domain (internet). That and the "777" permissions. Directories should not be executable. I can't remember off the top of my head what the proper permissions to use are, but I DO know that "777" will get you in trouble. Though, admittedly I do this in my server as well, but mine is a small intranet and security isn't one of the things I'm particularly worried about.

Split up your function. It is concerned with entirely too much. check_directories() should only be concerned with checking the directories, but then you start adding on subdirectories. This is a different concern altogether. Take a look at the Single Responsibility Principle. Additionally, look at "Don't Repeat Yourself" (DRY) Principle. Your if/else statement that I mentioned above is repeated, therefore it can be made into a function to avoid this. This will be the biggest contributor to reducing the size of this program. That and removing those unnecessary comments. Besides that, I don't think there are any other ways to do this.


Anytime I encounter a method that's only doing read-only parsing of strings and I see it's using String.IndexOf() and positions, it leaps out at me like a gigantic code smell.

Sometimes upon examination it turns out to be a legitimate and wise usage. However very often the programmer is manually splitting strings and looping through parts of the string. In other words they are doing exactly what String.Split() and foreach loops would offer them, but doing it the longer and less readable way.

This is one of those cases.

This may be just my personal taste in code. In any case, I can show you how I would tackle this problem using foreach and Split(), which I believe would be a great improvement to your methods. Except for this difference I think we might have taken comparable approaches.

Variable names

A lot of your variables are named with very little descriptiveness. You may understand that variables are named so that someone maintaining or reading the code (like me) can understand what's going on, but you could do much better in this department.

result: You use this word many times in your variable names. The problem is this name is completely useless to me. I can see it is the result of something (variously a function, a loop or some other process) but beyond that you might as well just call the variable foo or bar. hauseNummerVon and hauseNummerBin are far more understandable than resultVon and resultBin - I now know exactly what it is; it's the from house number and the to house number.

For either result[] array, I am left with nothing and I would have to read all of the code before I understood what they contained. This is a little backwards - I should know what the variable contains, then be able to read the code - with descriptive variable names giving me a greater understanding of what's going on.

bFound: Don't shorten your variable names like this. I'm left wondering: What is a b? What does it mean if it's found? Maybe this would be more recognisable to a German reader, but even so, expanding b to a word to say exactly what's found would do wonders for readability.
pos1, pos2: SeparatorPosition and SeparatorEnd would have been more descriptive. Better yet these variables are entirely unnecessary if you just use String.Split().

My approach

As I mentioned above, as oppose to editing your methods, I've written from scratch how I'd tackle this problem.

ParseHouseNumberRange

This is the entry method. You feed this method a string such as "20a bis 21c". It splits it up on the "bis" or the "-" (defined in the separators array) in order to produce smaller chunks of the original string.

Each of these chunks is passed to  then passes each of the results (in this case, "20a " and " 21c", spaces included) over to the non-public method ParseHouseNumber below. ParseHouseNumber will split these chunks up further and this method combines all the results into a single array which is returned.

Given "20a bis 21c" or similar, it returns an array: 20, a, 21, c.

public string[] ParseHouseNumberRange(string houseNumberRange)
{
    string[] separators = new string[] {"bis", "-"};
    string[] houseNumbers = houseNumberRange.Split(separators,
        StringSplitOptions.RemoveEmptyEntries);

    List<string> parsedList = new List<string>();

    foreach (string houseNumber in houseNumbers)
    {
        parsedList.AddRange(ParseHouseNumber(houseNumber));
    }

    return parsedList.ToArray();
}

ParseHouseNumber

This method takes a segment of an address from the method above, such as "20a ". After trimming out any spaces, it walks through the string character by character, plucking out digits and letters and sorting them into their own individual sections e.g. "1c4ad3" would be split into the sections 1, c, 4, ad, 3. Any non-digit non-letter characters are ignored.

Once all sections have been sorted out from the string provided to it, it returns those sections in the form of an array.

public string[] ParseHouseNumber(string houseNumber)
{
    bool firstRun = true;
    bool alphabeticMode = false; // set on first run

    houseNumber = houseNumber.Trim();

    List<string> sections = new List<string>();
    string currentSection = "";

    foreach (char c in houseNumber)
    {
        bool isLetter = Char.IsLetter(c);
        bool isDigit = Char.IsDigit(c);

        if (!(isDigit || isLetter)) continue;

        // If we've switched character type, then a section's finished.
        if (firstRun)
        {
            alphabeticMode = isLetter;
            firstRun = false;
        }
        else if ((isLetter && !alphabeticMode)
            || (isDigit && alphabeticMode))
        {
            sections.Add(currentSection);
            currentSection = "";
            alphabeticMode = !alphabeticMode;
        }

        currentSection += c;
    }

    if (currentSection != "") sections.Add(currentSection);

    return sections.ToArray();
}


Find a sum using just two different digits

Since your question is about Memory Limit Exceed. And the most memory consumed item is dp. You are going to make your dp matrix smaller. Your current memory usage is \$O(2^{log_{10}n}\cdot n) = O(n^2)\$. And you need to reduce it to \$O(n)\$.
Let's write down your current dp function:
$$ dp_{i,j} = \min \{ dp_{i-1,j}, dp_{i, j-usable_i}+1 \} $$
First, consider you only need dp[i] and dp[i-1] during iteration. All previous rows are not necessarily any more. You may only declare two rows as dp1[N + 1] and dp2[N + 1]. (To make the logic for even and odd rows consistent, use two pointers point to these array.) By using this approach, memory usage may reduced into \$O(2n) = O(n)\$.
Another approach may be just reduce your dp function into 1 dimension:
$$ dp_{j} = \min_{n \in usable} \{dp_{j-n}\} + 1 $$
So, you may only maintain dp[N + 1] instead. This also cost \$O(n)\$ memory. The second approach also make the array reusable when this function is invoked later. If you are going to handle multiple testcases in one run. You may simply declare it as global variable dp[MAX_N + 1] to reduce its time consume.
#include <stdio.h>

const int MAX_N = 1000000;
const int MAX_VAL = 128; // 2 ^ (log10(MAX_N) + 1)

int getCount(int n) {
  static int filled = 0;
  // values hold all numbers only contais 4 or 5 in 0 ~ 1e6
  static int values[MAX_VAL] = {4, 5};
  // steps is the array for dp
  // steps[i] = min(steps[i - values[j]] + 1 for every j)
  static int steps[MAX_N];
  int i, j, step, min_step;
  if (n > MAX_N) return -1; // We do not support input > 1e6
  // When first time run, we fill all values
  if (filled == 0) {
    for (i = 2, j = 0; i < MAX_VAL; j++) {
      values[i++] = values[j] * 10 + 4;
      values[i++] = values[j] * 10 + 5;
    }
    steps[0] = 0;
    filled = 1;
  }
  for (i = filled > 1 ? filled : 1; i <= n; i++) {
    // We use MAX_N+1 for values cannot be reached
    min_step = MAX_N + 1;
    for (j = 0; values[j] <= i; j++) {
      step = steps[i - values[j]] + 1;
      if (step < min_step) min_step = step;
    }
    steps[i] = min_step;
  }
  filled = n;
  if (steps[n] > n) return -1;
  return steps[n];
}

int main() {
  int n;
  for (n = 0; n < MAX_N; n++) {
    printf("%d\n", getCount(n));
  }
}


This will swap the values but is not very robust. If for instance one of the two keys is not defined this will generate notices and might cause sneaky errors further down in the code.

private function array_swap_assoc($key1, $key2, $array)

I don't see why that would be in a class. This is not realated to a specific group of activities. A simple function would do very well, and possibly be better (as in, respect the Single Responsibility Principle), as the class that contains it almost certainly is not a class containing exclusively array functions.

$newArray = array();

Creating a new array is a valid approach, but a different approach could be to pass the array as a reference to swap the values in the original array, unless you specifically need not to modify the original array. This will most of the time not do any noticeable difference, but it is more memory efficient:

private function array_swap_assoc($key1, $key2, &$array) {}

Notice the & in front of the variable. The $array local to this method will change the original one.

foreach ($array as $key => $value) {

It is a bit heavy handed to recreate the whole array. We only want to swap two values. Since we passed it by reference, we could just swap those two values without needing to reassign each and every key.

if ($key == $key1) {
    $newArray[$key2] = $array[$key2];
} elseif ($key == $key2) {
    $newArray[$key1] = $array[$key1];
} else {
    $newArray[$key] = $value;
}

The problem here is that there is no validation that both of the keys exist. We should validate that they do, and throw an exception if they don't.

if (array_key_exists($key1, $array) && array_key_exists($key2, $array) {}

Notice that I use array_key_exists and not isset, because the values could be null (which is a totally valid value) and null values will return false with isset.

So taking into account adding validation and using a passed by reference array, you could make that function more robust like this:

function array_swap_assoc($key1, $key2, &$array)
{
    if (array_key_exists($key1, $array) && array_key_exists($key2, $array)) {
        $value1 = $array[$key1];
        $value2 = $array[$key2];
        $array[$key1] = $value2;
        $array[$key2] = $value1;
    } else {
        throw new InvalidKeys;
    }
}

class InvalidKeys extends \Exception {}

array_swap_assoc('first', 'second', $array);
// no need to use the void return, the original array is modified


Extracting first name, last name, phone number, and address from a form

You could create a method for it!

bool Validate(string val, TextBox textBox, string description)
{
    if (!string.IsNullOrWhiteSpace(val))
    {
        val = textBox.Text;
    }
    else
    {
        MessageBox.Show("Please enter " + description");
        return false;
    }

    return true;
}

Then you could use it like so:

if (!Validate(firstName, firstNameBox, "a first name"))
   return;
if (!Validate(lastName, lastNameBox, "a last name"))
   return;


Simple object pool template container in C++

Don't do this:

using namespace std;

In anything other than a toy this will cause problems.

I don't like this:

#define itv(TYPE) std::vector<TYPE>::iterator

With C++11 this type if thing has been resolved by auto.

I would also define the iterator in terms of the object pool:

template <class TYPE>
struct object_pool
{
    typedef std::vector<TYPE>::iterator  iterator;

I would hide the fact that internally the object_pool uses a vector and queue. I would then add the obligatory functions to extract information:

template <class TYPE>
class object_pool
{
    std::vector<TYPE> pool;
    std::queue<size_t> avail;

  public:
    typedef std::vector<TYPE>::iterator       iterator;
    typedef std::vector<TYPE>::const_iterator const_iterator;

    iterator       begin()       { return pool.begin();}
    iterator       end()         { return pool.end();}
    const_iterator begin() const { return pool.begin();}
    const_iterator end()   const { return pool.end();}

To access elements I would also provide const version

    TYPE&       operator[](std::size_t index)       { return pool[index];}
    TYPE&       at(std::size_t index)               { return pool.at(index);}

    TYPE const& operator[](std::size_t index) const { return pool[index];}
    TYPE const& at(std::size_t index) const         { return pool.at(index);}

The methods that can be const should be const:

    size_t size() const { return pool.size(); }
             //  ^^^^^^^

The implementation details are fine.

    void add(size_t & pos)
    {
        if(avail.empty()) // no reusable object
        { pool.push_back(TYPE()); pos = pool.size()-1; }
        else
        { pos = avail.back(); avail.pop(); }
    }
    void rem(size_t & a) { avail.push(a); }

I would change the add() so it returned pos:

    size_t add();

Also the vector starts off very small and re-sizes to get bigger.
To make sure that it does not re-size too often I would add a constructor that gives the vector a reasonable size to start with:

object_pool::object_pool()
{
    pool.reserve(1000);
}

But I think you are using the wrong technique.
I would use a pool allocator and plug it into the vector.

You can read more about it here: https://stackoverflow.com/q/2984434/14065


Parse YAML file with nested parameters as a Python class object

If you split the configuration fields into magnitude and unit (as you've already done for surface_areas) you won't have to split and parse them in code.
If you then convert your configuration to JSON you won't need to convert strings to numbers. JSON strings must be quoted, and numbers must be unquoted, so the json module will simply do those conversions for you.

Other than that:

Configuration handling should be separate from building other objects - that way it's easy to use your code whether the configuration comes from a file or from command-line parameters.
Accessing properties two levels deep (such as pm.biomass.diameter) violates the Law of Demeter. You could write for example an as_parameter_list for each class to get a representation like f'rho_cat = {rho_cat}' etc.


Without commenting on the algorithm for a lack of knowledge regarding neural networks, this answer provides some style suggestions. Take the first method:

def weights_init(inSize,outSize): #initialize the weights
    return 2*np.random.random((inSize,outSize))-1

In python it is against the PEP style guide to use camelCase for arguments. That comment should be dropped down a line. Place some spaces in between your arguments and operators so it can breath better:

def weights_init(in_size, out_size):
    #initialize the weights
    return 2 * np.random.random((in_size, out_size)) - 1

Function names shouldn't be Uppercased.

def sigmoid(input, weights):
    #create a sigmoid layer and return a layer along with its derivative
    out = 1 / (1 + np.exp(-np.dot(input, weights)))
    derivative = out * (1 - out)
    return out, derivative

Default arguments in the param signature shouldn't have a space between the equals sign.

Also it would be nice to add double line breaks for ease or reading.

def backProp(layers, weights, deriv, size, rate=1):
    #get the cost function derivative
    derivative = deriv.pop()

    #reverse all the lists because we need to go backwards
    deriv = deriv[::-1]
    layers = layers[::-1]
    weights = weights[::-1]
    new_weights=[]

    #backpopagate
    new_weights.append(weights[0] + (layers[1].T.dot(derivative * rate)))

    #this one does not fit well the algorithm inside for loop, so it's outside of it
    for i in range(len(size) - 2):
        derivative = derivative.dot(weights[i].T) * deriv[i]
        new_weights.append(weights[i + 1] + (layers[i + 2].T.dot(derivative * rate)))
    return new_weights[::-1]

def train(input, size, rate=1, epochs=1):
    #train the network
    layers=[]
    weights=[]
    derivs=[]

    #weights initialization
    for i in xrange(len(size) - 1):
        weights.append(weights_init(size[i], size[i + 1]))

    #the training process
    for i in xrange(epochs):

        #online learning
        for example, target in input:
            layers.append(example)

            for i in xrange(len(size) - 1):
                #calculate the layer and itd derivative
                layer, derivative = sigmoid(layers[i], weights[i])

                layers.append(layer)
                derivs.append(derivative)

            #loss function
            loss_deriv = target-layer[-1]

            #multiply the loss function by the final layer's derivative
            derivs[-1] = loss_deriv * derivs[-1]

            #update the weights
            weights = backProp(layers, weights, derivs, size)
            layers=[]
            derivs = []

    return weights


Rearranging array - with empty strings in front and non-empty strings at back

Your code snippets are interesting... both of them.

The second is interesting because I feel it is your better-executed system, you used an interesting bi-directional approach, and it is efficient.

The first is interesting because I prefer the in-place solution, but your implementation is kludgey.... and hard to follow.

Temp-array solution

Notes:

use String.isEmpty().
make len final, it's not a big deal, but I find it helps readability.

As an aside, I would seriously consider a simpler temp-array solution, even though it loops twice:

final int len = arr.length;
final String[] temp = new String[len];
int pos = 0;
for (String s : arr) {
    if (s.isEmpty()) {
        temp[pos++] = s;
    }
}
for (String s : arr) {
    if (!s.isEmpty()) {
        temp[pos++] = s;
    }
}
return temp;

The above solution may be slightly slower (would need testing), but it is also clear, and scales in linear time still. It's not horrible.

In-place solution

This solution is just.... messy. I think a better option is to have two pointers..... one to the first non-empty, and the next to the first empty after that....

private static final int findEmptyState(final String[] data, int index, final boolean empty) {
    while (index < data.length && data[index].isEmpty() != empty) {
        index++;
    }
    return index;
}

with the above helper function, you can:

    final int len = arr.length;
    int notempty = findEmptyState(arr, 0, false);
    int empty = findEmptyState(arr, notempty + 1, true);

    while (notempty < len && empty < len) {

        // shift the next empty value in before the not-empty.
        String e = arr[empty];
        System.arraycopy(arr, notempty, arr, notempty + 1, empty - notempty);
        arr[notempty] = e;

        // find the next coordinates.
        notempty = findEmptyState(arr, notempty, false);
        empty = findEmptyState(arr, notempty + 1, true);
    }
    return arr;

Alternatives

A cheating alternative is to rely on the fact that Java sorts are stable... you can do:

Arrays.sort(arr, Comparator.comparingInt(value -> value.isEmpty() ? 0 : 1));
return arr;

which puts empty values first.

Or, as a duplicated solution, you can:

 return Stream.of(arr)
          .sorted(Comparator.comparingInt(value -> value.isEmpty() ? 0 : 1))
          .toArray(sz -> new String[sz]);


Optimize a simple and quick python script for transposing a .csv file

I believe there is a much simpler way of doing this.

If I correctly understand the problem, the idea is to produce a single column of frequencies.

with open('input.txt', 'r') as infile, open('out.csv', 'w') as outfile:
    print >> outfile, "Frequency"
    for line in infile:
        for freq in line.split()[2:]:
            print >> outfile, freq

This iterates over each line in the input file.  It uses split to eliminate whitespace and to split each line into fields.  It then discards the first two, which are assumed to be "Frequencies" and "--" and writes the remaining fields to the output file.


Need to condense the following into a looping function

You seem to always end with the check: Is there another parent? Or as it can be formulated, while there is another parent, grab that parent.

Luckily for you, there are while loops.

while (!empty($parent)) {
    $query = $connection->query("SELECT * FROM pages WHERE filename='$parent'");
    while($row = $query->fetch_array()) {
        $path_arr = explode('/',$row['path_to']);
        end($path_arr);
        $key = key($path_arr)-1;
        $parent = $path_arr[$key];
        break; // break from the inner loop that fetches each row
    }
}

This code will continue looping while there is a parent available. Note that the new parent uses the same variable as the previous one, this is an important part in making this loop work.

Other suggestions:

Use prepared statements! It is good that you seem to sanitize your inputs by using the real_escape_string method. But prepared statements is always better. And then you wouldn't have to use the real_escape_string call.
Since this code only gets the first result, you don't need the inner while loop and can replace it by a if instead.

while (!empty($parent)) {
    $query = $connection->query("SELECT * FROM pages WHERE filename='$parent'");
    if ($row = $query->fetch_array()) {
        $path_arr = explode('/',$row['path_to']);
        end($path_arr);
        $key = key($path_arr)-1;
        $parent = $path_arr[$key];
    }
}

I do have to ask though: What's the point in just grabbing the parent until there are no more parents? To store all the parents in an array, let's do like this:

$parents = array();
while (!empty($parent)) {
    $parents[] = $parent; // add parent to the array
    $query = $connection->query("SELECT * FROM pages WHERE filename='$parent'");
    if ($row = $query->fetch_array()) {
        $path_arr = explode('/',$row['path_to']);
        end($path_arr);
        $key = key($path_arr)-1;
        $parent = $path_arr[$key];
    }
}

Now, when this loop finishes, $parents contains all the parents that was not empty. Now you can loop through that using a foreach loop, or use it with implode or whatever you'd like :)


Finding an equilibrium of an index of an array

You can utilize built-in features of Python to refactor the code.

Use the sum() function

Python already provides a sum() function to add all elements of a list that you can use.

example_list = [1, 2, 3, 4, 5]
result = sum(example_list)

Slicing

Python allows selecting a range of values of a list. The syntax is:

list[start:end:step]

All these are optional. By default, start is 0, end is the length of the list, and step is 1.

Using this, you can select elements before the index by list[:index] and select elements after the index using list[index+1:].
Idiomaticity

Here, a and b are compared for equality. If a is equal to b, the expression a == b will be True, so True is returned.

if a == b:
    return True

# Refactored
return a == b

Naming conventions

snake_case is preferred over camelCase for naming in Python community. Use is_equilibrium instead of isEquilibrium.


Printing contents of list with indices from other list

It doesn't look like you're using <stdio.h>, so you can just remove it.
If you won't ever need to provide command line arguments, then you can remove main()'s parameters.
If you'll just be iterating though these lists forward, then it may be more beneficial to use an std::forward_list instead.  Or maybe you can just use an std::vector if there's no special need for a linked list.
Your list assignments is still pre-C++11.  Instead, use its initializer list:

list<int> listL { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };

list<int> listP { 0, 9 };

This will also allow you to make them const right away.


For variable and function names, use camelCase. For constants, or at least variables that are used as constants, use ALLCAPS_AND_UNDERSCORES. For constructor functions, use TitleCaps (I forgot how they called this). This is a convention which is common among programming languages and you should follow this to avoid misunderstandings.
Never forget semi-colons, even when JS inserts them for you at certain cases.
As much as possible, use strict comparison (===,!== etc.)
Use a tool to check for code quality. Most of the bad practices will be weeded-out by using such tools. You can use JSHint to check your syntax.

As for code:

$(function () {

    //A handy tip in keeping things clean is that you can use comma-separated
    //variable declarations. It's best you use this style when declaring
    //variables without assigning anything.
    var width, time, plusPos;

    //As for variable declaration with assignments, it's best they are var'ed
    //individually. Commas tend to get messy when assignments are done.
    var slide = $(".imgSection li");
    var imgSec = $(".imgSection").hammer();
    var crntPos = 0;

    function changeImg(e) {

      crntPos = $(this).index();

      var clkWth = width * .1;
      var newPos = (crntPos * width) - clkWth;

      slide.css("transform", "translate3d(-" + newPos + "px,0,0)");

      //I notice that changeImg is called every click of `slide`. This means
      //that if currentPos === 1, a handler gets attached? You might want to
      //review this one
      if(crntPos === 1) {
        $("li:eq(0)").on("click", function () {
            slide.css("transform", "translate3d(0,0,0)");
          });
      }
    }

    //I found that your resize function does the same thing regardless of
    //the condition. We'll remove the condition instead.

    function resize() {
      slide.eq(crntPos).trigger('click');
    }

    //.on() accepts a map of events and handlers. You can use this style to
    //bind events on an object in one place neatly. You also avoid wrapping
    //the same object more than once with jQuery. In this case, it's avoiding
    //the call of $(window) more than once.
    $(window).on({
        'load resize': function () {
          width = slide.outerWidth(true);
        },
        'resize': function () {
          clearTimeout(time);
          time = setTimeout(resize, 100);
        }

      });

    imgSec.on({
        'dragleft dragright': function (ev) {
          ev.gesture.preventDefault();
        },
        'swipe': function (ev) {

          var index;

          //You can cache repeatedly accessed values
          var direction = ev.gesture.direction;

          //As you can see, the only difference the conditions do is determine the
          //value for .eq(). You can DRY the code by extracting the common calls.
          if(direction === 'left') {

            //taking advantage that the direction in this block is already left
            //we merge in the last child check
            if($(this).is(':last-child')) {
              index = 0;
            } else {
              index = crntPos + 1;
            }

          } else if(direction === 'right') {

            //Use an else to avoid further execution of the condition. That way,
            //when direction is already 'left', it won't check if it is 'right'.
            index = crntPos - 1;
          }

          //Our factored-out call
          slide.eq(index).trigger('click');

        }

      }, 'li');

    FastClick.attach(document.body);
    slide.click(changeImg);

  });


First of all, you can't parse HTML with regex. RegEx is totally the wrong person for the job. Your code there assumes that the input HTML is properly formatted. If given broken HTML, you code won't even stand a chance. I suggest you use a parser instead. Creating one isn't trivial, so you might want to look for one out there.

Now, I see you use $ and I thought it was jQuery until I saw the code define it. Avoid using $. Name your function verbosely instead. That way, you don't confuse people to thinking it is jQuery when it isn't.

Now, speaking of jQuery, you could theoretically use jQuery to strip out HTML since it has a DOM parser and handy DOM functions:

// Get the HTML
var html = $('#code').val();
var DOM = $(html);

// Collect selectors to remove
var toRemove = [];
if(head.checked) toRemove.push('head');
if(style.checked) toRemove.push('style');
if(script.checked) toRemove.push('script');
if(form.checked) toRemove.push('form');

DOM.remove(toRemove.join(','));

if(comments.checked) DOM = DOM.filter('*');

var cleanHTML = DOM.html();

Just a theory. Dunno how it would really perform.


Image to HTML / CSS conversion using pure JS

After working on this for a while with other developers on Stack Overflow chat, the best solution I came up with (so far) was to use an asynchronous loop and adding nodes to a Document Fragment instead of adding them directly to the DOM.

The result:

document.addEventListener("DOMContentLoaded", function(event) {
 const file = document.getElementById('file');

 file.addEventListener('change', handleFile);

 function handleFile(e){
  document.getElementById('container').innerHTML = '';

  // Load image
  let img = new Image;
  img.src = URL.createObjectURL(e.target.files[0]);
  img.onload = function() {
   // Create canvas
   let canvas = document.createElement('canvas');
   let ctx = canvas.getContext('2d');
   canvas.width = img.width;
   canvas.height = img.height;

   // Draw image to canvas
   ctx.drawImage(img, 0, 0, img.width, img.height);

   let container = document.getElementById('container');
   container.style.width = img.width+'px';
   container.style.height = img.height+'px';

   let pixelData = ctx.getImageData(0, 0, img.width, img.height).data;
   let pixel = 0;
   let processedPixels = 0;
   let total = img.height*img.width;

   (function _asyncLoop(){
    let row = document.createElement('div');
    let fragment = document.createDocumentFragment();
    row.className = 'row';

    let rowPixels = 0;

    do {
     let col = document.createElement('div');
     col.className = 'col';

     col.style.cssText = 'background: rgba('+pixelData[pixel]+','+pixelData[pixel+1]+','+pixelData[pixel+2]+','+pixelData[pixel+3]+');';
     fragment.appendChild(col);
     processedPixels++;
     rowPixels++;
     pixel = pixel + 4;
    } while(rowPixels < img.width);

    row.appendChild(fragment);
    document.getElementById('container').appendChild(row);

    if( processedPixels < total ) setTimeout( _asyncLoop, 100 );
   }());

   URL.revokeObjectURL(img.src);
  }
 }
});
#container {
 margin-left: 50px;
 margin-top: 50px;
}
.row {
 overflow: auto;
}
.row {
 height: 1px;
}
.col {
 width: 1px;
 height: 1px;
 float:left;
}

Select an image from your computer and allow Javascript to draw it in the DOM using only DIV elements!

 <input type='file' id='file'/>


Your performance is going to suffer until you can create a "WHERE IN"-style query for users, either by building a string or by combining Expressions.

Or, if you want to keep it simple, just put the active criteria in your query, don't pull it up front. I'd recommend this approach.

Add .Expand("Users") on the active subscriptions query to pull back the related Users. I would avoid getting your ActiveBuilderSubscriptionSummary involved until you get your results back, at which point you can then project the query results to a collection of ActiveBuilderSubscriptionSummary objects using a standard LINQ .Select.

If you are hesitant to remove or change your method because you need to reuse it, or it is comfortably nestled in a repository, I'd refactor to use a stored proc instead. Otherwise, faced with the choice, it is way better to duplicate your query in code than to force an eager load of data up front.


K&R C Exercise 1-14: Histogram of the frequency of types of characters

Nice job on your code. I only have a few things to say along with some extra nit-picks at the end.

Refactor

I see this construct a lot in your code:

for (j = 0; j <= nwhite; ++j)
{
    if (nwhite - j > 0)
        putchar('*');
}
putchar("\n");

Of course, different variables are used every time, but the concept is the same. You could actually simplify your code if you extracted this logic to a separate function. Here is what I mean:

void print_stars(limit) {
    for(int i = 0; i < limit; i++) {
        if(limit - i > 0) {
            putchar("*");
        }
    }
    putchar("\n");
}

Now, you can just use this function every time you come across this construct:

print_stars(nwhite);
print_stars(nother);
for (i = 0; i < 10; ++i)
{
    print_stars(ndigits[i]);
}

Nitpicks

That refactoring was really all I had to say about your code. These are just extra (yet important) things.

Always use braces. I notice that you've omitted braces on some if statements, and that's probably because K&R does that a lot. In actual code, this is bad practice because it can lead to hard-to-find yet easy-to-get bugs.
You can simplify initializing arrays with 0s with this:

int ndigits[10] = {0};

There is no need for an extra loop to do this.


This being Python, where indentation is significant, it is important to consistently follow the convention of four spaces per level.

You shouldn't format the square root as %d, since the result is rarely an integer.

There are several recommendations that I could make about organizing this code, but the single most important point is that functions should not be treated as goto labels.  If you need a loop, then write a loop using while or for.  Don't have main call main().  Don't have repeat call main().  Don't have repeat call repeat().  Otherwise, you end up with spaghetti code.


int pointer = 1;

Looks like you're throwing away memory[0] here; I'd expect the pointer to initialize at the very start of the "tape".

if (System.IO.File.Exists(args[0]) == true)

The == true part is redundant, and the fully-qualified File.Exists feels... crowded. I'd remove System.IO. and add using System.IO; at the top of the file.

Arguably if no argument is specified, you should be throwing some ArgumentException instead of just saying "specify the source file" and exiting with a code-0, which would be interpreted as a successful run. Such a guard clause would help reduce nesting in the Main procedure:

    public static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            throw new ArgumentException("No source file was specified.");
        }
        if (!File.Exists(args[0]))
        {
            throw new FileNotFoundException("Specified source file was not found.");
        }

        BF(System.IO.File.ReadAllText(args[0]).ToCharArray());
    }

Notice the consistency with brace positioning; your code alternates between C#-style and Java-style braces, depending on whether we're looking at a member or its body - it really doesn't matter which one you prefer, but pick a style, and stick to it.

"BF" might perhaps possibly make a [bad] class name - it's a noun. But here BF is a method, and methods do something, they're verbs. Interpret or even Run would be a better choice.

BF is a simple language; you don't need to go out of your way and implement a lexer to tokenize input and a parser to make sense out of it - basically every single character is an instruction, so it makes sense to process it one character at a time.

But is it ideal to read an entire file's contents, iterate every single character to create a character array, and then pass that array to a method that will iterate it one item at a time? Seems rather inefficient, considering you could be streaming the file content into the interpreter, and finish interpreting the BF program as you finish reading the last character in the file, having iterated the contents exactly once.

I think I'd make a separate dedicated class for the interpreter, with the pointer and memory[] as instance fields; I'd make a Dictionary<char, Action> to map each BF token to a dedicated method, too.


AutoResetEventAsync, am I missing something?

Your code does have race conditions, so it won't work correctly. I think your main problem is that you make some “destructive” operation (e.g. dequeue a handler from the queue) without knowing that the followup operation will actually succeed and not handling the eventual failure in any way.

For example, the following sequence of events could happen:

The class is created in unset state.
WaitAsync() is called, creating a Handler, adding it to the queue and returning a Task.
Set() is called, setting isSet to 1.
The handler from step 2 is dequeued.
WaitAsync() is called from another thread. Since isSet is 1, it sets isSet back to 0 and immediately returns a completed Task.
Back on the previous thread, TryUnsubscribe() is called in the handler from step 4 and succeeds.
The handler is Invoke()d, but TryReset() fails.
Set() now returns.

After this, the Task from step 2 is now orphaned, it will never be completed, because its handler is not in the queue anymore.

I suggest you don't write code like this by yourself, but instead use code written by others with more experience in concurrent programming. Specifically, you could use Stephen Toub's AsyncAutoResetEvent or AsyncAutoResetEvent from Stephen Cleary's AsyncEx library.


SQL Injection

You are vulnerable to SQL injection via pageSize.

You need to use prepared statements for all values, not just some of them.

Naming

total and getTotalCount could be more descriptive. Currently, I don't really know what "total" means without looking at the code of the function. You also don't need "total" at all (it's assumed when talking about a count). $clientCount = getClientCountForGroup($mysqli, $id) would be easier to understand.

Duplication

Your two queries are basically duplicates apart from the WHERE clause. You may want to remove that duplication.


Removing any duplicate characters in a string

Remove Duplicates:  (Re-Write Ant's code so it is readable).

#include <stdio.h>

void removeDuplicates(char* ptr);

void removeDuplicates(char* ptr)
{
    char seen[UCHAR_MAX+1] = {0};

                              //
                              // Smallest data type is a char (unless you want to bit
                              // twiddle, and that has been shown to be not worth it
                              // see the complaints about std::vector<bool> in C++).
                              // 256 bytes is not much.
                              //
                              // By using char as they type it prevents all the complex
                              // multiplication/division an bit twiddling that Ant was doing.

    unsigned char* source = (unsigned char*)ptr;
    unsigned char* dest   = (unsigned char*)ptr;
    unsigned char  next;

    do
    {
        next  = *source;       // Get next character.
        if (!seen[next])       // Only enter the `if block` if we have not seen it.
        {
            seen[next] = 1;    // Mark it as seen
            *dest = next;      // Move it to destination.
                               // Note: source will change faster than dest when we
                               //       start seeing dupes, this acts as the copy back
                               //       over the duplicates.
            ++dest;
        }
        ++source;
    }
    while (next != '\0');      // Once we have copied the null terminator quit.
}


Your code looks pretty good to me. A few notes:

You have a bug here:

$userID=$env:UserName

$SourceRoot      = "C:\Users\$User"

You are referring to $User, which hasn't been set. I always put this at the top of my scripts to catch such bugs:

Set-StrictMode -Version Latest

Why introduce a new variable, by the way? Why not just use it directly?:

$SourceRoot      = "C:\Users\$env:UserName"

This line can be simplified for the sake of readability:

$Source      = Join-Path -Path $SourceRoot -ChildPath $Folder

To this:

$Source      = Join-Path $SourceRoot $Folder

This code would be cleaner using the pipeline:

$mappedDrives = @()

foreach ($drive in $drives) {
    if ($drive.DisplayRoot) {
        $mappedDrives += Select-Object Name,DisplayRoot -InputObject $drive
    }
}

Like this:

$mappedDrives = $drives | ? $drive.DisplayRoot | Select-Object Name, DisplayRoot

(Not tested because I don't have any mapped drives, but I believe it is correct.)

You can format it like this if you like:

$mappedDrives = $drives |
    ? $drive.DisplayRoot |
    Select-Object Name, DisplayRoot

This comment is misleading:

#####################################
###  Backup user's mapped drives  ###
#####################################

You aren't backing up the drives. You are recording the drive mappings.


First, the findX functions don't need to initialise the variable oneUpon inside. It's also unclear, anyway.

public static double findU(double v, double f) {

    double oneUpon;

    oneUpon = 1/f - 1/v;
    return 1/oneUpon;

}

public static double findV(double u, double f){

    double oneUpon;

    oneUpon = 1/f - 1/u;
    return 1/oneUpon;
}

public static double findF(double u, double v){

    double oneUpon = 1/u + 1/v;
    return 1/oneUpon;
}

Just return the variable directly.

I'd also like to point out that findU and findV are identical in function, just named differently.

Consider the following instead:

public static double findUV(double uv, double f) {
    return 1/(1/f - 1/uv);
}

public static double findF(double u, double v){
    return 1/(1/u + 1/v);
}

    System.out.println("Hello! This is a calculator based on the Mirror Formula. \n");
    System.out.println("The mirror formula is a relation between the object distance, the image distance \n and the focal length.");
    System.out.println("The formula is : 1/u + 1/v = 1/f.  (u=distance of object, v=distance of image, f=focal length.)");
    System.out.println("It is applicable for both convex mirrors and concave mirrors.");
    System.out.println();
    System.out.println("This calculator can calculate :");
    System.out.println();
    System.out.println("1. Distance of the object from the pole of the spherical mirror.");
    System.out.println("2. Distance of the image from the pole of the spherical mirror.");
    System.out.println("3. Focal length");
    System.out.println("[If you have 2 of the values.]");

This is not how you print large blocks. Separate your strings with line separators like /n. Keep the text as a large multi-line string block, and print that out instead. It will take less maintenance and less System.out.println calls.

Feel free to take the user input as a string/letter instead of an integer, makes everything much clearer. On a related note, an exit function would be nice too.

    switch (userChoice) {

    case 1 :


LESS CSS, including support for shadowboxes

Syntax is correct. When I was learning it was helpful to me to view the major LESS libraries out there and see what they were doing.

There are some mixin techniques that you will stumble upon as you advance your proficiency with the language. Also if you have JavaScript skills you can easily add additional logic to the mixins that make them even more powerful.

Once I got to a specific level with my proficiency I wrote my own library and I still use this to date for all of my projects. You can view it here - feel free to pick it apart and see if you find anything useful to use.

Edits suggested by @Dannnno

A few good techniques you will stumble upon are looping through the variables passed into a mixin. This is very powerful because as you create your mixins you will no longer have to create large pass ins that require comma separated notation like your '.shadowbox-format' mixin.

Also using @media inside of each mixin will result in larger then normal CSS output.

You might want to look into some of the Javascript features of LESS and build yourself a way to pass in array values to a holding variable so that when the compiler hits the @media mixin all values are itteraed in one @media statement rather then scattered throughout the document.


Your style generally looks fine. Do run flake8 and make the edits suggested, mostly adjusting whitespace. Starting out with zero and one, then switching to False, is a bit odd.

In e.g. last line of odd_sieve(), consider turning that into a three-line list comprehension.

    sieve = [False, False, True] + [True, False] * (n // 2 - 1)

That seems to allocate lots more than sqrt(N) entries.

The function name of number_of_odd_nums_below() appears to be off-by-one, as it's missing a comment explaining one may only pass in odd numbers. With such a restriction it seems that greatest_odd_number_below() would simply become n - 2.

My personal preference is for the naive code. The fancier version feels like it's cheating. If we get to use long division, why stop at 2? Why not 3, 5, 7, 11? When (before sqrt(N)) is the right place to stop, and transition to sieving? The advantage of the sieve is that, once having constructed a bounded list of primes, it can rapidly answer lots of prime queries. It would be interesting to see a particular problem domain involving many repeated queries where a natural tradeoff really does emerge.


Circular dependencies between immutable objects; the Freeze Pattern

This class should instead use an AtomicReference to ensure the state is kept valid. Alternatively, you should incorporate thread-safe handling of the String.

Consider:

private final AtomicReference<String> stateref = new AtomicReference<String>();

public void setState(final String state) {
    // only one initializer will succeed (assuming state is not null)...
    if (!stateref.compareAndSet(null, state)) {
        throw new IllegalStateException("state already set: '" + state + "'.");
    }
}

private void ensureInitialized() {
    if (stateref.get() == null) {
        throw new IllegalStateException(
            "state must be set before this instance is used."
        );
    }
}

This pattern ensures usage is consistent, there can be only one initialization of the instance, and that any thread-unsafe practices are handled well.


Python function to count syllables in a word

As a good practice to promote code reuse, the function should return a numeric result.  The print() should be done by the caller.

Constantly referring to is_previous_vowel is tedious. There are a couple of solutions you could use involving itertools. In particular, groupby() and zip_longest() could be useful.

Ultimately, the simplest solution is to use a regular expression to declare what you are looking for: one or more consecutive vowels ('[aeiouy]+'), but not an e at the end ('(?!e$)).

import re

def count_syllables(word):
    return len(
        re.findall('(?!e$)[aeiouy]+', word, re.I) +
        re.findall('^[^aeiouy]*e$', word, re.I)
    )


User class implemented with PHP 7.4 using Active Record

Inconsistent Function Imports

Import all used functions or none.
If I see this:

use function array_key_exists;

I assume that it is the only global function being used in that file. To my surprise, it is not true as password_hash is used inside the same file too.

Either import them all, or none.
I myself prefer no imports and instead prefix global function calls with the backslash to denote global scope (ie return \array_key_exists($k, $a);).

Useless Docblocks

In PHP 7.4 you get the benefit of typehinting properties. I dont see a reason to repeat that type in a docblock anymore in that case. Furthermore it may cause confusion of what the original intent was, if docblock and typehint mismatch. Like here:

/**
 * @var string
 */
private ?string $id = null;

So can it be null or not? I suppose it can, but you never know if you made it this confusing...

Active Record Anti-pattern

You asked to identify possible anti patterns. Active record is one of them. It combines two responsibilities. The entity should not know anything about where it is going to be stored and how. It may eventualy get stored on multiple places or be stored in various ways. The entity should only know that it has some structured data. Then another class(es) should know how to store it and reconstruct it from its permanent representation (ie a db row).

Also notice that save() is either going to have to be repeated in every entity. Or all entities must inherit the same parent or use the same trait (inheritance is oftne not a good idea, and multiple inheritance (traits) even worse).

Also notice that only one of User class's methods (namely the save) uses the database object. That only confirms that it should not be there. You should pass the user entity/structure to another object asking him to save the user into its persistent storage for later retrieval.

Check Your Arrays' Keys

In the fromArray() you are copying the values from array data without making sure that those data is there.

$this->setEmail($data['email']);
$this->setUsername($data['username']);
$this->setPassword($data['password']);

if (isset($data['email']) && \is_string($data['email'])) $this->setEmail($data['email']);

or set it to some default

$this->setEmail($data['email'] ?? '');

Handling Login

Although you have removed that part from your post, I will address it nevertheless.

isLoggedIn should not be persistent property of user entity (table). It should be stored (or inferred) from session. Otherwise how you make sure that it is turend to false after some time of inactivity?

Anyway User::login(string $email, string $pass): bool again breaks SRP. You should have it more like this: Authenticator::login(string $email, string $pass): ?User. You may be tempted to make it UsersRepository::login() but repository usualy does not need access to session while the login method does, therefore it should be in its own class, not in the repository.


Swapping of element with its neighboring element (Python)

Your code, while it works, has a lot of room for improvement.

Naming conventions

Python has a best practice guide for style and naming conventions called PEP 8. Your variable names generally follow the lines of this guide, but lenofalist should be called len_of_alist.

Duplicate code

Your code has a lot of duplicate code. 5 lines out of 19 are copied and pasted, that's over 25%. It lowers readability and makes any change to your code harder, as it may have to be changed twice.

In your case, the if ... else construct can be avoided altogether by exiting the loop before the last element is reach if the length of the list is odd.

Use for loops

You use while loops. It works, but is not the best fit for your case. You have to initialize an index and increment it manually, which makes the code longer and more complicated than it needs to be. Also, using i instead of index for a loop counter is generally accepted, as it is very common.

for i in range(0, len_of_alist, 2):
    # your code here

is functionally the same as your while loops, while being more concise and readable.

Swapping elements

In Python, you can swap the values of two variables using the following construct:

a, b = b, a

Your way of using a temporary variable is more language agnostic, but the Python way is much cleaner.

Make your code a function

Let's imagine you want to swap neighboring elements of a list as part of a larger project. It would be far more convenient and clear having this code in a function and calling it where you need it instead of inserting your code snippet where needed.

If you are using Python 3.5 or higher, you can use a type hint to make sure your function is indeed working with a list.

Putting it all together

Here is my take on improving your code:

def swap_neighbors(alist: list):
    for i in range(0, len(alist)-1, 2):
        alist[i], alist[i + 1] = alist[i + 1], alist[i]

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
swap_neighbors(my_list)

As a side effect, there are no variables that need to be declared ahead, cleaning up the code even further.


Parse a list of people to determine who likes someone

I like to break problems like this up into a few steps, makes it easier for my brain to understand.

import re

raw_text = """Friend Name                     Joe
Likes                           Jill
Age                             30
Gender                          Male

Friend Name
Likes                           Mark
Age                             30
Gender                          Male

Friend Name                     Bob
Likes                           Ralph
Age                             30
Gender                          Male"""

def split_row(row):
    items = re.split('\s\s+', row)
    if len(items) < 2:  # Value is blank
        return items[0], None
    return items

def parse_block(block):
    rows = block.split('\n')
    fields = map(split_row, rows)
    return dict(fields)

def process_text(text):
    blocks = text.split('\n\n')
    return map(parse_block, blocks)

if __name__ == '__main__':
    for like in process_text(raw_text):
        print(like)

Which generates the output

{'Likes': 'Jill', 'Friend Name': 'Joe', 'Age': '30', 'Gender': 'Male'}
{'Likes': 'Mark', 'Friend Name': None, 'Age': '30', 'Gender': 'Male'}
{'Likes': 'Ralph', 'Friend Name': 'Bob', 'Age': '30', 'Gender': 'Male'}


Generate 16-digit unique code (like product serial)

Okay first off, let's make your random character choosing better.

The simplest way to get random symbols is to simply define the alphabet and then index into it.

So here's how you'd typically do it:

static final private String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
final private Random rng = new SecureRandom();

char randomChar(){
    return ALPHABET.charAt(rng.nextInt(ALPHABET.length()));
}

String randomUUID(int length, int spacing, char spacerChar){
    StringBuilder sb = new StringBuilder();
    int spacer = 0;
    while(length > 0){
        if(spacer == spacing){
            sb.append(spacerChar);
            spacer = 0;
        }
        length--;
        spacer++;
        sb.append(randomChar());
    }
    return sb.toString();
}

The likelihood of generating two keys that are duplicates is  \$\frac{1}{36^{16}} \approx 8\cdot 10^{-24}\$. So if you generate 10000 (ten thousand) bulk keys, the likelyhood of not having any duplicates is: $$(1-\frac{1}{36^{16}})^{10000}=99.99999999999999999987\%$$.

In other words, you are not very likely to get duplicates as long as your random function is good (hence the use of SecureRandom instead of Math.random(). To be certain you have to always check against your database anyway as a last step so I would just not bother with duplicate checking on the client side as the likelihood of finding duplicates is so very low.


In large projects is important to save as much space as possible.
Your selectors are way to specific for example :
#Projects .card .card-text {}

Whereas this will do:
.card-text {}

If the purpose of this was a different card-text in a different card you can add another class to card-text as a modifier


You should be able to simplify that whole inner loop with a simple Where extension:

If you have the equality operator implemented:

baseClass obj = cognosGroup.members.value[y];
cognosGroup.members.value = cognosGroup.members.value.Where(x => x != obj).ToArray()

Or use the index option:

cognosGroup.members.value = cognosGroup.members.value.Where((x,i) => i != y).ToArray()

Another option is to store the data in a List<baseClass> instead and use the Remove or RemoveAt extension.


Longest common substring using dynamic programming

Sorry I've not examined too closely your code to make a comment, but just considering the problem as stated and the fact you are using Py3, I would probably solve it with itertools.accumulate, e.g.:

>>> import itertools as it
>>> import operator as op
>>> ss = ["thisishello", "dfdsishdllo", "ashsisdsdsf"]
>>> i, l = max(enumerate(it.accumulate(it.chain([0], zip(*ss)),
...                      lambda x, y: (x+1)*(len(set(y)) == 1))), key=op.itemgetter(1))
>>> i, l, ss[0][i-l:i]
(6, 3, 'sis')

Should work well for an arbitrary number of strings as it uses generators and doesn't create any intermediate data structures.
It does use the fact that a False equates to 0 with len(set(y)) == 1 but if that is uncomfortable you could simply replace with 1 if len(set(y)) == 1 else 0.

Note: I still wish that itertools.accumulate had an initial value argument much like functools.reduce has, would avoid the need of chaining the initial value to the iterable.


This:

def name():
    name = input("What is your name? ")
    while name.isdigit():
        print("Make sure to enter an actual name.")
        name = input("What is your name? ")
    return name

means that "1" is not a real name, but "a" and "17xy" are. I think it might be better to use some kind of a regular expression, or - better - just accept whatever nonempty string the user chooses to give you as his/her name.

In your user_input(), you try to convert the input to int, and - if that fails - to float. Why not straight to float? I don't see how is 17 better than 17.0.

Also, in the same function, your break statements will never execute, as the return statement terminates the function.

I think it'd be a much better program if the input was date of birth. Do you know your current age, as anything more precise than "between x and x+1 years old"?


Building filenames should be done using the System.IO.Path.Combine() method. This ensures that you don't skip a "\" by accident and also enforces that no invalid path/file characters are used.
Strings shouldn't be added to other strings (if done more than once), better use System.Text.StringBuilder

As Mat's Mug already pointed out, your variable naming should be enhanced.

So

Dim sNewFullName As String = sDir + "\" + sFileName + "_Temp.txt"

would become

Dim newFullName As String = System.IO.Path.Combine(currentDirectoryName, currentFileName + "_Temp.txt")

As Mat's Mug also pointed out you need to extract some of the responsibilities to separate methods.

So let us introduce a method which takes a filename as input parameter and returns an array of Strings representing the content of the file.

Private Function GetFileContent(fileName As String) As String()
    Return System.IO.File.ReadAllLines(fileName)
End Function

next we introduce a function which takes a filename as input parameter and returns wether the first character of the first line is the "|" . We first check if the read line is maybe Nothing by using String.IsNullOrWhiteSpace(). This prevents an exception if the file would be empty.

Private Function FirstLineStartsWithPrefix(fileName As String, prefix As String) As Boolean
    Using reader As New System.IO.StringReader(fileName)
        Dim line As String = reader.ReadLine()
        Return Not String.IsNullOrWhiteSpace(line) AndAlso line.StartsWith(prefix)
    End Using
End Function

Next we introduce a method which takes a String array as input parameter and returns the prefixed content. We are using the Append() and AppendLine() method. Both methods are returning a StringBuilder object, so we can use it in a fluent way.

Private Function AddPrefixToLines(content As String(), prefix As String) As String
    Dim sb As New System.Text.StringBuilder(1024)
    For Each line As String In content
        sb.Append(prefix).AppendLine(line)
    Next
    Return sb.ToString()
End Function

Next we introduce a method which takes a FileInfo object as input parameter and returns nothing (a Sub).

Private Const pipePrefix As String = "|"
Private Const fileNamePostFix As String = "_Temp.txt"
Private Sub ProcessFile(currentFileInfo As FileInfo)

    Dim fullName As String = currentFileInfo.FullName

    If Not FirstLineStartsWithPrefix(fullName, pipePrefix) Then Exit Sub

    Dim fileContent As String() = GetFileContent(currentFileInfo.FullName)

    Dim prefixedContent As String = AddPrefixToLines(fileContent, pipePrefix)

    Dim pureFileName As String = Path.GetFileNameWithoutExtension(fullName)

    Dim newFileName As String = Path.Combine(currentFileInfo.DirectoryName, pureFileName & fileNamePostFix)

    File.WriteAllText(newFileName, prefixedContent)

    currentFileInfo.Delete()

    File.Move(newFileName, fullName)

End Sub

Now your initial code will look like

Dim fileList As FileInfo() = dirList.GetFiles

For Each fiName In fileList

    ProcessFile fiName

Next