Checking for new software updates to the client

Simplified, examplified, trimmed code is frowned upon on this site; I'm surprised this question hasn't received any close votes yet.

I don't see anything blatantly done wrong here - I like . On the other hand if the client code you've shown is cohesively written in a specialized service (class) with a clear, focused interface that your ViewModel  receives as a constructor parameter and assigns to a private readonly field, then you've probably done the wpf part right.

If that very same code is written in some Button1_Click handler in your View's code-behind, it could be the most cleverly written, beautifully crafted little piece of code, it would still be horribly misplaced.

</rant>

I still have a couple of things to say about your code:

private ApplicationDbContext db = new ApplicationDbContext();

The db identifier is misleading. I prefer to use context over db, because db refers to a database; a context, or data context, is more accurate. That said, by newing up your context inside your controller, you have tightly coupled your controller with the specific ApplicationDbContext class.

The Controller class implements IDisposable; you should override the Dispose method and properly dispose of your ApplicationDbContext instance.

An alternative would be to depend on an abstraction instead:

private readonly IDbContext context;

The dependency can then be constructor-injected, and the Controller doesn't care what the actual implementation is, it's simply calling methods defined by some interface.

This would greatly improve the controller's testability.

CheckVersionResult result = new CheckVersionResult();

I'm not a fan of this verbose notation; I find result is screaming its type at me, and I don't need that.

var result = new CheckVersionResult();

I find var makes more concise code that literally reads as "there's a variable here called result that we're going to assign to a new instance of the CheckVersionResult type" - as opposed to "there's a variable here of type CheckVersionResult called result that we're going to assign to a new instance of the CheckVersionResult type". But it boils down to personal preference I guess.

What isn't about personal preference, is consistency. Why is the client code different?

var url = new Uri(CheckUrl + "?" + parameters);
using (var client = new System.Net.WebClient())
{
    var json = await client.DownloadStringTaskAsync(url);

..and the next line goes:

CheckVersionResult data = JsonConvert.DeserializeObject<CheckVersionResult>(json);

I really prefer var I don't mind either notation, but using both interchangeably is wrong.

I like that you're using await. This means you've written this code in an async method. That method's name should return a Task or a Task<T>, and have an Async suffix in its name, to follow convention.


Generate sample coordinates inside a Polygon

Style Nitpicks

Put spaces after commas / Keep Lines within 120 Chars

poly = Polygon([(141.4378366,-25.95915986), (165.4279876,-29.43400298), (163.1382942,-47.65345814), (133.1675418,-42.99807751)])

becomes

poly = Polygon([(141.4378366, -25.95915986), (165.4279876, -29.43400298), (163.1382942, -47.65345814),
                (133.1675418, -42.99807751)])

Use Pythonic Underscores

minx, miny, maxx, maxy = poly.bounds

becomes

min_x, min_y, max_x, max_y = poly.bounds

Eschew Semicolons (Personal Opinion)

You can use semicolons like this:

longs = np.arange(minx, maxx, 0.002); lats = np.arange(miny, maxy, 0.002)

But personally, I just wouldn't in Python. Eww.

An Alternative Algorithm

EDIT: Having read @MrE's and @MartinR's comments, I now propose this rejection sampling method. Although, this could miss frequently in a polygon with a large bounding box relative to its area; .e.g. an 8-point Christmas star with a small inner circle.

def random_points_within(poly, num_points):
    min_x, min_y, max_x, max_y = poly.bounds

    points = []

    while len(points) < num_points:
        random_point = Point([random.uniform(min_x, max_x), random.uniform(min_y, max_y)])
        if (random_point.within(poly)):
            points.append(random_point)

    return points

Another alternative that never misses, but may not be well distributed.

This was my original idea, but it didn't look so good in the morning.

Firstly, work out how to select one point within a polygon.

def random_point_within(poly):
    min_x, min_y, max_x, max_y = poly.bounds

    x = random.uniform(min_x, max_x)
    x_line = LineString([(x, min_y), (x, max_y)])
    x_line_intercept_min, x_line_intercept_max = x_line.intersection(poly).xy[1].tolist()
    y = random.uniform(x_line_intercept_min, x_line_intercept_max)

    return Point([x, y])

Then simply call that in a list comprehension to generate however many points you desire.

points = [random_point_within(poly) for i in range(5)]
checks = [point.within(poly) for point in points]

My approach is to select x randomly within the polygon, then constrain y.

This approach doesn't require NumPy and always produces a point within the polygon.


Form a firstname.lastname@domain.se address, eliminating diacritics from a name

You can chain replaces and you don't need to replace "n. spaces" -> " ", you can just replace them with a "." if you trim first

String s = JOptionPane.showInputDialog(null, "Ange namn och efternamn");
s = s.trim()
      .replaceAll("\\s{2,}", ".")
      .toLowerCase()
      .replace('å', 'a')
      .replace('ä', 'a')
      .replace('ö', 'o');
JOptionPane.showMessageDialog(null, s + "@nackademin.se");


WOMOIWIW: What Org-mode Opens is What I Want

That's a cool feature I've to say.  And the code looks excellent, I
suppose you could argue for one or the other wrt. cond vs. if
etc. but that's pointless pedantry IMO.
Given that it works flawlessly (tried locally and via tramp as well), I
was unsure there was actually anything to say here, but I found two
points that might be of interest:
Firstly, while the :around combinator works fine, it might be more
appropriate to use :filter-args, since it's really just filtering the
arguments:
(defun my-org-link-open-advice (args)
  "Advice for ORIG-FUN that expands patterns in 'file:' LINKs.
See `my-org-expand-file-link' for more information.
Optional argument ARGS are passed as-is."
  (list* (my-org-expand-file-link (first args)) (rest args)))

(advice-add 'org-link-open :filter-args #'my-org-link-open-advice)

The functionality is absolutely unchanged of course.
Secondly, and this is conflicting with the previous point, I could
imagine using the prefix argument (so C-u C-c C-o) to
distinguish the two cases of whether to run the original behaviour, or
not, like so:
(defun my-org-link-open-advice (orig-fun link &optional arg &rest args)
  "Advice for ORIG-FUN that expands patterns in 'file:' LINKs.
See `my-org-expand-file-link' for more information.
Optional argument ARGS are passed as-is."
  (apply orig-fun (if arg link (my-org-expand-file-link link)) arg args))

To quote the function docstring for org-link-open:

ARG is an optional prefix argument.  Some link types may handle it.
For example, it determines what application to run when opening a
"file" link.

This might interfere with the above idea, however practically I couldn't see a
difference with the unadvised function and this argument being present
or not, YMMV.


Rational class supporting precise numbers

Not a complete answer, but I noticed some bugs:

LCM = function(a, b) {
  return Math.abs(a * b) / GCF(a, b);
};

The computation of a * b will easily overflow (thus losing precision) for large numbers a, b. You can improve matters by rewriting it as

function LCM(a, b) {
  var g = a / GCF(a,b);
  return Math.abs(g * b);
}

I also used function LCM as opposed to LCM = function just as a stylistic preference. See here.

Similarly:

Rational.prototype.add = function(other) {
  var lcm = LCM(this.bottom, other.bottom);
  // If we multiply by lcm
  // it becomes an integer
  // but we round to prevent floating point innacuracies
  var top1 = Math.round(this * lcm);
  var top2 = Math.round(other * lcm);
  return new Rational(top1 + top2, lcm);
};

If I understand correctly, in the expression this * lcm, lcm is a Number, so you're basically doing this.valueOf() * lcm, which again wipes out all your pretended precision. You should avoid big numbers (which become floating-point), and you should definitely avoid unnecessary floating-point divisions.

Rational.prototype.add = function(other) {
  var lcm = LCM(this.bottom, other.bottom);
  var top1 = this.top * (lcm / this.bottom);
  var top2 = other.top * (lcm / other.bottom);

  return new Rational(top1 + top2, lcm);
};


The first part could be rewritten as

match list with
| hd1 :: hd2 :: tl when hd1 > hd2 -> getHighest (hd1 :: tl)
| hd1 :: hd2 :: tl -> getHighest (hd2::t1)
| hd1 :: [] -> hd1
| _ -> failwith "unknown pattern"

which is significantly simpler


All-purposes AJAX handler made with PHP and .htaccess that speaks JSON - Part 2

There are two things I would refactor.

The first if statement (now) checks if the session has been initialized. I think this can be done in a more readable way by using the native PHP function session_status(). You can also write the admin check into a variable. This small refactor will make the if-statement more readable.

$session_name = session_name();

/*
 * Checks if a session exists and that the session was initialized
 * properly.
 */
$session_active = (session_status() == PHP_SESSION_ACTIVE);

/*
 * Checks if an administrator is logged in and that his
 * access level is greater than 2.
 */
$admin_authorized = (isset($_SESSION['admin'] && $_SESSION['admin']['level'] > 2)

if(!isset($_COOKIE[$session_name]) || !$session_active || !$admin_authorized) {

    header('HTTP/1.1 403 Forbidden');
    echo '{"error":403}';

    /*
     * Remember to exit to ensure execution is stopped.
     */
    exit;

}

It doesn't hurt to write an extra variable if it helps readability. A too long or complex if-statement-body can hurt readability, because it can be hard to keep track of what conditions has been checked or what the condition actually does. By extracting the logic into variables you can also better document the specific piece of logic. Consider writing all documentation before the whole statement or before each variable definition.

Then there are the part where you check if the requested file exists. I think this should be refactored as well. You should also remove the silence operator. According to documentation is_file also checks if the file actually exists.

I would refactor this to:

/*
 * This may seem redundant, but experience has taught me that you should only
 * perform one manipulation on a variable per line. Its easier to read what is
 * actually happening and to modify it later.
 */
$file = preg_replace('@^/([a-z_]+)\.php@', '$1', $_SERVER['ORIG_PATH_INFO']);
$file = ROOT . '/ajax/' . $file . '.php';

if(!is_file($file)) {

    /*
     * The requested file does not exist.
     */
    header('HTTP/1.1 404 Not Found');
    echo '{"error":404}';
    exit;

}

// Continue execution as the file exists.

In the last post you also mentioned security. As said in that post I'm not security expert, but one thing that I have made a habit is to extract values from superglobals using the filter_input() function. It helps you filter out the input to better match your exact requirements. Imagine an input that was expected to provide a string, but was in fact an integer, due to a malicious user. This would break your code. As an example when extracting the ORIG_PATH_INFO you would write.

/*
 * There might be more/better filters. To add more filters delimit them
 * using the pipe-character: |
 */
$original_path_info = filter_input(INPUT_SERVER, 'ORIG_PATH_INFO', FILTER_SANITIZE_STRING);

This helps make sure the variable is actually a string. Its not bulletproof (no where near actually), but it could remove malicious code from a potential attacker.

Hope this helps, happy coding!


Convert a list of sets into the minimum list of non-intersecting sets

I guess this has a performance \$O(k \cdot n^2)\$ where \$n\$ is the count of lists, and \$k\$ is the average length of each set.

You shouldn't guess the time complexity, you should carefully analyze your code, so let's do that:

The empty test check is \$\mathcal{O}(n)\$.
The foreach is over all sets in the input, that's \$n\$.
The while loop is over all sets in the output so far. The number of iterations will form something similar to arithmetic progression, with maximum at \$m\$, the number of sets in the output. The average is going to be \$\approx m/2\$, so this part is going to contribute \$\mathcal{O}(m)\$.

(A formal proof would require proving that “something similar to arithmetic progression” will actually contribute that, but this is not a formal proof)
Calculating intersection and complements of sets is going to be \$\mathcal{O}(k)\$.
Inserting in the middle of a List of length \$\mathcal{O}(m)\$ is \$\mathcal{O}(m)\$.

Put together, we have \$\mathcal{O}(n + n \cdot m \cdot (k + m)) = \mathcal{O}(n \cdot m \cdot (k + m))\$.

That Insert annoyingly increases the complexity, but we can easily get rid of it either by using LinkedList (and walking it instead of using indexes) or by Adding at the end of the List (and making sure we don't iterate over the sets that were just added). This will bring us to \$\mathcal{O}(n \cdot m \cdot k)\$.

So, how big is \$m\$? Your estimate indicates you assumed it's \$\mathcal{O}(n)\$, but even your example shows that it can be larger than \$n\$. So, can it actually grow beyond \$\mathcal{O}(n)\$? Turns out, it can: when each of the \$n\$ sets has exactly one element in common with each other set*, then in the output, each of the \$n(n-1)/2\$ elements has to be in its own set, so the length of the output is \$\mathcal{O}(n^2)\$.

This means, that the total worst case complexity of your algorithm is \$\mathcal{O}(n^3  \cdot k)\$

* Or, in the language of graph theory, the sets are sets of incident edges for vertexes of a complete  graph on \$n\$ vertices.

For some inputs, your output contains lots of empty sets that don't belong there. For example, try it on new[] { new[] { 1 }, new[] { 1, 2 }, new[] { 1, 2, 3 } }.

// Special case: if there is a null set we have to add it first

No, you don't need a special case for the empty set. It doesn't intersect with anything, so both your requirement will be still fulfilled, even if you don't include it in the output.

.Count()

I think it's better to use the Count property instead of the Count() extension method, to make it clear that it's an \$\mathcal{O}(1)\$ operation, not \$\mathcal{O}(n)\$.


jQuery - Repeating same actions on different DOM elements

You're right, you are violating some DRY rules, so lets clean it up. First, I would cache some of the selectors you're calling.

var $info = $('.userInfo');
var $details = $info.find('.details');
var $detailsExpand = $info.find('.expandUserDetails');

Then I would take a look at some of the toggle options that jQuery offers, mainly:

toggleClass
slideToggle

This will save you the trouble of having to use .addClass, .removeClass, slideUp, and slideDown.

For example, you have:

if ($('.paymentInfo .details').is(':hidden')) {
    $('.paymentInfo .details').addClass('active').slideDown();
    $('.paymentInfo .expandPaymentDetails').removeClass('down').addClass('up').addClass('active');
} else {
    $('.paymentInfo .expandPaymentDetails').removeClass('up').addClass('down').removeClass('active');
    $('.paymentInfo .details').removeClass('active').slideUp();
}

We can remove that else statement, and just let our new toggle methods handle the adding/removing.

if ($details.is(':hidden')) {
    $details
        .toggleClass('active', true) // true means the class will be added
        .slideToggle();

    $detailsExpand
        .toggleClass('down', false)  // false means the class will be removed
        .toggleClass('up', true)
        .toggleClass('active', true);
}

Lastly, and this might be overkill, you could try creating a jQuery plugin:

$.fn.toggleDetails = function (options) {
    var settings = $.extend({
        infoClass: null,
        expandClass: null
    }, options);

    var $info = $(settings.infoClass);

    var $details = $info.find('.details');
    var $detailsExpand = $info.find(settings.expandClass);

    if ($details.is(':hidden')) {
        $details
            .toggleClass('active', true)
            .slideToggle();

        $detailsExpand
            .toggleClass('down', false)
            .toggleClass('up', true)
            .toggleClass('active', true);
    }
};

And then applying your new plugin would be as easy as calling the .toggleDetails method on your selected elements, and providing both an infoClass and expandClass.

$('.user .expandDetails a').toggleDetails({
    infoClass: '.userInfo',
    expandClass: '.expandUserDetails'
});

$('.user .paymentDetails a').toggleDetails({
    infoClass: '.paymentInfo',
    expandClass: '.expandPaymentDetails'
});

Caveats:

This code hasn't been tested.
I'm not sure how to assign a down or up to slideToggle. I would have expected a similar true/false parameter similar to toggleClass.


Use range

The loop over sizes doesn't use the loop index, so it can be written more idiomatically using range:

for _, size := range sizes {
    // ...
}

Variable declarations

At many places you declare variables at the top of the function. This is neither necessary not recommended. It's best to declare variables right before you need them, not sooner.

Related to this, most functions use a named return value. This can be useful sometimes. But in the posted code, most of the time you return a value explicitly, and only use a parameterless return at the end of functions, so you might as well drop the naming and return nil where you need it.

Lastly, in resizeImage signature, you could shorten width int, height int like you already did in other functions.

Logging

I don't understand what os.Stderr is doing in the calls to log.Println. This function will write to standard error the parameters passed to fmt.Sprintf. If you want to log to standard error, you can replace log.Println(os.Stderr, err) with simply log.Println(err). The os.Stderr is not doing anything useful there, I suspect it was a symbol mistake.

Formatting

The code doesn't follow the standard at a few places. Run go fmt to fix it.


K&R Exercise 1-6 & 1-7: working with EOF

This is a nice, clear, short attempt at the exercise.
You've avoided a couple of common problems:

You're correctly using int for the return value from getchar().  A common mistake is to be misled by the name and to assign directly to a char variable.  That doesn't work, because truncating to char prevents EOF from being distinguished from a valid char value.
You've correctly matched the %d specifier to the type of EOF.

One simple way to improve your code is to get the compiler to point out weaknesses for you (by default, most C compilers are very lenient; you have to specifically ask for more warnings):
gcc -std=c11 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion putchar.c -o putchar

You can make it easier by writing a simple Makefile that contains just:
CFLAGS = -std=c11 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion

And you can then build simply with
make putchar

When you've enabled warnings, you'll see:
198374.c:3:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
 void main()
      ^~~~

The fix for that should be obvious.

Now to the meat of the program.  Firstly, before the loop we have a statement
    c = getchar();

This consumes and ignores one character.  We probably didn't mean to throw that one away.

Now consider this expression:
 (c = getchar()) != EOF == (0 | 1)

We're actually comparing (after the assignment) c != EOF against 0|1.  But | is the bitwise-or operator, so 0|1 evaluates to just 1.  When c is not EOF, then c!=EOF is 1, and the condition is satisfied.  The last time around the loop (when c becomes EOF), then c!=EOF is 0, and the loop exits.
What we want to do is save the result of c != EOF and compare that to 0 and to 1 separately.  Or, even more simply for this exercise, just print it to standard output:
    do {
        c = getchar();
        printf("getchar() != EOF: %d\n", c != EOF);
    } while (c != EOF);

Note: given that we haven't been asked to copy the input to output, we shouldn't have the putchar() call.
If we really want to prove that c != EOF is always either 0 or 1, we could test it automatically:
    do {
        c = getchar();
        if ((c != EOF) != 0  &&  (c != EOF) != 1) {
            fprintf(stderr, "(c != EOF) was neither 0 nor 1\n");
            return 1;
        }
    } while (c != EOF);

You might choose to use a switch statement instead of the if; I think that's clearer:
        c = getchar();
        switch (c != EOF) {
        case 0:             /* okay */
        case 1:             /* okay */
            break;
        default:
            fprintf(stderr, "(c != EOF) was neither 0 nor 1\n");
            return 1;
        }

Modified code
#include <stdio.h>

int main()
{
        int c;

        do {
            c = getchar();
            switch (c != EOF) {
            case 0:             /* okay */
            case 1:             /* okay */
                break;
            default:
                fprintf(stderr, "(c != EOF) was neither 0 nor 1\n");
                return 1;
            }
        } while (c != EOF);

        printf("%d\n", c);
}


Iterate array with delay in between using promise

The promise is to do the JOB
and report back when done. Promises are not for timeouts to communicate, they do that already via the call back, and a timeout's callback is as good as a promise, with a lot less overhead.
I have not looked at the code for BlueBird so I can not determine its quality and thus your code. But I see two promises where there should only be one, so there is room for improvement.
Why do you need a promise?
You have to consider why you want to have a promise. Creating a promise just so you can start another is adding an extra layer of unneeded complexity.
You want a promise so that you can have some code execute when the job is complete, or if there is a chance the job may not complete, you have a promise to have code executed for that situation.
Whenever you write any sort of code, always ask yourself, is this step really needed, if you can do without then it should not be there.
One promise
The following will do what you want with only one promise needing to be created. The timeouts handle the timing, and all you want to know is that you get a promise to know when the job is done.

const log = arg => console.log(arg);
const keyOn  = key => log("On : "  + key);
const keyOff = key => log("Off : " + key);

const keyClick = (key, ms, end) => {
    keyOn(key);
    setTimeout(() => {
        keyOff(key);
        setTimeout(end, ms);
    }, ms);
}
// using async function means that if the keys array is empty
// you can just let the function fall through to resolve
async function keySequence(keys, ms = 50){
    var complete;  // to hold the resolving promise callback
    const step = () => {
        keyClick(  // do a key click, keyDown 50ms, keyUp, 50ms
            keys.shift(), // get the next key
            ms,           // delay between keys
            (keys.length > 0 ? step : complete) // call next step or resolve
        );
    };
    if (keys.length) {  // only if there are keys
        step();  // start the first key
        return new Promise(done => complete = done ); // get the resolve from promise
    }
    // function fall through automaticly resolves the async promise.

}
keySequence(["1","2","3","4","5"]).then(() => log("done"));

The example can be simplified by having the keyClick body in the step function, I seperated them to make it clearer.
Personally the rampant bad use of promises sometimes makes me wish they were never added to the language. We have gone from callback hell, to the promise chain highway to hell, and by the look of the other answer, awaiting a million promises in hell.


Merging (not removing) duplicated elements in a vector

Looks pretty good already! Here's some ideas for improvement.

You can make implement Add and AddAssign for Stat so that you can use + and += on those. Here's an AddAssign implementation:

impl std::ops::AddAssign for Stat {
    fn add_assign(&mut self, other: Self) {
        self.points += other.points;
        self.fouls += other.fouls;
    }
}

I like that you reached for a HashMap and fold, those are definitely how I'd do this. However, you only need to store the name and stat (HashMap<String, Stat>), which will make it so you don't have to clone the name each time and also reduce size. You can simply reconstruct the players at the end, before the collection.

Another thing is that you currently perform two lookups in the hashmap for every insertion. The Entry API is a great tool to learn for interacting with maps. It lets you interact with a possibly missing element of the map and only perform one lookup.

Here's a implementation with what I've mentioned so far.

use std::collections::hash_map::Entry;

let dup_merged: Vec<_> = players
    .into_iter()
    .fold(
        HashMap::new(),
        |mut acc: HashMap<String, Stat>, curr: Player| {
            match acc.entry(curr.name) {
                Entry::Occupied(mut occ) => {
                    // This player already exists, increase its stats
                    *occ.get_mut() += curr.stat;
                }
                Entry::Vacant(vac) => {
                    // No such player exists, insert these stats
                    vac.insert(curr.stat);
                }
            }
            acc
        },
    )
    .into_iter()
    .map(|(k, v)| Player { name: k, stat: v })
    .collect();

There's another simplification that can be made, due to Stat being a small, cheap struct with sensible default values: You can have Stat implement Default, and then instead of inserting an entry if its missing, you can just have it default to a zero'd Stat and always add:

#[derive(Default, Debug)]
struct Stat {
    points: u32,
    fouls: u32,
}
// ...
let dup_merged: Vec<_> = players
    .into_iter()
    .fold(
        HashMap::new(),
        |mut acc: HashMap<String, Stat>, curr: Player| {
            *acc.entry(curr.name).or_default() += curr.stat;
            acc
        },
    )
    .into_iter()
    .map(|(k, v)| Player { name: k, stat: v })
    .collect();


you can use groupby.transform

df["next_timestamp"] = df.groupby("id")["time_stamp"].transform(
    lambda x: x.shift(-1)
)


Solving the 'Vietnamese school maths problem'

I'm not familiar with either the alexandria or infpre packages; I wrote my solution in Common Lisp as well, but using only language primitives. Assuming that the infpre evaluator follows standard arithmetic order-of-evaluation rules, your code looks perfectly fine (and more compact and readable than mine) but of course requires having those packages available. More importantly, your code should produce the same answers as my (different) approach.

I used my approach to make sure that the variables were local and that the compiled code manipulated them efficiently. (I ran mine in Clozure Common Lisp which compiles all expressions to machine code before running them).

;; Transcription of expression from puzzle picture
(defvar *expression* '(+ a (/ (* 13 b) c) d (* 12 e) (* -1 f) -11 (/ (* g h) i) -10))

;; Macro to generate nested loops trying all combinations
(defmacro nested-loops (variables variable-initializer body)
  (let ((internal-variable (gensym)))
    `(let ((answers))
       ,(nested-loops-helper t variables variable-initializer body internal-variable)
       answers)))

;; Helper function for macro to generate loop guts for each level
(defun nested-loops-helper (first-time variables variable-initializer body internal-variable)
  (cond ;; no more variables, generate body
    ((null variables)
     `(,@body))
    ;; otherwise generate a loop setting this variable to all possible values except ones already used
    (t (let* ((this-var (pop variables))
              (extra (when first-time `(for ,internal-variable = nil))))
         `(loop for ,this-var ,@variable-initializer ,@extra
            unless (member ,this-var ,internal-variable)
            do (push ,this-var ,internal-variable)
            (,@(nested-loops-helper nil variables variable-initializer body internal-variable))
            (pop ,internal-variable))))))

;; Invocation of macro to solve puzzle (prints all answers and saves them in solutions variable)
(length (setq solutions
          (nested-loops (a b c d e f g h i) (from 1 to 9)
                (let ((value #.*expression*))
                  (when (eql value 66)
                (print (list a b c d e f g h i))
                (push (list a b c d e f g h i) answers))))))

(format t "~&There are ~d solution~:p saved in the variable solutions.~%" (length solutions))


Is my Node/Express-based authentication implementation with session properly done?

Heyo!

This is pretty good, but doesn't have any password hashing (storing your passwords in plain text is bad).

You might want to instead consider using an authentication library like either passportjs or stormpath.

If you're really set on rolling your own auth stuff, you could use this project I wrote as an example (it's using the same tools you are): https://github.com/rdegges/svcc-auth

UPDATE: Since I was asked to show a Stormpath example, here ya go!

var express = require('express');
var stormpath = require('express-stormpath');

var app = express();
app.use(stormpath.init(app, {
  apiKeyId: 'xxx',  // get this from your stormpath account
  apiKeySecret: 'xxx',  // get this from your stormpath account
  secretKey: 'some_long_random_string',  // this is used to encrypt sessions
  application: 'xxx',  // create a stormpath app, then copy the href here
}));

app.listen(3000);

That's it! The above code will automatically generate a registration, login, and logout page at /register, /login, and /logout, respectively.


I'm not sure how you would shorten this code. However I think that callback is a terrible name for a function that fades a CSS class. Remember that a function signature should represent what a function does and with that said I would rename it to something like fadeUpdateNotification().

And in the fashion of fading you could replace .show() with .fadeIn() to have the div fade in and out - I dunno how your styling/website looks like but that might look nice...


I'm not sure how the actual python implementation for this works but you could query the length of *args to assign the parameters to the right variables:

def Range(*args):
    len_args = len(args)
    if len_args == 2:
        args = args + (1,)
    elif len_args == 1:
        args = (0, args[0], 1)
    start, end, step = args
    ...

In addition I would make this a generator (similar to how it is in python 3.x):

def Range(*args):
    len_args = len(args)
    if len_args == 2:
        args = args + (1,)
    elif len_args == 1:
        args = (0, args[0], 1)
    start, end, step = args

    while start < end:
        yield start
        start += step


Efficient data-driven finite state machine

Nice work.

On findWeekdayDate() return, I'd expect a value that is enumerated like fWD_SUCCESS, fWD_FAIL, fWD_SUCCESS_for_foo_reason, fWD_FAIL_for_bar_reason, etc. Rather than magic numbers -1,0,3,....  It could end up being a simple bool.
As fsm[] is const struct fsmNode, I see no value in making a field const like const char target.  char target is simpler and sufficient.  OTOH, if there is some value, then next should also be const as in const struct fsmNode * const next.
Delay/remove #includes.

#include <string.h>  // Needed?
#include <stdlib.h>  // OK, for NULL
#include <ctype.h>   // Needed?

Style inconsistency.  Recommend empty for body to match other indentations.

// for ( ; state->target && *curr != state->target; ++state)
//{ /* do nothing */ }
for ( ; state->target && *curr != state->target; ++state) {
  /* do nothing */
}

Use an auto formatter.  The extra space betrays manual formatting as it is inconsistent with the rest of code.  Life is too short for manual formatting.

//             v
for (curr = str ; *curr; ++curr) {

Suggest adding link to software used to create FSM.


The "shoelace" formula finds the area of a simple polygon:

from __future__ import division

def polygon_area(points):
    """Return the area of the polygon whose vertices are given by the
    sequence points.

    """
    area = 0
    q = points[-1]
    for p in points:
        area += p[0] * q[1] - p[1] * q[0]
        q = p
    return area / 2

if __name__ == '__main__':
    square = [(0,0), (0,1), (1,1), (1,0)]
    irregular = [(1,1), (1,5), (2,5), (5,1)]
    print('Unit square area: {}'.format(polygon_area(square)))
    print('Irregular polygon area: {}'.format(polygon_area(irregular)))

This outputs:

Unit square area: 1.0
Irregular polygon area: 10.0


Generalize code that populates MFC list control?

To Generalize it:

class MyDialog
{
    template<typename T, typename A>
    void SetCustomerList(T const& customers, A action);
    ....
};

template<typename T, typename A>
void MyDialog::SetCustomerList(T const& customers, A action)
{
    .....
    // AddCustomerToListControl(*it);
    action(*it);
    .....
}

// At call point:
SetCustomerList(customers, &AddCustomerToListControl);

Other Changes:
You can use the standard algorithms:

    for(std::list<Customer*>::const_iterator it = customers.begin();
            it != customers.end() ; it ++)
    {
        AddCustomerToListControl(*it);
    }

Can be replaced with:

    std::for_each(customer.begin(), customer.end(), AddCustomerToListControl);
    // or in the new code:
    std::for_each(customer.begin(), customer.end(), action);


Simplify finding indices of all instances of certain characters in a string

Simplify is a relative term. If you want simple, then I would have:

public static int[] findWrappingIndices(final String s) {
    int pos = 0;
    int[] ret = new int[s.length()];
    for (int i = 0; i < s.length(); i++) {
        if (WRAPPING_CHARS.indexOf(s.charAt(i)) >= 0) {
            ret[pos++] = i;
        }
    }
    return Arrays.copyOf(ret, pos);
}

But, you want to complexify it by using a SortedSet (because int[] is not easy to use?), so you can then convert the int[] to the SortedSet.

I don't see why the SortedSet is a good idea, but, it is easy enough to convert to using it (even though it is bigger and slower than an int[] array).

I don't think you will find a simpler (or faster) alternative.

I would guess that you could quavify it with (note the data is being inserted in sorted order anyway):

public static SortedSet<Integer> findWrappingIndices(final String s) {
    SortedSet<Integer> indices = Sets.newTreeSet();
    for (int i = 0; i < s.length(); i++) {
        if (WRAPPING_CHARS.indexOf(s.charAt(i)) >= 0) {
            indices.add(i);
        }
    }
    return indices;
}


Select and delete objects from S3 container

I think your function names could use some work. There is no need to specify that return_candidates_for_deletion actually returns those candidates (it is obvious). It is also a bit superfluous to know that extract_list_of_backups returns a list. It is enough to know that it returns a collection that is iterable (whether or not that is a tuple, list, set or even just a generator does not really matter for the rest of the code).

In addition, you can save a lot of code by changing your internal data structure a bit. The main thing your code does is sort the backups by the gitlab version and then keep only some of them. So you should store the files in a dictionary with the gitlab version as the key:

import boto3
from collections import defaultdict

class GitlabBackups:
    def __init__(self, bucket_name):
        self.bucket_name = bucket_name

        self.s3 = boto3.resource('s3')
        self.bucket = self.s3.Bucket(bucket_name)

    def backups(self):
        return (obj.key
                for obj in self.bucket.objects.all()
                if 'gitlab_backup' in obj.key)

    def group_by_version(self, files):
        backups = defaultdict(list)
        for file_name in files:
            gitlab_version = file_name.split('_')[4]
            backups[gitlab_version].append(file_name)
        return backups

    def candidates_for_deletion(self, generations_to_keep=2):
        for files in self.group_by_version(self.backups()).values():
            # files.sort()  # is this not needed?
            yield from files[:-generations_to_keep]

    def delete_old_backups(self, generations_to_keep=2):
        for key in self.candidates_for_deletion(generations_to_keep):
            self.s3.Object(self.bucket_name, key).delete()

Here I put all the related standalone functions into the class. It has now one generator that yields all backup files, one that creates the dictionary with the versions as keys, one generator that yields all files except for the generation to keep for each version and then the actual deleting method.

Note that with this, as with your code, it is not guaranteed that the latest generation is actually at the end of the list of files. It depends on the order of self.bucket.objects.all(), so on how S3 returns it (which is apparently alphabetical). But you might want to make sure from your side as well and sort each files list in candidates_for_deletion.

In order to make this a bit more reusable, you could then pull out a groupby method that is similar to itertools.groupby but different because it consumes the whole input and therefore does not require the input to be sorted:

def groupby(objects, key=lambda x: x):
    out = defaultdict(list)
    for obj in objects:
        out[key(obj)].append(obj)
    return out

class GitlabBackups:
    ...
    @staticmethod
    def gitlab_version(file_name):
        return file_name.split('_')[4]

    def candidates_for_deletion(self, generations_to_keep=2):
        for files in groupby(self.backups(), key=self.gitlab_version).values():
            yield from files[:-generations_to_keep]


You could also use .hover, if you are going for shorter code.
Jquery Hover


First thing first
Don't use tqdm just to show some fancy progress bar. On their website, they say the overhead is low (which it might be the case), but you can just print something like: Processing data. Please wait... until the data is processed.
Or, you can use timeit module to see how long your code takes.

Second, fix the bug:
This line:
flow_session.append(str(temp.iloc[count, 2]) + temp.iloc[count, 3])

Will throw an IndexError: single positional indexer is out-of-bounds because of temp.iloc[count, 3] which makes your code off-topic for this site's purpose.
Perhaps you wanted:
flow_session.append(str(temp.iloc[count, 1]) + temp.iloc[count, 2])

Instead of:
visitors = set(d['visitor_id'])

You can use:
visitors = d.visitor_id.unique()

In your for loop, you already have the unique visitors so why calculating them again ? Just do:
for visitor_id in visitors
    ...

Use len(df.index) instead of len(df). Due to one additional function call it is a bit slower than calling len(df.index) directly, but this should not play any role in most use cases.

You're not using numpy so you can remove it.

After I spent quite some time on this, I came up with a different approach which is probably better (and shorter):
Suppose you have the following dataframe:
d = pd.DataFrame(columns=['visitor_id', 'row_num', 'contenttype'], data=[
    ['abc', 1, 'PageA'], ['abc', 2, 'PageB'], ['abc', 3, 'PageC'],
    ['def', 1, 'PageB'], ['def', 2, 'PageD'], ['crf', 7, 'PageE']
])

You can create a new column which is the joint between rownum and content:
d["joint"] = d.row_num.astype(str) + d.contenttype

Then, you just want to group your data by visitor_id and create a list of lists with that and the joint. That can be easily done using a list comprehension and groupby:
result = [list(group.joint.values) for name, group in d.groupby("visitor_id")]

So, the final code looks like this:
import pandas as pd

def process_data(_df):
    _df["joint"] = _df.row_num.astype(str) + _df.contenttype

    return [list(group.joint.values)
            for name, group in d.groupby("visitor_id")]

if __name__ == '__main__':
    d = pd.DataFrame(columns=['visitor_id', 'row_num', 'contenttype'], data=[
        ['abc', 1, 'PageA'], ['abc', 2, 'PageB'], ['abc', 3, 'PageC'],
        ['def', 1, 'PageB'], ['def', 2, 'PageD'], ['crf', 7, 'PageE']
    ])
    print(process_data(d))

I don't think you can get any better than that.


Here is how I've written most of my NSpec tests, I usually start a context out with an act.  This dry's up the specification.  If I find myself doing too many "acts", I end up breaking it up into separate specifications.

class describe_JavaScriptBundle : nspec
{
    JavaScriptBundle bundle;

    void AddTest1JS()
    {
        bundle.Add("test.js");
    }

    void before_each()
    {
        bundle = Bundle.JavaScript();
    }

    void adding_a_bundle()
    {
        context["no files added"] = () =>
        {
            it["GroupBundle contains default key"] = () =>
                bundle.GroupBundles.ContainsKey("default").is_true();

            it["has no Assets"] () =>
                bundle.GroupBundles["default"].Assets.Count.Is(0);
        };

        context["adding one file"] = () =>
        {
            act = () => AddTest1JS();

            it["contains the file"] = () =>
                bundle.GroupBundles["default"].Assets.Count.Is(1);

            context["adding the same file again"] = () =>
            {
                act = () => AddTest1JS();

                it["should still only contain one file"] = () =>
                    bundle.GroupBundles["default"].Assets.Count.Is(1);
            };
        };
    }
}


Kindergarten Garden challenge: ugly zip-group-flatten?

It's not a bad solution, but it doesn't feel quite fluently expressed in Python.  In particular, I feel like the conversions between lists and generators are unnatural.  It would also help if you toned down the functional thinking in favour of list comprehensions.

I'll start by mentioning that blank lines between method definitions would make your code more readable, as suggested in PEP 8.  Also, constants should be named using ALL_CAPS.

Let's start with the constructor:

def __init__(self, rows, students=None):
    self.rows = rows.splitlines()
    if students is None:
        students = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred",
                    "Ginny", "Harriet", "Ileana", "Joseph",
                    "Kincaid", "Larry"]
    self.students = sorted(students)
    self.plant_assignments = {student: list(plant_group) for student,plant_group
            in zip(self.students, self.plant_groups(self.rows))}

You aren't taking full advantage of the default parameter for students.
self.rows and self.students are never used outside of the constructor.  As they aren't useful as part of the state of the Garden object, they could just be local variables.
The dict(iterable) constructor would be a more succinct way to define self.plant_assignments than the set comprehension.

The "public" method, plants(), would be clearer if you renamed name to student.

The functions get_plant_name() and plant_groups() are for "internal" use.  Interspersing them among methods in the public interface makes your code less readable.

They are also "pure" functions that don't depend on any object state.  I suggest declaring them as static methods.

The heart of the solution is plant_groups():

def plant_groups(self,rows):
    """(Docstring omitted)"""
    grouper_by_two = partial(grouper, n=2)
    grouped_by_two = map(grouper_by_two, rows)
    cubewise = zip(*grouped_by_two)
    flat_cube = flatten(cubewise)
    flat_cube_with_names = map(self.get_plant_name, flat_cube)
    yield from grouper(flat_cube_with_names, 4)

In Python, map() is usually slightly better written as a list comprehension instead; partial() makes the case for a list comprehension even more compelling.

Instead of cubewise, I suggest the name plots, which forms a clear and simple mental image that is highly relevant to the problem being solved.

flatten() works recursively.  I suggest using a list comprehension (see implementation below) so that such recursion would no longer be necessary.  In fact, by flattening all the way to a linear list, you need to reorganize the individual pots into groups of 4.

Using yield from is an unnecessary complication.  It just requires the caller to convert the results back into a list using list(plant_group).

Putting everything together…

from itertools import chain

def grouper(iterable, n):
    return zip(*[iter(iterable)] * n)

def flatten(seq):
    yield from chain(*seq)

class Garden(object):
    PLANT_NAMES = {
         "G": "Grass",
         "C": "Clover",
         "R": "Radishes",
         "V": "Violets",
    }

    STUDENTS = [
        "Alice", "Bob", "Charlie", "David", "Eve", "Fred",
        "Ginny", "Harriet", "Ileana", "Joseph",
        "Kincaid", "Larry"
    ]

    @staticmethod
    def get_plant_name(plant_letter):
        try:
            return Garden.PLANT_NAMES[plant_letter]
        except KeyError:
            raise ValueError("Plant letter {} is not defined".format(plant_letter))

    @staticmethod
    def plant_groups(rows):
        grouped_by_two = [grouper(row, 2) for row in rows]
        plots = zip(*grouped_by_two)
        return [
            [Garden.get_plant_name(plant) for plant in flatten(plot)]
            for plot in plots
        ]

    def __init__(self, rows, students=STUDENTS):
        rows = rows.splitlines()
        students = sorted(students)
        self.plant_assignments = dict(zip(students, self.plant_groups(rows)))

    def plants(self, student):
        return self.plant_assignments[student]


size_t current_line = 1, columns;

It's generally better to either initialize every variable or none in a declaration.  This is especially so since you declare another variable without initialization on the next line.

size_t iter;

This use of iter is ... uncommon.  The name iter has a very specific meaning.  I would have expected this to be an iterator.  Instead, it's just a normal index variable.  You seem to be using it as a generic name for a variable used to iterate in a for loop, but there already is a standard variable for that:  i.

for(iter = 0; source[iter] != '\0' && current_line != line; iter++)

So as I read that, if current_line is greater than line, you should keep on incrementing until the program crashes or we loop around?  Admittedly that should never happen, but this code is not robust in the face of a change that would make it do so.

memcpy(buff, source + iter * sizeof(char), columns);

The iter * sizeof(char) is incorrect.  It will multiply iter by sizeof(char) twice:  once, explicitly; a second time, implicitly, for the pointer arithmetic.  The correct way to write this is just source + iter.  This probably works here, because sizeof(char) is usually 1.  It's highly vulnerable to someone using a multibyte char though.  And of course, it would give the wrong result for almost any other data type.


public interface IInfiniteCounter : IEnumerable<(int Value, InfiniteCounterState State)>

vs

    int Current { get; }

    (int Value, InfiniteCounterState State) Next();

    void Reset();

The interface itself looks a lot more like IEnumerator<> than IEnumerable<>, so IMO implementing IEnumerable<> is misleading and dangerous. The docs for IEnumerable<> don't say either way whether or not it's possible to have two active enumerators at the same time, but I can't think of any implementations in the standard library for which it isn't possible, and I've probably written a lot of code which assumes that it is possible.

    int Min { get; }

    int Max { get; }

    int Length { get; }

I can safely assume that Min is inclusive, but I absolutely need a comment to tell me whether Max is or not, and it would be helpful to have a comment indicating the standard implementation of Length. Also, should Length be uint both because it's guaranteed to be non-negative and to avoid overflow in edge cases?

public static class IndexMath
{
    public static int Flip(this int value, int min, int max)
    {
        return (-(value - max + 1) % (max - min)) + min;
    }
}

I don't understand why this method uses %. For me the obvious interpretation of the name (and the use case) is max - (value - min). If there's some trickery going on to avoid or handle overflow, it needs explanatory comments.


I would think a better approach might be to identify location of spaces in string and look for cases where there is index position > 40 between these spaces, and then to insert the space into the string as necessary.

This would certainly be a memory-optimized way of working with this as you could potentially only need to hold the subject string (with any inserted separators) in memory, along with a few helper variables.

Your current approach would hold all the following in memory:

$text - the main subject string
temporary storage of explode results
$word - a substring duplication of content already stored in $text)
$result - an array containing duplicated content from $text + inserts
$data - a duplicate copy of content in $result just joined into a string on the separator.

So, there is a lot of duplication of storage in your solution.

I am guessing there is also increased operational complexity around the explode() and implode() operations that could be avoided.

I would also consider generalizing this into a function.  I have given some sample code below for how this might look:

function chunk_substring(
    $subject_string,
    $separator = ' ',
    $max_substring_length = 40,
    $chunk_size = 8
) {
    // not shown - validate input as non-zero length strings or positive integers
    // as appropriate. May also want to check logic around chunk size
    // needing to be less than max substring length and such

    // loop through index positions of separator in target string
    $previous_index = 0;
    $continue = true;
    $separator_length = strlen($separator);
    while ($continue) {
        $next_index = strpos($subject_string, $separator, $previous_index);
        if($next_index === false) {
            // separator not found in remainder of string
            $continue = false;
            continue;
        }
        if($next_index === $previous_index) {
            // we had a separator match at beginning of string
            // or consecutive separators
            // let's increment $previous_index by separator length
            $previous_index += $separator_length ;
            continue;
        }
        if(($next_index - $previous_index) >= $max_substring_length) {
            // we have a "long" substring
            // let's start inserting separators into it
            $idx = $previous_index + $chunk_size;
            while ($idx < $next_index) {
                // insert $separator at $idx
                $subject_string = substr_replace(
                    $subject_string,
                    $separator,
                    $idx,
                    0
                );

                // update $next_index to account for length of newly added
                // segment to string
                $next_index += $separator_length;

                // increase $idx by $chunk_size + $separator_length
                $idx = $idx + $chunk_size + $separator_length;
            }
        }
        // We are done evaluating / modifying this string segment
        // Set $previous_index to $next_index value in preparation for
        // next iteration
        $previous_index = $next_index;
    }

    // return the string
    return $subject_string;
}

This approach would hold the following in memory:

$subject_string - would potentially grow as separators are inserted. You could also potentially have the function pass this by reference if you desire to have this function directly modify the external variable that is passed in
$separator - small string
Various low memory footprint integer variables for configuration and index storage.

Much less duplication in memory in this case to where overall memory utilization would scale (more or less) 1:1 with size of input string.

You might take a look at the accepted answer for the StackOverflow post I have linked below which deals with the related question of using explode() vs. string tokenization, which is, in essence, what I am proposing.  You might consider running a similar test to find out for your self what works best for your use cases.

https://stackoverflow.com/questions/5861826/exploding-an-array-within-a-foreach-loop-parameter


Processing array of objects into two strings

You can get by with just two lines:

particulars_string = items.map(&:particular).join("\n")
amounts_string     = items.map(&:amount).join("\n")

Enumerable#map, which is mixed into Array, creates a new array from an existing array by running a block on each element and storing the result. In this case though you don't need a full block, since you just need to call a single method (particular or amount). So it basically extracts those into new arrays and then joins those arrays.

As a rule of thumb, you almost never have to "manually" map stuff from one array to another in Ruby using each and <<. Be sure to read the docs for Array and Enumerable as they're full of good stuff.


Variable declaration outside or inside when using on of the methods of Array.prototype

Concerning your variable scope, I think it is safer to define it inside the function as it will assure you get the value inside it. That way you won't be able to access a filled in parts variable after your function - in this case it makes no difference, but once you have a couple more things going on it is best to declare your variables with as little scope as possible. This is because you variables will be cleaned up automatically after your function has ended (and garbage collection has come by), which means you are freeing up memory and not filling it with data you won't use anymore.

I have been able to eliminate almost all your variables because of returns. Instead of storing something when you just need to use it to return, just return it directly. It cuts down on a lot of variables, and a lot of code.

The point is that you don't need to use variables unless you need to use them later. After deciding what variables to use, you have to decide what scope you need. Keep the scope as small as possible, so it's as predictable as possible to see what variable is available where and reduce memory consumption.

window.app = {
    combos: {
        a: 'A-A-B-C-C',
        b: 'A-B-C',
        c: 'A-B-C-C-D'
    },
    check: function () {
        // If like declaring variables at the top, it keeps the rest consistent
        return Object.keys(this.combos).forEach(function(combo){
            // `combo` is already defined, and since you don't use
            // this.combos anymore after this, dont store it in a var
            var parts = this.combos[combo].split('-').sort();
            // Also, I also recently came across this
            // clever piece on Code Review:
            return parts.forEach(function(part, index){
                // To check duplicates, just check
                // if first index != last index
                if(index != parts.lastIndexOf(part)){
                    document.write('DUPLICATED PART IN: ' + combo + ' : ' + part + '
');
                    // You can just return here.
                    // Breaks the loop and returns!
                    return false;
                }
                return true;
            });
        }, this);
        return result;
    }
}

document.write('>>>' + (window.app.check() ? 'Completed without duplicates' : 'Duplicates found.'));

I also replaced your alert with document.writes as alerts are just... annoying in my opinion. Check the snippet above to see a nice result.

One more thing: if you do want to bind a this arguments to forEach, it already provides a quick way to do that: the second argument of the forEach function is actually defined as thisArg:

arr.forEach(callback[, thisArg])

Your assumption is correct: variables declared within blocks are scoped only to that block. If, however, you omit the keyword var, they will be avail;able outside your block as they are usually appended to the top-level object in the chain, usually the window.

document.write('Executing a function that uses var to declare local scope.
');

+function(){
    var foobar = 'Foo Bar';
}();

document.write(typeof foobar !== 'undefined' ? '>>Foobar is ' + foobar : '>> Foobar is undefined.
');

/*-------------------------------*/

document.write('Executing a function that does not use var to declare local scope.
');

+function(){
    foobar = 'Foo Bar';
}();

document.write(typeof foobar !== 'undefined' ? '>> Foobar is: ' + foobar : '>> Foobar does not exist
');

/* Note: using the + sign is equal to wrapping the function in brackets etc... Its create a temporary scope an executes in it. */


Why do you have a build_tree function instead of a BST class with a constructor? It can just be a container to wrap around Node, but that way you can encapsulate things better. Generally, a BST isn't used because people want access to the tree structure, but because it's being used as a min heap or for quicker searching than O(n). If you really want to, you can expose the Nodes, but it'd still be better to wrap it in a class, if only so that...
...You can write your search functions as methods on the tree class. That would make more sense than passing in a parameter which is, essentially, self.

You could then make more convenience methods, like insert and remove, which would allow you to easily create trees from unsorted arrays and provide those methods to the caller.

Use a Set for your visited collection, unless you really like O(n), as opposed to O(1). lookup.
Likewise, use a Queue for your queue. That way you get O(1) enqueue and dequeue; with a normal array, one of the two is O(1), but the other is O(n) (depending on which end you enqueue and dequeue from)
I'd bet you can guess what I'm gonna say about your stack variable. But you're wrong! Haha, fooled you! Anyway, an array is fine for that, since (a) there's no Stack class in the Ruby standard library, at least as far as I'm aware, and arrays have O(1) push/pop if you use the methods with those names (which you do), as long as it never needs to resize to accommodate more elements. Even if it does, though, that happens relatively rarely; it's normally O(1).
Why are you putsing your return values instead of using those arrays you love so much? And why do you exit instead of returning? What if I want to run your example and see both outputs?
All in all, this code doesn't feel very Ruby-ish -- it seems more like a straight translation from the C++ equivalent. However, I can't think offhand of an elegant, straight-forward way to do the same thing, so I'm just going to leave you with this vague admonishment.
On second thought, scratch #6. I didn't really pay attention to what you were doing, but you shouldn't replace puts with return. Instead, if you reach the end, return false; if you find an equal element, return either true or the path you took to get there, if the path is that important.

It's worth noting that there's no point in making this a binary search tree if you're going to do a brute-force search every time. The point of a BST is that, at any given node, you can compare what you're looking for with the data of that node, and figure out if you have to go left or right or if you've found it, and thereby eliminate the need for breadth-first searching in general.

If you're only going to have B/DFS, just make it a generic tree, and don't bother with that fancy stuff about ordering and the like that you have in your "constructor". That'll be a better test, anyway, since a B/DFS is typically used in cases where you don't have ordering. If you really wanna keep the ordering, try writing a binary search; it's a fun little exercise.


Using mutable keyword to implement an owner-pointer class (C++03)

OK. Lets ignore that you are screwing around with mutable.

No Strong Exception Guarantee.

void pass(T* ptr = NULL)
{
    if (p != ptr)
    {
        delete[] p;   // if p throws then your object is left in
                      // an invalid state and you have leaked the
                      // pointer `ptr`
        p = ptr;
    }
}

You should do this in an exception safe way. Which requires the use of a temporary.

void pass(T* ptr = NULL)
{
    if (p != ptr)
    {
        T* tmp = p;
        p = ptr;
        delete[] tmp;   // now it is safe to delete.
                        // even if it throws this object is consistent
                        // and you have not leaked ptr.
    }
}

Double ownership check

Both this method and the previous check for self assignment. Because this function calls the above function you perform a self assignment check twice when you use the assignment operator.

owner_ptr& operator=(const owner_ptr<T>& rhs)
{
    if (this != &rhs)  // Check here
    {
        this->pass(rhs.get_ownership());  // Check inside pass()
    }
    return *this;
}

I would change both of these methods to call a private method that does the check and work.

owner_ptr& operator=(const owner_ptr<T[]>& rhs)
{
    private_pass(rhs.get_ownership());
    return *this;
}

void pass(T* ptr = NULL)
{
    private_pass(ptr);
}
private:
void private_pass(T* ptr)
{
    if (p != ptr)
    {
        T* tmp = p;
        p = ptr;
        delete[] tmp;
    }
}

No Throwing methods

Since the get_ownership() method is guaranteed not to throw you should probably mark it as such.

T* get_ownership() throw();

Questions:

  Is it a bad idea to use mutable to solve the ownership-passing problem?

Probably. Mutable is really for designating members that are not part of the objects actual state (ie temporary caches).

  Are there any scenarios where it can cause undefined behaviour?

Don't think so. You will just loose out on certain optimizations.

  Is there anything that I implemented incorrectly in the template?

Don't see anything.

  Any affect on performance?

Yes. As noted above the compiler can not apply certain optimizations when a member is marked mutable.

  Before C++11, why did we have only the silly std::auto_ptr which couldn't be used with std::vector?

Because the language did not have the features required to implement modern smart pointers. The auto_ptr was the first attempt at a smart pointer and it worked to a certain extent it just had limitations.

It took them 8 years to improve the language enough so that smart pointers could be implemented properly.


Found a little inconsistency in your Vue template

Using v-bind: syntax here,

... but using : shorthand here:

Useless variable app

const app = new Vue({ /* ... */ });

Do I need to say more?

EDIT: YES.
From ESLint: "Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers."

Object method notation shorthand

Instead of using:

getOutput: function(number) { /* ... */ }
// ...
getClass: function(number) { /* ... */ }

You could use:

getOutput(number) { /* ... */ }
// ...
getClass(number) { /* ... */ }

Too specific CSS selector

You're specifying these selectors,

li.FizzBuzz { /* ... */ }
li.Fizz { /* ... */ }
li.Buzz { /* ... */ }

but there aren't any elements that would have these classes (FizzBuzz, Fizz and Buzz) other than li's. This means you could simplify it to:

.FizzBuzz { /* ... */ }
.Fizz { /* ... */ }
.Buzz { /* ... */ }


Not bad for a beginner, and I agree with Ben Aaronson's comments. Maybe not now, but when you progress, you should change some things:

Break the code up in logical parts (here: methods), and every part should
have one and only one task (Single Responsibility Principle). In your
application, getting the data is one task, calculating is one task and
displaying the results is one task
Error Handling (see Ben's answer)
Testing! Learn to write JUnit tests! It leads "automatically" to better code, not only because you avoid programming errors, but also because you learn to break up code to make it testable
Make your code both scalable, and applicable in different scenarios. For instance, the if-cascade is easy to write and to understand, but it doesn't scale (what if you need 20 cases?), and it is not freely applicable (e.g. you can't pass it around, the ifs are basically "glued" in place)

Although it might be a little bit too advanced for a beginner: Regarding the last point I want to show you a trick even some senior programmers don't know:

import java.util.Scanner;
import java.util.TreeMap;

public class BMI {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter your details to calculate your Body Mass Index.");
        System.out.println("Enter your weight in kilograms:");
        double weight = scanner.nextDouble();
        System.out.println("Enter your height in metres:");
        double height = scanner.nextDouble();
        scanner.close();
        double bmi = weight / (height * height);
        System.out.println("Your BMI is: " + bmi);

        TreeMap<Double, String> map = new TreeMap<>();
        map.put(40.0, "Serious obesity");
        map.put(30.0, "Obesity");
        map.put(25.0, "Overweight");
        map.put(18.0, "Standard");
        map.put(0.0, "Underweight");

        System.out.println(map.floorEntry(bmi).getValue());
    }
}

There is a data structure which can do all the if-checks for you, which makes the code trivial to write, scalable, and easy applicable: A TreeMap.

A Map is just a kind of dictionary where you can find "stuff" under a given key. In a TreeMap the keys are ordered. In Java's TreeMap you can not only ask for keys, but also for values between the keys, which get rounded up (ceiling...) or down (floor...) to the next key in the map.


Optimizing program to output all numbers summing to 100

General remark

Short code (as in less space in code) is not necessarily easier to read, nor does it need to be faster. You can try to keep removing unnecessary stuff until it is as short as possible, but please keep it readable. Writing code is hard, reading code is twice as hard.

Short answer

Online, everywhere, in books. "Effective Java" for example. Read about algorithms and data structures. Look at how others solved problems. Read many code reviews.
Use a profiler and measure where your code is slow.

Longer answer

You need to expose yourself to a lot of code, and start with simple problems. See how you would solve it, then look how others solved it and try to improve upon it.
For this case: try to represent your operators and operands in such a way that you can evaluate them in Java.  Generally: use the correct data structures and algorithms. That is most important. Then, try to use the right types. String concatenation is generally a lot slower in execution time than integer math.

Example

For example to evaluate and generate the permutations (using recursion just because we can :):

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

public class MakeHundred {

    private static int LENGTH = 8;

    // Encode the operators in a enum. We use the factor to implement
    // easier operation later on, and the display String as well.

    enum Operator {

        PLUS(1, "+"), MINUS(-1, "-"), NONE(0, "");

        private int factor;
        private String display;

        public String getDisplay() {
            return display;
        }

        Operator(int factor, String display) {
            this.factor = factor;
            this.display = display;
        }

        public int getFactor() {
            return factor;
        }

    }

    /**
     * Class for keeping a permutation, with is an list of operators which will be
     * used to create a sum, eg. 1 op1 2 op2 3.
     *
     * @author RobAu
     *
     */
    public static class Permutation {

        Operator[] operators;

        // Just one operator
        public Permutation(Operator operator) {
            this.operators = new Operator[] { operator };
        }

        // Copy the given permutation, append the given operator
        public Permutation(Permutation sourcePermutation, Operator operatorToAppend) {
            this.operators = Arrays.copyOf(sourcePermutation.operators, sourcePermutation.operators.length + 1);
            this.operators[sourcePermutation.operators.length] = operatorToAppend;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < operators.length; i++) {
                sb.append(i + 1);
                sb.append(operators[i].getDisplay());
            }
            // append the last digit
            sb.append(operators.length + 1);
            return sb.toString();
        }

        public int evaluate() {
            int index = 0;
            int currentNumber = 0;
            int total = 0;

            // We start with a previous operator (+),
            // So the code becomes simpler.
            // 1+2 = 0 + 1 + 2.
            Operator operator = Operator.PLUS;

            while (index < LENGTH) {

                currentNumber += (index + 1);

                // If there is no operator, we are making a bigger number.
                if (operators[index] == Operator.NONE) {
                    currentNumber *= 10;
                } else {

                    // We increate the total by adding the current Number
                    // and using the previously seen operator
                    total += currentNumber * operator.getFactor();
                    currentNumber = 0;
                    operator = operators[index];
                }
                index++;
            }

            // add the last number.
            currentNumber += index + 1;
            total += currentNumber * operator.getFactor();

            return total;
        }

        /**
         * Generate all permutation with length length
         */
        public static List<Permutation> generate(int length) {
            return generate(null, length);
        }

        private static List<Permutation> generate(List<Permutation> permutations, int length) {

            List<Permutation> perms = new ArrayList<>();
            if (length == 1) {
                for (Operator o : Operator.values()) {
                    perms.add(new Permutation(o));
                }
            } else {
                for (Permutation p : generate(permutations, length - 1)) {
                    for (Operator o : Operator.values()) {
                        perms.add(new Permutation(p, o));
                    }
                }
            }
            return perms;
        }
    }

    public static void main(String[] args) {
        for (Permutation p : Permutation.generate(null, LENGTH)) {
            if (p.evaluate() == 100) {
                System.out.println(p);
            }
        }
    }
}

Including JVM startup this runs in:

real    0m0,088s
user    0m0,088s
sys 0m0,012s


Convert minutes portion of time to decimal

Use const instead of let to declare variables if the value doesn't change.

You are executing time.split(':') twice.

A short method to convert a string to a number is the unary +.

JavaScript has the toFixed() method to format a number to a fixed number of digits:

function minuteConverter(time) {
   const [h, m] = time.split(':');
   const value = +h + +m / 60;
   return value.toFixed(2);
}


Formatting a datetime string in the YYYYMMDD format

Yes there is: Date Formatting

var dateString = DateTime.Now.ToString("yyyyMMdd");


Some thoughts about the code itself.

In general method names recommended as Pascal Case so sendEmail should ideally be named SendEmail
I might consider trying to make the class a bit more configurable so that it could be extended in more ways without being modified.  For example if you wanted to send a text email, or you wanted to send an email using a different server.

The modified code might look like:

public class Emailer
{
    // Required for emailer to work
    private readonly string _host;
    private readonly int _portNumber;

    // Optional configurable options
    public bool IsHtml { get; set; }
    public MailPriority Priorty { get; set; }

    public Emailer()
        : this("mailexchanger_String", 25)
    {

    }

    public Emailer(string host, int portNumber)
    {
        _host = host;
        _portNumber = portNumber;

        IsHtml = true;
        Priorty = MailPriority.High;
    }

    public void SendEmail(
        string bodyText,
        string sender,
        List<string> recipientAddresses)
    {
        SendEmail(
            bodyText,
            new MailAddress(sender),
            recipientAddresses.Select(p => new MailAddress(p)).ToList());
    }

    public void SendEmail(
        string bodyText,
        MailAddress sender,
        List<MailAddress> recipientAddresses)
    {
        // .NET 4.0 only for SmtpClient disposing
        using (var smtpClient = new SmtpClient(_host, _portNumber))
        {
            using (var mailMsg = new MailMessage())
            {
                mailMsg.From = sender;
                mailMsg.Body = bodyText;
                mailMsg.IsBodyHtml = IsHtml;
                mailMsg.Priority = Priorty;
                recipientAddresses.ForEach(p => mailMsg.To.Add(p));

                smtpClient.Send(mailMsg);
            }
        }
    }
}

You can also configure an SMTP client via the .config.  In that case
you do not need to provide the connection details in the code but instead can configure it via the .config file.

For an MVC.net application that may be in the web.config or for a desktop application that might be in an app.config.

<system.net>
<mailSettings>
  <smtp from="<fromaddress>">
    <network host="mailexchanger_String" password="??" userName="??" port="25" enableSsl="true" defaultCredentials="false" />
  </smtp>
</mailSettings>
</system.net>

This means that you could create the SMTP client on Emailer creation and then dispose it as necessary.  In this case the code might look like

internal class Emailer : IDisposable
{
    // Our smtp client that will be disposed
    private readonly SmtpClient _smtpClient;

    // Optional arguments
    private bool _isHtml = true;
    public bool IsHtml { get { return _isHtml;  } set { _isHtml = value; } }

    private MailPriority _mailPriority = MailPriority.High;
    public MailPriority Priorty { get { return _mailPriority;  } set { _mailPriority = value; } }

    public Emailer()
    {
        _smtpClient = new SmtpClient();
    }

    public Emailer(string host, int portNumber)
    {
        _smtpClient = new SmtpClient(host, portNumber);
    }

    public void SendEmail(
        string bodyText,
        string sender,
        List<string> recipientAddresses)
    {
        SendEmail(
            bodyText,
            new MailAddress(sender),
            recipientAddresses.Select(p => new MailAddress(p)).ToList());
    }

    public void SendEmail(
        string bodyText,
        MailAddress sender,
        List<MailAddress> recipientAddresses)
    {
        using (var mailMsg = new MailMessage())
        {
            mailMsg.From = sender;
            mailMsg.Body = bodyText;
            mailMsg.IsBodyHtml = IsHtml;
            mailMsg.Priority = Priorty;
            recipientAddresses.ForEach(p => mailMsg.To.Add(p));

            _smtpClient.Send(mailMsg);
        }
    }

    public void Dispose()
    {
        _smtpClient.Dispose(); // Or not if using < .NET 4.0
    }
}

And used like:

using(var emailer = new Emailer())
{
    emailer.SendEmail(
        bodyText,
        sender,
        "sendtome"
    );
}


You should add a class to all elements, something like .day, and then use that class in your code:

$('.day').click(function() {
    if ($(this).hasClass("active")){
        $(this).switchClass( "active", "inactive", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', true);
    } else {
        $(this).switchClass( "inactive", "active", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', false);
    }
    $(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});

Another way would be:

$('#Monday, #Tuesday, #Wendnesday').click(function() {
    if ($(this).hasClass("active")){
        $(this).switchClass( "active", "inactive", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', true);
    } else {
        $(this).switchClass( "inactive", "active", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', false);
    }
    $(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});


JavaScript coding tips on creating a string from variables tags

Fun project, but I feel like you have overengineered this quite a bit... Why not just build the url from the given values without all the "@@"? I see there is some difference between URLs, but my first suggestion would be to make them uniform and have a simple function that builds the url from the given components to reduce the complexity enormously.
But ok, let us focus on your code and how it can be improved.
I copied your code and it didn't run. In your function replaceAllTagsToValue, you are calling .reduce on a value, which will always be an object in your code. You cannot reduce an object so I don't know how this "works correctly" or, in fact, works at all. Nevermind that, I understand what you're trying to do! Let's have a look at my suggested edits:
const translator = {
  "@@login@@":  (user) => user.login,
  "@@passwd@@": (user) => user.passwd,
  "@@ip@@":     (_, camera) => camera.ip,
  "@@stream@@": (_, camera, type) => camera.flux[type].stream,
  "@@port@@":   (_, camera, type) => camera.flux[type].port,
  "@@flux@@":   (_, camera, type, flux) => camera.flux[type][flux]
};

const makeCameraUrl = (user, camera, type, flux) =>
  Object.entries(translator)
  .reduce(
    (url, [key, value]) => url.replace(key, value(user, camera, type, flux)),
    camera.url);

const user = json.users.view;
const camera = json.devices[102];
const type = "rtsp";
const flux = "hd";
makeCameraUrl(user, camera, type, flux);
// > "rtsp://user:yyyyyy@192.168.0.102:554/1"

You are actually doing a lot of nice stuff:

Properly using const for immutable values
Using arrow notation for simple one-line functions
Tricky higher-order array functions such as reduce

But there seems to be a problem with every one of those points. To start:

⚛ constantly changing
In javascript, you have four ways of declaring (I know, JS is horrible) a variable: var, let, const or none of those to define a global. For the sake of brevity: never use var (it's weird) and never make globals (this pollutes your namespace and maybe even other people's code).
As for let and const, they function identically to eachother but with an important difference: const declares a variable (or a constant, rather) that is immutable -- it cannot be changed after declaration.
const immutable = 1;
immutable = 2;
// > TypeError: Assignment to constant variable.

You can't reassign it.
This is useful for technical reasons (your javascript engine could optimise your code under the hood), but also for reasons of readability and deliberateness. When you use const, you're telling me, the reader, "I'm declaring a value here that I will not change later on, don't worry." I know I can trust this because javascript wouldn't even let you re-assign it even if you tried. You start off your program with two consts, but then you drop it and create a global :
makeCameraUrl = function (camera, type, flux, user) {
  //...
}

You have now created a function that will take up memory forever until you explicitly remove it from the global scope, and maybe you have just overwritten some other global value with that name... Globals, like I said, are a nightmare and I strongly advice against ever using them (like this anyways). The simplest fix here is to just plonk a const before it and we're save again:
const makeCameraUrl = function (camera, type, flux, user) {
  //...
}

 lets set this straight
But then, you're suddenly using let...
let cam_id = "102";
let url = makeCameraUrl(cameras_cfg.devices[cam_id], "rtsp", "hd", cameras_cfg.users.view);

The purpose of let is to create a mutable variable; its value can change at any time, in any place. Personally I think that's not a wise way to treat a value because we humans are dumb and history has shown us we are not good at keeping track of mutation of our variables.
But alright, if you have to change a value then go ahead and use let. But what I'm seeing here are values that never change. I know this because I read through the entire code, but I would have liked to know this from the start. When you use let, you're telling the reader "Hey, I'm defining a value here but I'm going to change it later on." When you never change a variable you've defined with let, you're lying  -- and code should never lie.
Again, the simplest fix here is to just make it const:
const cam_id = "102";
const url = makeCameraUrl(cameras_cfg.devices[cam_id], "rtsp", "hd", cameras_cfg.users.view);

 Consistency
Not only did you use three ways of defining variables, you also use two ways of defining functions. Again, all these inconsistencies make your code have a high amount of WTF/minute.

It doesn't matter wich way you define functions, as long as you are deliberate about it. In javascript there's only one reason to differentiate between function types but that doesn't apply to your code, so I suggest you just use arrow functions like you did in the beginning:
const makeCameraUrl = (camera, type, flux, user) => {
  //...
}

This code tells me there is nothing fancy going on besides a plain old function -- just how I like them.
This matter of consistency also applies to the way you name things. You use both snake_case and camelCase, but I couldn't really find a reason for the difference.
const cameras_cfg = //...
const replaceAllTagsToValue =  //...

makeCameraUrl =  //...

let cam_id =  //...
let url = //...

If I'm right in this assumption (code that requires assumptions has a high rate of WTF/minute), please stick to either one to avoid such confusion. Again, doesn't matter which one, just stick to it after you choose (things such as casing and other issues of consistency can be alleviated by using code linters such as eslint).
Personally I don't like either way of casing my variables but my preference would go to camelCase because that way I don't have to contort my hand to type underscores all the time. As for legibility, I'd say that snake_case is better. You choose.
const cameraConfig = //...
const replaceAllTagsToValue =  //...

makeCameraUrl =  //...

let cameraId =  //...
let url = //...

On a side-note: I took the liberty to change some variables to better describe what they are:

camera_cfg... Luckily I know that cfg is short for config, but don't make me guess. Plase don't abbreviate your variable names -- we're not in the 90's anymore . Also, is it really a config? Are you using this json to allow for customisation, or are you just using it to store data?
cam_id... Camper id? Camouflage id? I understand that you mean camera, but the less I have to interpret what you mean, the better I understand what you actually mean. Deliberateness is actually the most important part of programming; functioning code is merely a byproduct.

 The meat
Now that the low hanging fruit is out of the way, let's look at the most important part (the meat) of your program:
makeCameraUrl = function (camera, type, flux, user) {
    var url = camera.url;
    var Obj = {
        "@@login@@": user.login,
        "@@passwd@@": user.passwd,
        "@@ip@@": camera.ip,
        "@@stream@@": camera.flux[type].stream,
        "@@port@@": camera.flux[type].port,
        "@@flux@@": camera.flux[type][flux]
    };
    return replaceAllTagsToValue(Obj, url)
}

If I understand correctly, you're using an object to encode information about a camera, and putting that info into the camera's url and return it. That's a great idea, but the way you did it has a few nasty side-effects.
Creating an object in every function call (Obj in this case) is expensive, and the garbage collector will make your browser hang a little everytime your single-use objects need discarding. My proposed solution is to yoink the object out of the function scope, and into the scope of the rest of the program. To keep the dynamic nature of the values of the object, I used functions:
const translator = {
  "@@login@@":  (user) => user.login,
  "@@passwd@@": (user) => user.passwd,
  "@@ip@@":     (_, camera) => camera.ip,
  "@@stream@@": (_, camera, type) => camera.flux[type].stream,
  "@@port@@":   (_, camera, type) => camera.flux[type].port,
  "@@flux@@":   (_, camera, type, flux) => camera.flux[type][flux]
};

The way these functions are set up, allows you to just call them with predefined arguments (makeCameraUrl(user, camera, type, flux)) and always get the correct value back. The underscore (_) in some of these functions is a colloquial way of saying "I'm not interested in this parameter." It's quite universal between languages.
Lastly, I took the liberty to change your code a bit to make it run so your makeCameraUrl function does what I think you meant it should do:
const makeCameraUrl = (user, camera, type, flux) =>
  Object.entries(translator)
    .reduce(
      (url, [key, value]) => url.replace(key, value(user, camera, type, flux)),
      camera.url);

We loop over all entries of the translator object, which yields an array like this:
[
  ["@@login@@",  () => /*...*/]
  ["@@passwd@@", () => /*...*/]
  ["@@ip@@",     () => /*...*/]
  ["@@stream@@", () => /*...*/]
  ["@@port@@",   () => /*...*/]
  ["@@flux@@",   () => /*...*/]
]

An entry is a two-element array with its first element being the key, and the second being its value.
We then reduce over these entries, starting with a default value of the camera's URL. I'm going to write out the lengthy version of what this reduce does:
const makeCameraUrl = (user, camera, type, flux) =>
  Object.entries(translator)
    .reduce(
      (url, [key, value]) => url.replace(key, value(user, camera, type, flux)),
      camera.url);

// Is the same as the following:

const makeCameraUrl = (user, camera, type, flux) =>
  camera.url
    .replace("@@login@@",  translator["@@login@@"](user, camera, type, flux))
    .replace("@@passwd@@", translator["@@passwd@@"](user, camera, type, flux))
    .replace("@@ip@@",     translator["@@ip@@"](user, camera, type, flux))
    .replace("@@stream@@", translator["@@stream@@"](user, camera, type, flux))
    .replace("@@port@@",   translator["@@port@@"](user, camera, type, flux))
    .replace("@@flux@@",   translator["@@flux@@"](user, camera, type, flux));

// Is the same as the following:

const makeCameraUrl = (user, camera, type, flux) =>
  camera.url
    .replace("@@login@@",  user.login)
    .replace("@@passwd@@", user.passwd)
    .replace("@@ip@@",     camera.ip)
    .replace("@@stream@@", camera.flux[type].stream)
    .replace("@@port@@",   camera.flux[type].port)
    .replace("@@flux@@",   camera.flux[type][flux]);

Quite elegant, if this was your intention.

 The end
Hopefully you've learned some things form this answer (if not, sorry for the long post ). It's a good start, but keep my tips in mind and you'll be a JS guru in no time :)


I'll first offer some critique of your code, and then I'll show you how I would approach the problem.

Commented out code should be removed before asking for a code review #print(f"start={start}\tstop={stop}\tcount={count}")
Many of the comments don't add value. # last position doesn't mean much on its own. Why do you want the last position? Why doesn't the code do a good enough job explaining that?
Generally an if/else in a loop where one of branches is only taken once, either at the start or end, can be removed. You can iterate less, and deal with the case explicitly. You can add a sentinel value so you don't have to check if you are at the end of the iterator. You can used the available libraries or built-in functions, which will deal with the case for you.

# load with pandas
df = pd.read_csv(file, sep='\t', header=None)

# set colnames
header = ['chr','start','stop','strand','count']
df.columns = header[:len(df.columns)]

# index where count=1
col_count = df['count'].tolist()
li = [i for i, n in enumerate(col_count) if n == 1]

If the header is cut short len(df.columns) < len(header), the first thing to be cut off is the column df['count']. You then assume it exists straight away after by using it. Which is it? Will it always exist, or sometimes will there not be enough columns? Erring on the side of it always exists, the code becomes
# load with pandas
df = pd.read_csv(file, sep='\t', names=('chr', 'start', 'stop', 'strand', 'count'), header=None)

# index where count=1
col_count = df['count'].tolist()
li = [i for i, n in enumerate(col_count) if n == 1]

# index where count=1
col_count = df['count'].tolist()
li = [i for i, n in enumerate(col_count) if n == 1]

...

for idx, elem in enumerate(li):

If you are using pandas (or numpy) it is generally not the best to move the data back and forth between the library and Python. You lose most of the efficiency of the library, and the code generally becomes far less readable.
Don't use names like li. It doesn't give any information to the reader. If you have a list of indices, what will you use the list for? That would make a much better name.
Using pandas more, and renaming gives something like
splitting_indices = df.index[df['count'] == 1].tolist()

for idx, elem in enumerate(splitting_indices):

if next_elem - (elem+1) == 1: # cases where only one position and we cannot compute median
    count = df.iloc[elem+1]['count']
    #print(f"start={start}\tstop={stop}\tcount={count}")
else:
    count = df.iloc[elem+1:next_elem]['count'].median()

Finding this logic in amongst getting the data out from the dataframe is not easy. This is the core logic, and should be treated as such. Put this in a function at the very least.
def extract_median(df, elem, next_elem):
    if next_elem - (elem+1) == 1: # cases where only one position and we cannot compute median
        count = df.iloc[elem+1]['count']
    else:
        count = df.iloc[elem+1:next_elem]['count'].median()
    return count

Now it should be much more apparent that the comment is bogus. You CAN compute the median of a single element list. So why are we special casing this? df.iloc[elem+1:next_elem] works even if next_elem is only one bigger than elem+1.
def extract_median(df, elem, next_elem):
    return df.iloc[elem+1:next_elem]['count'].median()

And now we can see that a function is probably not necessary.

The approach I would take to implementing this is to try and stay using pandas as long as possible. No loops. No tolist. Since I won't want loops, indices are probably not needed too, so I can limit usage of iloc and df.index.
First, read in the data
df = pd.read_csv(file, sep='\t', names=('chr', 'start', 'stop', 'strand', 'count'), header=None)

     chr  start   stop strand  count
0   chr1      0  13320      -      1
1   chr1  13320  13321      -      2
2   chr1  13321  13328      -      1
3   chr1  13328  13342      -      2
4   chr1  13342  13343      -     18
5   chr1  13343  13344      -     36
6   chr1  13344  13345      -     18
7   chr1  13345  13346      -      6
8   chr1  13346  16923      -      1
9   chr1  16923  16942      -      3
10  chr1  16942  16943      -      2

Then, find every row of interest. That would be everywhere count is not 1.
df['count'] != 1

0     False
1      True
2     False
3      True
4      True
5      True
6      True
7      True
8     False
9      True
10     True

I want to group all the consecutive rows that are True together. The usual method to group consecutive rows by a column value is

Keep a running tally.
Compare each value in the column with the next one.
If they are the same, don't do anything.
If they are different, add 1 to a running tally.
Associate the tally to that value.
Groupby the tally.

In code
mask = df['count'] != 1
tally = (mask != mask.shift()).cumsum()

    count   mask  tally
0       1  False      1
1       2   True      2
2       1  False      3
3       2   True      4
4      18   True      4
5      36   True      4
6      18   True      4
7       6   True      4
8       1  False      5
9       3   True      6
10      2   True      6

Grouping then gives
df.groupby(tally).groups

{1: Int64Index([0], dtype='int64'),
 2: Int64Index([1], dtype='int64'),
 3: Int64Index([2], dtype='int64'),
 4: Int64Index([3, 4, 5, 6, 7], dtype='int64'),
 5: Int64Index([8], dtype='int64'),
 6: Int64Index([9, 10], dtype='int64')}

Since you only want the rows where count is not 1, we can reuse the mask to filter them out.
df[mask].groupby(tally).groups

{2: Int64Index([1], dtype='int64'),
 4: Int64Index([3, 4, 5, 6, 7], dtype='int64'),
 6: Int64Index([9, 10], dtype='int64')}

And finally the median is quick to get from a grouper
df[mask].groupby(tally).median()

         start     stop  count
count
2      13320.0  13321.0    2.0
4      13343.0  13344.0   18.0
6      16932.5  16942.5    2.5

In the end, the code is a lot shorter
df = pd.read_csv(file, sep='\t', names=('chr', 'start', 'stop', 'strand', 'count'), header=None)
mask = df['count'] != 1
tally = (mask != mask.shift()).cumsum()
df[mask].groupby(tally).median()


Project Euler 91 (via HackerRank): Right triangles with integer coordinates

righttri violates the single responsibility principle: it tests the triangle, and (possibly) appends it in the done list. Appending doesn't belong here.
righttri is surely working too hard: it calculates square roots just to compare them being squared back. Besides losing performance with unnecessary math, it also losing precision. With problems like this it is much better to stay within the integer domain.
Algorithm inspects every pair of dots on the grid, that is a time complexity is \$O(N^4)\$. That explains the timeouts. There are just too many pairs which do not form the right triangle.

A better algorithm would enumerate only right triangles via the Euclid's formula.