Function figuring out which close-by value comes from which input value

A couple of low-hanging fruit inefficiencies:

distance = dict().  The distance[k] value is computed in a loop, and only every used in the next statement of the loop.  It does not need to be stored in a dictionary.
all([ ...list comprehension... ]): You are using list comprehension to build up a list, which you immediately pass to all(...).  There is no need to actually create the list.  Just use all(...list comprehension...).
set1 = set(value).  This is inside a for val in other_values: loop, where value and set1 are not changed.  Move the statement out of the for loop, to avoid recreating the same set each iteration.
len_values is only used in the afore mentioned all(...), and only the the values of len_values dictionary are used.  As such, the len_value dictionary construction is also unnecessary, and the if statement can be written:

if all(len(val) <= 1 for val in alt_identification.values()):

Since you are returning alt_identification from the if statement, and after the if...else statement, you can invert the test, and remove one return statement:

if any(len(val) > 1 for val in alt_identification.values()):
    for key, value in alt_identification.items():
        # ... omitted for brevity ...

return alt_identification

Similarly, the two if condition: continue else: could be re-written if not condition:.

Other possible improvements:

tolerances[k] is only used in next for k loop.  The list can be removed and the calculations move into the loop.
numpy is only used for a list(np.where([...])[0]) operation, which is fairly obfuscated.  A simple list comprehension can be used instead.
The values of alt_identification are of type list, and converted (repeatedly) into a set() in the "control & correct" code.  They could be stored as set() to avoid repeated conversions.

Here is my rework of the code, with the changes based on above comments:

def traceback(tuple_node, tuple_node_alt):

    def close_alternates(x):
        tolerance = (0.1 if x <= 100 else 0.2) + 0.00001
        return set( k for k, alt_x in enumerate(tuple_node_alt)
                    if abs(alt_x/x - 1) <= tolerance )

    alt_identification = { x: close_alternates(x) for x in tuple_node }

    if any(len(val) > 1 for val in alt_identification.values()):
        for key, values in alt_identification.items():
            if len(values) > 1:
                other_values = [val for k, val in alt_identification.items() if k != key]
                if values not in other_values:
                    for other in other_values:
                        alt_identification[key] -= other

    return alt_identification

I'm getting up to a 2.8x speedup with the above code, on your test data set that require correction.


I believe you are overcomplicating things. Declaring a prototype, will not make your code any more robust or even faster. I'm sure you know, but actually something like the code below will be easier to read, more effective and also faster.

/**
 *    View_message
 *    Object Model
 */
var ViewMessage = function(div) {
    this.div = document.getElementById(div);

    this.messages = {
        empty: 'Please complete all fields',
        empty_bm: 'Please enter both a title and url',
        name: 'Only letters or dashes for the name field',
        email: 'Please enter a valid email',
        same: 'Please make emails equal',
        taken: 'Sorry that email is taken',
        pass: 'Please enter a valid password, 6-40 characters',
        validate: 'Please contact support to reset your password',
        url:  'Pleae enter a valid url'
    };

    this.display = function(type) {
        this.div.innerHTML = this.messages[type];

        return this;
    };

    return this;
};

Then two ways of doing this:

var view = new ViewMessage('divID');
    view.display('email');

OR

var view = new ViewMessage('divID').display('email');


Overall
I'm not really convinced of the value of this "trashcan" idea.  If deleting files doesn't actually delete them, then what's the point?  Trying to create free space would be ineffectual.  Worse, encouraging users to lean on an "undelete" facility will likely leave them in trouble when they move to a conventional system without such a crutch.  (Plus, it's a Good Thing to have an occasional minor accident - otherwise it's very easy to just assume that your backups are working, and never think to verify that you can actually restore from them!  I'm certainly guilty of that...)
Quoting issues
Much of your code doesn't quote expanded variables when it should.  One example:
case $file in
  -*) bypass $* ;;
  $trash/* ) bypass $* ;;
esac

This is unsafe, and needs to be written
case "$file" in
  -*) bypass "$@" ;;
  "$trash"/* ) bypass "$@" ;;
esac

There are many more similar instances; I won't list them all.
Testing for file-ness rather than existence
[ -f "$file" ] || error "File not specified."

Do you really want this error when you ask to trash a symlink?  In fact, I think the wording of the message is poor, even for the case you think you're testing.
Pathname matching
You test whether the argument is in the "trash" directory with
case $file in
  $trash/* )
esac

There's other ways to refer to the same directory as "$trash" - in particular, a relative name from the working directory.  You'll need to canonicalise path name if you're doing this kind of comparison; possibly you might want to compare device and inode numbers for real robustness if you might have bind mounts and the like.
Echo and read
This code:
echo -n "Which would you like to restore? [1]:"
read user

is usually written
read -p "Which would you like to restore? [1]: " user

(I'm not sure that user is a good name for the version number, either).


A very simple solution is to use a Map that (as its name implies) maps a string to a function so that you can pass an array of sorted strings and ask for the application to get each function and run it in the specified order.

Something like this:

var myFuncs={ 'firstI2C':firstI2C,
              'secondI2C':secondI2C,
              //so on
}

Then you can have a function that tells the program to run next function. For example:

var nextMethodIndex=0;

var methodOrder=['firstI2C','secondI2C','thirdI2C',....] // this array can be fed as JSON.

function runNextMethod()
{
    if(nextMethodIndex<methodOrder.length)
    {
         var func= myFuncs[methodOrder[nextMethodIndex]];
         nextMethodIndex++;
         setTimeout(func, 1000)
    }

}

Finally you should modify your functions to call runNextMethod when they finish their job.

function timer() {
  runNextMethod();
  setTimeout(timer, 5000)
}

function firstI2C() {
  Servo.writeReg(1, 250);
  Servo.writeReg(2, 128+16+0x0);
  Servo.writeReg(37, 0);
  console.log("1");
  runNextMethod();
}


Display related records, if they exist, in Rails view

There's a lot of ways to check the presence of an object, i prefer to use try :

device.try(&:name)


Actually the * operator does element-wise multiplication. So you need to use .dot() function to get the desired result.
Example :
import numpy as np

a = np.array([[1,2,3],
    [4,5,6],
    [7,8,9]])

b =  np.array([[1]
    ,[2],
    [3]])
print(a * b)
print(a.dot(b))

output :
[[ 1  2  3]
 [ 8 10 12]
 [21 24 27]]
[[14]
 [32]
 [50]]

Observe that when I have used * operator, every column in a is multiplied with b element-wise


first thing one could spot is this duplications:

size = data.data[0].images.standard_resolution.url;
          $("#insta-1").append("");
          size = data.data[1].images.standard_resolution.url;
          $("#insta-2").append("");
          size = data.data[2].images.standard_resolution.url;
          $("#insta-3").append("");
          size = data.data[3].images.standard_resolution.url;
          $("#insta-4").append("");
          size = data.data[4].images.standard_resolution.url;
          $("#insta-5").append("");
          size = data.data[5].images.standard_resolution.url;
          $("#insta-6").append("");
          size = data.data[6].images.standard_resolution.url;
          $("#insta-7").append("");
          size = data.data[7].images.standard_resolution.url;
          $("#insta-8").append("");

One could change it to something more condensed like:

for(var i=0; i<9; i++) {
    size = data.data[i].images.standard_resolution.url;
    $("#insta-"+i).append("")
}

Also creating new nodes multiple time is ineficient since browser will re-paint it every time, so you could change it to (I assume that #insta-X elements are just your way to hook it in some place in html, if that's the only reason you may ditch them and create ie.

)

links = "";
for(var i=0; i<9; i++) {
    size = data.data[i].images.standard_resolution.url;
    links += "";
}
$(".insta-container").append(links);

Also it looks like with size you accidentally declare global variable (window.size) - not a good idea - you need to make var size to make it local:

loadImages: function (userID) { // Get user photos
      var size, //declare local var, then use it as before
          getImagesURL = "https://api.instagram.com/v1/users/" + userID + "/media/recent/?access_token=" + accessToken + ""
      ;

Also you may want to read about hoisting to know those var ... declarations should be at the top of your function.


Wrapping an Exception with context-management, using the with statement

This:

if some_result is None:
    with ResultException:
        logger.exception(error_msg)

would seem to be equivalent (for most cases) to:

if some_result is None:
    logger.exception(error_msg)
    raise ResultException

And so using a context manager as you describe it would not seem to be helpful. That's probably why you can't find any instances of it. But this would not actually work because when you call logger.exception, you need to be in an exception handler.

You could do:

def raise_logged(exception):
    try:
         raise exception
    except:
         logging.exception(str(exception))
         raise exception

Then use it like

 if some_result is None:
       raise_logged( ResultException("not so good") )

However, throwing the exception just to catch it and log it is a bit yucky. Do you really need to log the exception as this point? Usually, we log exceptions when they are caught.


Removing properties and elements set to null in JavaScript

I can't think of any good use-case for this method. It may help to describe some examples of why you need this functionality.

That said, a few issues I see:

func could be named better (predicate perhaps?).
maxRecursion seems a bit unstable. This is where I have a hard time seeing the purpose of this method. What happens if you hit level 20 and it hasn't fully run it's course? Now you've got an object that is in a half-complete state without any way to know it. What if it spends 20 cycles on the first property which happens to be a circular reference?
I think the use of lodash here adds confusion to what would otherwise be pretty straightforward javascript (opinion).

Some fixes:

Don't use a recursive function. You could use a stack or a queue here to traverse the object tree.
Rather than limit the depth to avoid stack overflows for circular references, you could try to detect them by keeping a table of references and avoid re-traversing those trees altogether.
Rather than modifying an existing object, you could create a new one. That way, this method wouldn't produce any side-effects and potentially leave you in an unstable state. At minimum, you could return true/false if the method succeeded.


Is it bad practice to increment more than one variable in a for loop declaration?

I would agree with the OP in that the second code block would be the best approach.

Reason - readability.   In my opinion, the variable incremented in the for loop statement should only be used for keeping count of how many times we're looping.   count might be set before the loop, it might also be incremented / decremented in several different loops.   But in either case, count isn't used to keep track of the progress of the current loop - y is in this case.

So, I would say that it's best practice, for readability sake, to only increment the variable used to loop through the for loop in the for loop line itself.


Looking for a better way to handle this growing array used for preg_replace

You have two issues: how to represent all of the desired transformations as code, and how to perform the substitutions efficiently.

To address the data representation issue — you want to use an associative array.

$simple_replacement_patterns = array(
    '/\[b\](.*?)\[\/b\]/is' => '$1',
    '/\[i\](.*?)\[\/i\]/is' => '$1',
    '/\[u\](.*?)\[\/u\]/is' => '$1',
);

However, there is a lot of redundancy there, which violates the Don't Repeat Yourself principle.  Ideally, your source code should contain just

$simple_tag_translations = array(
    'b' => 'strong',
    'i' => 'em',
    'u' => 'u',
);

… and the computer build $simple_replacement_patterns for you.

Consider mapping [b]bold text[/b] to bold text, [i]italic text[/i] to italic text, and [u]underlined text[/u] to underlined text.  Not only would the mapping be trivial (BBCode is inspired by HTML designed to be easily translated, after all), you would also not be inferring semantic value into the style.  For example, maybe the BBCode text was italicized because it is a title in a bibliography entry, not because it is to be emphasized.


This is almost all style suggestions; the code itself looks great.

Personally, I prefer the brace-on-same-line style for everything in JS, and I prefer proper blocks instead of inlining expressions. But those are just preferences. I've also skipped the bitwise trick, added some strict comparisons instead of !stack.length etc., moved the i++ over to its "usual" place, and lengthened a few variable names, just for clarity.

Again: This is all basically pointless, but I just like spelling things out.

The only real difference is that rather than push the opening brace onto the stack, I push the position of the expected closing brace. It just makes the conditional a bit cleaner later on.

function parenthesesAreBalanced(string) {
  var parentheses = "[]{}()",
    stack = [],
    i, character, bracePosition;

  for(i = 0; character = string[i]; i++) {
    bracePosition = parentheses.indexOf(character);

    if(bracePosition === -1) {
      continue;
    }

    if(bracePosition % 2 === 0) {
      stack.push(bracePosition + 1); // push next expected brace position
    } else {
      if(stack.length === 0 || stack.pop() !== bracePosition) {
        return false;
      }
    }
  }

  return stack.length === 0;
}

Update: Actually, you can skip one stack.length check in the inner conditional; stack.pop() will just return undefined if the stack's empty, so this is enough:

if(stack.pop() !== bracePosition) {
  return false;
}


How can this rails controller test be cleaner refactored?

shared examples share the let scope, so you could further dry up your code (assuming you use do_action for every action) to this:

shared_examples :empty_success_response do

  before do
    do_action
  end

 ...
end

Also, if you are using do_action, I also like to add to my scopes:

describe '#destroy' do
  let(:do_action) do
    delete :destroy, id: subject.id.to_s
  end

  after do
    do_action
  end

  ...
end

This way, you don't have to call do_action if all you do in the test is set expectations.

it 'makes the call' do
  expect(controller).to receive(:destroy_item).once.times.with(subject.id.to_s)
end

If in some tests you want do_action to run before the end of the test - that's no problem, since let runs the code only once - so it won't run again at the end of that specific test!


Your code is pretty well written and I can't see anything too much I'd change...

(remainingCount > maxToReadOnce) ? maxToReadOnce : remainingCount

might be clearer as

Math.Min(maxToReadOnce, remainingCount)

but other than that it all looks really sensible.

That said, by mixing the batching into the processing code both are harder to read. Batching (splitting/sharding/whatever you want to call it) comes up a lot - I have an extension method lying around for it:

public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> enumerable, int batchSize)
{
    var c = 0;
    var batch = new List<T>();
    foreach (var item in enumerable)
    {
        batch.Add(item);
        if (++c % batchSize == 0)
        {
            yield return batch;
            batch = new List<T>();
        }
    }
    if (batch.Count != 0)
    {
        yield return batch;
    }
}

There are a whole bunch of variations on the above - feel free to make any changes... The ++c % batchSize == 0 has always bothered me a bit but I like the terseness of it.

With that extension method in place you can simplify your code to:

foreach (var batchOfEmails in emails.Batch(maxToReadOnce))
{
    Process(batchOfEmails);
}

(if you don't like var the type will be IEnumerable<IEnumerable<string>>)


Restricting search to a user's own department, if the user is not a manager

Merge your if statement into the where clause.

public ActionResult Index()
{
    AD_CurrentUserProfile currentUP = new ActiveDirectory().GetUserProfile(User.Identity.Name.Split("\\".ToCharArray())[1].ToString());

    IQueryable<IPACS_DT_MasterList> model =
        (from d in db.IPACS_Department
                where (currentUP.currentUser.isManager || d.name == currentUP.currentUser.department)
                join f in db.IPACS_Function on d.departmentID equals f.departmentID
                join pg in db.IPACS_Process on f.functionID equals pg.functionID
                join sop in db.IPACS_Procedure on pg.processID equals sop.processID
                select new IPACS_DT_MasterList
                {
                    departmentID = d.departmentID,
                    functionID = f.functionID,
                    processID = pg.processID,
                    procedureID = sop.procedureID,
                    departmentName = d.name,
                    functionName = f.name,
                    processName = pg.name,
                    procedureName = sop.name,
                    owner = sop.owner
                });

    return View(model);
}

If the current user is a manager, the first condition will return true and cause the where statement to short-circuit; otherwise it will compare the department name to the user's department.


Find first threshold crossing in numpy array

In principle you can use numpy.argmax for this. The only problem is that if no value is above the threshold, the maximum is False, so it returns 0 as the index of the maximum. We therefore need to subtract 1 for those cases:

above_threshold = data > thresh
react_tms = np.argmax(above_threshold, axis=1)
react_tms = react_tms - (~np.any(data > thresh, axis=1)).astype(float)
print(react_tms)
# array([ -1.,  -1.,  18.,  12.])

Whether or not that is really more readable, I am not sure. It is, however slightly faster than using numpy.where (and probably also faster than a list comprehension): https://stackoverflow.com/q/16243955/4042267

In the end this does not really matter:


The compiler gives me several warnings:

st.c: In function 'main':
st.c:34:5: warning: initialization makes integer from pointer without a cast [enabled by default]
     Range iRange = {test, test + 50};
     ^
st.c:34:5: warning: (near initialization for 'iRange.offset') [enabled by default]
st.c:34:5: warning: initialization makes integer from pointer without a cast [enabled by default]
st.c:34:5: warning: (near initialization for 'iRange.terminal') [enabled by default]

Indeed, your program has many casts from unsigned long to char *.
You shouldn't ignore warnings, and strive to eliminate them all.

There seem to be several problems with this piece:

    if(string[c + strlen(string) - 1] == '\0')
        break;

First of all, calling strlen in every iteration of the loop is wasteful,
it would be better to call it once before and cache the length in a variable.

Secondly, I doubt this is intended behavior.
This statement will cause the loop to exit when c = 1.
So if your test string is "Looking for S Sample string" and the string parameter is "Sample", then the output will be "S Sample string" instead of "Sample string".
So this looks like a bug.
Perhaps you're looking for something like if (c == len) { i -= c - 1; break; } (where len is strlen(string), cached before the loop).

The variable names don't seem great.
Why not simply range instead of iRange?
How about target instead of string?
Why use Range at all instead of two variables?


You've written a very literal and straightforward implementation to solve the challenge: test numbers for primality, and accumulate them until you have 1000 of them.

However, when you want to find many prime numbers, an algorithm such as the sieve-of-eratosthenes is more efficient than repeated trial division.  Here is a benchmark that illustrates the difference.  Your program follows the same basic outline as @Legato's solution, except that you haven't implemented some optimization hacks.  If you just want to sum the first 1000 primes, there isn't much of a difference in execution time, but your program will not scale up as gracefully as a sieve algorithm.


Parent/child relationships: adding/updating details to an answer

Separation of Concerns
I like that you're using EF's built-in unit-of-work implementation. However db (your DbContext class) looks like it's declared at instance level in your controller - make sure it's disposed properly at the end of the request (you could inject the context in the controller's constructor and use an IoC container to ensure per-request instantiation & disposal).
That doesn't mean the controller's [HttpPost] methods should be doing all the work!
Looking at the method's code, I think you can extract an entire service class that exposes at least 3 methods!

Answer CreateNewAnswer(string userName)
AnswerDetail FindByLeaderId(int leaderId)
AnswerDetail CreateNewAnswerDetail(int answerId, AnswerDetailVM item)

Extracting these methods into their own class will make it much easier to follow your controller methods' code, by adding a level of abstraction - the controller shouldn't be dealing with minute details, rather should call into more specialized objects that do their specialized stuff. Shortly put, separate the concerns ;)

SaveChanges
You don't need to call db.SaveChanges() for every entity you create in the loop - EF's DbContext is a unit-of-work that encapsulates a transaction, so calling SaveChanges is like saying "I'm done, now commit all these pending changes!" - call it once (or, as sparingly as possible - e.g. the parent would typically needs to exist in the db before a child can be added), when you're done.

Naming & Other Nitpicks

Answer AnswerRecord;
AnswerRecord = (db.Answers).Where(x => x.TeacherID.Equals(evaluation.CurrentTeacher.ID)).Where(y => y.LeaderID != null).FirstOrDefault<Answer>();

For readability, I prefer to split these across multiple lines:
AnswerRecord = (db.Answers).Where(x => x.TeacherID.Equals(evaluation.CurrentTeacher.ID))
                           .Where(y => y.LeaderID != null)
                           .FirstOrDefault<Answer>();

This is confusing, because x and y refer to the same object. Also I'd prefer == over .Equals in most cases, so I'd write it like this instead:
var answer = db.Answers.Where(answer => answer.TeacherID == evaluation.CurrentTeacher.ID
                                     && answer.LeaderID != null)
                       .FirstOrDefault();

The type parameter for FirstOrDefault is inferred from usage, doesn't need to be specified ;)

Comments
If these comments are real, in-code comments...

//I use this block if I know the child record is new:

//I use this block if I am updated the child record

...then they're both lying - the code blocks under each comment seems to be doing what the other comment is saying! Remove these misleading comments, calling _service.CreateNewAnswerDetail should be clear enough that you're creating a new AnswerDetail entry ;)
As for this one:

//Add New Parent Record:

and this one:

//End of ForEach Loop

...they both say nothing that the code doesn't say already, remove them as well, thank yourself later ;)


First off, you should probably allow a default ComName to be passed into the constructor, and the default should probably be null instead of an empty string (unless you have good reason to do otherwise).

function Serial(name) {
    this.ComName = name !== undefined ? name : null;
}

Next, getPortName is strange. You set it on Serial.prototype, which indicates it will be used as an instance method. In fact, however, it doesn't use instance state at all! As your code is currently laid-out, you would need to perform the following to call getPortName:

new Serial().getPortName()

In classical OOP parlance, this is a static function. It doesn't need instance state, so declare it on Serial itself, not Serial.prototype.

Serial.getPortName = function() { ... }

With that change, you can simply call Serial.getPortName(), as you would a static method in other languages.

Furthermore, your naming conventions are a little odd. You use ComName for the property but COMName for the setter. Use comName for the property for consistency. If you need the setter, use setComName. However, the setter is also unnecessary. Why not just access serial.comName directly?

Finally, these changes beg the question... why is this object-oriented code at all? The only state you appear to be representing is a single string with no actual methods on it. Why not just export getPortName and call it a day? If your code is more complex, using JavaScript's OO capabilities might be worth it, but otherwise, you don't need it. A simple function will do.


Implement metaclass for Maximumlikelihood estimator

Instead of constructing the object and then modifying its methods and attributes, you can directly add them in the __new__ method of the metaclass:

class LikelihoodEstimator(type):
    def __new__(cls, name, bases, dct, f):
        def loglike(self, params):
            return f.logpdf(self.endog, *params).sum()

        def fit(self, **kwargs):
            if 'start_params' not in kwargs:
                # This is for performance and! convergence stability.
                # The scipy function provides better starting params.
                kwargs['start_params'] = f.fit(self.endog)
            res = super(cls, self).fit(**kwargs)
            res.df_model = self.nparams
            res.df_resid = len(self.endog) - self.nparams
            return res

        dct.update(loglike=loglike, fit=fit, nparams=len(signature(f.pdf).parameters))
        return super().__new__(cls, name, bases + (GenericLikelihoodModel,), dct)

I also changed the name to more nicely fit within PEP8 guidelines. I also included back bases to avoid undesirable surprises when using this metaclass.

The other option that I think is more easily understandable is to use inheritance instead of metaclasses. There will still be a bit of boilerplate left but the understanding at a glance should overweight:

from scipy.stats import fisk, t
from statsmodels.base.model import GenericLikelihoodModel as _LikelihoodModel
from inspect import signature

class GenericLikelihoodModel(_LikelihoodModel):
    """A maximum likelihood estimator for any distribution"""

    def __init__(self, distribution, endog, exog=None, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds)
        self.nparams = len(signature(distribution.pdf).parameters)
        self.distribution = distribution
        super().__init__(endog, exog, loglike, score, hessian, missing, extra_params_names, **kwds)

    def loglike(self, params):
        return self.distribution.logpdf(self.endog, *params).sum()

    def fit(self, **kwargs):
        if 'start_params' not in kwargs:
            # This is for performance and! convergence stability.
            # The scipy function provides better starting params.
            kwargs['start_params'] = self.distribution.fit(self.endog)
        res = super().fit(**kwargs)
        res.df_model = self.nparams
        res.df_resid = len(self.endog) - self.nparams
        return res

class Fisk(GenericLikelihoodModel):
    """A maximum likelihood estimator for the fisk distribution"""
    def __init__(endog, exog=None, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds)
        super().__init__(fisk, endog, exog, loglike, score, hessian, missing, extra_params_names, **kwds)

class StudentT(GenericLikelihoodModel):
    """A maximum likelihood estimator for the Student-T distribution"""
    def __init__(endog, exog=None, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds)
        super().__init__(t, endog, exog, loglike, score, hessian, missing, extra_params_names, **kwds)


Object oriented design for access control

AccessGroup should contain a Set of permissions to be extensible, rather than have the Read permission and Write permission directly attached. Otherwise you end up with a dozen attributes hanging off AccessGroup in a year's time.
(this also means you can just union the permissions on a user to see what they can do, instead of messing with AccessGroup.getXXXX attributes)
You're overloading the terms 'add' and 'remove'. You should createUser and deleteUser
The User class is quite anemic. Perhaps you could use composition to hide the entire AccessManagement class inside it, maybe by having an AuthenticatedUser subclass that knows about its groups and permissions.
Your mediator should have specific methods to swapIn and swapOut. TBH I'd model it as an event stream so there would be no updates, only inserts.


Building session-variables from a SQL stored procedure

First your TryAutoLogin:

A SqlConnection is IDisposable. Use it in combination with using.
You have some duplicate lines of code, like seCmd.CommandType = CommandType.StoredProcedure;.
dtServerVars can never be null.
You do not have to open the connection, SqlDataAdapter will do that for you.
Since you are using only ONE datarow, just return one datarow.

Resulting in:

 public static DataRow TryAutoLogin(string strREMOTE_USER)
 {
      using(SqlConnection siConnection = new SqlConnection(Databases.getDbConnectionString("csSharedInfo")))
       {
           SqlCommand seCmd = new SqlCommand("GetSignOnDetails", siConnection);
           seCmd.CommandType = CommandType.StoredProcedure;
           seCmd.Parameters.AddWithValue("@DomainAccount", strREMOTE_USER);
           SqlDataAdapter sda = new SqlDataAdapter(seCmd);
           DataTable dtServerVars = new DataTable();
           sda.Fill(dtServerVars);
           if (dtServerVars.Rows.Count > 0)
                return dtServerVars.Rows[0];
           return null;
      }
 }

Having done this, the next piece of code will also be a lot easier:

DataRow drServerVars = clCommonFunctions.TryAutoLogin("europe\\MrTest");
Session["CablingUserID"]= drServerVars["CablingUserID"].ToString();
Session["CablingUseremail"] = drServerVars["CablingUseremail"].ToString();
Session["CablingLogin"] = drServerVars["CablingLogin"].ToString();
...


Python configuration module for a web framework

toml is a third-party library, so should be separated from the standard library imports:

import os
import sys

import toml

ConfigBase.__init__ seems a little strange:

def __init__(self):
    self.basename = ''
    self.default_options = {}
    raise TypeError('Should not use ConfigBase directly')

Why bother to set the attributes if you're then going to throw an error? Also you should use NotImplementedError for abstract base classes, by convention.

Config.load_config seems to be internal; are you expecting it to be called from anywhere other than Config.__init__? If not, rename it _load_config to indicate that it's an implementation detail. Also note that the temporary assignment to config is unnecessary:

def load_config(self):
    with open(FILEPATH, 'r') as f:
        return toml.load(f)

I'd also note that it seems weird to add a docstring for __getitem__ that just describes what that method is for, but then not document the non-standard load_config at all. Your target audience should already know what __getattr__ is for (or where to find out).

Talking of __getattr__, there's an awful lot of complexity hiding in there. Every other method you've written is nice and short, but this could do with breaking down. To describe it:

Get the default value
If the default is a dictionary, wrap it up and return it immediately
If not, but there's an appropriate value in the environment, return that
If not, but the default exists, return the default
If not, throw an error

That's how I'd structure the method:

default = self._get_default_value(item)
if isinstance(default, dict):  # or the more general collections.abc.Mapping
    return self._create_config_section(item, default)  # or maybe return ConfigSection(self._create_basename(item), default)
env = self._get_value_from_env(item)
if env is not None:
    return env
if default is not None:
    return default
raise ConfigError(self._create_error_message(item))

This reads like the description I wrote above, operates at a consistent level of abstraction (not delving into the details of e.g. how to get a value from the environment or where the default comes from) and reduces the nesting.

You can split out other obvious helper methods, like self._create_env_var(item), along the way. Doing so might highlight to you that it's a little weird to do the same thing two different ways in the same method:

self.basename + '.' + item
'.'.join((self.basename, item))

Finally, I don't think the distinction between ConfigBase, Config and ConfigSection is really helping you. You interact with them the two child classes in much the same way; only the initialisation differs. Instead, I might be inclined to do:

class Config:

    def __init__(self, basename='', defaults=None):
        self.basename = basename  # should already be lstrip-ped
        if defaults is None:
            defaults = self._load_config()
        self.default_options = defaults

    def __getitem__(self, item):
        ...

    ...


The idea behind your script is pretty cool and there's a couple ways to polish it up! While it certainly wouldn't cause a headache, I think that creating an entire class just to measure how long the request is going to take to complete is a little overkill.

Within the class itself, let's look at 2 things which aren't the best practice.

Use of a global variable
Use of the try/except block

Global variables

There's a brilliant StackOverflow question with really good answers as to why using global variables should be discouraged. While in the scope of your script it is not harmful, imagine you had many functions and methods in your script. Using the global variable could decrease readability and potentially alter the behaviour of your code. Mind you, global variables aren't the same as global constants (also discussed in the StackOverflow question).

Exception handling

Using a bare except statement will handle all exceptions, even the ones you might not anticipate. Catch errors explicitly, otherwise you might cause unexpected behaviour in your code, should it become more complex. In this scope, your bare except statement should become more like this:

try:
    ...
except requests.exceptions.ConnectionError:
    print("failed to connect")

This way, you are handling the case where your request actually fails and you let other errors happen in their intended way. Otherwise, a different exception could have been raised and you won't know what caused it.

Additionally, on this class:

Following naming conventions, class names should use CapWords.
In Python 3+, classes no longer need to be inherited from object.

Instead of the class, you could just define a simple function which retrieves the XML document from the RSS feed, declare your timing functionality within it and returns the XML document. Seeing as the URL query takes in what's seemingly an ISO 3166-2 country code as one of the parameters, you could pass the country code into this function and have the ability to fetch search trends for so many different countries! Please note that in the following snippet I am using f-strings which were introduced since Python 3.6.

def fetch_xml(country_code):
    url = f"https://trendse.google.com/trends/trendingsearches/daily/rss?geo={country_code}"
    start = time.time()
    response = requests.get(url)
    response_time = time.time() - start
    print(f"The request took {response_time}s to complete.")
    return response.content`

Parser

Looking at the docstring of your parser, one might argue it's a little misleading. You're mentioning "storable text" while you're only printing your output! To come closer to the intention of the docstring, it would be better to return the parsed data and decide what to do with it later. I think in this case, a dictionary would a very fitting data structure. Dictionaries store key-value pairs, so lets use the trend title as the key and the traffic approximation as the value.

Using re.sub() will allow you to remove different characters from a string in a single line, rather than replacing each character separately! This piece of code here:

for x in traffic_unformatted:
    x = x.text
    x = x.replace("+","")
    x = x.replace(",", "")

Can now become:

    for x in traffic_unformatted:
        x = re.sub("[+,]", "", x.text)

Zip the two lists of titles and traffic approximations together and iterate over them to create the dictionary. I am going to use a dictionary comprehension in the final script, however it works identically to the following.

titles = soup.find_all("title")
approximate_traffic = soup.find_all("ht:approx_traffic")
trends = {}
for title, traffic in zip(titles[1:], approximate_traffic):
    trends[title.text] = re.sub("[+,]", "", traffic.text)
return trends

Please pay attention to the titles function having its first element sliced off - this is because BeautifulSoup picked up the title of the entire XML document together with titles of the trends.

Finally, I am using an if __name__ == "__main__" guard to separate functions from the block of code where I am calling the functions from.

Entire script:

import time
import re
import requests
from bs4 import BeautifulSoup

def fetch_xml(country_code):
    url = f"https://trends.google.com/trends/trendingsearches/daily/rss?geo={country_code}"
    start = time.time()
    response = requests.get(url)
    response_time = time.time() - start
    print(f"The request took {response_time}s to complete.")
    return response.content

def trends_retriever(country_code):
    """Parses the Google Trends RSS feed using BeautifulSoup.

    Returns:
        dict: Trend title for key, trend approximate traffic for value.
    """
    xml_document = fetch_xml(country_code)
    soup = BeautifulSoup(xml_document, "lxml")
    titles = soup.find_all("title")
    approximate_traffic = soup.find_all("ht:approx_traffic")
    return {title.text: re.sub("[+,]", "", traffic.text)
            for title, traffic in zip(titles[1:], approximate_traffic)}

if __name__ == '__main__':
    trends = trends_retriever("US")
    print(trends)

Output:

The request took 0.2512788772583008s to complete.
{'Tiger vs Phil': '2000000', 'McKenzie Milton': '200000', 'Costco Black Friday': '200000', 'Nebraska Football': '200000', 'Patagonia': '100000', 'Michael Kors': '100000', 'Jcrew': '100000', 'finish line': '100000', 'WVU football': '100000', 'Texas football': '100000', 'Shoe Carnival': '100000', 'J Crew': '100000', 'Llbean': '100000', 'Cards Against Humanity': '100000', 'Bleacher Report': '100000', 'Steph Curry': '50000', 'Apple Cup': '50000', 'Bob McNair': '50000', 'Virginia Tech football': '50000', 'Glossier': '50000'}


If this is actually in live code somewhere, then whomever wrote it should be forced to write I will never call system on tainted user input again 1 googol times with a dull pencil.  Yes.  As written, this code contains an exploit.  Here's a simple example.

tmp$ cat foo.c
#include <stdlib.h>
#include <stdio.h>

int
main() {
    char *user = getenv("USER");
    char buffer[4096];
    if (user) {
        snprintf(buffer, sizeof buffer, "/bin/echo %s", user);
        printf("running %s\n", buffer);
        system(buffer);
    }
    return 0;
}
tmp$ gcc foo.c
tmp$ mkdir /tmp/xxx
tmp$ ls -ld /tmp/xxx
drwxr-xr-x  2 daveshawley  users  68 Nov 30 22:25 /tmp/xxx/
tmp$ USER='foo; rm -fr /tmp/xxx' ./a.out
running /bin/echo foo; rm -fr /tmp/xxx
foo
tmp$ ls -ld /tmp/xxx
ls: /tmp/xxx: No such file or directory
tmp$


There are several ways of making this more idiomatic:

A trivial note, but don't use Array.new.

Use [], it's shorter, clearer, and more idiomatic
Don't use category_hash[category] = [] unless category_hash[category]

Instead, use category_hash[category] ||= []. In general you can use a ||= b instead of a = b unless a. In the case of hashes, you can skip this completely and just give the hash an appropriate default value:

category_hash = Hash.new { |hash,key| hash[key] = [] }

Don't initialize a collection to an empty state, and then iterate over another collection, appending to the new collection. Use map/each_with_object/inject/etc. to turn one collection into another collection

A more idiomatic solution might look like this:

category_hash = things.each_with_object(Hash.new {|h,k| h[k] = [] }) do |thing,hash|
  thing.categories.each { |cat| hash[cat] << thing }
end

A completely different approach would be to map each thing's categories into a new hash, and then merge the resulting hashes. The problem is that you need a "deep" merge, like the one that comes with ActiveSupport:

categories_hash = things.map do |thing|
  Hash[thing.categories.map { |cat| [cat,thing] }]
end.reduce(&:deep_merge)


Lombokython - Automatic __eq__, __hash__, __repr__

1. Review

It would be substantially simpler to use a mixin instead of a decorator.
The test for equality is not symmetric: you have a == b if b belongs to a subclass of a's class, but not vice versa. So it's possible to have a == b but b != a, which makes no sense.

There are two sensible things to do here: either (i) ignore the class relationship, so that two objects compare equal if their vars are equal, regardless of which class they belong to; or (ii) insist that classes match, so that two objects compare equal only if they belong to the same class.
The intention seems to be for eqhash objects to hash based on their instance attributes, so that instances with different attributes get different hashes. But the code doesn't work! Here are two objects with different instance attributes, but whose hashes are the same:

>>> @eqhash
... class Data(SData):
...     pass
>>> d = Data(1)
>>> hash(d)
-9223372036573986785
>>> e = Data(2)
>>> hash(e)
-9223372036573986785

And here is one object that has different hashes at different times:

>>> d = Data(1)
>>> hash(d)
-9223372036573986785
>>> vars(d).values()
dict_values([1])
>>> hash(d)
-9223372036574014153

The problem is that you are constructing a dict_values object and then taking its hash. But dict_values objects don't hash based on their contents, only on their id (see Python issue 22192), so the hash doesn't tell you anything about the values, only about the location in memory of the dict_values object.

2. Revised code

class EqHash:
    """Mixin adding __eq__, __ne__, and __hash__ methods."""
    def __eq__(self, other):
        return (self is other
                or (type(self) == type(other)
                    and vars(self) == vars(other)))

    def __ne__(self, other):
        return not (self == other)

    def __hash__(self):
        return hash(tuple(sorted(vars(self).items())))

class Repr:
    """Mixin adding a __repr__ method."""
    def __repr__(self):
        return '{name}({values})'.format(
            name=type(self).__name__,
            values=', '.join(map(repr, vars(self).values())))

3. Answers to questions

functools.total_ordering is a decorator becuase it looks at the class in order to determine which ordering method was provided. See the implementation, which calls getattr(cls, op, None). It would be much harder to do this in a mixin.
I spotted the problems by thinking carefully!

First, equality is a symmetric relation, but isinstance is asymmetric, so it was suspicious that one was implemented using the other.

Second, it only makes sense to implement __hash__ on immutable objects, but the values of a dictionary are mutable, so this was also suspicious. See the documentation for __hash__, where it says:

  If a class defines mutable objects and implements an __eq__ method, it should not implement __hash__, since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).


Add timeline link to questions and answers on Stack Exchange

Direct per-attribute DOM building belongs to the '00s but, since you're using ES2015's let, let's use multiline template strings and make the final result of our code instantly readable:

let question = document.getElementById("question");
if (question) {
    question.querySelector(".post-menu").insertAdjacentHTML('beforeend', `

            timeline

    `);
}

for (let answer of document.getElementsByClassName("answer")) {
    answer.querySelector(".post-menu").insertAdjacentHTML('beforeend', `

            timeline

    `);
}

Notes:

.getElementsByClassName("abc")[0] ———> .querySelector(".abc")
Of course the former is faster but it doesn't matter in our case.
getElementsByClassName can never be null, it's a live HTMLCollection, so we can directly use it in a loop.
insertAdjacentHTML speed is about the same or faster than manual node building.


Diving into PHP's MVC - the application's core

For the actual code review, scroll to the bottom of this article

The "single pattern to rule them all"  pattern

This is a mistake a lot of starting developers are making. They read about how good MVC is. And that everyone should use it. A bit like jQuery, where jQuery is always the answer, independent of the question. It's like using a boat to plow a field because it is really good in the water and everyone like a boatride!

A pattern is not a rule, but a best practice to solve a certain problem. The MVC-pattern helps us solve some of the code-clutter and seperation of concern of domain logic, controlling logic an displaying stuff to the user.

Some even tend to say that MVC isn't a pattern but a way-of-life. Ignore those peeps.

Biggest problem of MVC

Because of the 'MVC solves everything' approach, you ended up writing an Application class that does, a bit of everything but only half and all in the constructor.

The moment you do more then assignments (plus the optional exception throwing for bad data) in a __construct, it's time to walk away from your code, take a break (or a beer) and then come back to look at it - with some fresh eyes.

Now that we've had our beer, try and explain to yourself why you should use the Application class and what problem it can help you solve. But because we are lazy, we simply write up the API for that class.

  The Application class has no dependencies (empty construct) and has no public methods.
  You do however have access to 4 parameters: url, controller, method and params.

Aaah, so it's a kind of parameterbag. But then without any get/set methods and only public variables.

So let's fire up that parameterbag:

$app = new Application();

  FATAL ERROR: controller not found / undefined or something like that

Application class gone wrong

The above example is a developer trying to use your code without reading it - you should never have to read code, the api should be enough.

KISS: Keept It Stupid Simple

Your application class is doing to much. And what happens if I want to run multiple applications? Each with a different url passed in? And what is a 'Application'? What does it represent/do? And more importantly: What problem does it solve?. Ow, and if the words describing the problem don't fit on a post-it, your class is doing to much.

The actual code review

construct

public function __construct()
{
    $this->getUrl();
    $this->splitUrl();

    $this->getController();
    $this->getMethod();
    $this->getParams();

    $this->loadController();
    $this->callMethod();
}

A constructor is there to instantiate the class. It shouldn't do anything. Let the developer choose when to load the controller, or filter the url, ...

Obsolete methods

private function getUrl()
{
    $this->url = getUrl();
}

What is the point here? Instead of having one line in the __construct and doing the assignement there. You added 4 lines. Remove them and add the assignment to the construct:

public function __construct()
{
    $this->url = getUrl();
}

But then there is the problem of tight coupling. A class should have as little as dependencies as possible. And all dependencies should be added in the __construct. If you need ask it:

public function __construct($url)
{
    $this->url = $url;
}

This makes testing a lot easier:

$url = 'controller/method/param1/param2';
$app = new Application($url);

And we have now succesfully decoupled the getUrl() function from our Application class. The Application class shouldn't care how the url is formed. It only tells us that it wants a url.

Misused constants

const DEFAULT_CONTROLLER = DEFAULT_CONTROLLER;
const DEFAULT_METHOD = DEFAULT_METHOD;

Setting a default controller and/or method seems like something that should be accessible as a public method of our Application:

public function setDefaultController($controller)
{
    $this->defaultController = $controller;
}

this gives us some extra sugar:

$app = new Application($url);
//If everything else failes
//we have a simple controller that
//can handle every url and prints out a small error message to the user
//and sends an email to support
$app->setDefaultController('SimpleController');

try {

    //do some heavy lifting, i.e. instantiate the database connection

    //Now that we have access to a lot of sugar
    //Our default controller can be a little more fancy
    //We now show random kittens from our database - sweet
    $app->setDefaultController('FancyController');

} catch($e)
{
    $app->run();
}

Design remarks
Your Application is in fact some kind of Router. It maps urls to controller::method(params). So why not call it a Router?

Good reads

A very good read is how the Symfony framework handles a Request:

Symfony http kernel

A good reads on patterns:

Misuse

And a last one, more of a amusing one but with a good underlying message:

Programming sucks


Filtering Gantt chart data involving hierarchical DTOs

Direction

I tried to rewrite your original code without much luck. After making a little bit of analysis I came to the idea that in order to have a more generic project shaking algorithm, we need a more generic project representation (data structure). Here's what the code looks after my second attempt.

Code

Here's the project tree object that has arbitrary number of subproject children defined as the same type as project itself (see Composite Pattern). The type placeholder T is something that will need some time to design properly, and this we can address separately.

Also, see that we've got the Activities enumerable declared on this level. Which means that even the root of the project hierarchy may have some activities. This is good and bad at the same time: it's good because now there's no artificial limitation applied to the root level; but it's bad because it diverges from what you had originally and if the original limitation is a business rule, you will need an external mechanism to maintain the rule.

public interface IProjectTree<T>
    : IEnumerable<IProjectTree<T>> // !!! The implementation should rely on Children field
{
    IEnumerable<IProjectTree<T>> Children { get; set; }
    IEnumerable<ActivityDto> Activities { get; set; }

    T SubtreeSpecificData { get; set; }
}

Now we can build a Traverse class that implements a generic method ShakeOff which is generalized and can be applied to any part of the tree and with any thinkable predicate on activity object (passed as a parameter).

public static class Traverse
{
    public static IProjectTree<T> ShakeOff<T>(this IProjectTree<T> targetTree, Func<ActivityDto, bool> activityPredicate)
    {
        if (!targetTree.Any())
        {
            targetTree.Children = new List<IProjectTree<T>>();
        }
        else
        {
            targetTree.Children = targetTree
                .Children
                .Select(subTree => subTree.ShakeOff(activityPredicate))
                .ToList();
        }

        targetTree.Children = targetTree.Children.Where(subtree => subtree.ActivityPredicateApplies(activityPredicate));

        return targetTree;
    }

    public static bool ActivityPredicateApplies<T>(this IProjectTree<T> target, Func<ActivityDto, bool> activityPredicate)
    {
        target.Activities = target.Activities.Where(activityPredicate);

        var hasSubtreesAndUnfilteredActivities = target.Any() && target.Activities.Any();
        return hasSubtreesAndUnfilteredActivities;
    }
}

Consumption

The consumer will then look like this:

DateTime fromEndDate = ...;
DateTime toEndDate = ...;
Func<ActivityDto, bool> activityPredicate = activity =>
     activity.EndDate >= fromEndDate && activity.EndDate < toEndDate;

IProjectTree<...> projectTree = null;
projectTree = projectTree.ShakeOff(activityPredicate);

Side notes

But wait, I can't change my DTO classes into IProjectTree. I am pretty sure your DTO structure is shaped by the Database or the service and you want to keep them as they are. This is the hardest part, and you may not like the answer.

You will need to translate your DTOs into IProjectTree<T>. It means, all your DTOs stay unchanged; add the ProjectTree type; and write a class that translates one thing into another (and vice versa). This will require a bit of work. And you will need to find a proper way to define the <T> (the trivial solution would be an object, the SubtreeSpecificData could then point to the source DTO ;) ).

IMO, this would be a better design. Operating directly on DTOs is counter-intuitive to me. DTOs are not supposed to be used as a part of the domain logic, but rather as a dummy objects in client-server communication processes.

Disclaimer

Traverse.ShakeOff() method is not a pure function, it modifies the provided targetTree object in-place. This may be dangerous in some scenarios (but probably, not in your case).
The code above may or may not be easy to apply due to architectural changes -- it's your judgement call. If I were you, I would not limit myself to a rigid unmanageable data structure just because my database/service returns DTOs in this format. As mentioned earlier, generic representation enables generic algorithms which are used a LOT (meaning the effort pays off).
I didn't have much time to test the solution (in fact, I still don't have access to my compiler), so burden of testing is on you.

Update 1

I updated code as per t3chb0t's comment and own observations:

Added IEnumerable<IProjectTree<T>> to IProjectTree<T>.
Replaced .Count() > 0 with .Any() where applicable.
Using extension method subTree.ShakeOff(activityPredicate) instead of an explicit static method invocation.


There is indeed a function for that.

>>> from datetime import timedelta
>>> print(timedelta(seconds=1239.123456))
0:20:39.123456

Now, if I understand you correctly, you want a divider for the millisecond.

from datetime import timedelta
def f(secs):
    t=str(timedelta(seconds=secs))
    index = t.find('.') + 4
    return t[:index] + ' ' + t[index:]
print(f(1239.123456))
# 0:20:39.123 456

I don't like that everything is hardcoded, if you want to use it for different applications (or even languages), you might want to generalize your bases and names.

Here is a generic way of doing any formatting you want:

def prod(f):
    total = 1
    l = [1]
    for i in range(len(f)-1, 0, -1):
        total *= f[i][0]
        l.append(total)
    return reversed(l)

def format_time(number, f=((24, ':'), (60, ':'), (60, '.'), (1000, ' '), (1000, ''))):
    return ''.join(
        (f"{(number//div)%base:0>{len(str(base-1))}}" + delimiter)
        if number//div else ''
        for div, (base, delimiter) in zip(prod(f), f)
    )

formatting = (
    (24, ' hours '),
    (60, ' minutes '),
    (60, ' seconds '),
    (1000, ' milliseconds '),
    (1000, ' nanoseconds'),
)

print(
    format_time(1551198373998173),
    format_time(1551198373998173, formatting),
    format_time(1551739, formatting),
    sep="\n"
)

The result is:

16:26:13.998 173
16 hours 26 minutes 13 seconds 998 milliseconds 173 nanoseconds
01 seconds 551 milliseconds 739 nanoseconds

What are it's advantages, you can do any formatting in any base, with any names. We could even do a base 2 converter.

binary_formatting = (((2, ' '),)+((2, ''),)*3)*10 + ((2, ''),)

print(
    format_time(155933900, binary_formatting),
    format_time(3279, binary_formatting),
    sep="\n"
)

1001 0100 1011 0101 1100 1100 1100
1100 1100 1111

Other than that, if your code need to accomplish a single purpose and it does it well, good for you.


Project Euler #10 in Ruby. Three ways to sum primes below 2 million

You should use implicit looping (filtering):

def primes_below(limit)
    (1..limit).select{|i| Prime.prime?(i)}
end

You should use the built-in profiler:

require 'benchmark'
puts Benchmark.measure{primes_below(limit).inject(:+)}


First, (not (null x)) is not very idiomatic; just use x instead.

Next, you are not handling all the cased in your cond (and you obviously mean (null arc-2) and not (null (arc-2))). If fact, I would drop the let and use nested ifs instead.

Finally, to answer your original question: of course loop can do everything reduce can, but if your intent is clearer with the latter, use it!

EDIT: unless is more idiomatic than when (null ...).


#define handle_error(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)

There's a long-standing convention to use UPPER_CASE for preprocessor macros.  This helps draw attention to them as text replacements, which don't obey the same rules of scope as C identifiers (and which sometimes - though not in this case - expand their arguments multiple times).

void print_files(char* dir, FILE* out)

Why a const char* dir?  Surely we have no need to overwrite its contents?  Also, I'd be inclined to always write to stdout in this program - let the user apply ordinary shell plumbing if a different destination is desired.  That's easier than having a special argument in each program.
In larger programs, it's usually a bad idea to exit() from within functions, particularly if it's possible to either recover, or produce useful information regardless of the error.  As a concrete example, if we find a subdirectory we can't read, it's probably more helpful to emit a warning message to stderr but continue listing the directories the user does have permissions for.
The code using open() and syscall() is much lower level than we'd normally use for this, and tightly bound to Linux rather than POSIX as claimed.  I think opendir() and readdir() would be more suited.
Be careful with resource management and non-local exits in C.  We only reach close(fd) in the success case.  Although handle_error() currently exits the program, if we change that in future, we'll find ourselves leaking file descriptors.  Kudos for closing the descriptor before the recursive call - it's easy to leave it open until the end of the function, and you avoided that trap.

char* buffer = malloc(sizeof *buffer * BUF_SIZE);

The multiplication by sizeof *buffer is borderline pointless.  I say "borderline" in case there's a chance that we might want to change the type (but still have BUF_SIZE of them).
We don't seem to handle reading directories larger than BUF_SIZE at all - not even with an error message.

    char path[400];
    strcpy(path, dir);
    strcat(path, "/");
    strcat(path, d->d_name);

Where's that 400 come from?  Why not use the system's MAX_PATH constant?
strcpy() followed by strcat() is wasteful - that causes another traversal of the string just written, in order to find where to start writing.  In this case, we could use printf() like this:
int path_len = snprintf(path, sizeof path, "%s/%s", dir, d->d_name);

Remember to test path_len to determine whether the path was truncated at this stage.

    if (d_type == DT_DIR)
         print_files(path, out);
    else if (d_type == DT_REG)
        fprintf(out, "%s\n", path);

Why don't we print the other kinds of file?  I wouldn't expect all my symlinks, sockets, FIFOs and device files to simply disappear from the listing unless I specifically asked for that.

   fprintf(out, "-------------[ START ]---------------------\n");

Consider using fputs() when there's no conversions to be done.
As a general style point, I'd advise more vertical space for conditionals, and use of braces as a consistent rule.  E.g.
if (buffer == NULL) {
    handle_error("Error malloc.\n");
}


Looping through columns in Entity Framework

So I had a look and made a few modifications, see below with comments.

// Made the method generic, the constaint is required by DbSet
static void LoopThroughColumns<T>(Func<someDbContext, DbSet<T>> getTable)
    where T : class
{
    using (var db = new someDbContext())
    {
        // Selecting columns exlicitly was unnecessary
        var query = getTable(db);
        var columnAccessors = CreateAccessors<T>();

        foreach (var row in query)
        {
            foreach (var col in columnAccessors)
            {
                var val = col(row);
            }
        }
    }
}

// Parameter is unnecessary as you never used it
static Func<T, object>[] CreateAccessors<T>()
{
    // Index and Property values weren't being used
    // ToArray() was an unnecessary conversion
    var propertyAccessors = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => p.CanRead)
                .Select((p, i) =>  CreatePropertyAccessor<T>(p));

    return propertyAccessors.Select(e => e).ToArray();
}

static Func<T, object> CreatePropertyAccessor<T>(PropertyInfo prop)
{
    var param = Expression.Parameter(typeof(T), "input");
    var propertyAccess = Expression.Property(param, prop.GetGetMethod());
    var castAsObject = Expression.TypeAs(propertyAccess, typeof(object));
    var lambda = Expression.Lambda<Func<T, object>>(castAsObject, param);
    return lambda.Compile();
}

Usage is a little different now, you would call it like this:

LoopThroughColumns(e => e.someTable);

To be extra-super cool (ie. generic) you could even pass in an Action<object> and have that define what is done with val, then derive different methods on that one. Below I'm creating a PrintColumnValues method which calls LoopThroughColumns with an specific Action<object> to perform.

static void LoopThroughColumns<T>(Func<someDbContext, DbSet<T>> getTable, Action<object> actionOnObject)
    where T : class
{
    using (var db = new someDbContext())
    {
        var query = getTable(db);
        var columnAccessors = CreateAccessors<T>();

        foreach (var row in query)
        {
            foreach (var col in columnAccessors)
            {
                actionOnObject(col(row));
            }
        }
    }
}

static void PrintColumnValues<T>(Func<someDbContext, DbSet<T>> getTable)
    where T : class
{
    LoopThroughColumns(getTable,
        new Action<object>(e =>
        {
            Console.WriteLine(e);
        }));
}

Usage

PrintColumnValues(e => e.someTable);


In any programming language you should always use meaningful names for your variables, functions, methods, and whatever else you need to assign a name.
In your case, var1 is completely non-descriptive. A better name would be bottles, bottle_count or bottles_remaining to be even more specific.
Secondly, in Ruby, you rarely need to use a plain loop. In your case, you basically want to repeat roughly the same thing 99 times (well actually, no, you don't exactly, but we'll get to that later).
A simple way to do this in Ruby is to say:
99.downto(1) do |remaining|
  # stuff to do 99 times
end

The remaining variable will start at 99 and count down to 1, so we can use it to print the verses.
And speaking of printing, you're making things difficult for yourself by not using string interpolation.
If you use double quotes instead of single quotes, you can use #{...} to insert stuff into strings. Like so:
99.downto(1) do |remaining|
  puts "#{remaining} bottles of beer on the wall, #{remaining} bottles of beer."
  puts "Take one down and pass it around, #{remaining-1} bottles of beer on the wall."
  puts # print a blank line between verses.
end

Note that #{...} can contain any Ruby code (but keep it simple for your own sake!), so a bit of arithmetic to subtract 1 works too. And there's no need to use to_s everywhere, as that happens automatically when using string interpolation.
The above code is pretty much equivalent to your current code, except that it prints a blank line between verses. And the fact that it prints 99 verses - you're actually only printing 98 verses in your version.
... However, it's printing wrong lyrics. Grammatically incorrect lyrics, at any rate.
Most verses do indeed go like this:

X bottles of beer on the wall, X bottles of beer.
Take one down and pass it around, (X-1) bottles of beer on the wall.

where X is whatever number of bottles we have left. (Note, by the way, how much this looks like the Ruby code above; the code's almost as simple to read.)
But notice the changes in the last 3 verses:

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer.
Take it down and pass it around, no more bottles of beer on the wall.
No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.

And that's why it's a programming challenge. If it was just about writing those 5 lines of code above, it wouldn't be too tricky.
But what's interesting is when you have exceptions to the rules, and those last 3 verses are just that. They don't even follow a single, different set of rules - they're each different in their own way.
How you go about handling that is up to you, though. It's a challenge, after all. There are clever ways, simple ways, complex ways, nonsensical ways... which one you pick is up to you. The idea is to make you consider the problem and its potential solutions; there isn't a single correct answer. The destination is already given (print the lyrics), so it's all about the journey.

Other small stuff:

The Ruby convention is to use 2 spaces of indentation - not 4 spaces, not tabs.
The break line should be indented.
The parentheses in var1 = (var1 - 1) are completely unnecessary. Furthermore, you can write it as var1 -= 1, which is a shorthand for the same thing.


#include
You didn't supply the contents of "stdafx.h", but I was able to compile simply by removing that include, so you probably don't need it.
You do seem to be missing a necessary include of <string.h>.
malloc()
In main() you allocate a fixed length buffer on the heap.  There's no advantage over stack allocation (unless you're compiling for a system with a tiny stack), and no need to multiply by 1: sizeof (char) is necessarily 1, by definition:
char str[MAXLENGTH];

Also, I note that there aren't many platforms that support 3400-bit longs, so you could probably make the input buffer a bit smaller.
Having done this, your call to readline() can be
readline(&str, sizeof str)

readline()
You take a pointer to pointer, but don't ever change the pointed-to value, so you could introduce a const between the stars, or (better) remove a level of indirection:
bool readline(char *buf, const size_t buf_len) {
    if (fgets(buf, buf_len, stdin)) {
        str_cmp(buf);
        return true;
    }
    return false;
}

Also, it's not clear whether you want to return true for a partial-line read; it's probably worth a comment to clarify this.
str_cmp()
You should remember the value returned by strchr, rather than recomputing it:
void str_cmp(char* str) {
    char *nl = strchr(str, '\n');
    if (nl)
        *nl = '\0';
}

I also prefer to write '\0' in preference to 0 to show we're dealing with string characters here.
Since it's only used from one place, we can inline this function.  It's a judgement call, but I don't see enough benefit from having this separate.
back to main():
This code doesn't do what it claims:
char* err = str_to_long(str, &cnvt_numb);
/* ... */
fprintf(stderr, "That number '%s' was not convertible...\n", err);

The value you get back as err isn't the string - it's only the portion after the parseable digits.  So for input such as 10x, you'll just print x; it's not obvious that's what you want.  I'd show the whole string to the user:
fprintf(stderr, "That number '%s' was not convertible...\n", str);

You probably don't want to return EXIT_SUCCESS in that case, either.
You test for output of LONG_MAX, but not LONG_MIN.  Actually, both of those are legitimate outputs, so by not testing errno, you are unnecessarily reducing the range you accept.
There's a call to getch() but that's not declared in any of the headers.  Perhaps you meant getchar()?  Either way, asking for extra input just to exit the program is user-hostile, and I'd just excise that part.

Putting it all together
Here's what I ended up with:
#include <errno.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#define MAXLENGTH 40            /* supports 128-bit long */

bool readline(char* buf, const size_t buf_len) {
    if (!fgets(buf, buf_len, stdin))
        return false;
    char *nl = strchr(buf, '\n');
    if (nl)
        *nl = '\0';
    return true;
}

// returns NULL on success, or the unparseable portion of input on failure
char* str_to_long(const char* const str, long* out) {
    char* end;
    errno = 0;
    *out = strtol(str, &end, 10);
    if (!*end && end != str)
        end = NULL;
    return end;
}

int main() {
    char str[MAXLENGTH];
    long cnvt_numb = 0;

    printf("Enter a number: ");
    while (!readline(str, sizeof str)) {
        printf("Try again...\n");
    }

    char* err = str_to_long(str, &cnvt_numb);
    if (err) {
        fprintf(stderr, "That number '%s' was not convertible...\n", str);
        return EXIT_FAILURE;
    } else if (errno == ERANGE) {
        fprintf(stderr, "INPUT OUT OF RANGE...\n");
        return EXIT_FAILURE;
    } else {
        printf("Your number was: %ld\n", cnvt_numb);
        return EXIT_SUCCESS;
    }
}

It accepts input from -9223372036854775808 to 9223372036854775807 (on this system, where long is 64 bits), and correctly reports a range error for -9223372036854775809 and for 9223372036854775808.
12345aoeu is rejected with

That number '12345aoeu' was not convertible...


I kind of wish you had posted the elevator class as well, but it's kind of interesting how you much you can tell about the CUT (code under test) from looking at the just the tests themselves.

First, your elevator shouldn't be responsible for getting what floor it should go to from the user. Your program should tell it where to go. If you inverted control, you wouldn't have to subclass the code under test in order to test it.

Which brings me to my second point...

If you have to mock the CUT, you're no longer actually testing anything. You can't have confidence that your real class is going to behave as you expect it to, because you've very explicitly changed how it behaves. You're not testing your elevator. You're testing your mock elevators, which is no test at all.

Sure, you are testing the elevator. I know that, but certainly, this class has too many responsibilities. It shouldn't be getting user input from the console. How could you possibly reuse the elevator class in a GUI application later?


You don't have to maintain the DropDownList's seelcted item becouse it will do it by it's self. The problem will only occur when you have disabled the ViewState for the control.


Flatten your method body

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

can be re-written as:

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    g, y, x = egcd(b % a, a)
    return (g, x - (b // a) * y, y)

because returning halts the function.

Use in-line 'ternary' to reduce verbosity

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        return 0
    else:
        return x % m

should become

def modinv(a, m):
    g, x, y = egcd(a, m)
    return 0 if g != 1 else x % m

Say something meaningful when asking for input

t = raw_input()

The user sees nothing, only an hanging interpreter.

Use a main function

Python code runs faster in functions
You can use an if name ... block to avoid execution when the module is imported.

Convert directly (minor)

Do not waste lines:

n = raw_input()
n = long(n)

should become

n = long(raw_input()) # <- also add a meaningful prompt

Follow naming conventions (minor)

You follow the naming conventions pretty well, just one imprecision:

Sum = 1

should be:

sum = 1

Use proper spacing (minor)

For example this line:

prod = ((n+1)%MOD * (n)%MOD)%MOD

is hard to read because all the symbols are squashed together.

Modularize more (important)

You defined two functions, that is very good, but you could do more to reduce the 35 lines of top level imperative code that is too much.

Usually each function (including main) should be no more than 10-15 lines of code.

Use doctests to for automatic testing

In Math code, automatically testing your functions each time you run the programme can be invaluable, just use something like:

import doctest

def egcd(a, b):
    """
    Meaningful description here...

    >>> egcd(4132, 434)
    (2, -48, 457)
    """

    if a == 0:
        return (b, 0, 1)

    g, y, x = egcd(b % a, a)
    return (g, x - (b // a) * y, y)

doctest.testmod()

and the code will be tested automatically.

Tell why

I can see many calculations in your code, but why? Following which algorithm, please write this inside the docstrings of your functions.


Javascript / ES6 parse value from arrays of objects

Granularity

All code can be said to have a level of granularity. This is a measure of how many functions it contains. Low granularity has fewer larger functions that has benefits of faster run-times at the expense of readability, while high granularity has many smaller functions, trading off performance for more readable and maintainable code.

Just how granular to make some code is something that comes from experience as there are no hard and fast rules to go by. However there is a general rule of thumb that increasing granularity should always reduce code complexity and source code size.

Too granular

Your code is too granular,

It is bloated with the source required only to define functions, call and pass arguments.
It adds un-needed complexity with arguments transforming the abstraction implied by naming from one value to another of and then back again to value.
It has forced you to repeat code.
It contains a function that is only an alias for existing functions find is an alias for Array.find and provides no additional processing.

The function getLabel processes  the result of find returning "No info" for undefined results. But this is repeated in the calling function.

Reducing granularity to improve code

Reducing granularity will not always improve code, well I should say very seldom and only in the case where the code is already too granulated.

Your module can be done in a single function

export default (value, type) => {
    var array, result;
    switch (type) {
        case 'paymentMethod':
            array = paymentMethods;
            break;
        case 'paymentTerm':
            array = paymentTerms;
            break;
        case 'dateType':
            array = dateTypes;
    }
    if (array) { result = array.find(item => item.value === value) }
    return result && result.label || "No info"
}

Or as there are only a few cases in the switch use if else

export default (value, type) => {
    var array, result;
    if(type === "paymentMethod") { array = paymentMethods }
    else if(type === "paymentTerm") { array = paymentTerms }
    else if(type === "dateType") { array = dateTypes }

    if (array) { result = array.find(item => item.value === value) }
    return result && result.label || "No info"
}

This can be even further reduced by using type to index the array via bracket notation, replacing the unwieldy switch or if else statements

const types = {paymentMethods, paymentTerms, dateTypes};
export default (value, type) => {
    var result;
    const name = type + "s";
    if (types[name]) { result = types[name].find(item => item.value === value) }
    return result && result.label || "No info";
}

Or if the names are not always pluralized with an s.

const types = {paymentMethod:paymentMethods, paymentTerm:paymentTerms, dateType:dateTypes};
export default (value, type) => {
    var result;
    if (types[type]) { result = types[type].find(item => item.value === value) }
    return result && result.label || "No info";
}

Your questions

  What would be more ES6, faster and concise way to achieve this?

More ES6? Not really, the  ES6 - eness of the code has not changed.
Faster? Yes there is less code to execute and few function states to create, push, and pop from the call stack.
Concise? Yes in my view it is much more concise. From 17 lines and three functions to 6 lines, one function, and no repeated code.


Adding a specific list of numbers to an array

It's always good to ask questions and try to find potentially better ways to do things. You've come to the right place.

So here's what I'm thinking regarding your question:

Yes, I think there is a better way to handle this that will benefit you in the long term, especially with respect to maintenance efforts. Right now you've hard-coded all the various ranges and values that you're excluding from your results. Let me first suggest that this kind of task is better probably handled by a database and a query to that database rather than coding rules in this manner. If you have all of your products and serial numbers in a database you can maintain the data in one place using a system that is designed for data management and you won't have to update your code every time your number scheme changes.

The basic idea is that you're coding data rather than generic logic and structures to support the use of the data. In order to illustrate this I have put together some Java code, but did not implement any database queries as that would take additional time and you can probably research this more on your own without too much difficulty.

So, the first thing I notice is you have very complex if statements that contain hard-coded ranges. If you create a generic Range class and use it to create Range objects to represent the various ranges of values you need you can make your code more generalized, reliable, and maintainable. Here is the Range class I created:

public class Range {
    private boolean isUpperBoundExclusive = true, isLowerBoundExclusive = true;
    private int upperBound, lowerBound;

    public Range(int value){
        isUpperBoundExclusive = false;
        isLowerBoundExclusive = false;
        upperBound = value;
        lowerBound = value;
    }

    public Range(int lower, int upper){
        lowerBound = lower;
        upperBound = upper;
    }

    public void setUpperBoundExclusive(boolean isUpperBoundStrict) {
        this.isUpperBoundExclusive = isUpperBoundStrict;
    }

    public void setLowerBoundExclusive(boolean isLowerBoundStrict) {
        this.isLowerBoundExclusive = isLowerBoundStrict;
    }

    public boolean isWithinRange(int check){
        return (isLowerBoundExclusive ? lowerBound < check : lowerBound <= check)
                && (isUpperBoundExclusive ? upperBound > check : upperBound >= check);
    }
}

Notice how this class represents data, but does not hard-code any data within it. I can configure an instance of this class to represent a single value using the first constructor or a range of values that is inclusive or exclusive at either end.  Notice there is also a method to determine whether a value is within the range called isWithinRange(int check). Please forgive the lack of Javadoc comments, but this is something I just created and I'm preparing to go to bed soon.

By using the Range class we can test the general logic and then we can have some certainty that it works as expected and that if we see errors while using it we're probably using it wrong in some way. So I wrote a quick JUnit test class to test the Range class, here it is:

import static org.junit.Assert.*;

import org.junit.Test;

public class RangeTests {

    @Test
    public void test() {
        Range range = new Range(10,20);
        assertFalse(range.isWithinRange(21));
        assertFalse(range.isWithinRange(9));
        assertFalse(range.isWithinRange(-1));
        assertFalse(range.isWithinRange(0));
        assertFalse(range.isWithinRange(10));
        assertFalse(range.isWithinRange(20));
        assertTrue(range.isWithinRange(11));
        assertTrue(range.isWithinRange(19));
        assertTrue(range.isWithinRange(15));
    }

    @Test
    public void test2() {
        Range range = new Range(10,20);
        range.setLowerBoundExclusive(false);
        assertTrue(range.isWithinRange(10));

        assertFalse(range.isWithinRange(21));
        assertFalse(range.isWithinRange(9));
        assertFalse(range.isWithinRange(-1));
        assertFalse(range.isWithinRange(0));

        assertFalse(range.isWithinRange(20));
        assertTrue(range.isWithinRange(11));
        assertTrue(range.isWithinRange(19));
        assertTrue(range.isWithinRange(15));
    }

    @Test
    public void test3() {
        Range range = new Range(10,20);
        range.setLowerBoundExclusive(false);
        range.setUpperBoundExclusive(false);
        assertTrue(range.isWithinRange(10));
        assertTrue(range.isWithinRange(20));

        assertFalse(range.isWithinRange(21));
        assertFalse(range.isWithinRange(9));
        assertFalse(range.isWithinRange(-1));
        assertFalse(range.isWithinRange(0));

        assertTrue(range.isWithinRange(11));
        assertTrue(range.isWithinRange(19));
        assertTrue(range.isWithinRange(15));
    }

    @Test
    public void test4() {
        Range range = new Range(10,20);
        range.setUpperBoundExclusive(false);
        assertFalse(range.isWithinRange(10));
        assertTrue(range.isWithinRange(20));

        assertFalse(range.isWithinRange(21));
        assertFalse(range.isWithinRange(9));
        assertFalse(range.isWithinRange(-1));
        assertFalse(range.isWithinRange(0));

        assertTrue(range.isWithinRange(11));
        assertTrue(range.isWithinRange(19));
        assertTrue(range.isWithinRange(15));
    }

    @Test
    public void test5() {
        Range range = new Range(10);
        assertFalse(range.isWithinRange(11));
        assertFalse(range.isWithinRange(9));
        assertTrue(range.isWithinRange(10));
    }
}

Next, if we had a list of products we could use inside our main logic it would help simplify the code. I'm not sure whether that's possible since you didn't really specify what sort of data and objects you have to work with, but here is what I'm thinking:

import java.util.ArrayList;
import java.util.List;

public class Product {
    private String name;
    private List<Range> serialNumExcludedRanges;

    public Product(String name){
        this.name = name;
        serialNumExcludedRanges = new ArrayList<Range>();
    }

    public String getName(){
        return name;
    }

    public void addExcludedSerialNumRange(Range rangeToAdd){
        serialNumExcludedRanges.add(rangeToAdd);
    }

    public boolean isSerialNumExcluded(int check){
        for(Range excludedRange: serialNumExcludedRanges){
            if(excludedRange.isWithinRange(check))
                return true;
        }
        return false;
    }
}

Notice how the Product itself contains a list of excluded ranges that it then uses when the isSerialNumExcluded method is called. At that time it uses these ranges in order to determine whether the given input is excluded or not and returns a boolean value accordingly.

Finally, going back to the main logic here's what we're now able to write:

public static List<Integer> getSerialNums(String name) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    for (Product product : productList) {
        // Note: should handle possible null here - what if the "name" param
        // is null?
        if (name.equals(product.getName())) {
            for (int i = 1; i <= 100; i++) {
                if (!product.isSerialNumExcluded(i)) {
                    numbers.add(i);
                }
            }
        }
    }
    return numbers;
}

Remember, this assumes that we have already defined our list of products prior to calling this method. In this example I created a static variable and added a simple main method to initialize them, but this is where a database query would really become useful. Rather than initialize them by hard-coding the values (for completeness I have provided the initialization logic below) you could store the data in a database then query for the values you want and populate your data structures.

private static List<Product> productList = new ArrayList<Product>();

public static void main(String[] args) {
    //Define product A below:
    Product productA = new Product("A");
    Range r1 = new Range(46, 50);
    r1.setLowerBoundExclusive(false);
    r1.setUpperBoundExclusive(false);
    productA.addExcludedSerialNumRange(r1);

    Range r2 = new Range(60, 73);
    r2.setLowerBoundExclusive(false);
    r2.setUpperBoundExclusive(false);
    productA.addExcludedSerialNumRange(r2);

    Range r3 = new Range(91);
    productA.addExcludedSerialNumRange(r3);
    Range r4 = new Range(96);
    productA.addExcludedSerialNumRange(r4);
    Range r5 = new Range(97);
    productA.addExcludedSerialNumRange(r5);
    productList.add(productA);

    //Define product B below:
    Product productB = new Product("B");
    Range r6 = new Range(50, 55);
    r6.setLowerBoundExclusive(false);
    r6.setUpperBoundExclusive(false);
    productB.addExcludedSerialNumRange(r6);

    Range r7 = new Range(65, 88);
    r7.setLowerBoundExclusive(false);
    r7.setUpperBoundExclusive(false);
    productB.addExcludedSerialNumRange(r7);

    Range r8 = new Range(90);
    productB.addExcludedSerialNumRange(r8);
    Range r9 = new Range(98);
    productB.addExcludedSerialNumRange(r9);
    Range r10 = new Range(99);
    productB.addExcludedSerialNumRange(r10);
    productList.add(productB);
}

I hope my code has helped to illustrate the difference between data, business logic, and data structure. Consider what happens when you need to update your code - you risk introducing bugs every time you change something. Keeping the data separate from the logic allows you to isolate the cause of problems. If the code didn't change, odds are it's a data problem. Once again, I just want to restate that I'm not really suggesting you store the ranges of values and so forth in a database - I suggest you store the product information itself and then use that data rather than generate a list of it with a loop.  Hope this helps and best of luck!


What would be a better way of adding the functionality to "add" a student?

mysql_* functions

Stop using them, immediately! They are essentially deprecated, as they refer to MySQL before version 4.1. They are not removed as to not brake backward compatibility, but there's no point in using them.

The drop in replacement is myslqi_* functions, which are based around a newer MySQL driver that works better with MySQL 5.x. You can easily replace most references to myslq_* functions by just adding the extra i.

But a far better solution is PDO, an object oriented database agnostic interface. Since you are starting out in object oriented PHP you'll definitely appreciate the object orient part, and as for the database agnostic part, it means that you can easily switch databases (with minor modifications).

I would advise against an ORM solution at this point, ORM's are extremely useful but can be easily abused if you aren't 100% certain on what you are doing.

global $db;

Never ever do that again. Forget about the global keyword completely. It has its uses, but in most situations it's an extremely bad habit. The object oriented way to achieve the same effect would be:

class Student {
    private $db;

    public function __construct($db, $user_id) {
        $this->db = $db;

        ...
    }
}

That's a minor example of Dependency Injection. In sort, you should feed your object what it needs, and not depend on something being available in the global namespace. You can't always be absolutely sure of that.

Public properties

Public properties violate the object oriented concept of encapsulation. You really don't want to do that, trust me :)

The most common object oriented workaround are setters and getters:

class Student {
    private $user_id;
    private $name;

    ...

    public function setUserID($user_id) {
        if( !is_int($user_id) ) {
            throw new InvalidArgumentException();
        }

        $this->user_id = $user_id;

        return $this;
    }

    public function setName($name) {
        if( !is_string($name) ) {
            throw new InvalidArgumentException();
        }

        $this->name = $name;

        return $this;
    }

    public function getUserID() {
        return $this->user_id;
    }

    public function getName() {
        return $this->name;
    }

    ...

}

Wow! So much more code for such a simple thing! Before you get discouraged, notice that I also validate the input on the setters and I'm throwing exceptions if something is wrong. That's a very good reason to use setters instead of public properties, that way you have the ability of checking what the parameter is, and if it's not the one you are expecting you can deal with it accordingly.

In the instances above I'm throwing an InvalidArgumentException, which is one of the many pre-built SPL extensions. Learn about the SPL, it offers quite a few core object oriented interfaces and classes, such as iterators.

A far better way to validate common datatypes is the filter functions, I'm not using them in the example above to not confuse you any further. And, when you feel confident enough, you can minimize the code via magic Property overloading. Fair warning, don't go there unless you know exactly what you're doing.

But never ever again have public properties, always write getters and setters. And of course, the $db property from my previous example should have its own setter. No need for a getter, unless of course you actually need to pass around the database connection object.

Lastly, notice how I return $this on the setters? This isn't something you have to do, it's a trick to allow method chaining:

$student = new Student( ... );
$student->setUserID(1)->setName("Yannis");

Or, if you prefer a slightly more readable version:

$student->setUserID(1)
        ->setName("Yannis");

Naming

As @jiewmeng writes, studentInfo should be renamed getStudentInfo. You should be very consistent on how you name functions, prefixing functions that return results with get and those that set info in the class with set is a very common practice, and one that will be familiar to most programmers, as it alludes to the concept of getters and setters I've described above.

Always return something

I don't really like it when functions don't return something:

public function studentInfo($id) {
    global $db;

    $u = mysql_fetch_array(mysql_query("SELECT * FROM $db[students] WHERE id='$id'"));
    if($u) {
         return $u;
    }
}

Here, of course you return $u;, but only if($u). For that function, I would probably return false as well:

public function studentInfo($id) {
    global $db;

    $u = mysql_fetch_array(mysql_query("SELECT * FROM $db[students] WHERE id='$id'"));
    if($u) {
         return $u;
    }

    return false;
}

Of course null is returned by default when you don't return something explicitly, but I find it a lot better when I know exactly what I should expect from a function return, and false will tell me that something failed long after I totally forget what goes on in the function. If you are in a situation where you can't think of something obvious to return, that might be a good place to throw an exception instead.

Adding a student

You could do a save() function:

class Student {

    ...

    public function save() {
        if(!this->validate()) {
            return false;
        }

        return $this->store();
    }

    private function validate() {
        // check all properties
        // if the required ones are filled and valid, return true,
        // else return false
    }

    private function store() {
        if($this->userExists()) {
            return $this->insert();
        }

        return $this->update();
    }

    private function userExists() {
        // determine if user already exists in the database
    }

    private function insert() {
        // insert user in the database
    }

    private function update() {
        // update existing user
    }

    ...
}

Of course that's more pseudo code, than code. But more or less, that's the common workflow.  I'm assuming each function returns either true or false. Notice how the return value propagates from insert() or update() to save()?

In conclusion

You need to do a lot of research into the fundamental object orient concepts. The wikipedia article is as a good place to start as any, and most articles on the specific concepts have PHP examples. Your code is clean, and you do quite a few things correctly, but you are starting out in a new programming paradigm, one that is extremely useful and extremely vague. More often than not "best practices" are not obvious, and you'll need quite solid conceptual foundations to write object oriented code.

And please, consider writing phpDoc comments.

Happy new year!


Instead of that complex switch statement, I'd just use an option object:

var allLinks = $('nav ul li a');
var rotation = 0;

$('nav').on('click', 'ul li a', function() {
    'use strict';
    var $this = $(this);
    var item = $this.parent();
    var navAll = $this.parents('ul');

    var option = {
        '0_1': {
            rotateAll: '-=90deg',
            rotateThis: '90deg',
            rotation: 270
        },
        '0_2': {
            rotateAll: '-=180deg',
            rotateThis: '180deg',
            rotation: 180
        }
        // Add them all here
    }[ rotation + '_' + item.index() ];

    if ( option ) {
        navAll.transition({rotate: option.rotateAll});
        allLinks.transition({rotate: option.rotateThis});
        rotation = option.rotation;
    }
}

There are 2 more things to consider:

Are you sure you really need that nav ul li a selector? Wouldn't nav a do the job just the same? While we're at it, why are you listening to the click on the a elements, and then find the li via .parent()? Can't you just listen to the click event on the lis themselves?
Is there any method to that configuration? I wasn't able to deduce any algorithm from what you've provided, but I'm sure there is. You'd be better off calculating it on the fly, if possible.


I'd start extracting some more functions.

What about decomposing

int NetPay(int hours){
    int payedBeforeTaxes = payedBeforeTaxes(hours);
    return applyTaxes(payedBeforeTaxes);
}

int payedBeforeTaxes(hours){
    return regularPay(hours) + overtimePay(hours);
}

int applyTaxes(int amountBeforeTaxes){
    int firstRateTaxes  = applyFirstRate(amountBeforeTaxes);
    int secondRateTaxes = applySecondRate(amountBeforeTaxes);
    int thirdRateTaxes  = applyThirdRate(amountBeforeTaxes);
    return amountBeforeTaxes - firstRateTaxes -
           secondRateTaxes - thirdRateTaxes;
}

At this point you just need to implement the functions with the appropriate code.
You'll notice that with this structure each function only does one thing and it will be much simpler and clearer.

Alternatively you can replace your apply taxes introducing an array of `(rate, threshold).
You will have to loop through the array, and at each step compute the amount you have to apply that tax rate and the associated tax amount.


Code review-wise, I'd avoid long if-elsif chains and see about converting them to a case. Also, I'd move the final formatting to the end. Otherwise, not too bad except for the fact that there are much more concise ways to do this.

One is to notice that if you go from the end of the string backwards, there are fewer cases. In fact, just one:

def price_formatter(price)
  "$" + price.reverse.scan(/.{1,3}/).join(',').reverse
end

This reverses the string, looks for groups of up to 3 and joins them with commas, then reverses back.

You may have suspected that there might be a single regex that can do the trick. You would be correct:

def price_formatter(price)
  "$" + price.gsub(/(\d)(?=\d{3}+(\.\d*)?$)/, '\1,')
end

It's a little more obtuse in my opinion.

If you happen to be using Rails, I'd use the built-in helper:

def price_formatter(price)
  number_to_currency(price)
end

There are more options to number_to_currency, but the default is the output you want. In fact you are just recreating it, so you could refactor your method away completely.

Note you need to add return if price.nil? to handle the nil case in all the above.


Properly create and customise a web app using visual studio 2015 C# MVC template

The short answer to what you are trying to do is; let the Identity classes handle Authentication and User management. You can put your User into a Model class of it's own. Then reference that from the ApplicationUser class that comes with MVC.

Another approach would be to extend the ApplicationUser class itself by adding the additional properties for your profile.

As for Business Logic and N-Tier architecture; put all that aside for the time being. The MVC architecture Semantic approach and Entity Framework kind of help to handle that stuff organically.

I would suggest going through the free training at the Microsoft Video Academy website. That should clear things up for you.
There's also a class specifically for Entity Framework.

As for the class you submitted. It looks fine. You'll probably want to revisit all the annotations learning more about Entity Framework, depending on your use case..

MVC

Identity Resources