Count chars difference between two strings

How about this variant?

object Hamming {

    def apply(a: String, b: String): Int = if (a.length != b.length) {
        throw new IllegalArgumentException(s"Strings a=$a and b=$b have different length.")
    } else a.zip(b).count {
        case (charA, charB) => charA != charB
    }

}

The zip-function does create a new collection of tuples with two corresponding chars side by side in every tuple. (Char, Char)
The count-function counts the number of elements for which a boolean evaluation function, passed as an argument, returns true. This should work not only for characters, because it uses pattern matching. Also if there are two arguments of the same type (e.g. for comparison) and I cannot further specify what they are, then I like to name them a and b.
I cannot tell if this solution is faster than yours, but I don't think there will be a significant difference.

P.S.:

I see the function is named compute. Thats really general and abstract. I named it apply. It can be called like this: Hamming("Alice", "Bob")
Look at what I did with the brackets.
If you would like to use the function for other sequences than characters you can change the snippet to this:

def apply(a: Seq[_], b: Seq[_]): Int = if (a.size != b.size) {
    throw new IllegalArgumentException("Parameters have different length.")
} else a.zip(b).count {
    case (charA, charB) => charA != charB
}


Project Euler 10: find the sum of all the primes below two million

Most of the time the line all.remove(x) is running, and it is executed for all non-prime numbers, which is most of the numbers.

Moreover, your remove items by value, which means that each time you remove it, a searching by value is performed on the list, making it even slower.

You can avoid this if, instead of removing the non-primes, you

set zero in their place and access the list by index
build a list for collecting the identified primes

But I would suggest a completely different approach:

Instead of starting with list of all numbers all = list(range(2, 2000000)), and then removing the non-primes, it is better just start with empty list and adding the number if it is prime. Or if you need only the sum, don't save the primes at all; just sum them.

if you want to check if the number \$n\$ is prime, you don't need to check division for all the numbers. Check only from 2 to \$\sqrt{n}\$.


Single letter variable names are highly discouraged. A variable name should give a reader an idea about what value is stored in it. n, v, and t tells a reader nothing. v and n are the same type, but how would someone who hasn't seen the code before know which means what.

You are checking if n is null. The only way this can happen is if an exception is thrown in execute() or if execute() returnsnull`. In the first case, you can directly return from that catch block. Doing this will more clearly indicate that an exception will stop execution of the chain.

In the second case, that means that null is a valid return value from execute(). However, execute() returns an enum, which is a way to explicitly state all valid values. If null is a valid value, it would just be another state that should be explicitly stated.

The code doesn't have any documentation. While the interface is fairly simple, it does assume that a reader interpreters the signatures properly.

fail() takes an Exception as an argument. But what should the implementer do with this exception. The method can also thrown an exception, does that mean a valid implementation could be the following?

public void fail(Exception ex) throws Exception {
  throw ex;
}

If execute() returns the same enum value that it was passed, the chain of execution is stopped. This is extra logic that would not be clear to someone who hasn't seen the implementation. Since there is no documentation, someone needing to use this code has to look at the code to know that this is the way to stop execution.


Performing calculations with a catalog of stars

This looks like procedural code, poorly dressed up in object-oriented style.  Python doesn't require you to write object-oriented code, but if you do, you should model it properly.

Think of objects as "smart" data structures.  If your classes are well designed, you can ask the objects to perform operations on themselves in such a way that you don't have to worry about the details of how it performs the task.

For example, StarCatalog should definitely be a class of its own.  There should probably be a Star class as well.  The outline of those classes might look like:

class Star:
    def __init__(self, id, magnitude, right_ascension, declination):
        ...
    def id(self):
        ...
    def magnitude(self):
        ...
    def coordinates(self):
        ...

class StarCatalog:
    def __init__(self):
        ...
    def add_star(self, star):
        ...
    def remove_star(self, id):
        ...
    def get_star(self, id):
        ...
    def __iter__(self):
        ...

class StarCatalogImporter:
    def __init__(self, catalog):
        ...
    def import_file(filename):
        ...

Once your model is defined, you can start using it!

catalog = StarCatalog()

importer = StarCatalogImporter(catalog)
try:
    importer.import_file(raw_input('Input pathname of stellar catalog: '))
    print 'Stars imported successfully.'
except IOError:
    print 'Star import unsuccessful. Check that the star catalog file-path is correct. Program exiting now.'
    raise

corrector = InterstellarCorrector(correction_factor=0.2342)
corrected_catalog = corrector.correct(catalog)

result = least_sq_correlator.correlate(corrected_catalog, dusty_model)

Notice how the classes are designed to separate concerns.  The StarCatalogImporter class knows how to add the stars listed in a file into a StarCatalog; once that is done, you can ask the catalog to enumerate its stars.  The StarCatalogImporter interface should be as reusable as possible.  For example, if it encounters an error while importing, it raises an exception, rather than printing a message and exiting.  The code that uses the StarCatalog decides how to handle those situations.  (It might print an error message and exit.  It might be a GUI application, in which case it would display the error in a dialog box.  It might translate the error message into another language.  It might try to load a different catalog instead.)  On the other hand, the code that uses a StarCatalog should make no assumptions about how the star catalog is implemented.  It doesn't know if the StarCatalog internally uses an array, a dict, or a numpy matrix.  Therefore, it should only use the functions exposed by the class.

The class interfaces that you design are what prevent your code from being spaghetti.  If you design your class interfaces well, you will have a loose coupling, such that you will be able to reuse the class in other programs, and modify the inner workings of the class without disturbing the code that uses your class.

A good rule to follow is that each class should represent one thing.  If you can't think of a short, descriptive name for the class, that's a sign that you're on the wrong track.  Also, the class name must be a noun; if it's a verb, you're using procedural rather than object-oriented thinking.


Constraints
    1 <= N <= 100000
    0 <= K <= 109
    0 <= H[i] <= 109
    1 <= Q <= 100000
    0 <= l <= r < N

My rule of thumb for this kind of challenge is that 109 operations is a limit. So, ignoring the hidden constant of Landau notation, we're looking at something which is \$O(N\sqrt N + Q\sqrt Q + Q\sqrt{N} + K)\$. In particular, each query shouldn't take more than \$\sqrt N\$ time. That would seem to push us towards a preprocessing step which is \$O(N\sqrt N + K)\$ and which allows us to process individual queries fast. Alternatively, we might have a preprocessing step which takes into account the queries, but that's likely to be more complicated.

Since your approach takes (in the worst case) \$O(QN\lg N)\$ time, it's definitely nowhere near complying with my rule of thumb.

If we consider first the idea of a preprocessing step which takes into account the queries, it's quite easy to construct a really nasty case where we have boundaries between every consecutive pair of wrestlers, and each one contributes to multiple queries. E.g. take the following 100000 queries:

(0, 99999), (1, 99998), (2, 99997), ..., (49999,50000),
(0, 49999), (1, 50000), (2, 50001), ..., (49999, 99998)

I don't find that approach promising.

Ideas which might be more promising are bucketing the wrestlers in buckets of width \$K\$, so that each wrestler can only interact with those in the same bucket and some of those in the adjacent buckets - although the "some of" is a problem; and inclusion-exclusion, although I can't quite get that to work. It's "fast enough" to precompute tables \$C[a]\$ which is the number of valid fights between \$i \le a < j\$; \$L[a]\$ which is the number of valid fights between \$i < j \le a\$; and \$R[a]\$ which is the number of valid fights between \$a \le i < j\$. But the closest I can get to the number of valid fights between \$l \le i < j \le r\$ is the difference of that with the number of valid fights between \$i \le l\$ and \$j \ge r\$.


Find all integers between m and n whose sum of squared divisors is itself a square

If you were able to write this after just two weeks, knowing nothing previously about programming, then I would have to say: well done!  This is excellent code for a beginner.  I really like the way you have applied transformations and filters to entire arrays, instead of falling into the trap of proceeding instruction by instruction.

Performance

Where is the performance problem likely to lie?  It's almost certainly with the factoring (calculating r).  For every number z, you test every candidate divisor from 1 to z.  If you have n numbers to factor, then we would say that this step is O(n2).  That indicates a scalability problem.

Calculating squarenumbers is relatively straightforward.  Summing the squares of a list of numbers is easy.  Checking whether their square roots are integer is slightly more expensive, but still a simple operation.

Calculating booleans is also straightforward.  But it's repeating exactly the same calculations as for calculating squarenumbers, which is wasteful.

The last three statements to gather the result are also quite simple.

So, the problem is with factoring.  How can that be improved?  Observe that factors always occur in pairs: 1×42 = 2×21 = 3×14 = 6×7.  Once you discover the factors of \$z\$ up to \$\sqrt{z}\$ by trial-and-error, you automatically know the corresponding larger factors.

Readability

In the first statement, you used z for the dummy variable.  In subsequent statements, you switched to x.  I recommend using the same name for variables that serve the same purpose.

There are some nested map calls.  That makes the code trickier to read.  What can we do about that?  Notice that we test every z (subsequently called "x") independently.  Therefore, there is no need to calculate the divisors of each number in an array of arrays.  We can just consider each number in [m, m + 1, m + 2, …, n] on its own.

Suggested solution

require 'set'

def list_squared(m, n)
  (m..n).map do |num|
    divisors = Set.new((1..Math.sqrt(num)).select { |d| num % d == 0 })
    divisors += divisors.map { |d| num / d }

    sum_sq_divisors = divisors.map { |d| d * d }.inject(:+)
    [num, sum_sq_divisors] if Math.sqrt(sum_sq_divisors) % 1 == 0
  end.compact
end


Simple stack implementation using linked list

I see some things that you might want to use to improve your code.

Use appropriate #include files

The implementation requires #include <stdexcept> so that should part of the template.

Eliminate unneeded variables

The push function doesn't really need any temporary variables:

template<class T>
void Stack<T>::push(const T& t) {
    first = new Node<T>{t,first};
    ++n;
}

Create a default constructor for Stack

An instance of Stack is not necessarily initialized to any particular values when it's created.  To address this, you should implement a default constructor.

Stack() : first{nullptr}, n{0} {}

Match new with delete

If you allocate memory using new, you must also free it using delete or your program will leak memory.  Since you use new in push(), you should use delete in pop():

template<class T>
T Stack<T>::pop() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    Node<T>* oldnode = first;
    T t = first->item;
    first = first->next;
    --n;
    delete oldnode;
    return t;
}

Create a copy constructor if you need one

The compiler will create a default copy constructor which does a shallow copy, but this won't work for data structures, like yours, which use pointers.  Instead, if you really want to create a new Stack from an existing one, you'll need to creat your own copy constructor:

template<class T>
Stack<T>::Stack(const Stack<T> &s) : first(nullptr), n(0) {
    for (auto t=s.first; t; t = t->next)
        push(t->item);
}

The default-constructed operator= will now use this copy constructor.

Create a destructor if you need one

For similar reasons, you need have a delete for Stack and not for Node.  The one for Stack could be like this:

template<class T>
Stack<T>::~Stack() {
    while (!empty())
        pop();
}

Use const where possible

The peek() function doesn't (and shouldn't) alter the underlying Stack so it should be declared const.

Consider using references

While this code works (with the adjustments listed above), ther is still some room for improvement.  First, things inserted into the stack are copied rather than moved there.  Also things that are popped from the stack are also copied rather than moved.  This means that there are many more constructor and destructor calls made than are strictly necessary.

To see how this works, here's a class that contains a string, but includes instrumentation so we can see what's happening:

class MyString {
public:
    MyString() : str(), id(serial++) { std::cout << "creating empty string " << id << "\n"; }
    MyString(const char *msg) : str(msg), id(serial++) {
        std::cout << "creating string \"" << str << "\" " << id << "\n"; }
    MyString(const MyString &s) : str(s.str), id(serial++) {
        std::cout << "copying string \"" << str << "\" " << id << "\n"; }
    MyString(MyString &&s) : str(), id(serial++) {
        std::swap(str, s.str);
        std::cout << "moving string \"" << str << "\" " << id << "\n"; }
    ~MyString() { std::cout << "destroying string " << id << "\n"; }
    friend std::ostream &operator<<(std::ostream &out, const MyString &m) {
        return out << m.str;
    }
private:
    static unsigned serial;
    std::string str;
    unsigned id;
};

unsigned MyString::serial = 0;

Now we specialize your templated stack and try it out:

int main() {
    Stack<MyString> x{};
    x.push("one");
    x.push("two");
    x.push("three");
    std::cout << x.peek() << '\n';
}

Output from this program (with the other fixes included):

creating string "one" 0
copying string "one" 1
copying string "one" 2
destroying string 1
destroying string 0
creating string "two" 3
copying string "two" 4
copying string "two" 5
destroying string 4
destroying string 3
creating string "three" 6
copying string "three" 7
copying string "three" 8
destroying string 7
destroying string 6
copying string "three" 9
three
destroying string 9
copying string "three" 10
destroying string 8
destroying string 10
copying string "two" 11
destroying string 5
destroying string 11
copying string "one" 12
destroying string 2
destroying string 12

As you can see, even though we've only got three items on the stack, we've created and destroyed 13 objects.  By making only a single small change to the Node constructor, we can reduce that to 10:

Node(const T &t, Node* link) :item{t}, next{link} {}

More savings could be realized by not using pop in the destructor since pop creates a copy of T to return:

template<class T>
Stack<T>::~Stack() {
    if (first) {
        for (Node<T> *n = first->next; n; n = first->next) {
            delete first;
            first = n;
        }
        delete first;
    }
}

Consider using smart pointers

Using something like a std::unique_ptr would free you (pun intended) from having to manage the mechanics of new and delete explicitly.


Refactored to use polymorphism in place of case statements

public class JobType : IJobType
{
    public IJob GetJobType(string jobTypeCode)
    {
        if(jobTypeCode == JobTypeToProcess.Notify.ToString())
            return new NotifyJob();

        if (jobTypeCode == JobTypeToProcess.ConflictedAppointmentMessageJobType.ToString())
            return new ConflictedAppointmentMessageJob();

        if (jobTypeCode == JobTypeToProcess.UnifiedExport.ToString())
            return new UnifiedExportReportJob();

        return jobTypeCode == JobTypeToProcess.FTPJobType.ToString() ? new FTPJob() : null;
    }
}

This seems to be some kind of a factory. So I would rename JobType to JobTypeFactory and IJobType to IJobTypeFactory having the GetJobType() method changed to Create().

instead of using the string representation of the enum you should use Enum<T>.TryParse()
I don't see any advantage on using multiple if statements over a switch..case.
Although braces {} are optional you should use them always to make your code less error prone.

Putting the mentioned points together will lead to

public class JobTypeFactory : IJobTypeFactory
{
    public IJob Create(string jobTypeCode)
    {
        JobTypeToProcess jobType = JobTypeToProcess.None;
        if(!Enum.TryParse<JobTypeToProcess>(jobTypeCode, out jobType)) { return null; }

        switch(jobType)
        {
            case JobTypeToProcess.Notify:
                return new NotifyJob();

            case JobTypeToProcess.ConflictedAppointmentMessageJobType:
                return new ConflictedAppointmentMessageJob();

            case JobTypeToProcess.UnifiedExport:
                return new UnifiedExportReportJob();

            case JobTypeToProcess.FTPJobType:
                return new FTPJob();

            default:
                return null;

        }
    }
}

which is a little bit longer than the original, but it is more readable IMO.

public bool RunNextJob()
{
    //  Return true if we found a job to run
    DeferredJob dJob = _jobRepository.GetNextJob();
    SessionProvider sessionProvider = ObjectFactory.GetInstance<SessionProvider>();

    if(dJob != null)
    {
        Logger.Info(string.Format("Running job type: {0} Id: {1}", dJob.JobType, dJob.Id));
        dJob.ProcessedDate = DateTime.Now;
        _jobRepository.Update(dJob);
        sessionProvider.Flush();

        var jobType = new JobType();
        var job = jobType.GetJobType(dJob.JobType);

        if (job != null)
            job.RunJob(dJob);

        return true;
    }

    return false;
}

By adding a guard clause you could remove some horizontal spacing,
Its a little bit strange setting the ProcessedDate before the job had been processed.
What is the sense of getting the SessionProvider if maybe the job is null ?
for the case you are running C# 6.0 you could use string interpolation instead of string.Format().

Leaving aside the setting of ProcessedDate because I don't know if that would cause sideeffects but including the changes from above, the mentioned points would lead to

public bool RunNextJob()
{
    //  Return true if we found a job to run
    DeferredJob dJob = _jobRepository.GetNextJob();

    if (dJob == null) { return false; }

    SessionProvider sessionProvider = ObjectFactory.GetInstance<SessionProvider>();

    Logger.Info($"Running job type: {dJob.JobType} Id: {dJob.Id}"); // C# 6.0 only

    dJob.ProcessedDate = DateTime.Now;
    _jobRepository.Update(dJob);
    sessionProvider.Flush();

    var jobTypeFactory = new JobTypeFactory();
    var job = jobTypeFactory.Create(dJob.JobType);

    if (job == null) { return false; }

    job.RunJob(dJob);

    return true;

}


Yes it is perfectly valid.

lambdas in C++ were designed to be functionally equivalent to functors that were used a lot in C++03.

So you can consider:

auto x = [state1, state2](Param1 param1, Param2 param2){/* Do Stuff */};

To be functionally equivalent to:

struct AnonClassX
{
    State1  state1;
    State2  state2;
    AnonClassX(State1 state1, State2 state2)
       : state1(state1)
       , state2(state2)
    {}
    returnValue operator()(Param1 param1, Param2 param2) const
    {
         /* Do Stuff */
    }
};
AnonClassX   x(state1,state2);

It is quite normal to use static variables in functions and methods. Lambda is just a shorthand for creating an anonymous class with state and an operator()() to make it act like a function. So it should be very normal to put static members inside it.


First of all use one h1 on the page (it's not stated anywhere but it's generally good practice), which means you cannot use in sidebar. I would start with h3 and do subheadings as h4 in your case.

Using aside (http://html5doctor.com/aside-revisited/):
When used in article tag it will be good structure, however when outside of it, it will mean that it's a sidebar(not connected to article itself).

You might as well use figure and fiugurecaption element with images and their caption (it's nice to provide image probably there).

One more thing. If your infobox is separate content why not use article instead of aside? Let's say you are writing text about peanuts. If you want to put that peanuts are produced in kongo  in infobox it qualify as separate content in my opinion.

EDIT:

About wikipedia. Wikipedia is using tables as the data inside is table alike. In your case too. dl doesn't really make sense in this case as it shows that is dictionary definition list, where it actually is table data. It will be better visible when you add for example english name next to latin you will see even more that data is table suitable


What are the draw backs, if any, in using C and C++ together? Is doing so considered correct by the large?

You can't write exclusively in both C and C++.
You can write

exclusively in C
exclusively in C++
or using a combination of the two different languages.

to code in C is outright dumb, and it is the language of past generations.

C may be an old language but it is still heavily used and has its place.
It is practically the only glue language that is universal so great for writing effecient modules for other languages or gluing languages together.
It is also great for low level coding where you want/need to get close to the hardware.
But there are downsides to writing in C (but saying it is dumb to do so is stretching it a bit). But you should be able to justify your choice of choosing C over an alternative.

So, in terms of maintenance, acceptance, common practice and efficiency; is it something professionals on large scale projects see/do?

Are there large code bases writing in C that need maintenance: Yes.
Is it common practice to use C: That is entirely dependent on what you are doing it is imposable to generalize.
Personally I write exclusively in C++.
There is nothing I can do in C I can't do in C++ so I don't write C anymore (In fact I have dropped it from my resume (especially since I don't want to write C)). The advantage of C++ is I can get code written to as low a level as C but I also have higher level constructs (though not as high as modern scripting languages).
Code Review:
I see no advantage of using frpintf(). In situations like this C++ std::ofstream is much more flexible,
printHeading(FILE * fp)
{
    fprintf(fp, "Employee            Pay        Reg Hrs     Gross       Fed        SSI        Net\n");

// I would always use C++ stream.
// It can be more than just a file.
printHeading(std::ostream& stream)
{
     stream <<  "Employee            Pay        Reg Hrs     Gross       Fed        SSI        Net\n";

Also if you are doing anything complex it is TYPE SAFE. *Unlike C code using fprintf(). This is one major area that C falls down in and is the cause of some of the major bugs in C code.
You check for an invalid number. But you are not checking for completely invalid input. What happens if somebody typed "Fred"
cin >> e.hours;
while(e.hours < 0)
{
    cout << "  You did enter a valid amount of hours!\n";
    cout << "  Please try again: ";
    cin >> e.hours;
}

You expect that there is never more than 100 bad characters in the input?
cin.ignore(100, '\n');

What happens if I accidentally paste in a paragraph of text.
And last but worst of all:
using namespace std;

Never do this. It is OK if you are writting a ten line toy project. But once you get past anything more than a toy it causes more problems (in name clashes) than it is worth. The reason standard library is shortened to std:: is to make it easy and quick to type.


The loop iterates over the whole range(len(M)). It means that the last few products exercise less than 13 digits. It doesn't matter in this particular example (they are all zeros anyway), but may lead to erroneous result in general case. Iterate over range(len(M) - 13).
Digit-to-int conversion happens 13 times for each digit. Better convert them once in a separate loop before doing calculations.
Every time a 0 is encountered, you may safely skip the whole bunch of digits: the product will be 0 anyway.
A sliding window technique may help.

In pseudocode:

product *= data[head]
product /= data[tail]
head += 1
tail += 1

(be careful to not divide by 0).


Normalise list of N dimensional numpy arrays

The trick is to use the keepdims parameter.

import numpy as np

num_vecs = 10
dims = 2

vecs = np.random.normal(size=(num_vecs, dims))

vecs /= np.linalg.norm(vecs, axis=1, keepdims=True)

assert np.allclose(np.linalg.norm(vecs, axis=1), 1.)


Rspec unit test for updating a property of a model

It looks like you don't need the whole user-task-task item setup for the test you provided. It's actually a TaskItemUserReference spec, not Task spec.

RSpec.describe TaskItemUserReference, type: :model do

  describe "#toggle_property" do
    it "updates property" do
      task_item_user_reference = TaskItemUserReference.new(completed: true)

      expect do
        task_item_user_reference.toggle_property(:completed)
      end.to change {task_item_user_reference.completed}.from(true).to(false)
    end
  end
end


I don't see the point in using goto here. There's no resource clean up or any other strong reason to resort to it.  It just makes the control flow more complicated.
How to fix it? In the main function, you can just return the value immediately in case of an error. In the gcd function, you can run the while loop with a condition a != 0. It'll make the code easier to folloow and eliminate a corner case a = 0.
The error message fprintf(stderr, "Error: missing or too many arguments\n"); seems too generic to me. It would be more helpful if it were more detailed (too many and missing arguments are clearly different cases).
An LCM of two int's may not fit into int. I'd recommend to document that your program has undefined behavior if the LCM is too large or use a wider integer type.


Using PostgreSQL effectively with a banking app

this looks really ugly from a readability/formatting point of view.

    public void beRegister()
    {
        try
            {
                if( setConnection() != true )
                    {
                        System.err.println("[+] Connection Error");
                        return;
                    }
                tempRegister();
                System.out.println("[+] Registeration Successfully");
            }catch(Exception e)
            {
                System.err.println(e.getClass().getName()+": "+e.getMessage());
                System.exit(0);
            }
    }

You should use consistent Egyptian (Java) bracing for this along with making sure that you leave some space around the Braces and not around the parenthesis.

Key words also like their space from parenthesis.

Look how much cleaner this little piece of code looks now.

public void beRegister() {
    try {
        if (setConnection() != true) {
            System.err.println("[+] Connection Error");
            return;
        }
        tempRegister();
        System.out.println("[+] Registeration Successfully");
    } catch (Exception e) {
        System.err.println(e.getClass().getName()+": "+e.getMessage());
        System.exit(0);
    }
}


I see a number of things that might help you improve your program.

Use li rather than la to load a constant

As has already been noted, the la $v0, 10 instruction should actually be li $v0, 10.  It works that way because you're loading the address 10 into $v0 which has the same effect, but it's a little strange looking.

Put the $zero at the end of the instruction

The instruction add  $s0, $zero, $v0 is perfectly valid, but it might look a little odd to those experienced with MIPS assembly language.  The typical idiom that I've seen is to put the constant at the end, so that instruction would instead read add  $s0, $v0, $zero which does exactly the same thing, but I find it easier to pick out the $zero at the end rather than in the middle.  That's purely a stylistic suggestion, though.

Minimize register use

You don't really need both a counter and a number.  What you can do instead is to use the original input number in $s0 as the counter and decrement instead of incrementing.

Avoid the overhead of subroutine calls

There's nothing wrong with using subroutines, of course, but they add cycles to the program, and for such a small and simple program as this, the call isn't really necessary.  Instead, you could put the loop inline.

Prefer to branch at the end of a loop

A while... loop in higher level languages does not even execute once if its condition is false.  A do ... while loop executes at least once, which seems to me to be what is desired here.  You can then minimize branching so that there is only one conditional branch at the end of the loop.

Use a better algorithm

Carl Friedrich Gauss came up with a clever algorithm as a child.  You can read about it and see if you can implement it for even faster code.

Putting it all together

When we apply all but the last suggestion, we get something like this:

        .data
Prompt: .asciiz "Enter number to get summation: "
Output: .ascii  "Sum of numbers is: "
        .globl main
        .text
main:
    # Prompt for input
    li   $v0, 4
    la   $a0, Prompt
    syscall

    # Read input
    li   $v0, 5
    syscall
    add  $s0, $v0, $zero  # s0 used as loop countdown
    add  $s1, $s1, $zero  # s1 used for summation = 0
loop:
    add  $s1, $s1, $s0    # add number to summation

    # Begin summation
    addi $s0, $s0, -1     # decrement number
    bgtz $s0, loop        # keep going until 0

        # Display
    li   $v0, 4
    la   $a0, Output
    syscall

    li   $v0, 1
    add  $a0, $s1, $zero
    syscall

    # Exit
    li   $v0, 10
    syscall


Representing the opening and closing time for a business

Yes, too much for one line, yes, too confusing. Making a map an lambda for two values like that is silly, unless you are trying to win an obfuscation contest.

So, the middle version is best.


Create a structuringselement in the form of a line with a certain degree and length

Type hints

def bresenham(x0, y0, x1, y1):

should be, at a guess,

def bresenham(x0: float, y0: float, x1: float, y1: float) -> List[float]:

or maybe int, but you get the idea.

Type promotion

You don't need decimals here:

err = dx / 2.0

/2 will accomplish the same thing.

Termination

What happens if you call bresenham(0, 0, 9.5, 9.5)? I suspect that it will iterate infinitely and hang, due to

  while x != x1:

One way to fix this, if your algorithm permits, is - rather than making an sx dependent on the comparison of x0 and x1, simply swap x0 and x1 if they're in the wrong order. Then, rather than !=, use <, and you don't have to calculate sx.

Use a generator

For some use cases this will dramatically decrease memory consumption. Instead of building up points in memory, just yield whenever you have a point. Allow the caller to decide whether they want to cast to a list, a tuple, or just iterate over the points.

Int casting

  n_rows = int(2 * max([abs(point_y) for point_y in points_y]) + 1)

is overambitious in application of the int cast. The multiplication and addition don't need to be done in floating-point math, so you can instead do

  n_rows = 2 * int(max(abs(point_y) for point_y in points_y)) + 1

Also note that you shouldn't pass a list to max - just pass the generator directly.


It is considered bad practice (by most people) to declare more than one variable on a line.

double number, decValue;
int remainder, intValue;
string binary1, binary2;

Though it is not a problem here there are some corner cases where the declaration gets confusing.

Second you declare all your variables at the top of the function.
This is a very C like style and in C++ it is usually better to declare the variable as close to the point of usage as possible (no need to invoke a constructor if you are never going to use the variable, also it makes reading the code easier as you can see the type at the fist point of usage).

I know all the books say to use:

using namespace std;

But in the long run its not a good idea. Get used to prefix things with their namespace std::string, or importing the specific bits you want using std::string (even then scope as tightly as possible (you would not believe how many time string has been reinvented)).

Variables should be descriptive (and more importantly unique and easy to find in the source).

for(int i = 1; i <= 5; i++)

Think about 10 years of maintenance on this code. The code now covers 5 long pages. Try and find and update all usages of i. This becomes a pane as i will appear in nearly every other identifier in all the comments in lots of places etc. So try and use variables that can be easily searched for.

In your ConvertXXX() functions. You are saving integer values into the string. This is fine. But you are then extracting those char values and converting to int for printing. Why not convert the values directly into the characters you want to print.

string ConvertDec(double value)
{
    // STUFF
         binary += '0' + integer; // each digit will be the character 0 or 1
    // MORE STUFF
}

When printing:

cout <<  (int)binary1[i];

// Can change this too:

cout <<  binary1[i];

More importantly you can replace the loop:

for(int index = 1; index < binary2.length(); index++)
{
    cout << (int)binary2[index];
}

// Can be changed too:

cout << binary2

Looking at your loops:

for(int i = (binary1.length() - 1); i <= (binary1.length() - 1); i--)

Does this even work?
It seems that i is getting smaller and smaller then goes negative.

It is easier to loop up and subtract in the range:

for(int loop = 0; loop < bianry1.length(); ++lop)
{
    std::cout << bianry1[binary1.length() - 1 - loop];
}

But the std containers (including string) provide iterators (and more importantly reverse iterators)

for(std::string::const_reverse_iterator loop = bianry1.rbegin(); loop != binary1.rend(); ++loop)
{
    std::cout << *loop;
}

Second loop:

for(int index = 1; index < binary2.length(); index++)

Problem here is that you are starting from 1. arrays/containers nearly everything is indexed from 0 and you can access the elements 0 -> (size() - 1). So here you are starting at the wrong point and going past the end of the string.

But as mentioned above you don't even need this as you can replace the loop.


You have created a good model overall and I can only suggest you some consideration.

Instead of using, created & lastModified.
I would recommend you to use timestamp option in mongoose.

const GAPFApplicationSchema = new Schema({
  facultyId: { type: Number, index: true },
  status: { type: String, enum: ["SUBMITTED", "BUDGET_ALLOCATED"] },
  attachedDocuments: [
    {
      name: String,
      link: String,
      attachedDate: Number
    }
  ]
}, {timestamp: true});

With this you won't need lastModified & created you will get 2 attributes createdAt & updatedAt and they would be handled by mongoose, so you wont have to worry about updating them.

status: { type: String, enum: ["SUBMITTED", "BUDGET_ALLOCATED"] },

you can also improve this piece of code, by changing it to number and create an internal mapping, this would allow mongoDB to search faster, as comparing string is much heavier task, than comparing numbers.


Nearest Neighbour classification algorithm

One helpful function is Data.Ord.comparing:

comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering
comparing p x y = compare (p x) (p y)

With this and using function composition you can write:

getMostCommon :: (Eq a) => [a] -> a
getMostCommon = head . maximumBy (comparing length) . groupBy (==)

Similar changes apply to several places.  Another small simplification could be changing (\x -> (fst x) == (snd x)) to uncurry (==).


Syntax Checker C++ Data Structure - Stack

Ok, first things first, there are a couple of formatting points that would make your code a little nicer to read:

Be consistent with your curly braces {}. In a couple of places, you have the opening brace on the same line as the thing before it whereas you don't in others.
Be consistent with your naming too. I would name your stack s because it fits better with the camelCase used elsewhere.
Spaces on your #include <header>s too please. It's just nitpicking but it's what most other programmers will be doing / used to.

That aside, lets get into the body of the code itself:

bool arePair(char, char) is very verbose in it's definition. You could turn the entire function into a single boolean expression of the form:

return (start == '(' && end == ')')
    || (start == '{' && end == '}')
    || (start == '[' && end == ']');

An alternative would be to use a switch statement:

switch (start) {

case '(': return end == ')';
case '{': return end == '}';
case '[': return end == ']';

default:
    return false;
}

What you choose is a matter of preference. I would probably go for the switch approach, however, because to me it is clearer what is intended.

areParanthesesBalanced is badly named. There is a typo in "parentheses" and parentheses refers specifically to () not {}, [] or <>. areBracketsBalanced would be more appropriate.
One idea would be to pass const std::string& exp to the function rather than std::string. This prevents the program having to make a copy of the entire string in case you modify it.
Your for loop for (int i = 0; i < exp.size(); i++) { ... } never actually makes use of the value of i. Instead you could use a range for like this for (char c : exp) which just gives you each character in turn.
Your else is unnecessary because you've already returned execution from the function at that point.
The line return s.empty() ? true : false; is bad because stack<>::empty() returns a boolean! Therefore, just use return s.empty();.

Overall this gives:

bool arePair(char start, char end)
{
    switch (start) {

    case '(': return end == ')';
    case '{': return end == '}';
    case '[': return end == ']';

    default:
        return false;
    }
}

bool areBracketsBalanced(const std::string& exp)
{
    std::stack<char>  s;
    for (char c : exp)
    {
        if (c == '(' || c == '{' || c == '[')
            s.push(c);
        else if (c == ')' || c == '}' || c == ']')
        {
            if (s.empty() || !arePair(s.top(), c))
                return false;
            s.pop();
        }
    }
    return s.empty();
}

But...

That covers a lot of smaller points but having constants defining your pairs of brackets in multiple places seems messy. Here's one possible solution but there might well be a nicer one I haven't thought of:

int isBracket(char c)
{
    switch (c) {

    case '(': return  1;
    case ')': return -1;

    case '{': return  2;
    case '}': return -2;

    case '[': return  3;
    case ']': return -3;

    default:
        return 0;
    }
}

bool areBracketsBalanced(const std::string& exp)
{
    std::stack<char>  s;
    for (char c : exp)
    {
        if (isBracket(c) > 0) // Opening brackets
            s.push(c);
        else if (isBracket(c) < 0) // Closing brackets
        {
            if (s.empty() || isBracket(s.top()) + isBracket(c))
                return false;
            s.pop();
        }
    }
    return s.empty();
}

Instead of printing fail...

You want to know the position of the failing bracket? Try changing the return type of areBracketsBalanced to int. You're already determining at what position it fails implicitly by returning false.


Idiomatic F# for iterating a seq and mapping whenever changes occur on a given selection

|> Seq.map(fun state -> fst state, snd state)

I think this last operation is unnecessary as it is a map from 'a * 'b to 'a * 'b (fst returns the first element in the tuple and snd the second).

If you want to get rid of the mutable variables, you can use Seq.mapFold instead:

let mapChange selector mapping seq =
    seq
    |> Seq.mapFold (fun (previous, change) item ->
        let currentValue = selector item
        match differentOrNew previous currentValue with
        | true ->
            let newChange = mapping item
            (item, newChange), (Some currentValue, newChange)
        | false ->
            (item, change), (previous, change)
    ) (None, def)
    |> (fst)


Display message that content depends on variable value

This answer applies only when you want to have well defined messages across whole application.

I would use neither.
Let me first explain why and then my proposition.

Critique

Assuming you are going to use your enum elsewhere some duplication might occur. Imagine souch example: you decided to use switch in some method in catch closure and this looks good because it is clean enough. However since you built an entire enum for simply displaying the message to the user you probably would want to use it in other method or class which is very handy.

What do I propose ?

I propose something what I like to call "descriptors", it is somewhat between dictionary and switch.
What would you do is create attributes over each enum with it's description :

public enum ExitCode {
    [Description("Success message")]
    Success = 0,
    [Description("Warning message")]
    Warning = 1,
    [Description("Error message")]
    Error = 2
}

and then add an extension method to your application (Source)

public static class EnumHelper
{
    public static string GetDesc(this ExitCode enumVal)
    {
        var type = typeof(ExitCode);
        var memInfo = type.GetMember(enumVal.ToString());
        var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
        return ((DescriptionAttribute)attributes[0]).Description;
    }
}

or similar. Hence you have beautiful alternative to your switch:

if(process.ExitCode == ExitCode.Success){
    CallSomeMethod();
}
Console.WriteLine(process.ExitCode.GetDesc());

Code is untested but you might get the idea. Furthermore, if you want to have more freedom with messages you can add second argument to extension method:public static string GetDesc(this ExitCode enumVal, string additionalComment)
and use it as such:

Console.WriteLine(process.ExitCode.GetDesc("More comment needed");


Calculating men's risk of getting coronary heart disease

Each of your if blocks are very similar. You basically the same thing in each if block. This a sign that you've got the conditionally at the wrong level. Instead of writing code that does:

If age category 1

Add points for age
Add points for cholestoral
etc

If age category 2

Add points for age
Add points for cholestoral
etc

etc

Write it like this:

Add points for age

Handle age category 1
Handle age category 2
etc

Add points for cholestoral

Handle age category 1
Handle age category 2
etc

etc

So adding the age points should look something like:

if( strAge.equals("20 to 34") ){ // Minus 7 points
    points = points - 9;
}
else if( strAge.equals("35 to 39") ){
    points = points - 4;
}
else if( strAge.equals("35 to 39") ){
    points = points - 4;
}
else if( strAge.equals("40 to 44") ){
    points += 0;
}
else if( strAge.equals("45 to 49") ){
    points += 3;
}
else if( strAge.equals("50 to 54") ){
    points += 6;
}
else if( strAge.equals("55 to 59") ){
    points += 8;
}
else if( strAge.equals("60 to 64") ){
    points += 10;
}
else if( strAge.equals("65 to 69") ){
    points += 11;
}
else if( strAge.equals("70 to 74") ){
    points += 12;
}
else if( strAge.equals("75 to 79") ){
    points += 13;
}

But doesn't that repeat the .equals way too much? Yes. But the repetition here is much simpler and easier to deal with then what you had before. So we prefer this. Once we have this we can simplify it.

The next key is to use data not code. That is, make lists of things and look them up rather then putting them in code.

static String [] ageCategories = {"20 to 34", "35 to 39", "40 to 44", "45 to 49", "50 to 54", "55 to 59", "60 to 64", "64 to 69", "70 to 74", "75 to 79"}
static int agePoints = {-9, -4, -4, 0, 3, 6, 8, 10, 11, 12, 13};

points += agePoints[Arrays.asList(ageCategories).indexOf(strAge)];

This looks up the age level and the points by looking in the arrays. No ifs required. You should basically not need to use any if statements whatsoever in this particular code. You should rewrite it to fetch everything out of arrays like this.

As the number of age ranges increases, it may be easier to work with a map because each point adjustment is matched up to its corresponding age range.

static final Map<String, Integer> pointsByAgeRange = new HashMap<>() {{
    put("20 to 34", -9);
    put("35 to 39", -4);
    ...
    put("75 to 79", 13);
}};

points += pointsByAgeRange.get(strAge);  // assumes range is in map


Insert and attach tag to the post in same time

Use the following:

 public function store(Request $request)
    {
        $input = $request->all(); //get inputs value

        $tag = $input['tag'];
        $tagdone = Tag::create(['name'=>$tag]);
        $tagid = $tagdone->id; //insert tag to tags table

        $posts = Posts::create($input); //insert posts table

        $posts->tags()->attach($tagid); //attach tag to the post
    }

This will reduce your database queries by one SELECT by removing Posts::find($postid).

Apart from the above, is there any reason for using three database tables? Just from the code provided it doesn't seem to be necessary and I would only use one table with all three inputs. Or at least reduce to two database tables as follows:

 public function store(Request $request)
    {
        $input = $request->all(); //get inputs value

        $tag = $input['tag'];
        $tagdone = Tag::create(['name'=>$tag]); //insert tag to tags table

        $input['tagid'] = $tagdone->id;

        $posts = Posts::create($input); //insert posts table, including tagid
    }


First of all, nice code, very readable and good comments.

There are several improvements you can do:

Reindex your dataframe with t. You are writing a lot of times .t, if you will use index some of pandas index optimization will kick in and your code will be faster.
Do not do concat on only 2 items. Concatenate function will work much faster if you will just do all of the concatenation of all 5 elements at once.
Why do you need h2? Try to avoid unnecessary coping of the data frame. You can work on the original h1 or even idat since your function does not change anything implicitly.
Use type annotations. Using type annotations can make the code run faster since the interpreter does not need to figure out what is the variable type. Also, probably even more important, it helps readability.


Honestly? It looks pretty straightforward. Everything in your code screams you've done this before. Good!

You're adhering to the standards of Python (the PEPs). The imports are at the exactly right places. The code is readable, easy to understand and does things the easiest way possible. In other words: it's Pythonic.

You could consider wrapping your print statements in main into a template so you'll only need one print call. However, since you only print once, I'm not sure how useful this would be in the end.

While your code is easy to understand, you might want to make the naming even better. You got 5 variables with the term edges in it, not even counting main where you use some of the exact names again. You're also overwriting cells_edges after the for after using it as a temporary variable. That's probably not the most maintainable way.

Single-character variable names should be avoided, even if they appear to be obvious.

d[f].append(k)

Yea, not a good idea. c, d, f and k should be renamed.


Generic Repository without Entity Framework

I think you are in the right direction but let me suggest some things.

Remove the try catch and let the repository throw the exception. Either that or catch and throw your own exception.

Inject IDbConnection in the constructor of the repository and remove the using on the repository methods

    private IDbConnection _connection;

    public CustomerRepository(IDbConnection connection)
    {
        _connection = connection;
    }

Probably you want to use the repository in this way in many scenarios and with your current implementation you lose the transaction scope.

    public void DoWork()
    {
        using (var connection = ...)
        {
            //begin transaction
            var repository = new CustomerRepository(connection);
            var otherRepository = new OtherRepository(connection)
            var customer = repository.GetById(2);
            //do some stuff
            otherRepository.Update()...
            repository.Delete(customer);
            //commit transaction
        }
    }

This can be combined with IoC container.


Generating strings dynamically in Python

You're pretty much reinventing urllib.parse.urlencode:

from urllib.parse import urlencode

def prepare_query_string(**kwargs):
    return urlencode([(key, value) for key, value in kwargs.items() if value is not None])

Usage being:

>>> prepare_query_string(active=1)
'active=1'
>>> prepare_query_string(active=1, user=None)
'active=1'
>>> prepare_query_string(active=1, user='bob')
'active=1&user=bob'
>>> prepare_query_string(file='foo.tar.gz', user='bob')
'file=foo.tar.gz&user=bob'
>>> prepare_query_string(file='foo.tar.gz', user='bob', active=None)
'file=foo.tar.gz&user=bob'
>>> prepare_query_string(file='foo.tar.gz', user='bob', active=1)
'file=foo.tar.gz&user=bob&active=1'


Python reimplementation of Lost In Space by Tim Hartnell

Nested functions

Not really sure what your motivation was, here, but this Russian nesting doll of functions is not really necessary. Under certain narrow circumstances, like limiting the number of publicly visible methods in a library, it might be called-for - but not really here. You don't need closures for this code, so just move things up to global namespace.

Variable case

A-C should be lower-case because they aren't types.

Random unpacking

a, b, c = (int(7*random() + 1) for _ in range(3))

Never except:

Currently, you can't Ctrl+C out of the program, because you're catching all exceptions. Narrow your exception type.

Don't materialize generators

D, E, F = [get_input(axis) for axis in "YXZ"]

should be

d, e, f = (get_input(axis) for axis in "YXZ")

because you don't need to keep that list in memory.

Format strings

print(str(D) + str(E) + str(F))

becomes

print(f'{d}{e}{f}')

Stack abuse

You call game, which calls end, which calls game... Don't do this. Just loop.


This is a bit faster

Public Function RepStr2(txt As String, str1 As String, str2 As String) As String

    RepStr2 = Join(Split(txt, str1), str2)

End Function

Light testing with about 300K cells in col A, output in col B:

RepStr2(CStr(arr(i, 1)), "a", "x")

Col A          | Col B
abcabcabc      | xbcxbcxbc
aaa            | xxx
aaaaaaaaa      | xxxxxxxxx
aaaaaaaaaaaaaa | xxxxxxxxxxxxxx
... (duplicated down to 300K)

After repeated tests all functions run faster

Your version: 2.039 secs
This version: 1.406 secs
MS version:   1.688 secs (bellow)

Edit (as pointed out by ThunderFrame in the comment)

Microsoft's version is fast as well:

Public Function RepStr3(sIn As String, sFind As String, sReplace As String, _
                        Optional nStart As Long = 1, Optional nCount As Long = -1, _
                        Optional bCompare As VbCompareMethod = vbBinaryCompare) As String

    Dim nC As Long, nPos As Integer, sOut As String

    sOut = sIn
    nPos = InStr(nStart, sOut, sFind, bCompare)

    If nPos = 0 Then GoTo EndFn:

    Do
        nC = nC + 1
        sOut = Left(sOut, nPos - 1) & sReplace & Mid(sOut, nPos + Len(sFind))

        If nCount <> -1 And nC >= nCount Then Exit Do

        nPos = InStr(nStart, sOut, sFind, bCompare)

    Loop While nPos > 0

EndFn:

    RepStr3 = sOut

End Function


The code doesn't fulfill the requirements. You are supposed to log the last N orders. Instead you log all of them. The old orders shall be removed from the list as it grows beyond N.

Bug. The list is initialized with the size being set to N. However, at the beginning it may contain less than N elements. In the scenario
  List is empty
  An order is added
  get_last(2) is called

the loop
  for (int j = 0; j < i - 1; j++)
  {
      current = current->prev;
  }

is guaranteed to access a null pointer.

The above loop complexity is \$O(N)\$.

All that said, I recommend to use not a list, but a circular buffer. No need to malloc anything, and get_last is executed in \$O(1)\$.


Code Style

Your code contains a few lines that accomplish nothing and obfuscate your intent:

    else:
        continue

If the conditional is false, you'll automatically continue on to the next iteration without having to tell the program to do that.

    return None

All Python functions implicitly return None. While PEP 8 appears to endorse this practice ("explicit is better than implicit"), it seems noisy to me.
num_lst = list(range(len(nums))) effectively generates a list of all the indices in the nums input list. Then, you immediately enumerate this list, which produces pairs of identical indices indx, num. If all you're attempting to do is iterate, this is significant obfuscation; simply call enumerate directly on nums to produce index-element tuples:

def twoSum(self, nums, target):
    for i, num in enumerate(nums):
        for j in range(i + 1, len(nums)):
            if num + nums[j] == target:
                return [i, j]

This makes the intent much clearer: there are no duplicate variables with different names representing the same thing. It also saves unnecessary space and overhead associated with creating a list from a range.
Following on the previous item, indx, num and num_lst are confusing variable names, especially when they're all actually indices (which are technically numbers).

Efficiency

This code is inefficient, running in quadratic time, or  \$\mathcal{O}(n^2)\$. Leetcode is generous to let this pass (but won't be so forgiving in the future!). The reason for this is the nested loop; for every element in your list, you iterate over every other element to draw comparisons. A linear solution should finish in ~65 ms, while this takes ~4400 ms.

Here is an efficient solution that runs in \$\mathcal{O}(n)\$ time:

hist = {}

for i, n in enumerate(nums):
    if target - n in hist:
        return [hist[target-n], i]
    hist[n] = i

How does this work? The magic of hashing. The dictionary hist offers constant \$\mathcal{O}(1)\$ lookup time. Whenever we visit a new element in nums, we check to see if its sum complement is in the dictionary; else, we store it in the dictionary as a num => index pair.

This is the classic time-space tradeoff: the quadratic solution is slow but space efficient, while this solution takes more space but gains a huge boost in speed. In almost every case, choose speed over space.

For completeness, even if you were in a space-constrained environment, there is a fast solution that uses \$\mathcal{O}(1)\$ space and \$\mathcal{O}(n\log{}n)\$ time. This solution is worth knowing about for the practicality of the technique and the fact that it's a common interview follow-up. The way it works is:

Sort nums.
Create two pointers representing an index at 0 and an index at len(nums) - 1.
Sum the elements at the pointers.

If they produce the desired sum, return the pointer indices.
Otherwise, if the sum is less than the target, increment the left pointer
Otherwise, decrement the right pointer.

Go back to step 3 unless the pointers are pointing to the same element, in which case return failure.

Be wary of list slicing; it's often a hidden linear performance hit. Removing this slice as the nested loop code above illustrates doesn't improve the quadratic time complexity, but it does reduce overhead.

Now you're ready to try 3 Sum!


Well, your code works, though it needs \$O(n)\$ space and \$O(n^2)\$ time.

It's also quite cleanly implemented, so kudos.

Still, there's naturally something which can be improved:

If you need a generic loop-index, the natural name is i. If you need a second one, ask for j. Yes, they are short, but they are the standard names, so you cannot get more descriptive.
Your additional array's name should reflect its use: Call it keys.
You have a general tendency for long names. Try to keep it as brief as you can without sacrificing clarity.
Avoid using a type with sizeof. If the receiving variable ever changes its type, you have to keep it in sync manually, and its not idiomatic. Use:

int* keys = malloc(arrayLength * sizeof *keys);

You assume that malloc() won't fail. You know assume makes an ass out of u and me?
Do you know that signed integer-overflow is Undefined Behavior? I didn't find anywhere in the problem-description a guarantee that array[i] * (i + 1) won't overflow, so you might want to use a bigger type for the keys.
Should you really write your own sub-standard sorting-algorithm, or can you use the one in the standard-library?

The following trades more extra-space for using qsort(), which should have \$O(n * \log(n))\$ runtime:

typedef struct pair {
    long long key;
    int value;
} pair;

static int sortByValueAndIndex_comp(const void* pa, const void* pb) {
    long long a = ((pair*)pa)->key;
    long long b = ((pair*)pb)->key;
    return (a > b) - (a < b);
}

int* sortByValueAndIndex(int* arr, int n) {
    assert(arr || !n);
    assert(INT_MAX <= LLONG_MAX / INT_MAX);
    pair* kv = malloc(n * sizeof *kv);
    if (!kv)
        return 0;

    for (int i = n; i-- > 0;) {
        kv[i].key = arr[i] * (i + 1LL);
        kv[i].value = arr[i];
    }

    qsort(kv, n, sizeof *kv, sortByValueAndIndex_comp);

    for (int i = n; i-- > 0;)
        arr[i] = kv[i].value;

    free(kv);
    return arr;
}


The code as it is, is fine. The biggest point is that you should perform the .split("=") only once:

String[] parts = terms[i].split("=");
keys[i] = parts[0];
values[i] = parts[1];

However there is a more general point: Why are you using arrays?

It's very unusual to use arrays at all in Java, especially in this case where you say yourself the input my be not well formed, possibly leaving you with gaps in the array, which you'll need to work around later. You should at least use Lists. Or even more fitting would be a Map (if the "keys" are unique):

String[] terms = query.split(",");
Map<String, String> map = new HashMap<String, String>(terms.length);

for (String term in terms)
{
    if(term.contains("="))
    {
        String[] parts = term.split("=");
        map.add(parts[0], parts[1]);
    }
}


Recursive function for listing directories

To relate your parent directories to their children, you could have plist declared like this:

static Dictionary<String, List<String>> plist = new Dictionary<string, List<string>>();

Each time you hit a child folder, you add its name to

Console.WriteLine("".PadLeft(start * 4, ' ') + item.Name);
string parent = path.Split('\\').Last();
if (!pList.Keys.Contains(parent))
    pList.Add(parent, new List<string>());
pList[parent].Add(item.Name);

Sorry, I don't have access to a C# compiler at the moment so I can't verify this 100%, but it's a starting point at least.

Edit: After thinking about it, I don't think C# likes it if you use [] before an element is in the Dictionary.  I edited the above code to include how to get the parent and included the Console.WriteLine so you know where I would put it.


Programming / detail review

Fan(Fan *peer__ = NULL);

  (and some more occurrences)

Identifiers that contain a double underscore are reserved for the compiler/libary ("C++ implementation").

The NULL macro can be thought of as deprecated. Use the nullptr keyword instead. It is more typesafe.

static Fan * create(Fan *peer = NULL);

Since those pointers you return from create own a resource (dynamically allocated memory / an object with dynamic storage duration), you should consider making them smart pointers:

static std::unique_ptr<Fan> create(Fan *peer = nullptr);

The function parameter can remain a raw pointer, since it does not convey/transfer ownership. One could argue that some dumb pointer wrapper that explicitly states it does not own a resource might be more appropriate.

Inproc(std::unique_ptr<Fan> bound__,
       std::unique_ptr<Fan> connected__);

In your original version, you used a std::unique_ptr<Fan>&&. Let's examine the alternatives:

void myfunc(std::unique_ptr<Fan>);
void myfunc(std::unique_ptr<Fan>&&);
void myfunc(std::unique_ptr<Fan>&);
void myfunc(std::unique_ptr<Fan> const&);

Only the first guarantees that the unique_ptr you pass in will be empty afterwards. All others do not, by means of (parameter) types, tell you what happens to your pointer. For more details, see the solution of GotW #105: Smart Pointers, Part 3

If you want to always acquire ownership of the pointer argument, you should define your interface using pass-by-value for unique_ptrs.

Let's see how we can refactor Inproc::create() using these changes:

unique_ptr<Inproc> Inproc::create() {
    if (auto bound = Fan::create() ) {
        if (auto connected = Fan::create(bound.get())) {
            return new(std::nothrow) Inproc(std::move(bound), std::move(connected));
        }
    }
    return nullptr;
}

Note that by returning nullptr in all cases of an error, you lose information about what error occurred.

Design review

private:
    Fan(Fan *peer__ = NULL);

Derived classes can only copy a Fan, they cannot create a new one. This seems contradictory to the virtual dtor, which seems to provide "support" for inheritance.

static Fan * create(Fan *peer = NULL);

From the code shown, it is unclear to me why you need to restrict Fans to be created via this factory function (is there a pattern name for this?). It certainly decreases reusability of this class.

For Inproc::create(), the situation could even be worse: You cannot test Inproc independently of Fan, since you can't provide some kind of mocked Fan to construct it. Also, it doesn't seem to require the dynamic storage duration of its unique_ptr subobjects; but again, we don't see the whole program here.

nwp's answer reminded me that you might use pointers to indicate an error. I think that is not a good reason to require dynamic storage duration (-> new + pointers). One solution could be a factory function that returns an optional, or that creates objects in-place at a location passed as a parameter. The former can even be used easily for aggregation; neither can easily be used for inheritance. Another option is to introduce an empty / error state, that the object is set to if construction fails. I don't really like the idea of "empty states" for a class, since those weaken the guarantees / invariants it can provide. But it's a common sight to be able to implement e.g. default constructors. Look at std::thread, std::Xstream etc. - they all have default constructors, even though they leave the object in an almost unusable state.


First-come first-serve job scheduling algorithm

I think this question would actually benefit from both a C review (just change the cout's to printf, etc) and a C++ review since you seem to be using a very C-orientated programming style.

This post will be a C++ review.
Please note that the Turbo C++ compiler is not available to me, so my suggestions will revolve around the C++98/03 standard.

My first bit of advice would be to switch to an object-oriented approach.
Turn process into a class and create a second class, process_queue.

In process, replace char name [32] with std::string name. This way, you don't have to worry about buffer overflows.

Refactor inc(), pop(), and addnode() into member functions for the new class process_queue.

Make pop() return a process instead of an int. This is because you have a queue of processs, not a queue of ints.

Rename inc() to something more readable like increment_all_wait_times(). That's a long name, but your code will be self-documenting.

Take out the user-input logic from inc(), pop(), and addnode().
This will improve their flexibility.
A function should only do one thing, and do it well.

For function parameters, prefer the use of references over the use of pointers.
This will save you from having to check for NULL.

Here is an idea of what a process class might look like:

class process
{
public:
    process (const std::string &name, const int burst_time = 0, const int wait_time = 0) ;

    // getters
    std::string name () const ;
    int burst_time () const ;
    int wait_time () const ;
    const process* next () const ;
    process* next () ;

    void decrement_burst_time (const int time) ;

private:
    int burst_time_;
    int wait_time_;
    std::string name_;
    process *next_;

    friend  std::ostream& operator<< (std::ostream &os, const process &proc) ;
    friend class process_queue ;
};

This would encapsulate your variables and (for the most part) make them read-only.
Because the process_queue class is tightly coupled with this class, I would make it a friend class. There are two versions of the next() method for the sake of const-correctness.

Here is an idea of what a process_queue class might look like:

class process_queue
{
public:
    process_queue () ;
    ~process_queue () ;

    bool empty () const ;
    void add_node (const process &proc) ;
    void increment_all_wait_times (const int wait) ;
    process pop () ;
    size_t size () const ;

    friend std::ostream & operator<< (std::ostream &os, const process_queue &pq) ;

private:
    size_t size_ ;
    process *head_;
    process *tail_; // for O(1) insertions
};

This, once again, encapsulates your variables while still providing useful functionality.

Here's what a constructor implementation might look like:

process::process (const std::string &name, const int burst_time, const int wait_time)
    : name_ (name), burst_time_ (burst_time), wait_time_ (wait_time), next_ (NULL)
{
}

What you see here is a constructor initialization list. It is important to initialize your variables or else you may suffer from subtle bugs.

Here is a destructor for the process_queue class:

process_queue::~process_queue ()
{
    while (size_ > 0) {
        this->pop () ;
    }
}

This makes sure all of our resources (memory in this case) are cleaned up when an instance of this class goes out of scope. This strategy is called RAII. RAII is important for writing exception-safe code.

Here is an example implementation of all of the above combined (somewhat sloppily):

#include <iostream>
#include <string>
#include <stdexcept>

class process_queue ;

class process
{
public:
    process (const std::string &name, const int burst_time = 0, const int wait_time = 0) ;

    std::string name () const ;
    int burst_time () const ;
    int wait_time () const ;
    const process* next () const ;
    process* next () ;

    void decrement_burst_time (const int time) ;

private:
    int burst_time_;
    int wait_time_;
    std::string name_;
    process *next_;

    friend  std::ostream& operator<< (std::ostream &os, const process &proc) ;
    friend class process_queue ;
};

process::process (const std::string &name, const int burst_time, const int wait_time)
    : name_ (name), burst_time_ (burst_time), wait_time_ (wait_time), next_ (NULL)
{
}

std::string process::name () const
{
    return name_ ;
}

int process::burst_time () const
{
    return burst_time_ ;
}

int process::wait_time () const
{
    return wait_time_ ;
}

const process* process::next () const
{
    return next_ ;
}

process* process::next ()
{
    return next_ ;
}

void process::decrement_burst_time (const int time)
{
    burst_time_ -= time ;
}

std::ostream & operator<< (std::ostream &os, const process &proc)
{
    os  << "{Name = " << proc.name ()
        << ", Wait time = " << proc.wait_time ()
        << ", Burst time = " << proc.burst_time ()
        << ", Next = " ;

    if (proc.next () != NULL) {
        os << proc.next ()->name () ;
    }

    else {
        os << "None" ;
    }

    os << "}" ;

    return os ;
}

class process_queue
{
public:
    process_queue () ;
    ~process_queue () ;

    bool empty () const ;
    void add_node (const process &proc) ;
    void increment_all_wait_times (const int wait) ;
    process pop () ;
    size_t size () const ;

    friend std::ostream & operator<< (std::ostream &os, const process_queue &pq) ;

private:
    size_t size_ ;
    process *head_;
    process *tail_; // for O(1) insertions
};

process_queue::process_queue () : head_ (NULL), tail_ (NULL), size_ (0)
{
}

void process_queue::add_node (const process &proc)
{
    process *temp = new process (proc) ;

    if (tail_ != NULL) {
        tail_->next_ = temp ;

        if (head_ == tail_) {
            head_->next_ = temp ;
        }

        tail_ = tail_->next_ ;
    }

    else {
        tail_ = temp ;
        head_ = tail_ ;
    }

    ++size_ ;
}

void process_queue::increment_all_wait_times (const int wait)
{
    process *temp = head_ ;

    while (temp != NULL) {
        temp->wait_time_ += wait ;
        temp = temp->next_ ;
    }
}

// Pops the head off.
process process_queue::pop ()
{
    if (head_ == NULL) {
        throw std::range_error ("process_queue::pop() called while the process_queue was empty.") ;
    }

    process ret = *head_ ;
    process *temp = head_ ;
    head_ = head_->next_ ;
    delete temp ;
    --size_ ;

    return ret ;
}

bool process_queue::empty () const
{
    return (size_ == 0) ;
}

size_t process_queue::size () const
{
    return size_ ;
}

std::ostream & operator<< (std::ostream &os, const process_queue &pq)
{
    process *temp = pq.head_ ;

    while (temp != NULL) {
        os << *temp << "\n" ;
        temp = temp->next () ;
    }

    return os ;
}

process_queue::~process_queue ()
{
    while (size_ > 0) {
        this->pop () ;
    }
}

namespace scheduler
{
    void run_first_come_first_serve (process_queue &pq)
    {
        std::cout << "Running first-come-first-serve scheduler with no preemption." "\n" ;

        while (pq.empty () == false) {
            process proc = pq.pop () ;

            std::cout << "Running " << proc.name () << "\n" ;

            std::cout << proc.name () << " finished running after " << (proc.burst_time () + proc.wait_time ()) << " ns." "\n" ;
            pq.increment_all_wait_times (proc.burst_time ()) ;

            std::cout << "Queue:\n" << pq << "\n" ;
        }
    }
}

int main(void)
{
    process notepad ("notepad.exe", 500) ;
    process firefox ("firefox.exe", 1500) ;
    process excel ("excel.exe", 100) ;
    process visual_studio ("visual studio.exe", 200) ;
    process super_virus ("super virus.exe", 1000) ;

    process_queue pq ;
    pq.add_node (notepad) ;
    pq.add_node (firefox) ;
    pq.add_node (excel) ;
    pq.add_node (visual_studio) ;
    pq.add_node (super_virus) ;

    scheduler::run_first_come_first_serve (pq) ;

    return 0 ;
}


As you found yourself, this has to work.

I only have 2 minor nitpickings:

Do not use console.log() in production code..
You are not using element and attrs, you might as well declare function($scope)

Very nice code.


Codeigniter - in the view or in the controller?

These 0, 4 and 7 means nothing to any code reader, nor 1, 2 and 3 for the label.

Move this logic in the controller and consider using ENUMs in your controller class i.e.:

const BADGE_IMPORTANT = 0;
const BADGE_INFO = 4;
const BADGE_WARNING = 7;

This way it will be more readable for the one who will read and change it later, also it will became less hard changable and more reusable.

Also, try to not echo HTML, I mean, use PHP blocks only when you have PHP in it. HTML should be outside:

<?php foreach ($solicitud as $key => $value): ?>

              <span class="label label-sm<?=$label;?>"><?=ucfirst($value['status']);?>
              <span class="badge <?=$class;?>"><?=$value['priority'];?>
              <?=$value['sname'].$value['last_name'];?>
              <?=$value['name'];?>
               ....

<?php endforeach; ?>


Only a quick shot at AssembleMEFComponents() method

declare your variables as near to their usage as possible.
using try..catch like you do is not only superfluous but also breaks the stacktrace.
comments like //Add to the aggregate catalog are superfluous too. Comments should describe why something is done in the way it is done. What is done should be described by the code itself by using meaningful and descriptive name for methods, variables and classes.

That being said your method should look like so

public void AssembleMEFComponents()
{

    var directoryCatalog = new DirectoryCatalog(directoryPath, "*.dll");

    var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

    var aggregateCatalog = new AggregateCatalog();
    aggregateCatalog.Catalogs.Add(directoryCatalog);
    aggregateCatalog.Catalogs.Add(assemblyCatalog );

    var container = new CompositionContainer(aggregateCatalog);

    container.ComposeParts(this);
}


Prevent Double Form Submit within X seconds

Regarding the global variable, you're already using jQuery so why not just attach an attribute or class to the form?

jQuery.fn.preventDoubleSubmit=function(duration) {
    duration = duration || 1984;
    jQuery( this ).submit( function() {
        if ( this.hasClass("locked") ) return false;
        jQuery(this).addClass("locked");
        that = this;
        setTimeout(function() {
            jQuery(that).removeClass("locked");
        }
        , duration );
    });
};

You may want to change the class name to something a little more unique, but that should work.


Javascript to change element property based on user input

As you have already stated passing an HTML string is not the best way to create a new DOM element. You can create a new one using plain Javascript, like this:

var newDiv = document.createElement('div');

and together with few changes to your code, function could look similar to this:

function generateGrid(numGrid) {
    var squareSize = $('.grid_container').height() / numGrid;
    var $square = $(document.createElement('div')); // we create and fetch a new element

    // here come some handy methods from jQuery, please check'em out on jquery.com
    $square.width(squareSize).height(squareSize).addClass('square');
    $('.grid_container').append($square);
}

generateGrid(4);

Hope this will help you!


There is no need to use an image to give the wrapper the neccesary height to contain the responsive video. I loaded the image in my browser and found that its dimensions are 75*134, using this we can set the height of the wrapper with a little trick.

HTML code:

CSS code:

.video-wrapper {
  position: relative;
}
.video-wrapper::after
{
  content : ' ';
  display : block;
  padding-top: 55%; /* 100*75/134 % proportional to the width of the parent */
}
.video-wrapper iframe,
.video-wrapper object,
.video-wrapper embed,
.video-wrapper video {
  width: 100%;
  height: 100%;
  position: absolute;
  display: block;
  top:0;
  z-index:1; /* there is no need of this z-index property */
}

If you need more information about this "trick", refer to this post: https://stackoverflow.com/questions/22673008/css-make-div-width-proportional-to-height

If you know the correct proportion, you'll be able to make it responsive.

And no, there is no problem, it's your layout ;)

Regards.


Overall, this is a nice, clean solution, congratulations!

Performance

  Can you suggest If I can do away with looking up twice. Currently this solution only runs better that around 36% of the other submissions for this current problem. So, I believe there must be a better and faster way.

"Looking up twice" is not the appropriate term. You do one lookup by key, and another lookup by value. These are very different operations, and lumping them together as "two lookups" hides important details. Imagine a program that does one lookup in an array and one lookup with a Google search on the internet, and the author would wonder if slowness might be caused by doing "two lookups". It would hide a crucial detail that one of the "lookups" is clearly much slower than the other.

The lookup in the dictionary by key is very fast, an \$O(1)\$ operation.

The lookup by value in a typical dictionary (or hash map) implementation is much slower, \$O(n)\$, because dictionaries are indexed by key, not by value. They are designed for fast lookups by key, not by value.

To make the lookup by value faster, you can add a set for values.

Scope

It's good to limit the scope of variables to the minimum needed.

matchstr should be declared inside the loop, as it is not needed outside
mapPattern should be initialized after the early return, as it might not be needed


Using JavaScript promises to display weather and location information

$.when(getPosition())

$.when is only used when listening to multiple promises. Since getPosition is just one and it already returns a promise, $.when isn't required and you can simply chain then to getPosition().

var getWeather = function(position) {

  return $.getJSON('https://api.forecast.io/forecast/{APIKEY}/' + position.coords.latitude + ',' + position.coords.longitude + '?callback=?')
     .then(function(data) {
        return data;
    });

}

var getLocationName = function(position) {

  return $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&key={APIKEY}')
    .then(function(data) {
        return data;
  });

}

Attaching then which just returns the resolved data data is unnecessary. $.getJSON already returns a promise-like object that resolves to data. Any then attached to it will get data in the same way this then receives it.

Additionally, suggesting you use then instead of the jQuery-specific done. then is standard, and allows you to easily move over to the standard Promises.

I usually recommend pushing off the "flow logic" of promises to the caller instead of spreading it across different functions. This allows you to easily write functions as promise-returning operations while keeping all the "flow logic" in one place.

On other stuff, suggesting you move the url into a variable. This keeps your AJAX operation short and free from the string concatenation madness. A;so recommending using named function instead of function expressions. They're easier to debug as their names appear in the stack trace.

Your code could be simplified into:

function getPosition () {

  return $.Deferred(function(deferred){
    navigator.geolocation.getCurrentPosition(deferred.resolve, deferred.reject);
  }).promise();

};

function getWeather (position) {
  var url = 'https://api.forecast.io/forecast/{APIKEY}/' + position.coords.latitude + ',' + position.coords.longitude + '?callback=?'
  return $.getJSON(url);
}

function getLocationName (position) {
  var url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&key={APIKEY}';
  return $.getJSON(url);
}

$(document).ready(function() {

  getPosition().then(function(position){

    return $.when(getWeather(position), getLocationName(position));

  }).then(function(weatherData, locationData){

    $('#userLocation').text(locationData.results[3].formatted_address);
    $('#weatherDescription').text(weatherData.currently.temperature);
    $('#temperature').text(weatherData.currently.summary);

  });

});

If you can write using ES6, the code becomes simpler and you can drop the jQuery dependency for the data gathering functions. ES6 now has native promises as well as template strings, and modern browsers have fetch. This reduces jQuery footprint to only the DOM-interacting operations.

function getPosition() {
  return new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition(resolve, reject));
};

function getWeather(position) {
  const url = 'https://api.forecast.io/forecast/${APIKEY}/${position.coords.latitude},${position.coords.longitude}?callback=?';
  return fetch(url).then(response => response.json());
}

function getLocationName(position) {
  const url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.coords.latitude},${position.coords.longitude}&key=${APIKEY}';
  return fetch(url).then(response => response.json());
}

$(document).ready(function() {

  getPosition()
    .then(position => Promise.all(getWeather(position), getLocationName(position)))
    .then(function(data){
      const weatherData = data[0];
      const locationData = data[1];

      $('#userLocation').text(locationData.results[3].formatted_address);
      $('#weatherDescription').text(weatherData.currently.temperature);
      $('#temperature').text(weatherData.currently.summary);
    });

});


There could be smarter ways to write your code in such a way that it would scale better (for instance, if you were to consider squares of side 4 or 5, you'd have 16 or 25 nested loops and local variables to handle).

First thing first, let's try to see what can easily be improved in your code.

You are considering all matrices of the following form :

 a b c
 d e f
 g h i

by making the different values go from 0 to t (included) and then check that a+b+c == d+e+f == g+h+i == a+d+g == b+e+h == c+f+i. However, things could be done in a much faster way : once a and b are fixed, you know that c == t - (a+b). Similarly, you can define f as t - (d+e). Then you can go one step further as g, h and i can also be determined using column values.

Once, this is done, the corresponding code becomes :

int main()
{
    int n=3,t=5;
    int total_num=0;
    for(int a=0;a<=t;a++)
    {
        square[0][0]=a;
        for(int b=0;b<=t;b++)
        {
            square[0][1]=b;
            int c = t - (a+b);
            if (c>=0)
            {
                square[0][2]=c;
                for(int d=0;d<=t;d++)
                {
                    square[1][0]=d;
                    for(int e=0;e<=t;e++)
                    {
                        square[1][1]=e;
                        int f = t - (d+e);
                        if (f >= 0)
                        {
                            square[1][2]=f;
                            int g = t - (a+d);
                            if (g >= 0)
                            {
                                square[2][0]=g;
                                int h = t - (b+e);
                                if (h >= 0)
                                {
                                    square[2][1]=h;
                                    int i = t - (g+h);
                                    assert(i == (t - (c+f)));
                                    if (i >= 0)
                                    {
                                        square[2][2]=i;
                                        if(final_check(n,t))  //check
                                        {
                                            display(n);
                                            total_num++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    cout<<"total number of semi magic square: "<<total_num<<endl;
    return 0;
}

Once this is done, the final_check method becomes useless as all the generated squares are "magic".

Something else could easily be improved : you shouldn't use global variables as they make things hard to follow. In your case, it is quite easy to get rid of it. I also take this chance to re-organise the different loops/checks and change the limits for the loops so that we do not need to check that values are in the right ranger afterwards :

void display(int a, int b, int c, int d, int e, int f, int g, int h, int i)
{
    cout << a << "\t" << b << "\t" << c << endl;
    cout << d << "\t" << e << "\t" << f << endl;
    cout << g << "\t" << h << "\t" << i << endl;
    cout <<"************"<<endl;
}

/*
   a b c
   d e f
   g h i */

//count $H_3(1)$
int main()
{
    int t=5;
    int total_num=0;
    for(int a=0;a<=t;a++)
    {
        for(int b=0;b<=t-a;b++)
        {
            int c = t - (a+b);
            assert(c>=0);
            for(int d=0;d<=t-a;d++)
            {
                int g = t - (a+d);
                assert(g >= 0);
                for(int e=0;e<=t-d && e<=t-b;e++)
                {
                    int f = t - (d+e);
                    assert(f >= 0);
                    int h = t - (b+e);
                    assert(h >= 0);
                    int i = t - (g+h);
                    assert(i == (t - (c+f)));
                    if (i >= 0)
                    {
                        display(a, b, c, d, e, f, g, h, i);
                        total_num++;
                    }
                }
            }
        }
    }
    cout<<"total number of semi magic square: "<<total_num<<endl;
    return 0;
}

A few last things I'd like to tell :

using namespace std; is sometimes considered a bad practice. Some might say it is ok in a cpp file (by opposition to header file)
one could easily do with a few more comments
I am quite surprised that your code seems to assume that t is known.

This is as far as I can go re-using your code. A more interesting approach would use backtracking. You should be able to find already implemented algorithms using it to generate magic squares.


How to parse arrays back and forth to function in a smart way

My question is this, how can I do this smarter?
statsArray = pushStats(aa, bb, cc, statsArray);

Is this the only way to do this? To send statsArray back and forth like this?

This question is the result of a misunderstanding: You're not "passing [the array] back and forth." Arrays are objects. Variables don't directly contain objects, they contain a value called an object reference which says where the object is elsewhere in memory. So what you're doing is passing that object reference into your function and returning that reference out of it. The actual array isn't passed into and out of the function.
Since you're not changing the value of statsArray in your function (you're just changing state the object it refers to contains), you don't need to return it, and you don't need to assign that return value. Just remove the return statsArray; from the end of the function and
var statsArray = [];
pushStats(r, htmlRecp, '', statsArray);
pushStats(e, '', htmlExpe, statsArray);
// ...

Let's explain why that works:
After this line
var statsArray = [];

in memory you have this:

                    +−−−−−−−−−−−+
statsArray−−−−−−−−−>|  (Array)  |
                    +−−−−−−−−−−−+
                    | length: 0 |
                    +−−−−−−−−−−−+

The variable statsArray contains an object reference for the array, which exists elsewhere in memory. (An object reference is a bit like a memory address.)
That means that during the first call:
pushStats(r, htmlRecp, '', statsArray);

...the statsArray parameter contains that same reference, and both the variable and the parameter refer to the same array:

                            +−−−−−−−−−−−+
statsArray−−−−−−−−−−−+−−−−−>|  (Array)  |
                    /       +−−−−−−−−−−−+
                    |       | length: 0 |
                    |       +−−−−−−−−−−−+
+−−−−−−−−−−−−−−−−+  |
| (Call Context) |  |
+−−−−−−−−−−−−−−−−+  |
| statsArray     |−−+
| ...            |
+−−−−−−−−−−−−−−−−+

Changes that pushStats makes to the state of the array change the array, not the reference. So if pushStats pushes a new entry onto the array, you get this:

                            +−−−−−−−−−−−+
statsArray−−−−−−−−−−−+−−−−−>|  (Array)  |
                    /       +−−−−−−−−−−−+
                    |       | length: 0 |      +−−−−−−−−−−+
                    |       | 0         |−−−−−>| (Object) |
+−−−−−−−−−−−−−−−−+  |       +−−−−−−−−−−−+      +−−−−−−−−−−+
| (Call Context) |  |                          | ...      |
+−−−−−−−−−−−−−−−−+  |                          +−−−−−−−−−−+
| statsArray     |−−+
| ...            |
+−−−−−−−−−−−−−−−−+

After the call returns, the call context is cleaned up, and you have

                    +−−−−−−−−−−−+
statsArray−−−−−−−−−>|  (Array)  |
                    +−−−−−−−−−−−+
                    | length: 0 |      +−−−−−−−−−−+
                    | 0         |−−−−−>| (Object) |
                    +−−−−−−−−−−−+      +−−−−−−−−−−+
                                       | ...      |
                                       +−−−−−−−−−−+

The key thing here is that the array is an object, and pushStats just changes the state of that object, via the reference you pass into it.

Side note: You can make the function a bit more efficient using Array#find instead of Array#filter:
function pushStats(currKey, lineRecp, lineExpe, statsArray){
    var selectStats = statsArray.find(function(obj){
        return obj.key == currKey
    });
    if (!selectStats) {
        statsArray.push(
            {
                'key'       : currKey,
                'receipt'   : lineRecp,
                'expense'   : lineExpe
            }
        );
    } else {
        if (lineRecp) {
            selectStats.receipt = lineRecp;
        } else {
            selectStats.expense = lineExpe;
        }
    }
    return statsArray;
}

It needs a polyfill for obsolete browsers, but it has the advantage that it doesn't create an unnecessary array, and stops looping through statsArray as soon as it finds the entry you want.


Building a string with only two repeating characters

Your algorithm has a flaw - it's too greedy. Take this example:
Foo(6, 2) // "AABBAAAA"

Alas, it should return "AABAABAA".
In terms of a review, your method shouldn't be called Foo - give it a descriptive name.
Great use of StringBuilder. You could initialize the length to a+b in the constructor as you know what size your finished string will be.
Expression bodied members can greatly improve readability in my opinion:
static char SwapChar(char c) =>
    c == 'A' ? 'B' : 'A';

Try to avoid variables like flag. I had to read the whole loop before I knew what that variable meant. I'd call it something like repeatCount.


C code to reset all usb devices (because ubuntu laptop disables usb mouse after sleep)

Use consistent indentation
I don't know if the indentation style of the code you pasted here is as you wrote it, but if it looks the same in your code editor, you should definitely try to fix it and make it more consistent. I would not bother trying to fix this manually, instead use either code formatting functions of your editor, or use an external tool such as GNU indent, ClangFormat or Artistic Style to reformat your source code.
Return a non-zero exit code on error
When you encounter an error you call perror(), which is great, but then you let the program continue to run, and eventually you will always return 0. It would be better if your program would return a non-zero exit code when it has encountered an error, in particular return EXIT_FAILURE, which is declared in <stdlib.h>.
Don't hardcode the USB bus number
You only open USB bus 1. What if you attach your mouse to a different USB port, which might be on a different bus? I would make it so that the USB bus number has to be passed as a command line option. This makes the program a lot more flexible.
Beware of buffer overflows
While arguably the /dev/bus/usb pathnames can never be longer than 255 bytes, it is bad practice to make any assumptions. At the very least, make sure you never overflow this buffer, by using strncpy() and strncat() instead of strcpy() and strcat() (read the documentation of these functions carefully and be aware what happens if the destination buffer is not large enough to hold the input), or use snprintf(). However, there is another way to sidestep this issue entirely:
Avoid the need for concatenating paths
Instead of manipulating filename all the time, you can avoid all this by calling chdir() to go into the USB bus's directory, like so:
if (chdir("/dev/bus/usb/001/") == -1) {
    perror("Error accessing USB bus directory");
    return EXIT_FAILURE;
}

DIR *d = opendir(".");

if (!d) {
    perror("Error reading USB bus directory");
    return EXIT_FAILURE;
}

struct dirent *ent;

while ((ent = readdir(d)) != NULL) {
    int fd = open(ent->d_name, O_WRONLY);
    ...

Declare variables as close as possible to where they are used
In C99 and later, you can declare a variable anywhere. It is considered good practice to declare a variable close to where it is used, and ideally you also declare and initialize it in one go. I've used this in the example above.


Calculator for area and perimeter of a window

Typos / Spelling issue

Attention to detail is important.  Spelling errors, in variable names + strings should be avoided.  They give a bad impression.  You have several.  mininium should be minimum, maxuimum should be maximum, Sentences should start with a capital letter etc.

Be clear with the user

You ask the user for the width/height of the window, however you don't tell the user what unit the measurements are in. Your original code you were converting to feet (by multiplying by 3.25).  If you're going to do something like this, consider defining a constant with a name that reflects what it is, FeetPerMetre for example (Constants should be in Pascal, not ALL_CAPS naming).  You also haven't told the user the min/max values either when you prompt for input, or when you decide to use them.

Contain your functionality

The code you've posted is all in a single block.  It doesn't appear to have been wrapped in a function, suggesting that it's just sitting in a static main somewhere.  Think about what elements the code contains and break it out into functions that you might be able to reuse.  Some possible functions might be:

int GetLengthFromUser(string prompt, double minLength, double maxLength)
double CalculateWindowFrameLength(double width, double length)
double CalculateWindowPaneArea(double width, double length)
double ConvertFeetToMetres(double length)

Interpolated Strings

Depending on the C# version you're using, you may be able to use interpolated strings which can things like WriteLine statements look a bit cleaner:

Console.WriteLine($"The lenth of the wood is {woodLength} feet");

double.Parse / Convert.ToDouble

Both methods can fail and throw an exception if the user enters something other than a number (which will inevitably happen eventually).  Consider using TryParse and re-prompting the user when it fails.


Search through multiple lists, but have functions that do that in parts

I would suggest that you don't use a repository at all. You already have a library that handles abstracting the database. You don't need the repository abstraction. And if you need some kind of abstraction, use a query object.

Some extensions are handy to build the query:

public static class AddressQueryExtensions
{
    public static IQueryable<Address> WhereStreetContains(this IQueryable<Address> query, string street)
    {
        return query.Where(address => address.Street.Contains(street));
    }

    public static IQueryable<Address> WhereCityContains(this IQueryable<Address> query, string city)
    {
        return query.Where(address => address.City.Contains(city));
    }

    public static IQueryable<Address> WhereStateContains(this IQueryable<Address> query, string state)
    {
        return query.Where(address => address.State.Contains(state));
    }

    public static IQueryable<Address> WhereZipContains(this IQueryable<Address> query, string zip)
    {
        return query.Where(address => address.Zip.Contains(zip));
    }
}

These can be combined however you want:

var addresses = DbSet
    .WhereStreetContains(street)
    .WhereCityContains(city)
    .WhereZipContains(zip)
    .Where(x => x.State == null)
    .ToList();

Some reading regarding repositories and ORMs.

https://lostechies.com/jimmybogard/2012/09/20/limiting-your-abstractions/
https://lostechies.com/jimmybogard/2012/10/08/favor-query-objects-over-repositories/
https://ayende.com/blog/3955/repository-is-the-new-singleton


Getting the average score for hotel scores in different countries using pandas

You should probably use pandas.DataFrame.groupby.

The string manipulations to extract the countries can also be simplified using pandas.DataFrame.str methods.

import pandas as pd

# Reading original hotel reviews dataset.
# Reduce dataframe to two columns: 'Hotel_Address' and 'Average_Score'.
df = pd.read_csv(DATASET_PATH).loc[:, ["Hotel_Address", "Average_Score"]]

# Extract country from address
df["Country"] = df.Hotel_Address.str.split().str[-1]
df.drop(columns=["Hotel_Address"], inplace=True)

# Get average average score per country, rounded to two decimal places
print(df.groupby("Country").mean().round(2))


Constructing MongoDB document from a dict with character code-to-integer translation

If all attributes are in item, then you can create an instance simply with:

s = ScoreDetail(**item)

This is just a guess though. Your code looks like Django, where this would work, but even though this isn't Django, I suspect this to be supported similarly.

Without a friendly framework to convert between objects and json, you could use the serialization/deserialization features of the json package, with custom serializer/deserializer implementations.