This is pretty nice. I got some comments, some of which are my personal opinion (for example how to declare variables), some are accepted conventions (naming), and some are bug fixes.

Declaring variables

While it might be more performance friendly to declare all variables from the outset, it is best practice, I think, to declare variables only within the scope they're used. This is to decrease variable pollution in bigger functions. In such a simple app, it doesn't matter. But as your application gets bigger and better you don't want too many variables in scope.

From your code: num01, num02, playeranswer, and answer are only used within the loop. So it is better to declare then inside the loop (or you might accidentally use them outside or simply crowd your intellisense).

Also, for some variables you're splitting declaration (int numofquestions;) and assignment (numofquestions = Convert.ToInt32(Console.ReadLine());), and for other you're not. I think it is better to have declaration and assignment in one line, it is terser and more readable: (int numofquestions = Convert.ToInt32(Console.ReadLine());).

Naming

.Net convention is to use PascalCase for methods and classes and the like, and camelCase for variables. So, in your code: playeranswer becomes playerAnswer, and so on. You don't have any methods defined but you need to know the convention. It makes it easier to read your code. Again, it doesn't really matter for such a short app but for bigger apps such practices are a life saver. (A crude example, but I am sure you have seen the photo where KidsExchange reads like KidSexChange due to uniform capitalization KIDSEXCHANGE.)

I also like questionCount more than numOfQuestions. Shorter and uses clearer vocab.

Using a for loop

for loops are easier for humans to process than while loops, I think. Well easier for me.

So this :

int questionCount= Convert.ToInt32 (Console.ReadLine ());
int questionLeftCount = questionCount;

while (questionLeftCount > 0)
{
    // .. do stuff
    questionLeftCount --;
}

Can be better written as:

int questionCount= Convert.ToInt32 (Console.ReadLine ());

for (int questionLeftCount = questionCount; questionLeftCount > 0; questionLeftCount--)
{
    // do stuff ..
}

And it is exactly the same.

Also, since questionLeftCount is only used within the for loop definition, just use i or iter for iterator. It is standard practice. (It also standard practice to increment rather decrement). I am sure you have seen something that looks exactly like this in your readings.

for (int i = 0; i < questionCount; i++)
{
    // do stuff ..
}

Much shorter and nicer.

Verifying input

Your code crashes when I type something that is NOT a number. Obviously if you're shipping the app (I know you're not, but humor me), you can't have that.

The trick is to use int.TryParse to parse inputs. TryParse returns a bool to indicate whether the conversion is successful or not, and has an out variable which assigns a value to an already declared variable. The syntax is a bit weird and takes some getting used to, but it is being made nicer in C# 7.0 (not released yet).

// Usage
int playerAnswer;

if (int.TryParse (Console.ReadLine (), out playerAnswer))
{
    // do stuff with playerAnswer
}
else
{
    // show error message
}

If you want to keep asking for input until you get something valid, you can use a while loop :

 int playerAnswer;

 while (!int.TryParse (Console.ReadLine (), out playerAnswer))
 {
     Console.WriteLine ("Invalid Input. Please type a number using digits");
 }

Something of note: you need this little piece of code in two places. When you ask for the number of questions and when you ask for the answer. Instead of typing it twice, you should extract it into a method. You can easily do that in Visual Studio by selecting the code you want to extract into a method, pressing Ctrl + . or the small light bulb to the side, and selecting, well, Extract Method. It does all the thinking for you and it is fantastic.

I am not very imaginative so I just called it RequestInput.

static int RequestInput ()
{
    int playerAnswer;

    while (!int.TryParse (Console.ReadLine (), out playerAnswer))
    {
        Console.WriteLine ("Invalid Input. Please type a number using digits");
    }

    return playerAnswer;
}

Final result

class MainClass
{
    public static void Main ()
    {
        var rand = new Random ();

        Console.Write ("How many questions would you like to answer? ");

        int correctCount = 0;
        int questionCount = RequestInput ();

        for (int i = 0; i < questionCount; i++)
        {
            int num01 = rand.Next (11);
            int num02 = rand.Next (11);

            Console.Write ($"What is {num01} times {num02} ?");

            int playerAnswer = RequestInput ();

            if (num01 * num02 == playerAnswer)
            {
                Console.WriteLine ($"{playerAnswer} is correct!");
                correctCount++;
            }
            else
            {
                Console.WriteLine ($"{playerAnswer} is incorrect!");
            }
        }

        Console.WriteLine ($"You got {correctCount} of {questionCount} correct.!");
        Console.ReadKey ();

    }

    static int RequestInput ()
    {
        int playerAnswer;
        while (!int.TryParse (Console.ReadLine (), out playerAnswer))
        {
            Console.WriteLine ("Invalid Input. Please type a number using digits");
        }

        return playerAnswer;
    }
}

I did a few other things I like but that are just style choices and mild annoyances (for me). Using var instead of Random, for example, makes it easier for me to read, since Visual Studio has the same coloring for keywords like var and int but different for class names like Random. I also removed Console.ReadKey () from within the loop because it annoyed me when trying out your app. I removed Try Again because you didn't actually let me try again the same question. You could make it possible to try until you get the right answer in a similar pattern to the one dome earlier when verifying input. Finally, I used string interpolation syntax (introduced in C# 6.0) which is much, much, more pleasant to use.

Bonus, how to set a timer

There is a Timer class, which I have never used. (I am a beginner myself, mind you). There is also System.Diagnostics.StopWatch, which as you can tell is used for diagnostics.

Here is the code with Stopwatch. Mind that you'll need using System.Diagnostics at the top of the file.

class MainClass
{
    public static void Main ()
    {
        var rand = new Random ();

        Console.Write ("How long do want to play in seconds?");

        var ts = TimeSpan.FromSeconds(RequestInput ()); // type is System.TimeSpan

        int correctCount = 0;
        int questionCount = 0;

        var sw = Stopwatch.StartNew ();

        while (sw.Elapsed < ts)
        {
            // .. same old
            questionCount++;
        }
        sw.Stop ();

        Console.WriteLine ($"You got {correctCount} of {questionCount} correct in {sw.Elapsed}.!");
        Console.ReadKey ();

    }
}

You will notice I used Stopwatch.StartNew() which is a static method that creates a new instance of Stopwatch and starts it immediately. You could also do var sw = new Stopwatch(); sw.Start();

Edit: i realized there was a bug in my original implementation because I didn't understand how the TimeSpan struct works. I think it should work as expected now for longer times that 1 minute. Make sure to check the MSDN documentation

Let me know in the comments if there is anything unclear.

Edit : On the other answer, I think creating new classes for a simple console app is overkill, but it is definitely good practice for larger apps and it allows you to extend your game more flexibly.


Crawler for performing reverse search and writing results into a CSV file

There are multiple things we can do to improve the code:

variable naming - try to be consistent with PEP8 naming suggestions - for instance:

Page should probably be page - or even better url
Address would be address
Contact would be contact
f can be input_file
g can be output_file

titles variable is never used
move the url format string into a constant
you don't need writer = csv.writer = csv.DictWriter(...) - just assign the writer to the DictWriter instance directly
since you are crawling the same domain, re-using requests.Session() instance should have a positive impact on performance
use .findtext() method instead of xpath() and then getting the first item
I would also create a separate crawl function to keep the web-scraping logic separate

Here is the modified code with the above and other improvements combined:

import csv

import requests
from lxml import html

URL_TEMPLATE = "https://www.yellowpages.com/los-angeles-ca/mip/{}-{}"

def crawl(entries):
    with requests.Session() as session:
        for entry in entries:
            url = URL_TEMPLATE.format(entry["Name"].replace(" ", "-"), entry["Lid"])
            response = session.get(url)
            tree = html.fromstring(response.text)

            titles = tree.xpath('//article[contains(@class,"business-card")]')
            for title in titles:
                address = title.findtext('.//p[@class="address"]/span')
                contact = title.findtext('.//p[@class="phone"]')

                print(address, contact)

                entry['Address'] = address
                entry['Phone'] = contact
                yield entry

if __name__ == '__main__':
    with open("predefined.csv", "r") as input_file, open('newly_created.csv', 'w', newline='') as output_file:
        reader = csv.DictReader(input_file)
        field_names = reader.fieldnames + ['Address', 'Phone']

        writer = csv.DictWriter(output_file, fieldnames=field_names)
        writer.writeheader()

        for entry in crawl(reader):
            writer.writerow(entry)

(not tested)


Function to set nested property by dot-path, like _.set

Your code looks quite reasonable, there are only a few minor things that stand out to me.

You're constructing a new array every time a recursive call is made. For example, if the property passed is foo.bar.baz.qux.quuz, you will be constructing the following arrays of properties:

['foo', 'bar', 'baz', 'qux', 'quuz'] // initial call to `set`
['bar', 'baz', 'qux', 'quuz'] // 2nd call (recursive)
['baz', 'qux', 'quuz'] // 3rd call (recursive)
['qux', 'quuz'] // 4th call (recursive)
['quuz'] // 5th call (recursive)

These are all entirely separate arrays - when you .slice, you create a new array, it's not just a reference to a particular subset of the old array's indicies. Admittedly, it's unreasonable for a property list to be large enough for this to be a problem, but it seems a bit inelegant for space complexity. If you want to keep going the recursive route, you could fix it by creating the array only once in the initial call, then passing along an index to access.

Since the property is actually expected to be an array of properties, it would make more sense to pluralize the variable name. Also, since you're worried about purity, if you want to make it a bit more functional, rather than reassigning the parameter (which is better avoided when possible), put the result into a different variable, maybe by using a default argument:

function set (object, propertyStr, value, properties = propertyStr.split('.'), i = 0) {
  if (i === properties.length - 1) {
    object[properties[i]] = value;
  } else {
    set(object[properties[i]], '', value, properties, i + 1);
  }
}

const object = {
  position: {
    x: 5
  }
};
set(object, 'position.x', 1);
console.log(object);

But note that the function is still fundamentally impure, because its purpose is to mutate an argument. (That's not a problem unless you want it to be one, just something to keep in mind when discussing purity)

I think the recursion aspect makes things a bit more confusing than they need to be. I'd prefer to use reduce to iterate over the properties and access the last object, then assign the value to the last property on that last object:

const object = {
  position: {
    nested: {
      x: 5
    }
  }
};

function set(object, propertyStr, value) {
  const properties = propertyStr.split('.');
  const lastProperty = properties.pop();
  const lastObject = properties.reduce((a, prop) => a[prop], object);
  lastObject[lastProperty] = value;
}

set(object, 'position.nested.x', 'with pop');
console.log(object);

// If you want to avoid the .pop mutation, then:
function setNoPop(object, propertyStr, value) {
  const properties = propertyStr.split('.');
  const lastObject = properties.slice(0, properties.length - 1)
    .reduce((a, prop) => a[prop], object);
  lastObject[properties[properties.length - 1]] = value;
}

setNoPop(object, 'position.nested.x', 'no pop');
console.log(object);

The code will currently throw an error if an intermediate property doesn't exist or, in strict mode, is not an object. If you want an error to be thrown in this situation, that's OK, but you might prefer for the function to return a boolean indicating success or failure.

const object = {
  position: {
    nested: {
      x: 5
    }
  }
};

const isObj = param => typeof param === 'object' && param !== null;
function set(object, propertyStr, value) {
  const properties = propertyStr.split('.');
  const lastProperty = properties.pop();
  const lastObject = properties.reduce((a, prop) => isObj(a) ? a[prop] : null, object);
  if (isObj(lastObject)) {
    lastObject[lastProperty] = value;
    return true;
  } else {
    return false;
  }
}

const success1 = set(object, 'position.nested.x', 'with pop');
console.log(success1);
const success2 = set(object, 'position.doesNotExist.x', 'with pop');
console.log(success2);


Find and display the position of a word in a sentence

please note I am not that great at vb.net

Variables - Define them! You haven't defined

   TxtAddWord
   TxtAddSentence (though I see txtSentence commented out)

are they defined on the form design?

Testing for something to be "" usually has a better way. I think something like this -

If String.IsNullOrEmpty(txtaddsentence) Then

Speaking of that if - you have it twice - why?

If TxtAddSentence.Text = "" Then
    MsgBox("The sentence box is empty, so there are no matches.")
End If

I can't see TxtAddSentence changing after the first check as there aren't any functions to return a string.

Speaking of strings, why are you always using

TxtAddSentence.Text

When you can just

    Dim TxtAddSentence = "The cat sat on the mat" ' Temp for testing
    Dim TxtAddWord = "sat"

Which are string type.

Naming - use variable names to describe what is happening, and avoid that hungarian notation.

Variable -> can be ->
TxtAddSentence      sentenceAddition
TxtAddWord          wordToAdd
strSearchWord       searchWord
strText             why? it's already sentenceAddition
strArray            why? it's already wordArray
strWordList         what is this? a List Type? An Array Type? A String?
intIndex            index
strPosn             searchPosition
strWord             listedWord

Additionally, you're not giving a type to your variables:

ByVal strText, ByRef strArray)
ByVal strSearchWord, ByVal strWordList

Can be, as far as I can tell

Private Sub FindPositionOfWords(ByVal searchWord As String, ByVal wordArray() As String)
Private Sub BuildWordArray(ByVal sentenceAddition, ByRef wordArray)

It would be best practice to give a type to the variables in BuildWordArray - but I'm not entirely sure what type they should be.

Here -

Dim strPosn As String = ""

If this is position, why isn't it an integer? I would expect an integer, not a string.


Adding a node to a Binary Search Tree and printing the path to it

if(root != null){
        if(node.data == root.data) return;

        BNode p = root;

        while(p != null){

p cannot be null on the first pass.

Convert your while-loop into a do-while loop.

            }else{
                if(p.left != null){
                    p = p.left;
                }else{
                    p.left = node;
                    node.index = depth;
                    break;
                }
            }

else block containing only a if-elseif chain.

Merge them, like so:

            }else if(p.left != null){
                p = p.left;
            }else{
                p.left = node;
                node.index = depth;
                break;
            }


There are some confusing aspects to your XML, and some practices that you may end up appreciating.....
Technical
Your XML is valid, but it does not follow best practices. The XML:

   <con gurd="min>b"  type="if">

This should be written:
    <con gurd="min&gt;b"  type="if">

Even though your XML is valid, the > in the attribute value can lead to confusion. Even the XML Syntax parser here on Stack Exchange is failing to parse that part right....
Naming
XML is by nature relatively verbose. You are already 'paying' for that, so you may as well use it to your advantage. con should be condition, ins should be ..... instruction ? What is gurd ?
Additionally, you should be consistent in cases. InOut should be inputoutput or something. Mixing cases for XML tag names is a problem. I recommend making it all lowercase. I would actually call it 'interface', and have 'input' and 'output' as child elements.
Functional
When you use XML, you need a parser. There is always a balance between what you parse, and what you let the parser parse. The 'text' component in the XML elements are technically called PCDATA (Parsed Character Data). The XML Parser will Parse that data looking for more XML. That's all it does. Your actual data has things like: min=a Is your application manually parsing that content as well? If it is, you should probably make your text content attribute values instead.
Additionally, the white-space in your element text is scattered all over the place. Consider:

<calc>
     a=3
     b=5
     min=a
</calc>
<con gurd="min>b"  type="if">
    <calc>
        min=b
    </calc>
</con>

In your first  elements you have space surrounding the text. In your later  there is no space.
Is the space important? If it is, you should either use attributes, or set xml:space="preserve" on your XML.
Update
FYI, I ran your XML through xmllint and it output your XML as:
<?xml version="1.0"?>
<start>
  <InOut>
    <in>  a </in>
    <in>  b </in>
    <out> min </out>
  </InOut>
  <calc>
     a=3
     b=5
     min=a
  </calc>
  <con gurd="min&gt;b" type="if">
    <calc>
      min=b
    </calc>
  </con>
  <con gurd="min&gt;b" type="else">
    <calc>
      min=a
    </calc>
  </con>
</start>

xmllint --format your.xml is a fantastic commandline tool that validates and reformats your XML to be consistent. I recommend it to anyone using XML that has access to Linux


Maximum profit earned on weighted un-directed tree

Firstly, use a PEP8 checker. It will raise a lot of issues about whitespace and also tell you to change

            if visited[k[0]-1] == False:

to either

            if visited[k[0]-1] is False:

or

            if not visited[k[0]-1]:

The DFS is far more complicated than necessary:

We don't need visited: given that we know that the graph is a tree, it suffices to track the previous vertex.
I'm used to DFS tracking vertices, not edges.
There's no reason for dfs to take profit as an argument: the profit that can be made in a rooted subtree is independent of the profit made getting there.

Rewriting with those notes in mind, we can reduce it to

    def start(self, power):
        return max(self.dfs(u, power, None) for u in range(1, self.nodes+1))

    def dfs(self, u, power, prev):
        return max((edge[2] + self.dfs(edge[0], power - edge[1], u)
                    for edge in self.graph[u]
                    if edge[0] != prev and edge[1] <= power),
                   default=0)

However, I think this is still inefficient in some cases. It's doing \$n\$ depth-first searches, for overall time \$\Theta(n^2)\$. But those searches are traversing the same vertices. I believe (although I haven't written the code to verify it) that it should be possible to do it in \$\Theta(np)\$ where \$p\$ is the starting power. The idea would be to do one DFS, but for each subtree to return a complicated structure containing the largest score available solely within that subtree, and the largest scores available from the root of that subtree for different powers (which would obviously be monotonically increasing). Then it would be necessary to combine these.

(Floyd-Warshall is cubic time, so that would be worse. Similarly, matrix-based all-pairs-shortest-path algorithms for general graphs would be worse).


Some quick suggestions:

The requests module can urlencode strings for you if you use the params keyword:

import requests

cities = ["Menlo Park, CA"]
pages = range(1, 3)
url = "https://www.facebook.com/careers/jobs/"

for city in cities:
    for page in pages:
        params = {"page": page, "results_per_page": 100, "locations[0]": city}
        response = requests.get(url, params=params)

Organize your code using functions. This allows you to give them a readable name (and even add docstrings).

def get_job_infos(response):
    """Parse the content of the request to get all job postings"""
    page_soup = BeautifulSoup(response.text, 'lxml')
    job_containers = page_soup.find_all("a", "_69jm")

    # Select all 100 jobs containers from a single page
    for container in job_containers:
        site = page_soup.find("title").text
        title = container.find("div", "_69jo").text
        location = container.find("div", "_1n-z _6hy- _21-h").text
        job_link = "https://www.facebook.com" + container.get("href")
        yield site, title, location, job_link

This is a generator over which you can iterate. Using the lxml parser is usually faster.

Note that csv can write multiple rows at once using writer.writerows, which takes any iterable of rows:

with open('facebook_job_list.csv', 'a', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(get_job_infos(response))

This way you only have to open the file once per page, instead of a hundred times. Even better would be to make the whole thing a generator, so you can write all rows while opening the file only once:

def get_all_jobs(url, cities, pages):
    for city in cities:
        for page in pages:
            params = {"page": page, "results_per_page": 100, "locations[0]": city}
            response = requests.get(url, params=params)
            # check status code

            yield from get_job_infos(response)

            # rate throttling, etc here
            ...

if __name__ == "__main__":
    cities = ["Menlo Park, CA", ...]
    pages = range(1, 3)
    url = "https://www.facebook.com/careers/jobs/"

    with open('facebook_job_list.csv', "w") as f:
        writer = csv.writer(f)
        writer.writerow(["Website", "Title", "Location", "Job URL"])
        writer.writerows(get_all_jobs(url, pages, cities))

This way the get_all_jobs generator will yield jobs as it is being iterated over, getting the next page when needed.


The problem as stated was:

  There is an sorted array. You need to find all the missing numbers. Write the complete code, without using any generics or inbuilt function or binary operators. First and last terms will be given. Array will be sorted. Array always starts with zero.

When I ask questions like this in interviews, one of the things that I'm looking for is can the candidate read a specification and make good decisions on implementing it?  The spec says what the inputs are and what the outputs are, so I would expect that somewhere in the code there would be a method with signature

int[] findMissingElements(int[] elements, int first, int last)

Note that the method is not void. This idea that a method prints out its result is found only in interviews and college assignments; it is nowhere found in industry.

I would also like to see some verification of the method preconditions given.  If the method is private then an assertion is appropriate. I'd also like to see the candidate take initiative to add some more preconditions that I did not give. I often give underspecified problems to see how the candidate deals with ambiguity: by asking clarifying questions, or by ignoring the problem and hoping for the best. In this case it is not stated that first is less than or equal to last but it seems reasonable to assume that.

int[] findMissingElements(int[] elements, int first, int last)
{
    assert(elements.Count > 0);
    assert(isSorted(elements));
    assert(elements[0] == 0);
    assert(first <= last);

If the method is public then these should be if(!precondition) throw ...


begin() vs rbegin(): how can I avoid duplication?

I would re-write the display to take iterators.

template<typename I>
void display(I begin, I end)
{
    std::for_each(begin, end, [](const Widget* x) {
         std::cout << x->id << std::endl;
    });
}

Then you can pass any container that contains Widget pointers to the method. Also solves the problem about ordering. You pass the appropriate iterators for the task.

But my main problem. Is why are you storing pointers in a container?
Who owns the pointers? If it is the container then you are doing it wrong as the destructor will not clean up (nor will replacing elements do the correct thing). For this you should use boost::ptr_set (in <boost/ptr_container/ptr_set_adapter.hpp>) or std::set<std::unique_ptr<Widget>> if the container is not taking ownership then it should hold references to the object std::set<std::ref<Widget>> there are other alternatives but it depends intirely on the semantics you intend to achieve.

But pointers in containers is a no-no (in general). Better have a darn good reason.


Simulate a pool using multithreading in Python

Naming

type is a built-in function in Python and therefore a name to avoid. Also, the widely followed Style Guide for Python Code aka PEP 8 recommends to use lower_case_with_underscores for variable names. CamelCase or more specifically TitleCase is usually "reserved" for class names.

Duplicate code

The behaviour function has an enormous amount of duplicated code. The code code for each of the if branches is basically the same, the only variable parts are the thresholds on which those branches are triggered and the amount of water that is either drained or added. Also the type parameter of behavior is redundant, since self already knows its type. Another thing that might need a closer look is the way you use the look. My threading is a bit rusty, but if I understood your code correctly, there is a separate lock for each instance of Pipe. As a consequence, there is no real synchronization between the threads and the happily check and modify Pipe.waterVolume as they go. But maybe I'm wrong here. Under the assumption that I'm right, let's look at a refactored version of your code:

class Pipe:
    water_volume = 0
    _lock = threading.Lock()

    def __init__(self, type_, flow, activation_condition):
        self.pipe_type = type_
        self._flow = flow
        self._activation_condition = activation_condition

    @classmethod
    def pipe1(cls):
        """A pipe of type 1 adding 100l when the volume is below 700"""
        return Pipe(1, 100, lambda volume: volume < 700)

    @classmethod
    def pipe2(cls):
        """A pipe of type 2 adding 80l when the volume is below 700"""
        return Pipe(2, 80, lambda volume: volume < 700)

    @classmethod
    def pipe3(cls):
        """A pipe of type 3 draining 110l when the volume is above 600"""
        return Pipe(3, -110, lambda volume: volume > 600)

    def behaviour(self):
        while True:
            with Pipe._lock:
                if self._activation_condition(Pipe.water_volume):
                    Pipe.water_volume += self._flow
                    action = "added" if self._flow > 0 else "drained"
                    print(f"Pipe {self.pipe_type+1} {action} {abs(self._flow)} liters")
                    print(f"Volume is: {Pipe.water_volume}")
            time.sleep(1.5)

A lot has changed here, so lets go through step-by-step.

I changed the naming to follow the PEP8 recommendation linked above.
The lock is now shared between all instances of the class (and their associated threads) the same way the water volume is.
The code duplication is gone.

To reach that goal, the Pipe class was made more general in that it now accepts a flow rate (positive or negative) and a condition under which this pipe is active. To have to same "preconfigured" pipes as before, I added three classmethods which act as a simple factory. Each factory method also got a short description what to expect from the returned pipe.
behaviour (in lack of a better idea for a name) is now quite a bit shorter since it's basically the same code for all instances which add live to add via their properties. The lock is now also acquired before checking on the current volume. From a coding standpoint that absolutely makes sense, it's however up for discussion if a real system could/would be setup with this level of synchronization. The console output is now also generically built from what is known about the pipe object currently in action. I used f-strings (available from Python 3.6+) to format the output contrary to the "old-style" % formatting. Maybe have a look at this blog post to learn more about the different kinds of string formatting available to Python programmers.

Make it stop

I don't know if you have ever heard of the poem "Der Zauberlehrling" (The Sorcerer's Apprentice) by the German writer Johann Wolfgang von Goethe. In the poem, a young sorcerer summons a broom to help him carry water in order to clean his masters house. When he is done with the task, he tries to stop the broom from carrying more and more water into the house but fails to do so. From there on the events quickly spiral out of control until his master returns and finally takes control over the broom again.

Sounds vaguely familiar? Well, that's because once one has started your program, not even Ctrl+C will stop it (at least under Windows). This answer on SO could be used as a starting point to make that work.

A few closing words on threading in Python, especially in the most widely used reference implementation CPython. CPython has something called the global interpreter lock or GIL for short. The GIL takes care that at any time there is only a single thread executing Python code. That has significant impact on what you can expect to see when changing your pure Python code to multi-threading. Positive gains are mainly found when you have blocking IO operations or something like calls to a web API where the underlying code actively releases the GIL in order to allow other threads to do their work. Apart from that, the Python interpreter will also stop threads from time to time in order to allow over threads to run. When this happens depends on which Python version you are using (Python 2 vs. Python 3).

Since this is a topic that can quite involved, let me give you another link to a blog post on realpython and to a question/answer on Stack Overflow to read more about that topic.


Angular2 Toggling showing and hiding between two elements

Separate content and logic

It is a good practice (recommended by Angular style guidelines) to separate component template and component code.

Move template to an own my-app.component.html file and refer to it via templateUrl property instead of template.

Avoid logic in your template

oneShowing=true,twoShowing=false in and twoShowing=true,oneShowing=false parts are technically logic.
It does need to be in the template, and it should not be there.

my-app.component.html

<button type="button" (click)="displayBoxWithNumber(1)">1</button>
<button type="button" (click)="displayBoxWithNumber(2)">2</button>

my-app.component.ts

displayBoxWithNumber(boxToShow: number): void {
  this.hideAllBoxes();
  this.displayBox(boxToShow);
}
private hideAllBoxes(): void {
  this.oneShowing = false;
  this.twoShowing = false;
}
private displayBox(boxToShow: number): void {
  if (boxToShow === 1)
    this.oneShowing = true;
  else if (boxToShow === 2)
    this.twoShowing = true;
  else
    throw new Error(`Invalid box number provided ${boxToShow}`);
}

Please notice that the code above is for illustrational purposes in your specific context.
Any more or less real project will use *ngFor directive to iterate over some data source to construct the boxes dynamically.
Something like the code below.
Do not worry if you don't understand it yet.
You'll get there later with a bit of practice.

<div *ngFor="let box of boxeList; boxIndex = index; trackBy: trackByBoxId">
  <button type="button" (click)="displayBox(box, boxIndex)"> {{ box.number }} </button>
  <div class="box" *ngIf="isBoxActive(box)">
    <simple-box-view [value]="box"></simple-box-view>
  </div>
</div>

Know your tool/language

In typeScript you can initialize class' properties inline (this is the same as setting the values in constructor).
You can also omit the type of the variable it is inferred.
Similarly, if your constructor does not do any work, it can be got rid of.

export class App {
  name: string;
  oneShowing = true;
  twoShowing = false;

  // Methods...
}


Finds a pattern in a string by returning index of where the pattern starts in the string in Java

Naming

findFirstSubstringOccurrence is quite a long name. substringIndex is shorter and still very explicit about what it does.

Your parameters are not named very well. When calling your method, how do you know which of the strings is the substring and which one the containing string? I suggest the method header int substringIndex(string containing, string candidate).

Style

Your use of white space is very unconventional. Usually you would have spaces around operators for example.

Using braces around one liners makes your code prettier and more readible, and also prevents bugs when you add a line without noticing the missing braces. Instead of this:

if(s.charAt(i+j)!=s.charAt(i))
    i += j;

write this:

if (s.charAt(i + j) != s.charAt(i)) {
    i += j;
}

Your initialization of j is redundant, since you assign 0 at the start of the loop anyway. So just declare it before the loop, then assign it in the loop.

Performance

Expecting the likely case that your string does not contain the substring candidate and returning early can improve your performance in many cases, so check before looping whether the candidate is longer than the containing string.

After finding the first occurence of the first letter of the candidate in the containing string, the next improvement would be to check whether the last letter of the candidate is at position firstLetterPosition + candidateLength - 1. That allows you to quickly find situations, where only a part of the substring is contained. Then you can check the middle part.


If you come from C and you start using C++, you might be use to have pointers whenever you want a function to be able to update one of its parameter.
In C++, if you want to do so, you can use references which gives you a clearer and slightly safer result. Please refer to the wiki page for more details.

However, I'd like to point out that whenever you compute the lowest common multiple of the two integers, you probably don't want to change the value of this integers.

Thus, I'd expect the following code to do what you are trying to achieve (not tested, not even compiled):

#include <iostream>

using namespace std;

int euclideanAlgorithm(int a, int b);

int main() {
    int a, b;
    cin >> a;
    cin >> b;
    cout << a / euclideanAlgorithm(a, b) * b << endl;
    return 0;
}

int euclideanAlgorithm (int a, int b) {
    return (b == 0) ?
        a :
        euclideanAlgorithm(b, a % b);
}

Then, regarding the style : you can avoid forward declaration by changing the order of the functions. Also, it would probably be better to call you function with a shorter but still more explicit name such as gcd (hiding the implementation details : whether you use Euclid's algorithm or Wk_of_Angmar's algorithm shouldn't make any big difference for the one who is using the function).


Detect resolution of X display and change font accordingly

You wrote calls to setq-default twice, with blah-blah-size-34-or-18. Call it just once, with a :size of an if expression that evaluates to 34 or 18.

Put another way, your "then / else" clauses are evaluated for side effects. I'm suggesting to exploit the functional aspect of if, where its return value comes either from the "then" clause or from the "else" clause.


Your method is currently doing three things at a time and repeating the same logic multiple times:

parsing logs-1 (parsing a line)
parsing logs-2 (parsing a line again with the exact same code)
comparing both logs

It would be much easier to optimize and use it if you refactored it into  specialized structures/methods.

You put the first two cases into the static factory method Parse. It'll encapsulate the parsing part so you have implemented it only once.

Then you need to encapsulate the equality. You do this by implementing the IEquatable<LogLine> interface. You should do this very carefuly because both the Equals and GetHashCode methods are important for the performance.

This new class can now be very easily tested for: equality, parsing and performance.

public class LogLine : IEquatable<LogLine>
{
    public string Errorcode { get; set; }

    public string[] Data { get; set; }

    // add other properties...

    public static LogLine Parse(string log, IEnumerable<int> ignoreColumns)
    {
        // implement parsing
    }

    public bool Equals(LogLine other)
    {
        // implement log equality
    }

    public override bool Equals(object obj)
    {
        return base.Equals(obj as LogLine);
    }

    public override int GetHashCode()
    {
        // implement log hash-code
    }
}

And that's it because you now have a very LINQ-friendly class that you can use like this where you can parse all lines with a simple Select:

// dummies
var logs1 = Enumerable.Empty<string>();
var logs2 = Enumerable.Empty<string>();
var ignoreColumns = Enumerable.Empty<int>();

var logLines1 = logs1.Select(l => LogLine.Parse(l, ignoreColumns));
var logLines2 = logs2.Select(l => LogLine.Parse(l, ignoreColumns));

And you can compare them however you like with Except or Intersect or use GroupBy or Distinct or whatever you want. If you use more then a single extension should call .ToList() after each parsing so that you don't parse them multiple times.


Most popular element with count in Array with Java

(Useful: What is the difference between O, Ω, and Θ?)

  How do I calculate time complexity and what is it in this case?

Algorithmic time complexity, as we commonly understand it, is a measure of how an algorithm scales in terms of its input. We're usually interested in asymptotic complexity, meaning we want to see how it performs in the generalized, large-scale cases. It is the answer to the question: "What if we make it bigger?"

How you calculate is fairly straightforward: you figure out the number of steps your algorithm needs compared to your input size, and you crib out the scalars:

Θ(4n² + 25n + 842) = Θ(n²) ; Θ(28n * 6 log (18n)) = Θ(n log n)

... with the understanding that, as n approaches very large numbers, all scalars become insignificant. (This isn't entirely accurate, but it's good enough for envelope-and-fingers calculations.)

Here is a line-per-line of your code:

// annotated with time complexity, with n = inputList.size()
public static RepeatedEntry findMostPopularItem(List<Integer> inputList) {
L1: Collections.sort(inputList); // Θ(n log n) hopefully
L2: Set<RepeatedEntry> resultSet = new TreeSet<>(); // Θ(1)
L3: for (int i = 0; i < inputList.size(); i++) { // Θ(n)
L4:     int thisEle = inputList.get(i); // Θ(1)
L5:     int lastIndexOfThisEle = inputList.lastIndexOf(thisEle); // Θ(n)
L6:     int repeatedCount = (lastIndexOfThisEle - i) + 1; // Θ(1)
L7:     if (repeatedCount != 1) { // Θ(1)
L8:         RepeatedEntry repeatedEntry = new RepeatedEntry(); // Θ(1)
L9:         repeatedEntry.setNumber(thisEle); // Θ(1)
L10:        repeatedEntry.setCount(repeatedCount); // Θ(1)
L11:        resultSet.add(repeatedEntry); // Θ(log n)
L12:    }
L13:}
L14:return resultSet.iterator().next(); // Θ(log n)
}

L3 * L5 gives you an algorithmic time complexity approached by Θ(n²) (consider the case where no numbers are repeated).

If the input is already sorted, you can find the top in a Θ(n) fashion:

E maxItem = null;
int maxLength = 0;

int start, end;
for ( start = 0, end = 1; end < inputList.size(); end++ ) { // Θ(n)
  if ( !inputList.get(end).equals(inputList.get(start)) ) { // Θ(1)
    if ( end - start > maxLength ) { // Θ(1)
      maxItem = inputList.get(start); // Θ(1)
      maxLength = end - start; // Θ(1)
    }
    start = end; // Θ(1)
  }
}
// case: maxItem is top/last element
if ( end - start > maxLength ) { // Θ(1)
  maxItem = inputList.get(start); // Θ(1)
  maxLength = end - start; // Θ(1)
}
return new RepeatedEntry(maxItem, maxLength); // Θ(1)

... but sorting itself is a Θ(n log n) operation in the ideal case.

  I thought of storing the result in HashMap but avoided as it needs further processing to fetch the output, any answer using HashMap improving complexity would help me learn too and best possible solutions as well.

Map<E, Integer> frequency = new HashMap<>();
E maxItem = null;
int maxLength = 0;

for ( E item : inputList ) { // Θ(n)
  int count = frequency.merge(item, 1, Integer::sum); // Θ(1) [!]
  if ( count > maxLength ) { // Θ(1)
    maxItem = item; // Θ(1)
    maxLength = count; // Θ(1)
  }
}
return new RepeatedEntry(maxItem, maxLength); // Θ(1)

The exclamation mark at Map.merge is because, while HashMap provides access in asymptotically constant time, the actual constant time may be significant, and it depends on practical factors like load factor, bucket sizes, and hash spread.


Intended to return account address using account ID, which uses Spring Stored Procedure class

As @Pimgd mentioned in his answer: You are setting defaults just to overwrite them. this sounds like you are not certain what is going to happen in your code and you want to 'make sure'. It's better to read your code over a few times and make sure you know what will happen, rather than set values you won't need. To another developer it will sound like there is a situation where you will need the results map you assigned.

Don't declare parameters (with defaults) if you don't use them outside of the scope you need them in. when a method grows, the distance between the parameter (at top of try) and the place it gets used grows, making it more likely that it will get reused (bad) or that it gets left behind because developers don't notice it isn't used anymore.
Use the exception, not just to report an error. either return null or return an empty List, whichever you want. (or if you dislike return statements in a catch, set the data field to null/empty list)
If you are going to return the dataset without mutation, why not return it straight away?

I would suggest:

public List<String> getAccountAddress(String accountId) {
    try{
        Map<String,Object> params.put("accountId",accountId);
        Map<String,Object> results = execute(params);
        return (List<String>) results.get(0);
    } catch (DataAccessException e) {
        // log errors
        return new LinkedList<String>();
    }
}


Your code should make use of using statements instead of the finally statement of the try/catch.

It will allow you to get rid of those ugly private variables in exchange for fun scope specific variables in the using statements. And no matter what the connections are all closed.  I think that you are leaving open the OldDbCommand which might be holding onto the OleDbConnection or at the very least just holding the whole command in memory, but when it runs again it creates an entirely new command.

private OleDbConnection mycon;
private OleDbCommand oleDbCmd;
private OleDbDataReader dataReader;

//This method looks for the Alerts in the Data Base and displays the info in a User Control
private void ShowData()
{
    try
    {

        mycon.Open();

        string queriesLabels = "SELECT *FROM MP where State = @stateAccepted OR State = @stateRejected";

        oleDbCmd = new OleDbCommand(queriesLabels, mycon);
        oleDbCmd.Parameters.Add("@stateAccepted", OleDbType.VarChar, 10).Value = "Accepted";
        oleDbCmd.Parameters.Add("@stateRejected", OleDbType.VarChar, 10).Value = "Rejected";

        dataReader = oleDbCmd.ExecuteReader();
            while (dataReader.Read())
            {

                tabPage page = new tabPage("MP "
                             + (DTL.TabPages.Count + 1).ToString());
                UserControls.userControlAlert aForm = new UserControls.userControlAlert();
                aForm.Parent = page;
                aForm.showReaderRow(dataReader);
                DTL.TabPages.Add(page);
                theDataPages.Add(aForm);
            }
    }
    catch (Exception error)
    {
        MessageBox.Show(error.ToString());
    }
    finally
    {
        dataReader.Close();
        mycon.Close();
    }
}

Here is what I would do:

private void ShowData()
{
    try
    {
        using (OleDbConnection mycon = new OleDbConnection("connectionString")
        {
            mycon.Open();
            string queriesLabels = "SELECT *FROM MP where State = @stateAccepted OR State = @stateRejected";

            using (OleDbCommand oleDbCmd = new OleDbCommand(queriesLabels, mycon))
            using (oleDbDataReader dataReader = oleDbCmd.ExecuteReader())
            {
                oleDbCmd.Parameters.Add("@stateAccepted", OleDbType.VarChar, 10).Value = "Accepted";
                oleDbCmd.Parameters.Add("@stateRejected", OleDbType.VarChar, 10).Value = "Rejected";

                while (dataReader.Read())
                {
                    tabPage page = new tabPage("MP "
                                + (DTL.TabPages.Count + 1).ToString());
                    UserControls.userControlAlert aForm = new UserControls.userControlAlert();
                    aForm.Parent = page;
                    aForm.showReaderRow(dataReader);
                    DTL.TabPages.Add(page);
                    theDataPages.Add(aForm);
                }
            }
        }
    }
    catch (Exception error)
    {
        MessageBox.Show(error.ToString());
    }
}

Your OleDbCommand makes use of the IDisposable interface, so use it and make sure that it doesn't leak.


Quicksort in JavaScript, using nested functions

Nesting functions
There is nothing wrong with your approch, a few years back and I would have not said so as some browsers would parse functions within functions each time they were call, with the obvious performance hit. That is a thing of the past and functions are parsed then cached for use next time the function is called.
Modules to keep global scope clean.
Modern JS has modules that let you define exports and then import them as needed in other modules
Each module has its own top level context and thus does not add to the global scope.
Use the export token to define what can be imported.
The only way to access items in the module is via the import token, and only those items explicitly exported.
Modules also use strict mode by default.
Thus you can flatten you code without worrying about name conflicts.
If you create a default export in a module you can also import it under another name.
Example of a module, and flatting your quick sort.
/* in file quickSort.js */
export default function sort(array) {
    quickSort(array, 0, array.length - 1);
}

function quickSort(array, start, end) {
    if (start < end) {
        let pivot = partition(array, start, end);
        quickSort(array, start, pivot - 1);
        quickSort(array, pivot + 1, end);
    }
}

function partition(array, left, right) {
    let pivot = array[right];
    let i = left - 1;
    for (var j = left; j < right; j++) {
        if (array[j] <= pivot) {
            i++;
            let temp = array[j];
            array[j] = array[i];
            array[i] = temp;
        }
    }
    let temp = array[i + 1];
    array[i + 1] = array[right];
    array[right] = temp;
    return i + 1;
}

To access it from another module
import sort from "quickSort";
sort([4,3,6,3,7,8]);

Or use another name, but only for the default export.
import qSort from "quickSort";
qSort([4,3,6,3,7,8]);

Note that modules must be in files for both export code and import code, and the script element must be of type "module" eg <script type="module" src="quickSort.js"></script>
Also as a convention not a requirement modules have the extension .mjs rather than .js and some will use .es.mjs. They all have the same MIME type text/javascript
Singleton
Before modules it was common to use the singleton (AKA immediately invoked function) to reduce or completely eliminate any intrusion to the global scope.
Example of a singleton
const sort = (() => {
    function sort(array) {
        quickSort(array, 0, array.length - 1);
    }

    function quickSort(array, start, end) {
        if (start < end) {
            let pivot = partition(array, start, end);
            quickSort(array, start, pivot - 1);
            quickSort(array, pivot + 1, end);
        }
    }

    function partition(array, left, right) {
        let pivot = array[right];
        let i = left - 1;
        for (var j = left; j < right; j++) {
            if (array[j] <= pivot) {
                i++;
                let temp = array[j];
                array[j] = array[i];
                array[i] = temp;
            }
        }
        let temp = array[i + 1];
        array[i + 1] = array[right];
        array[right] = temp;
        return i + 1;
    }

    return sort;
})();

sort([4,3,6,3,7,8]);


Can this simple percentage calculator be further optimized?

Since floating-point divide is sometimes a little slower than multiply (and never faster, AFAIK), I'd write your function like this:

public double getValueWithPercentage(double number, double percentage)
{
    return number * (1 + percentage * 0.01);
}


I'd say your solution is pretty good! Since you probably won't re-use your leibniz-numerator function, you might want to make it private by declaring it with defn-, or you could declare it within the body of your main function using let or letfn.

Also, you might notice that your function actually computes pi with half the number of terms given has parameters (might not be of importance).

I can share some alternatives I came up with.

We could start by generating the sequence (4 -4 4 -4...). To do that, we can use the method iterate:

(take 4 (iterate - 4))
;;=> (4 -4 4 -4)

Then we want the sequence (1 3 5 7). You already found method rangefor that:

(take 4 (range 1 10 2))
;;=> (1 3 5 7)

If you divide those to element wise, you will get (4 -4/3 4/5 -4/7...). You can do that with map

(take 4 (map / (iterate - 4) (range 1 10 2)))
;;=> (4 -4/3 4/5 -4/7)

In our final computation, this can get really slow because we're using decimals. Let's use floats instead, and put everything together:

(defn calc-pi-leibniz [terms]
  (reduce + (map / (iterate - 4.0) (range 1.0 terms 2.0))))

But for some reason, this is 5 times slower than your solution. If someone could tell me why, I'd be grateful. I suspect that is because map has to go through two lists instead of one, but since they are both lazy this should not matter?

For a faster solution (but less elegant), we can see that there are two subsequences in the leibniz formula. One that is (4 4/5 4/9) and one that is (-4/3 -4/7 -4/11). With that in mind, you can get the following:

(defn calc-pi-leibniz [terms]
  (* 4 (- (reduce + (map / (range 1.0 terms 4.0)))
          (reduce + (map / (range 3.0 terms 4.0))))))

Which runs as fast as your solution.


Find all local maxima in a one-dimensional array

This shouldn't involve an instance of a class: you can (and should) implement this as a standalone static method, which takes the input array as a parameter and returns the peaks. Introducing a class to record the state is just introducing complexity which will make the code harder to maintain without providing any benefit.

I would also like some documentation explaining exactly what the method does: for example, it doesn't return non-positive peaks, and (as Toby Speight's comment indicates) some might thing it would return plateaus. Basically you need a better specification, and that needs to appear as documentation, so that the intention of the code is completely unambiguous (for the benefit of the implementer, maintainer, and consumer). I would not expect a method like this to return the heights of peaks, rather than their position.

IGNORE_FIRST_POSITION sounds like the name of a boolean, not an int. You'd be better off, I think, changing the for loop to start at 1, end at array.Length - 1, and include a comment explaining why this is the case.

I like that CheckPeak is its own method because it puts the corresponding logic 'all in one place', but I don't like that you are creating a new array every time you check for a peak: I would much prefer you pass the array and candidate position as parameters, and it checks 'in-place'. This is a simpler API (the current one lacks any specification that it takes an array of three parameters), and will reduce the overhead from calling the method.

I also don't like that it returns the height of the peak, rather than whether or not a peak appears: this too is lacking documentation (though granted it is private, so it isn't as important as the public method). Much better to return true or false if it is a peak, then add the peak to the list of peaks if it returns true, otherwise do not (then you can remote the confusing filterZeros at the end).

This can also remove the unpleased output variable, which is defined too early. It only has meaning once it is assigned, and if it isn't assigned it just has a default value you will filter anyway, so you might as well declare and assign it in one.

Really tiny thing that is almost completely subjective: I'd prefer to write

if (inputArray[1] > inputArray[0] && inputArray[1] > inputArray[2])

as

if (inputArray[0] < inputArray[1] && inputArray[1] > inputArray[2])

It keeps them 'in order, and makes it a little easier to feel what is going on.

Your code only works with Integers: if I wanted to find peaks in a Double[], I would need to write a new class. You might want to make it generic on a type T that implements Comparable<T>. This can create some confusion with floating point types (i.e. NaNs), but by depending on a basic interface, your code will be reusable and harder to 'get wrong'.

You might also consider taking an abstract collection as a parameter; it's good that you return List<T> rathern than ArrayList<T>.

Example rewrite (disclaimer: untested, and I don't know Java, and I'm running out of time...):

public class ArrayPeak
{
    public static <T extends Comparable<T>> List<T> findPeaks(T[] array)
    {
        List<T> peaks = new ArrayList<>();

        // ignore first and last elements
        for (int position = 1; position < array.length - 1; position++)
        {
            if (checkPeak(array, position)
            {
                peaks.add(array[position]);
            }
        }

        return peaks;
    }

    private static <T extends Comparable<T>> int checkPeak(T[] array, int position)
    {
        if (inputArray[position - 1].compareTo(inputArray[position]) < 0 && inputArray[position].compareTo(inputArray[position + 1]) > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


Displaying model statistics (as a sentence) in a view

I'd add a counter cache to Author, i.e. quote_count just to avoid doing the extra query to fetch the number of quotes.

Don't put view concerns (the sentence, in this case) in a model; use I18n/localization instead, especially since you're dealing with pluralization (and right now you're taking the lazy route of saying author(s) and assuming quotes, plural).

Even if there's only English, the I18n stuff can do some tricks, for instance (in config/locales/en.yml or similar):

en:
  users:
    show:
      your_authors:
        one: "Your author"
        other: "Your authors"
      author_quotes:
        one: "%{name} has %{count} quote"
        other: "%{name} has %{count} quotes"

With that your view can be something like:

<%= t(".your_authors", count: @authors.count) %>
<%= @authors.map { |author| t(".author_quotes", name: author.name, count: author.quotes.size }.to_sentence %>

And #author_statistics can be removed entirely.


try this:

Create function dbo.SplitString(@inputStr varchar(1000),@del varchar(5))
RETURNS @table TABLE(col varchar(100))
As
BEGIN

DECLARE @t table(col1 varchar(100))
INSERT INTO @t
select @inputStr

if CHARINDEX(@del,@inputStr,1) > 0
BEGIN
    ;WITH CTE1 as (
    select ltrim(rtrim(LEFT(col1,CHARINDEX(@del,col1,1)-1))) as col,RIGHT(col1,LEN(col1)-CHARINDEX(@del,col1,1)) as rem from @t
    union all
    select ltrim(rtrim(LEFT(rem,CHARINDEX(@del,rem,1)-1))) as col,RIGHT(rem,LEN(rem)-CHARINDEX(@del,rem,1))
    from CTE1 c
    where CHARINDEX(@del,rem,1)>0
    )

        INSERT INTO @table
        select col from CTE1
        union all
        select rem from CTE1 where CHARINDEX(@del,rem,1)=0
    END
ELSE
BEGIN
    INSERT INTO @table
    select col1 from @t
END

RETURN

END


Find combinations of items in a nested collection

I'm going to admit right off the bat that I don't fully understand what this algorithm is supposed to do. I can make suggestions for extrusion though.

Note how in extrusion you're explicitly calling first and rest on xs once per iteration, then processing the head, and recursing on the tail. The more idiomatic way to split the head from the tail would be to use deconstruction. This also lets you get rid of the call to empty?:

(defn extrusion2 [input]
  (loop [result [[]]
         [x & xs] input] ; Split the "head" from the "tail"

    (if x ; x will be nil when the collection is empty
      (recur (smash result x) xs)
      result)))

I wouldn't use loop here at all though (even though I love loop). You're just iterating over a collection while maintaining an accumulator. This is a textbook case for reduce:

(defn extrusion3 [input]
  (reduce (fn [result x]
            (smash result x))
          [[]]
          input))

Since you conveniently gave smash the same argument order as the required reducing function though, this can be simplified to:

(defn extrusion4 [input]
  (reduce smash [[]] input))

If you really wanted to ridiculous, since input is the last argument to reduce, you can just make the function a partial application of reduce:

(def extrusion5
  (partial reduce smash [[]]))


Would be possible to refactor this PHP code more?

Ah, the yoda syntax, don't see that too often. Anyways, on to the subject at hand. Here are a few ways you can refactor it, I'll address your specific question towards the end.

You can use the empty() function in your first comparison, it will return TRUE if the value is any FALSE value ('', 0, NULL, FALSE, "false", etc...), so it does the same thing but is a little cleaner.

if( empty( $value ) ) {
    return;
}

Another possible refactor, is to not use typecasting unless necessary. For instance, below you have a string typecast that is converting the element of an array to a string. This is unnecessary, at least if I'm reading the doc page on preg_match() properly. The 0th element will already contain a string, so this is redundant. Below that is another typecast that converts a string to an integer. This also seems unnecessary. PHP is a very loosely typed language, meaning transitioning from a integer to a string, or vice-versa, doesn't require any special type-casting or syntax. BTW: below each example is also another way to refactor the statement that may be a little better.

$vatin = (string) $matches[0];
$vatin = $matches[ 0 ];//the same
$vatin = array_shift( $matches );//avoids magic numbers, even though most will know where the 0 comes from

$dgt  = (int) substr($vatin, $i, 1);
$dgt = substr( $vatin, $i, 1 );//the same
$dgt = $vatin[ $i ];//string array syntax avoids the unnecessary function call

Avoid calling functions in for or while loop parameter lists. Both of these loops call any parameter functions on every iteration, meaning more overhead. Set the value before the loop. I'd also suggest doing the same in foreach loops, but its not as important.

$length = strlen($vatin);
for( $i = 0; $i < $length; $i++ ) {

Another problem you have here is that you are violating "Don't Repeat Yourself" (DRY) by using the same, or almost the same values in the addViolation() method so many times. A better way would be to set up a default, then log it once. There are probably a few different ways to go about this, but here's an example of one.

//in class
$violation = array(
    $constrain->message,
    $value
);

if( ! preg_match() ) {
    return $violation;
}
//repeat or return different violation as necessary

//implementation
$violation = $instance->validate( $value, $constraint );
if( is_array( $violation ) ) {
    list( $message, $value ) = $violation;

    $instance->context->addViolation( $message, array(
        '{{ value }}' => $value
    ) );
}

Now, the question you are asking about is more or less a style choice. The one-return vs many. At least if I am understanding your question correctly. I used to be of the first camp, but I think I'm leaning a little more towards the other now. Sometimes it makes sense to use a single return, but its a matter of context. For instance, if I found what I was looking for in the middle of a loop, its better to return from the loop early rather than finish it and then test a few other things. Your code can quite easily get skewed or convoluted or redundant when trying to maintain a single return.

So, while it may seem undesirable, your code is actually benefiting from these multiple return statement. I wouldn't try refactoring them out, but if you absolutely must, you can modify the $violation array I showed you above so that the value is only set if an error occured, then, at the end of your function, if it has been set you can return the array.

The only other solution I can think of, and perhaps a better one, would be to not use returns at all, but to throw errors instead. That appears to be very close to what you are doing anyways, so you might want to seriously contemplate this switch.


Detect that a class is marked by a custom annotation in Spring

I'm not that familiar with Spring, but if your goal is to get all types annotated with FooBar and then the enabled attribute, you may just use the Reflections library.
When your application is bootstrapping you would:

Reflections reflections = new Reflections("my.project");

And in your listener:

@EventListener
void contextRefreshedEvent(ContextRefreshedEvent event) throws NoSuchFieldException, IllegalAccessException {
    Set<Class<?>> classes = reflections.getTypesAnnotatedWith(FooBar.class);
    for (Class clazz : classes) {
        boolean enabled = clazz.getAnnotation(FooBar.class).enabled();
        System.out.println("Enabled: " + enabled);
    }
}

Notice that you don't need to get all annotations in the class, check types and then cast if you use getAnnotation. The advantage of using Reflections is that class metadata is indexed, which means the expensive reflection operations aren't done all the time. It won't work, however, if Spring changes annotations on runtime (which I don't know if it does or not). If you can't use the Reflections library, just the getAnnotation method is already an improvement over your original for over each annotation.


Validating a list of dictionaries of names and tags

There're some modules that might help you get rid of the structure you're complaining about like marshmallow or voluptous and since you didn't added the reinventing-the wheel tag I guess that's perfectly okay.

For the sake of example, I'll refer to the former one because IMO it better fits our purpose (and is also probably clearer).

From the docs:

  Marshmallow is an ORM/ODM/framework-agnostic library for converting
  complex datatypes, such as objects, to and from native Python
  datatypes.

  In short, marshmallow schemas can be used to:

  Validate input data.
  Deserialize input data to app-level objects.
  Serialize app-level objects to primitive Python types. The serialized objects can then be rendered to standard formats such as
  JSON for use in an HTTP API.

First of, you'll need to define your Schema:

class DataSchema(Schema):
    name = fields.String(required=True)
    tags = fields.List(fields.String(), required=True)

In the above, name and tags are the keys of our dictionaries. In our class I've specified each key type (str and list). They're also mandatory, so I added required=True.

Next, to validate our top-level list, we need to instantiate our list item schema with many=True argument and then just load the data we need:

data, errors = DataSchema(many=True).load([
    {'name': 'Frank', 'tags': ['dog', 'cat']},
    {'name': 'Manfred', 'tags': ['dog', 'chicken']}
])

Printing the above:

print(data)
print(errors)

Will have the following output:

[{'name': 'Frank', 'tags': ['dog', 'cat']}, {'name': 'Manfred', 'tags': ['dog', 'chicken']}]
{}

Now, if we try to pass an invalid data to our dict, the errors will warn us about this. For example, passing a str instead of a list in our tags key will result in:

[{'name': 'Frank'}, {'name': 'Manfred', 'tags': ['dog', 'chicken']}]
{0: {'tags': ['Not a valid list.']}}

Full code:

from marshmallow import Schema, fields

class DataSchema(Schema):
    name = fields.String(required=True)
    tags = fields.List(fields.String(), required=True)

data, errors = DataSchema(many=True).load([
    {'name': 'Frank', 'tags': ['dog', 'cat']},
    {'name': 'Manfred', 'tags': ['dog', 'chicken']}
])

Now, IDK if the above will be valid for all the test-cases (e.g it might allow you to pass an empty list), but it should give you a good overview of what you can achieve with this module.


for(int j=0;j<i;j++){
        prefix.append(s.charAt(s.length()-1-j));
    }

An easy optimization is to change this to

    for (int j = 1; j <= i; j++) {
        prefix.append(s.charAt(s.length() - j));
    }

You can go further if you like, e.g.

    for (int j = s.length() - 1, m = s.length - i; j >= m; j--) {
        prefix.append(s.charAt(j));
    }

But if you're doing that, you might as well change

public static String rotateAntiClockWise(String s, int offset){
    int i = offset%s.length();
    StringBuffer prefix = new StringBuffer();
    for(int j=0;j<i;j++){
        prefix.append(s.charAt(s.length()-1-j));
    }
    return prefix.append(s.substring(0, s.length()-i)).toString();
}

to

public static String rotateAntiClockWise(String s, int offset){
    int i = s.length() - (offset % s.length());
    StringBuffer prefix = new StringBuffer();

    for (int j = s.length() - 1; j >= i; j--) {
        prefix.append(s.charAt(j));
    }

    return prefix.append(s.substring(0, i)).toString();
}

Now we only subtract from s.length() twice.  Before we subtracted from it i + 1 times.

But I actually think that the best version is

public static String rotateAntiClockWise(String s, int offset){
    int i = s.length() - (offset % s.length());
    StringBuffer prefix = new StringBuffer(s.substring(i));

    return prefix.reverse().append(s.substring(0, i)).toString();
}

Now I can easily read this and see that we are reversing the last part of the string and appending the first part.

I'm not really feeling the rotateAntiClockWise name.  That's not really what we're doing.  We're more mirrorSuffixToPrefix or something.


Scraping titles and links from a site using python

There are a couple of things you can improve. I'll start by mentioning some PEP8 related observations:

variables / methods should be lower_cased (instead of GrabbingData you should write grabbing_data;
for readability, you should have two newlines between your methods;
use spaces around operators like =, + etc;
after each , you should put a space;
constants are usually uppercased so page_link should be PAGE_LINK and blink should be BLINK;
add docstrings to your functions;
It's good practice to split the words using _ (e.g: start_point instead of startpoint);
it's also recommended to have one newline between builtin modules and 3rd party modules.

Now, about the code

it's not necessary to create a new session in all of your functions. It's preferred to create only one session for the same website as it can give a boost of speed to your scrapper. More, the session object allows you to persist certain parameters across requests (if needed);
you only use got_already in your last function, so define it there. Or better yet, use a Set()
instead of if "author" not in title and "year" not in title you can use all()
PAGE_LINK is irrelevant and confusing. You can build your full video links using just BLINK.
last but not least, I'd use beautifulsoup for html parsing: but, here I'd like to add that The downside of using this parser is that it is much slower than the HTML parser of lxml. So if performance matters, you might want to consider using soupparser only as a fallback for certain cases.

That said, if I were you, I'd have built the scrapper like this:
from requests import Session
from bs4 import BeautifulSoup as bs

def get_html_source(_session, url, min_pag, max_pag):
    """Yield the source html for each set of videos"""

    for i in range(min_pag, max_pag):
        html_source = _session.get('{}/default-{}.htm'.format(url, i)).text
        yield bs(html_source, 'html.parser')

def parse_html(soup, url):
    """
    Process the html and get all the titles and the
    video urls that match the condition
    """
    for a in soup.find_all('p', attrs={'class', 'woVideoListDefaultSeriesTitle'}):
        video_title = a.find('a').text
        video_url = a.find('a', href=True)['href']

        if "author" not in video_title and "year" not in video_title:
            print('Title: {} | Url: {}{}'.format(video_title, url, video_url))

def main():
    _session = Session()
    url = 'http://www.wiseowl.co.uk/videos'

    for soup in get_html_source(_session, url, 1, 14):
        parse_html(soup, url)

if __name__ == '__main__':
    main()

Things that I did differently:
Intro
If you were paying attention, the website adds \url\video\default-N.htm at the end of the url depending on the set of pages you click in the bottom of the page. There's a total of 13 urls.
Coding around
In my first function, I've created a function which will go through each page and will yield the source html for each one.
In the second function, I've just used BeautifulSoup to get the title and the urls of the videos that you're interested in. I've also cut off A LOT of the logic you had because it wasn't needed anymore. I've also printed the data a bit different than you did. You should know that printing huge amounts of data has a big impact on performance. I'd recommend logging into a file.
The third function is the one that will be called in our safeguard if __name__ == '__main__'


- (NSString *)stringForResultEventDescriptor:(NSAppleEventDescriptor *)resultEventDescriptor
{
    NSString *result = nil;

    if (resultEventDescriptor) {
        if ([resultEventDescriptor descriptorType] != kAENullEvent) {
            if ([resultEventDescriptor descriptorType] == kTXNUnicodeTextData) {
                result = [resultEventDescriptor stringValue];
            }
        }
    }
    return result;
}

This method can be rewritten far more simply:

- (NSString *)stringForResultEventDescriptor:(NSAppleEventDescriptor *)resultEventDescriptor {
    return (resultEventDescriptor.descriptorType == kTXNUnicodeTextData) ? resultEventDescriptor.stringValue : nil;
}

- (void)collect{
    [self runWithEvent];
}

This method seems entirely unnecessary.  Why doesn't the timer just call runWithEvent directly?


Use NSHashTable from iOS 6+ SDK.
The hash table is modeled after NSSet with the following differences:

It can hold weak references to its members.
Its members may be copied on input or may use pointer identity for equality and hashing.
It can contain arbitrary pointers (its members are not constrained to being objects).

Example usage:

 NSHashTable *hashTable = [NSHashTable
 hashTableWithOptions:NSPointerFunctionsCopyIn];
 [hashTable addObject:@"foo"];
 [hashTable addObject:@"bar"];
 [hashTable addObject:@100];
 [hashTable removeObject:@"bar"];
 NSLog(@"Members: %@", [hashTable allObjects]);


class Pri(int):    # Subclass int to get handy comparison functions etc.

Abbreviating words in class names makes it harder to follow. Just call it Priority

    '''Task priority'''

    public_from_internal = {1: 1, 2: 2, 3: 3, 4: 'N'}
    internal_from_public_str = {'N': 4, '1': 1, '2': 2, '3': 3}
    _dict = dict()

Naming this _dict doesn't give me a hint about what its used for

    def __new__(cls, level):
        try:
            level = Pri.internal_from_public_str[str(level)]

I don't like stringifying anything that gets passed in here. You really only want to support strings and ints not things that happen to stringify into the correct types.

        except KeyError:
            raise ValueError, "Pri must be 'N', '1', '2', or '3'"

        # If there's already an instance of this priority, don't create a new one.
        if level in Pri._dict: return Pri._dict[level]
        else: return super(Pri, cls).__new__(cls, level)

Use the following construct instead:

try:
   return Pri._dict[level]
except KeyError:
   return super(Pri,cls).__new__(cls, level)

I think its clearer, and it will be slightly faster.

    def __init__(self, level):
        super(Pri, self).__init__()
        Pri._dict[self] = self

I do this is __new__ and not have an __init__ function.

    def __repr__(self): return "Pri('" + str(Pri.public_from_internal[self]) + "')"

I don't like putting the method name and implementation on the same line. I think it makes it look clutered. I'd also recommend using return "Pri(%s)" % Pri.public_from_internal[self] as I think its clearer as to the result.

    # Priority 1 is clearly greater than priority 3, so invert cmp
    def __cmp__(self, other): return (-cmp(int(self), int(other)))

You inherited from int to get comparisons. But then you have to reimplement the comparisons anyways. Now you also have all the other stuff like adding/multipyling/subtracting/etc which don't make sense to apply to priorities. Basically, there is no reason to inherit from int here, and many reasons not to.

How I'd do this

class Priority(object):
    priorities_by_name = {}
    @classmethod
    def from_string(cls, name):
         return cls.priorities_by_name[name]

    priorities_by_number = {}
    @classmethod
    def from_number(cls, number):
         return cls.priorities_by_number[number]

    def __init__(self, name, number):
        self.priorities_by_name[name] = self
        self.priorities_by_number[number] = self
        self.name = name
        self.number = number

    def __repr__(self):
        return "Priority<%d>" % self.number

    def __cmp__(self, other):
        return -cmp(self.number, other.number)

Priority.First = Priority('1', 1)
Priority.Second = Priority('2', 2)
Priority.Third = Priority('3', 3)
Priority.None = Priority('N', 4)

Priority.__init__ = None # Prevent any future creations

I explicitly call class method to get a priority from either the string or number. I dislike overloading the one constructor to take either.
For a small number of items, I prefer to create them all upfront. It makes the construction simpler
I can access Priority objects at Priority.First (etc)

Truth be told I probably wouldn't implement a Priority class, instead I'd keep track of the priority as an int.


In 3-Layer design, we have below three layers

Presentation Layer: In this case your aspx and code behind files.

Business Layer: It seems this is missing in your project. You may include this for various purposes e.g., filtering items based on different scenarios, logged in user, etc.

Data Layer: This layer interacts with data store, external services, etc. CBLists class in this case.

Also, in OO programming class names are singular so CBLists should be changed to CBList.


Rather than using System Events to generate keystrokes, consider using TextEdit itself to insert text.

tell application "TextEdit"
    activate
    tell first document to set its text to its text & "Hello World!\n"
end tell

There is a difference, though: this version always appends "Hello World!" to the end of the document, rather than wherever the cursor happens to be.  (Unfortunately, TextEdit's AppleScript dictionary mentions nothing about cursors.)

A side benefit of this approach is that you don't have to grant permission to use Assistive Access to your script.


It's good to see code that comes with tests - well done!
I would add some more tests in places.  Specifically, we ought to test is_palindrome() with a single-letter input, as that's something that could easily get broken, and find_palindrome() needs testing with some strings where the longest palindrome is at beginning, middle or end.
I'm concerned at

assert find_palindrome('ab') == 'b'

There's nothing in the problem statement that says we couldn't return 'a' instead, so this is actually over-testing the code.  There's something similar going in in test_generate_substrings() where we require a specific order (we'd be better testing the result converted to set rather than list, to make the test more reasonable).

In terms of the algorithm, I see an obvious candidate for improvement:

for string in generate_substrings(string):
    if is_palindrome(string):
        vec.append(string)

for string in vec:
    if len(answer) <= len(string):
        answer = string

We store all of the palindromes in vec, even though we only want the longest one.  So we don't really need vec:
for string in generate_substrings(string):
    if is_palindrome(string) and len(answer) <= len(string):
        answer = string

We could do even better if we arrange for generate_substrings() to return all the substrings longest first.  Then we wouldn't need to generate or use all the shorter substrings:
for string in generate_substrings_longest_first(string):
    if is_palindrome(string):
        return string


Parser for tab-delimited data as a subclass of StringReader

Conceptually, I do not see anything inherently wrong with subclassing a framework object, particularly since many of them provide virtual/abstract members specifically to allow it.

In this case, it may be better to wrap a TextReader object instead of inheriting from StringReader.  This would allow you to provide tab delimited reading for multiple data sources instead of limiting yourself to in-memory strings.  For example, you could still pass in a StringReader for reading strings, but you could also pass in a StreamReader if you wanted to support reading from files instead.

Additionally, I noticed that HasMore is dangerous to call due to its side-effect.  It is not immediately obvious to a caller that checking HasMore would alter the reader's current position.  I would suggest using Peek instead.

You would then need to update _nextLine elsewhere.  You could have it be a side-effect of calling ReadFields.  Or, perhaps better, you could add another method (e.g., AdvanceLine) that is simply responsible for moving the reader to the next line.


Return a list of values from a single column in a DataTable

Two code-style issues are immediately obvious:

Use braces for 1-liners
only split lines where it overflows

Code like:

var item = result
   .SingleOrDefault(e => e == "Order");
if (item != null)
    baseTypes.Add(item);
item = result
   .SingleOrDefault(e => e == "Motion");

Should be

var item = result.SingleOrDefault(e => e == "Order");
if (item != null)
{
    baseTypes.Add(item);
}
item = result.SingleOrDefault(e => e == "Motion");

Then, the logical thing to do to simplify those cascading statements, is to create an array of keys to look for (perhaps by loading from a configuration file, or as a static constant array...):

string[] keys = {"Order", "Motion", .....};

then loop through them like:

foreach (string key in keys)
{
    var item = result.SingleOrDefault(e => e == key);
    if (item != null)
    {
        baseTypes.Add(item);
    }
}


Taking a look at your Coin class, there are a few things that aren't quite idiomatic C#.
The most obvious thing is that you're using what looks nearly like Java Doc comments. C# uses XML doc comments so this:
/// Constructs a coin.
/// @param aValue the monetary value of the coin
/// @param aName the name of the coin

Should be:
/// Constructs a Coin.
/// <param name="aValue">The monetary value of the Coin.</param>
/// <param name="aName">The name of the Coin.</param>

In C#, we have properties which mean you don't need to write explicit GetXyz and SetXyz. I'm not sure whether you're using an old version of .Net (e.g. using ArrayList) but it's normal to have those as auto-implemented properties like this:
 public double Value { get; }
 public string Name { get; }

If you can't use auto-properties, you'll have to do a bit more typing. I'm going to assume you're stuck on an older .Net and try to avoid newer features.
private readonly double value;
public double Value
{
    get
    {
        return value;
    }
}

That means you get rid of GetValue and GetName methods. I'd also suggest that you remove the empty constructor to force creation with a value and a name. That only leaves your Equals and GetHashcode implementations.
Let's consider a couple of test cases:
new Coin().Equals("blah"); // InvalidCastException :(
new Coin().Equals(null); // NullReferenceException :(

Oh dear, we've got a problem here! Let's fix those bugs:
public override bool Equals(Object otherObject)
{
    return Equals(otherObject as Coin);
}

public bool Equals(Coin coin)
{
    if (ReferenceEquals(null, coin))
         return false;

    return coin.Value == this.Value && coin.Name == this.Name;
}

That's nice and clear and most importantly, is correct! This is a common pattern and you can implement IEquatable at the same time if you want.
I think a coin should have a name in your model so you should validate that in the constructor.
So we're up to here:
///
/// A coin with a monetary value.
///
public class Coin : IEquatable<Coin>
{
    private readonly double value;

    public double Value
    {
        get
        {
            return value;
        }
    }

    private string name;

    public string Name
    {
        get
        {
            return name;
        }
    }

    /// Constructs a coin.
    /// <param name="value">The monetary value of the Coin</param>
    /// <param name="name">The name of the Coin</param>
    public Coin(double value, string name)
    {
        if (name == null)
            throw new ArgumentNullException("name");
        this.value = value;
        this.name = name;
    }

    public override bool Equals(Object otherObject)
    {
        return Equals(otherObject as Coin);
    }

    public bool Equals(Coin coin)
    {
        if (ReferenceEquals(null, coin))
            return false;

        return coin.Value == this.Value && coin.Name == this.Name;
    }

    // C# requirement:
    // since we override Equals, MUST also override GetHashCode ( !! )
    public override int GetHashCode()
    {
        return base.GetHashCode();
    }

}

So, only one thing left to talk about: GetHashCode. We must override GetHashCode and implement it correctly. I'll link you to this SO post: https://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden
Your GetHashCode should look like this:
public override int GetHashCode()
{
    int hash = 13;
    hash = (hash * 7) + Value.GetHashCode();
    hash = (hash * 7) + Name.GetHashCode();
    return hash;
}

Now we've got a class that correctly implements equality.
ETA:
As has been pointed out in the comments, value is a contextual keyword so you may want to think twice before calling a field value. I don't see the problem myself as syntax highlighting in VS, for example, would know it wasn't a keyword. Calling it theValue would be worse for readability in my opinion. If you're on C# 6 or later, you should prefer the auto property so you don't need the field. Either way, if you write this class well at the beginning, the field is an implementation detail and you'll never read this source code again.


I don't really like the method of exception pseudo-typing you're doing, I'd use different objects to represent the type of exception rather than the content, like so:

function macaddresses($ip, $name)
{
    try
    {
        //some code....
        if($obj->connect())
        {
            //do something else
            return $macaddies;
        }
        else
        {
            throw new UserVisibleException("Unable to connect to device. Please contact administrator!");
        }
    }
    catch(Exception $e)
    {
        $this->processException($e);
    }
}

private function processException($exception)
{
    if($exception instanceof UserVisibleException)
    {
        throw $exception;
    }
    else
    {
        log_message('error', $exception->getTraceAsString());
        throw new UserVisibleException(null, $exception);
    }
}

class UserVisibleException extends Exception
{
    public function __construct($message = null, $cause = null, $code = 1)
    {
        parent::__construct
        (
            $message === null ? "Oops!  Something big just happened." : $message,
            $code, $cause
        );
    }
}

I put processException() as a method as it isn't clear whether you're using this design pattern elsewhere, but I assume so as you're connecting to something and there's usually other exceptions that can happen later. If you aren't, you can just stick it back into the catch block of macaddresses().

Additionally, if it isn't clear, the ternary is so you don't have to manually type in the message to attach a cause to an unknown exception being wrapped. And I took the liberty of replacing the generic message "connection" with the stack trace of the exception that caused it being passed to your logger, as this more detailed information will be useful should you wish to debug the cause of it.


Using using namespace std;

Don't. See here: Why is "using namespace std" considered bad practice.

Exception Handling

class mException { };

Please just throw the correct standard exception std::invalid_argument, std::runtime_error and so forth. At the very least, inherit from std::exception. You can find all of the standard exceptions here: cppreference.com.

Array(int nsize=1)try:data(new T[nsize]),size(nsize)
{

}
catch(bad_alloc& r)
{
    cout<< "Cant allocate";
    throw;
}

I've never actually seen this type of try/catch used... If your allocation throws a bad_alloc you may be in an out of memory situation or the block was too large. At any rate it is not the job of your container class to print the message or handle the allocation failure, it is the user's job. Just let the exception fly.

Use Copy & Swap idiom for operator =

Copy and swap is an easy way to implement operator = with strong exception safety. You can read more about it here: What is the copy and swap idiom?.

Throw specification

You rarely need to specify the classes thrown here, just skip them. Also throw std::out_of_range instead.

To reduce code duplication you can implement the mutable (non-const) version using the const version and two const_casts (but not the other way around).

T& operator[](int index) throw (mException)
{
    if(index<0 || index>=size) throw mException();
    return data[index];
}
const T& operator[](int index) const throw(mException)
{
    if(index<0 || index>=size) throw mException();
    return data[index];
}

So this should be:

T& operator[](int index){
    // Being pedagogical here so you see what's going on.
    // The below return statement is equivalent to this.
    // const Array* const_this = const_cast<const Array*>(this);
    // const T& const_ref = (*const_this)[index];
    // return const_cast<T&>(const_ref);
    return const_cast<T&>((*const_cast<const Array*>(this))[index]);
}
const T& operator[](int index) const
{
    if(index<0 || index>=size) throw std::out_of_range("Index out of range!");
    return data[index];
}

Note that it's important that the mutable version calls the const version. Not the other way around.

If you have a mutable instance, then calling a const method is OK. As the operator returns a reference into your mutable instance (even though you're accessing it in a const manner), then casting away the constness is safe.

But if you on the other hand call a mutable function from a const method, then the mutable function might modify your const data and this my friend, is no bueno.

Operator ++

The pre- and post- increment operators don't make sense to me. But I guess you need them for something.

Simplify your logic

This:

    for(int i=0;i<rhs.size;i++)
    {
        out << rhs.data[i];
        if(i<rhs.size-1)
         out <<  " ";
    }

could be:

    for(int i = 0; i < rhs.size - 1; i++) {
        out << rhs.data[i] <<  " ";
    }
    if(rhs.size > 0){
        out << rhs.data[rhs.size-1];
    }

It avoids checking the condition inside of the loop each time. (Although your compiler might already do this).

Input stream operator

It is not the array's job to print the explanation of how to use the input operator, that's up to your user. So this:

friend istream& operator>>(istream& in,Array& rhs)
{
    cout << "enter " << rhs.size << " digits to fill the array" << endl;
    for(int i=0;i<rhs.size;i++) in >> rhs.data[i];
    return in;
}

Should simply be:

friend istream& operator>>(istream& in,Array& rhs)
{
    for(int i=0;i<rhs.size;i++) in >> rhs.data[i];
    return in;
}

As you are using istream it means that you can pass a ifstream pointing to a file on the disk to read from. And it's just silly to be forced to print the instructions each time you read from the file automatically.

Return by reference

Your front() and back() methods should return by reference. And you should also implement const versions of these.

Iterator implementation

A basic pointer satisfies the random access iterator criteria and has specialisations for std::iterator_traits. So you could basically just do this:

typedef T* iterator;

and be done with it. But as this is a learning experience, lets look at your iterator code.

You are storing the base pointer and the index. You can simply store 1 pointer to the indexed element and increment and decrement the pointer instead, this reduces your code. Also you're missing the required typedefs for an iterator for example you're not specifying what iterator category it is so your iterator is not compatible with many standard library functions. You need these as std::iterator_traits is not specialised for your type. The easiest way to get the right typedefs is to inherit from std::iterator<...> and give the correct type arguments to the template. Note that this only gives you the type defs and no other functionality, you still need to implement the iterator.

You can read more about what requirements are put on iterators here: RandomAccessIterator and on the linked pages.

Also there is an easier way to implement the operator ==/!=:

    friend bool operator==(const iterator& rhs,const iterator& lhs)
    {
        return !(rhs.index!=lhs.index);
    }
    friend bool operator!=(const iterator& rhs, const iterator& lhs)
    {
        return !(rhs.index==lhs.index);
    }

should be:

    friend bool operator==(const iterator& rhs,const iterator& lhs)
    {
        return rhs.index == lhs.index;
    }
    friend bool operator!=(const iterator& rhs, const iterator& lhs)
    {
        return !(rhs == lhs);
    }

Now whenever operator == changes, operator != is automatically updated as it uses operator ==. Clever huh?

The whole thing rewritten with just one pointer should be:

class iterator{
    const T* data;
public:
    iterator(const T* arr): data(arr) { }
    const T& operator*() const
    {
        return *data;
    }
    const iterator operator++(int)
    {
        iterator temp = *this;
        ++*this;
        return temp;
    }
    iterator& operator++()
    {
        ++data;
        return *this;
    }
    friend bool operator==(const iterator& rhs,const iterator& lhs)
    {
        return !(rhs.index!=lhs.index);
    }
    friend bool operator!=(const iterator& rhs, const iterator& lhs)
    {
        return !(rhs.index==lhs.index);
    }
};

iterator begin() const{ return iterator(data); }
iterator end() const{ return iterator(data + size); }

Notice how the iterator class behaves like a restricted pointer? Yepp, you are correct, it basically just wraps a pointer in a pointer-like interface. So you could just as well have used a pointer (like I mentioned at the start, a pointer is a fully fledged random access iterator, I hope the above made it clearer as to why it's OK).

You're also missing operator -> and a lot of other things but I choose to ignore that for now.

Style

For crying out loud, white space is free. Use them! At least put spaces around all operators. For example this:

    for(int i=0;i<size;i++)

should be

    for(int i = 0; i < size; i++)

for readability.


LINQ foreach - error handling and general improvement

First, the least important: Personally I don't like using the .ForEach extension method as it looks too much like LINQ query commands which are mainly for projection/filtering. I just use a straight-up foreach loop most of the time. But that's just style points.

You can simplify .Where(lambda).FirstOrDefault() to FirstOrDefault(lambda).

You're referencing context every time, but you don't have to, you're right. You could enumerate over context.JobOrderTypes and store it in memory before iterating. Chances are it's going to be more performant than hammering your db every iteration. You are pulling back an entire table into memory, though, so be aware of the implications of that.

Your code is going to crash but you can fix it either very simply:

var val = ...FirstOrDefault(x => x.JobOrderTypeIdentifier == identifier);
i.JobOrderTypeString = val != null ? val.Title : "SomeDefaultValue";

Or you can flatten to an IEnumerable of Titles first (essentially saying "Give me the first of all Titles of objects that match my criteria" instead of saying "Give me the Title of the first object that matches my criteria, if no matches then null"):

i.JobOrderTypeString = context.JobOrderTypes.Where(x => x.JobOrderTypeIdentifier == identifier).SelectMany(j => j.Title).FirstOrDefault();

I'm not an EF expert so I'm not sure if the following will generate the same SQL, but it's cleaner LINQ:

i.JobOrderTypeString = context.JobOrderTypes.SelectMany(j => j.Title).FirstOrDefault(x => x.JobOrderTypeIdentifier == identifier);

Generally code that has a hydrated collection, but then goes through and iterates through the collection and sets values on each element in the collection means that you can do it better. I don't know where this code lives, but make sure it's in a place that says "right before I write these to the database, calculate!" You could also do this computation whenever the column value on i changes or when i is instantiated.

This may be a sign that your problem could be better solved by using a stored proc or a computed column, or you need to wrap the in a "BeforeInsert"-type event.


I wonder that I have to add or remove some corner-case handlings for read(), malloc(), or realloc().

int scan_ps(struct my_proc ***ptr, int (*filter)(const struct my_proc *));

Make review easier

Allocating to the size of the type rather than the size of an object obliges a reviewer to double check - did code use the right type?  Instead, make code easier to review, code right and maintain.

// ps_list = malloc(sizeof(struct my_proc *)*size);
ps_list = malloc(sizeof *ps_list * size);

// current_ps = malloc(sizeof(struct my_proc));
current_ps = malloc(sizeof *current_ps);

Why use unsigned?

With array sizing and indexing, size_t is the Goldilocks type, neither too narrow nor too wide.

// unsigned int size = 16;
size_t size = 16;

Questionable type

Why use int when read() returns ssize_t?

// int n;
ssize_t n;
n = read(fd, buf, MAX_LEN_STR);

Questionable code

Why potentially shorted n and not report this as an error?  Just read less.

// n = read(fd, buf, MAX_LEN_STR);
// n = (MAX_LEN_STR - 1) > n ? n : (MAX_LEN_STR - 1);

n = read(fd, buf, MAX_LEN_STR - 1);
// or better
n = read(fd, buf, sizeof buf - 1);

Proper use of goto

goto is often mis-used.  This is an acceptable usage.

Why MAX_LEN_STR?

For a max path length, I'd expect PATH_MAX

// char path[MAX_LEN_STR];
char path[PATH_MAX /* maybe + 1 */];

Why 256?

Avoid naked magic numbers as in char cmdline[256];.  Perhaps char cmdline[MAX_LEN_STR];?

Why MAX_LEN_STR?

In limiting string copy, best to use the size of the destination and not some other constant.

// strncpy_v2(current_ps->cmdline, buf, MAX_LEN_STR);
strncpy_v2(current_ps->cmdline, buf, sizeof current_ps->cmdline);

Missing error report

strncpy_v2() does not indicate it failed to copy a complete string. With all the other good error checking, it is curious code does not report this.  If failure cannot occur because of the construction of code, why then have strncpy_v2() versus simple strcpy()?  Being "safe" by not over-writing memory is good, yet not reporting insufficiencies is not.

Sign and potential print specifier mis-match

A pid_t is some signed type.  Ref.  Best to use signed math and cast to a wide signed type to print.

// pid = atoi(dp->d_name);
pid = atoll(dp->d_name);

// snprintf(path, sizeof(path), "/proc/%u/cmdline", pid);
snprintf(path, sizeof(path), "/proc/%jd/cmdline", (intmax_t) pid);
// or
snprintf(path, sizeof(path), "/proc/%lld/cmdline", (long long) pid);

Other stuff

What is *ptr in failure?

When scan_ps() fails, returns -1, consider setting *ptr = NULL;

Lose a *

Further, consider using re-architect and using a return value of NULL as an error indication.  Otherwise the return value is a pointer to a NULL terminated array.  You do lose one *, but I'd say that is good.

struct my_proc **scan_ps(int (*filter)(const struct my_proc *));

Why define FALSE, TRUE?

Instead, use stdbool.h.

// #define FALSE               (0)
// #define TRUE                (!FALSE)
//   return TRUE;

#include <stdbool.h>
...
   return true;