Getting device type from user agent in Python - is explicit better than implicit?

Equivalence considerations

1 is not the same as 2 or 3 for older versions of Python. In 2 and 3, you have an ordered execution sequence that determines the priority of returned variables. In 1, you have a dictionary whose order is inherently unknown. This might be OK for you, or it might not. If it isn't, a workaround is to use an OrderedDict.

For newer versions of Python (3.6+) this should not be an issue.

Drop boolean redundancy

No matter what you do, you should probably stop writing is True if you know that the target variable is already boolean. If the variable can have mixed type (i.e. integer or boolean), which is bad but sadly often possible in Python, and if you care about this, then you need to keep is True.

Ownership

Do you control the design of user_agent? If so, then you can enforce a stable interface, and my favourite of your options is 2, simply because it's more concise. If not, then only (3) would work well with static analysis to catch a changing interface.

Other options

try:
    return next(type for type in ('mobile', 'tablet', 'pc', 'bot')
                if get_attr(user_agent, f'is_{type}'))
except StopIteration:
    return 'unknown'

The bigger problem

is that you're representing an idea of a type with multiple booleans when it should be a single enum-style variable. If you can change your user agent to do this, do this. If not, you may want to consider writing a multivariate-boolean-to-single-enum shim class to sanitize the rest of your business logic.


You don't want to dispose it. Otherwise your client code will be working off a disposed object and you'll be getting ObjectDisposedException's left and right.

The question is, does your client code really need a DataSet? or does it simply need a representation of the data?

If it actually needs to be working off a DataSet object, you can ignore the warning, as long as your client code is properly disposing it when it's done working with it.

If all you need is a representation of the data, then the solution is to not return a DataSet, but some IEnumerable<Foo> or IReadOnlyList<Foo>, where Foo is a Plain Old CLR Object (POCO - a simple class exposing nothing more than property getters and setters).

Instead of using a DataSet, you could use a SqlDataReader, which you obtain by executing a SqlCommand - note that returning an IEnumerable<T> makes it possible to yield return your results:

public IEnumerable<Foo> GetData(string connectionString, string sqlStatement)
{
    using (var connection = new SqlConnection(connectionString))
    using(var command = new SqlCommand(sqlStatement, connection))
    {
       connection.open();
       using (var reader = command.ExecuteReader())
       {
            while (reader.Read())
            {
               yield return new Foo
                   {
                       Bar = (int)reader[0], // retrieve by field index, or..
                       Something = (string)reader["SomeField"] // retrieve by field name
                   };
            }
       }
    }
}

Couple of other points:

Don't use underscores in identifiers. Use the more standard camelCase instead.
Don't abbreviate or disemvowel identifiers. There's no reason to do this.
Don't update the UI in a method whose responsibility is to retrieve data.
If you don't know what to do with an exception, let it bubble up, the client code is more likely to know what to do (e.g. pop a messagebox, or show a meaningful error message in the UI).
Use objects. The instruction MainForm.wasSuccess = true; looks very very much like you're accessing a static member, which is bad because static things belong to a type, as opposed to an instance.


Test if arithmetic operation will cause undefined behavior

OP edited post.
Is the description backwards?

If they return non-zero the operation is then carried out and the result returned. If they return zero, an error message is printed out to the user.

int is_undefined_mult(int a, int b) {
    if (a > 0) {
        if (b > 0) {
            if (a >= INT_MAX / b) {
                return 1;  // 1 is the overflow condition here.

This hints that using a macro or enumerated result would be less error prone than 0 or 1.

a == INT_MIN && b == -1 is only a problem with 2's complement:
int is_undefined_div(int a, int b) {
  #if INT_MIN < -INT_MAX
    if (a == INT_MIN && b == -1) return 1;
  #endif
  return b == 0;
}

As @JS1 noted, replace INT_MAX with INT_MIN in 2 places.  Otherwise, per my tests, the  functions are correct,  expecting is_undefined_div().

[Edit]
Candidate is_undefined_mult() simplification - really just a collapsing of the if structure.
int is_undefined_mult1(int a, int b) {
  if (a > 0) {
    if (b > 0) {
      return a > INT_MAX / b;       // a positive, b positive
    }
    return b < INT_MIN / a;         // a positive, b not positive
  }
  if (b > 0) {
    return a < INT_MIN / b;         // a not positive, b positive
  }
  return a != 0 && b < INT_MAX / a; // a not positive, b not positive
}

[Edit2]
A potential simplification with is_undefined_add()/is_undefined_sub().
int is_undefined_add1(int a, int b) {
  return (a < 0) ? (b < INT_MIN - a) : (b > INT_MAX - a);
}

int is_undefined_sub1(int a, int b) {
  return (b < 0) ? (a > INT_MAX + b) : (a < INT_MIN + b);
}


The line Dim LRow, LRow2, i, n, serviceID As Long isn't doing what you think it is. When you declare multiple variables on the same line, you need to individually assign types to all of them - otherwise the default to Variant.  I'm assuming that line was meant to be Dim LRow As Long, LRow2 As Long, i As Long, n As Long, serviceID As Long. You could probably also give them names that have more meaning than i and n.

Kudos on using the code names to refer to your worksheets instead of indexing the Worksheets collection - this is a much more reliable method to access them. However, you are still repeatedly accessing them.  I'd wrap the majority of this Sub in With Sheet6.  That not only keeps you from repeatedly dereferencing the same thing, it makes it much more clear when you are using Sheet5 by making it stand out more. While you're at it, I'd rename the worksheet code names to something more descriptive. I have no clue what Sheet5 even means beyond that it was the fifth worksheet that was added to the workbook.

This might be a micro-performance thing, but using .Cells() is typically better than using .Range() when you only need one cell. This not only avoids concatenating your cell addresses, but it prevents making Excel convert your alpha columns back to numbers. Finally, it lets you use column constants that are more descriptive than "AH".  You can use something like this...

Const FooColumn As Long = 34
'...
Sheet6.Cells(currentRow, FooColumn)

...which is much more readable.

You are using implicit default member calls on the tests Sheet6.Range("AH" & n) <= Sheet5.Range("BM" & i) and Sheet6.Range("AH" & n) >= Sheet5.Range("BL" & i). This appears to be an oversight, in that you're using explicit calls to Value everywhere else.

Performance

DON'T USE COPY AND PASTE FOR VALUES. This is horrendously inefficient. You can assign these directly like so: Sheet5.Range("BU" & i).Value = Sheet6.Range("B" & n).Value. Even better would be to suck all of your source data into an array and use that instead. That cuts down on the round-trips you're making to the worksheet.  Ever time you touch a cell, Excel has to at minimum recalculate and redraw. If you can do all of your work in memory, do that, then use the Worksheet simply for "output".

The call to Sheet5.Application.WorksheetFunction.CountIf(Range("BU:BU"), serviceID) is absolutely killing you.  First, you're applying it over the entire column (1,048,576 rows) and you're doing it in a nested loop. Finally, If statements are not short-circuited in VBA, so you're always performing this lookup. If the only thing you need to do is find out if the serviceID exists in that column, read all of the values there into a Scripting.Dictionary, and look them up in that instead:

Private Function GetServiceIDLookup() As Scripting.Dictionary
    Dim results As New Scripting.Dictionary
    With Sheet5
        Dim currentRow As Long
        Dim serviceID As Long
        For currentRow = 1 To .Cells(.Rows.Count, LookupTargetColumn).End(xlUp).Row
            serviceID = .Cells(currentRow, LookupTargetColumn).Value
            If Not results.Exists(serviceID) Then results.Add serviceID, serviceID
        Next
    End With
    Set GetServiceIDLookup = results
End Function

Build the lookup, then instead of Sheet5.Application.WorksheetFunction.CountIf(Range("BU:BU"), serviceID) = 0, you would be doing something more like this:

'Outside the loops
Dim serviceIDs As Scripting.Dictionary
Set serviceIDs = GetServiceIDLookup
'...
For i = 3 To LRow
    Fastighet = Sheet5.Cells(i, 79).Value
    For n = 3 To LRow2
        serviceID = Sheet6.Cells(n, 2).Value
        'Dictionary lookup
        If serviceIDs.Exists(serviceID) And WhateverElse Then

Between that change and pulling arrays instead of repeated worksheet accesses, you should be able to reduce the runtime by several orders of magnitude.


A puzzle about how to write more clean and understandability code

Personally, option 2.

In option 1, by breaking out of the loop, you have to look down until after the end to see what happens, just to see a return.
In option 2, it's obvious what you want and when you get it. Although, I think the condition is a little complex.

There are, of course, other options:

private function getFeatureByParam ($classname, $module, $action) {
    foreach ($this->featureConf as $featureIndex => $feature) {
        if ($feature['classname'] != $classname) continue;
        if ($feature['module'] != $module) continue;
        if ($feature['action'] != $action) continue;

        return $feature;
    }
    return array();
}

private function getFeatureByParam ($classname, $module, $action) {
    foreach ($this->featureConf as $featureIndex => $feature) {
        if ( featureMatches( $feature, $classname, $module, $action ) ) {
            return $feature;
        }
    }
    return array();
}

I'm inclined to option 4 :)


You should use the JavaScript Module Pattern to create a private scope for your function declarations:

// Directives for JSLint
/*global console, prompt, $ */ // declaration of global variables used
/*jslint unparam: true, sloppy: true, white: true */ // disable less useful checks

// create a closure for private scope
(function(){

  // Private declarations

  var calendarOptions, // object, options for calendar diary
      trainingDiary;   // object, training diary using jQuery plugin fullCalendar()

  function onDayClick(date, allDay, jsEvent, view) {
    // Function: onDayClick(day, allDay, jsEvent, view)
    // Callback for the selection of a day in the calendar.
    //
    // Parameters:
    //   date - type?, description?
    //   allDay - type?, description?
    //   jsEvent - type?, description?
    //   view - type?, description?

    // single var declaration
    var title,       // string, event title, input by user
        dayObj,      // object, jQuerified DOM element
        ajaxOptions; // object, options for AJAX call to addtrainingday script

    // this declaration must be nested to access date, allDay... in closure scope
    function onAjaxSuccess(msg) {
      // Function: onAjaxSuccess(msg)
      // Callback for a successful AJAX call to server-side addtrainingday script.
      //
      // Parameter:
      //   msg - string, message received from server, for logging purpose

      var event = {
        title: title,
        start: date,
        allDay: allDay,
        backgroundColor:'#cccccc'
      };

      trainingDiary.fullCalendar(
        'renderEvent',
        event,
        true // make the event "stick" across calendar pages
      ); // added missing semicolon

      dayObj.css({
        'background-color':'#339933',
        'background-image':'url()'
      }); // added missing semicolon

      console.log(msg.valueOf());

    } // end of onAjaxSuccess declaration

    // Init
    title = prompt('Event Title:');
    dayObj = $(this);
    ajaxOptions = {
      url: "/app_dev.php/addtrainingday",
      global: false,
      type: "POST",
      // getDate() returns day of month. getDay() returns day of week
      data: "dayNo=" + date.getDate(),
        async: true,
        success: onAjaxSuccess
    };

    //console.log($(this));
    if (title) {
      $.ajax(ajaxOptions); // added missing semicolon
    } else {
      trainingDiary.fullCalendar('unselect');
    }

  } // end of onDayClick declaration

  // Initialization code

  calendarOptions = {
    dayClick: onDayClick,
    theme: true,
    header: {
      left: 'title',
      center: '',
      right: 'today prev next'
    },
    firstDay: 1
  };

  trainingDiary = $("#training_diary").fullCalendar(calendarOptions);

}()); // the function is called immediately to make the declarations effective

I also created extra variables to hold options objects, to enhance readability, and I added comments to describe the intent and parameters of functions declared.

Note that trainingDiary is now declared in the private scope as well. If you need to access it in the global scope, you will need to export it to the global object by assigning it to global this or window:

(function(){

  // Private declarations
  (...)

  // Init
  (...)

  // Public declarations
  this.trainingDiary = trainingDiary;
}());

I checked the code with latest JSLint; it is a useful tool once you know what to expect from it, e.g. by reading "JavaScript: The Good Parts" from its author Douglas Crockford. It would definitely help you to spot the missing semicolons, which can cause unexpected issues when you minify your code.


Performance improvements related to approach

Interger base

For better performance we can split number not by every digit but by set of digits with given base. Look at Number.MAX_SAFE_INTEGER and some math

\$ max\_number = 2 ^ {53} - 1 = 9007199254740991 \$

\$ digits = \lfloor \log_{10} max\_number \rfloor \$

\$ base = 10 ^ { digits } \$

Note: base will be lower by one if logarithm gives interger.

What I want to say?

\$ max\_number \$ can hold \$ digits \$ digits to be able to handle overflowing during additions.

What meaning of \$ base \$ ?

Currently you are using algo with \$ base = 10 ^ {digits} = 10 \$.

Here res.push(subres % 10); you are performing modulo operation with base equals 10. Which means you are storing array with numbers that consists of single digit.

But Number allows you to store up to 15 digits. Execute Math.log10(Number.MAX_SAFE_INTEGER) in you browser to find this value (do not forger to take floor of resulted decimal).

Look at c++ example at e-maxx.ru for idea how to implement this. I have not found good enough english article, but you can use google translate.

Benchmark base \$ 10^1 \$ vs base \$ 10^{15} \$

function plain(lnum, rnum) {
  lnum = lnum.split('').reverse();
  rnum = rnum.split('').reverse();

  var len = Math.max(lnum.length, rnum.length)
    , acc = 0
    , res = [];

  for (var i = 0; i < len; i++) {
    var subres = Number(lnum[i] || 0) + Number(rnum[i] || 0) + acc;
    acc = ~~(subres / 10);
    res.push(subres % 10);
  }

  if (acc !== 0) {
    res.push(acc);
  }

  return res.reverse().join('');
}

DIGITS = Math.floor(Math.log10(Number.MAX_SAFE_INTEGER)) - 1
BIG_INTEGER_BASE = Math.pow(10, DIGITS);
FILL_STRING = (BIG_INTEGER_BASE + '').substr(1)

function readBigInteger(str, base) {
  var res = [];
  for (var i = str.length; i > 0; i -= base)
    if (i < base)
      res.push(Number(str.substr(0, i)));
    else
      res.push(Number(str.substr(i - base, base)));
  return res;
}

function printBigInteger(integer, base) {
  for (var i = 0; i + 1 < integer.length; ++i) {
      var s = FILL_STRING + integer[i]
      integer[i] = s.substr(s.length - base)
  }
  return integer.reverse().join('');
}

function plainWithDifferentBase (a, b) {
  lnum = readBigInteger(a, DIGITS)
  rnum = readBigInteger(b, DIGITS)

  var len = Math.max(lnum.length, rnum.length)
    , acc = 0
    , res = [];

  for (var i = 0; i < len; i++) {
    var subres = (lnum[i] || 0) + (rnum[i] || 0) + acc;
    acc = ~~(subres / BIG_INTEGER_BASE);
    res.push(subres % BIG_INTEGER_BASE);
  }

  if (acc !== 0) {
    res.push(acc);
  }

  return printBigInteger(res, DIGITS);
}

var fib = function(num, add) {
    var prev = '1',
        curr = '1',
        temp;
    while (curr.length < num) {
        temp = curr;
        curr = add(prev, curr);
        prev = temp;
    }
    return curr;
};

SIZE = 10000

console.time("plainWithDifferentBase");
fib(SIZE, plainWithDifferentBase);
console.timeEnd("plainWithDifferentBase");

console.time("plain");
fib(SIZE, plain);
console.timeEnd("plain");

Results

Using \$ base = 10^{15} \$ is 90 times efficiently.

plainWithDifferentBase: 23848ms
plain: 182856ms

Performance improvements related to interpreter

Look at this:

formatting list of variables
converting character to integer using charCodeAt
preallocating array of required size
using standard language library API (builtins)

function characterToInt(char) {
  // 48 is char code of zero.
  return char.charCodeAt(0) - 48;
}

function longAdd(lnum, rnum) {
  // Here we didn't use lambda function (anonimous) to prevent creating
  // additaional objects and give less work to GC.
  lnum = lnum.split('').reverse().map(characterToInt);
  rnum = rnum.split('').reverse().map(characterToInt);
  // With comma as third character you didn't broke approach of formating
  // using 2 whitespaces.
  var len = Math.max(lnum.length, rnum.length)
    , acc = 0
    // Allocate required space for an array to prevent reallocation overhead
    , res = new Array(len);
  for (var i = 0; i < len; ++i) {
    var subres = (lnum[i] || 0) + (rnum[i] || 0) + acc;
    // Use Math.floor instead of 2 additional operations, as it is library
    // function which can be written with some optimizations.
    acc = Math.floor(subres / 10);
    res[i] = subres % 10;
  }
  if (acc !== 0) {
    res.push(acc);
  }
  return res.reverse().join('');
}

Possible ways to allocate array of required size:

var a = new Array(size) // 1
var a = []; a.length = size // 2

Note: it is not final or most optimized version ever, I have tried to show you set of approached you might want to know to optimize your code even further.

Benchmark using browser

Just open console in your browser and paste following code

var strAdd = function(lnum, rnum) {
  lnum = lnum.split('').reverse();
  rnum = rnum.split('').reverse();
  var len = Math.max(lnum.length, rnum.length),
      acc = 0;
      res = [];
  for(var i = 0; i < len; i++) {
    var subres = Number(lnum[i] || 0) + Number(rnum[i] || 0) + acc;
    acc = ~~(subres / 10); // integer division
    res.push(subres % 10);
  }
  if (acc !== 0) {
    res.push(acc);
  }
  return res.reverse().join('');
};

function characterToInt(char) {
  return char.charCodeAt(0) - 48;
}

function longAdd(lnum, rnum) {
  lnum = lnum.split('').reverse().map(characterToInt);
  rnum = rnum.split('').reverse().map(characterToInt);
  var len = Math.max(lnum.length, rnum.length)
    , acc = 0
    , res = new Array(len);
  for (var i = 0; i < len; ++i) {
    var subres = (lnum[i] || 0) + (rnum[i] || 0) + acc;
    acc = Math.floor(subres / 10);
    res[i] = subres % 10;
  }
  if (acc !== 0) {
    res.push(acc);
  }
  return res.reverse().join('');
}

var fib = function(num, add) {
    var prev = '1',
        curr = '1',
        temp;
    while (curr.toString().length !== num) {
        temp = curr;
        curr = add(prev, curr);
        prev = temp;
    }
    return curr;
};

console.time("preallocated");
fib(1000, longAdd);
console.timeEnd("preallocated");

console.time("plain");
fib(1000, strAdd);
console.timeEnd("plain");

My results are:

Google Chrome 46.0.2490.80

preallocated: 1620.238ms
plain: 4311.755ms

Mozilla Firefox 41.0.2

preallocated: 849.72ms
plain: 3747.05ms

Nodejs and preallocation

Lets start with this test where we conditionally switches allocation from static to dynamic.

var plain = function(lnum, rnum) {
  lnum = lnum.split('').reverse();
  rnum = rnum.split('').reverse();
  var len = Math.max(lnum.length, rnum.length),
      acc = 0;
      res = [];
  for(var i = 0; i < len; i++) {
    var subres = Number(lnum[i] || 0) + Number(rnum[i] || 0) + acc;
    acc = ~~(subres / 10); // integer division
    res.push(subres % 10);
  }
  if (acc !== 0) {
    res.push(acc);
  }
  return res.reverse().join('');
};

var preallocated = function(lnum, rnum) {
  lnum = lnum.split('').reverse();
  rnum = rnum.split('').reverse();
  var len = Math.max(lnum.length, rnum.length),
      acc = 0;
      res = [];
  if (len > 1000)
      res.length = len;
  for(var i = 0; i < len; i++) {
    var subres = Number(lnum[i] || 0) + Number(rnum[i] || 0) + acc;
    acc = ~~(subres / 10); // integer division
    if (len > 1000)
      res[i] = subres % 10
    else
      res.push(subres % 10);
  }
  if (acc !== 0) {
    if (len > 1000)
      res = res.concat(acc)
    else
      res.push(acc);
  }
  return res.reverse().join('');
};

var fib = function(num, add) {
    var prev = '1',
        curr = '1',
        temp;
    while (curr.toString().length !== num) {
        temp = curr;
        curr = add(prev, curr);
        prev = temp;
    }
    return curr;
};

console.time("preallocated");
fib(2000, preallocated);
console.timeEnd("preallocated");

console.time("plain");
fib(2000, plain);
console.timeEnd("plain");

I have results:

$ node /tmp/help.js
preallocated: 1278ms
plain: 4249ms

$ node --version
v0.12.7

Warning: didn't run benchmark for node in you browser.

Google Chrome 46.0.2490.80 gives time

preallocated: 61737.298ms
plain: 16982.603ms

Mozilla Firefox 41.0.2

preallocated: 12759.65ms
plain: 14391.38ms

Summary

We have different results depending on platform. People love js because of 2 things:

event loop
same codebase for backend and frontend

But, as you saw before, you have to optimize frontend and backend in different way. How to solve it is up to you.


The easiest way to think of this problem is to use a k-character sized window that slides across the number.

First calculate the product of the first k characters
Check to see if the next digit is 0, if it is, keep going until you hit a non-zero element and restart the process from that digit
If the next digit is not 0, then multiply the existing product by that digit and divide by the first digit of the existing product (the number that is going to be dropped off the window)

Keep track of the best sequence found and its product and you have your answer

The beauty of this approach is you only ever look at/multiply an element exactly once, giving O(n) time (where n is the length of the string). Your approach may multiply the same number k times (where k is the length of the window), resulting in O(kn) time, which is quite a bit slower.


Error handling for function calls to parse a GIF file

Without knowing the context, I'd write it as:

if( (errno = GifLoad( g, &bufTemp )) == GIF_SUCCESS ) {
  // Process the correctly loaded image as necessary.
  GifProcess( g );
}

// Release memory once processing is complete.
GifDispose( g );
*gPtr = NULL;

// Single exit point to the function.
return errno;

Then write a wrapper for GifLoad that calls the three other functions.

This might not be a suitable solution if, for example, the processing is part of an interactive program wherein the processing is indeterminate. If processing cannot be coded at this point in the source, then consider:

if( (errno = GifLoad( g, &bufTemp )) != GIF_SUCCESS ) {
  // Perform whatever is necessary to inform the user the GIF cannot be loaded.
  GifInvalid( g );

  // Release memory.
  GifDispose( g );
  *gPtr = NULL;
}

return errno;

In both cases consider abstracting the three function calls into a single function, which cleans up the code and expresses the intent of those three function calls more concisely.


The functions you use (kde, dkde, hpi, ...) do not seem to be standard R functions and you are not very explicit on your exact data structur, so it's hard to help. Could you provide more info on that (packages used, ...)?

What I think to realize though - but correct me if I'm wrong - is the following. When substituting h1 in the second line of your loop with its function body, you could simplify the function and get rid of all exp and log, which should speed up your script at least a bit:

    exp( h1(thetas) - h1(theta.mh[i1-1,s,t]) )
--> exp( log(p1(...)*p2(...)) - log(p1(...)*p2(...)))
--> exp(log(p1(...)*p2(...))) / exp(log(p1(...)*p2(...)))
--> p1(...)*p2(...) / p1(...)*p2(...)

that means, what your second line actually computes is:

p1(y[s,t],thetas)*p2(thetas) / p1(y[s,t],theta.mh[i1-1,s,t])*p2(theta.mh[i1-1,s,t])

I hope that is of some use to you...


Add a shebang line

If you want to be able to run your program without explicitly specifying the interpreter, then you should make the script executable and start the script with a #! line:

#!/bin/sh

Usage reporting

If the arguments aren't specified, show how to use the program (and exit with an error status):

if [ -z "$1" ] || [ -z "$2" || [ "${3:-}" ]
then
  echo "Usage: $0 <username> <password>" >&2
  exit 1
fi

I've redirected the error message to the standard error stream, so it will be seen; and I've replaced the Bash test -o with a more portable alternation of test commands.

It's up to you whether an empty password (as opposed to an unset password) is allowable.

Care with variable expansions

You've been pretty diligent about quotes (well done), but there is one place where you might get tripped up:

fulltoken=`curl ... "{\"password\":\"$2\"}" ...`

Could $2 contain "?  If so, you might want to escape it (${2//\"/\\\"}) or detect it and abort before executing curl.

The if $? antipattern

Instead of running a command and then separately testing the status, it's more idiomatic to use a single if:

if echo "$fulltoken" | grep authToken >/dev/null 2>&1
then
  ...
fi

A couple of further observations on this particular line: you could replace echo with a <<< redirection; you could replace the grep with testing against a substituted string (both of these involve Bash extensions, so you might prefer to lean towards the portability above):

if <<<"$fulltoken" grep -q authToken 2>/dev/null

if [ "$fulltoken" != "${fulltoken/authToken}" ]

Related to this is

Keep the error handling close by

The program has more than one structure that looks like

if some_test
then
    ...
    lots
    ...
    of
    ...
    code
    ...
    here
    ...
    if second_test
    then
        ....
        more
        code
        ...
    else
        echo "INNER FAIL"
    fi
else
    echo "FAIL"
fi

This can make it harder to relate the else clause to the correct if.  My usual approach to this is to define a die function:

die(){
    echo "$@" >&2
    exit 1
}

Then the structure above becomes more linear and less indented:

some_test || die "FAIL"
...
lots
...
of
...
code
...
here
...
second_test || die "INNER FAIL"
....
more
code
...

This might not work for you if you want to report more than one problem per run, but it's certainly something to consider and possibly adapt for your purposes.

Use the simplest tool for the job

Although awk can pick out fields from a line, that's the sole purpose of cut, and I think it's clearer that that's all you're doing if you write like

token=$(echo "$fulltoken" | cut -d: -f8 | cut -d, -f1 | tr -d \")

Conversely, if you use awk, use it fully - the applnId pipeline (sed|grep|awk) can be done with a single awk invocation:

awk -F: 'BEGIN { RS = "," } $1 == "applnId" {print $2}'

Note that this is now a stricter test - it won't be fooled by a value containing applnId, for instance; it recognises only a key of exactly applnId.

Actually, since you have asked for JSON output, it's easier and more reliable to use jq than pure Bash to parse it:

applnId=$(jq -r applnId <<<"$exactserverdetails")

Similarly, to test the environment name:

test "$(jq -r environment_Name <<<"$exactserverdetails")" = Dev \
    || die "Environment name is not 'Dev'"

Be more specific when reporting errors

This test doesn't tell the user much:

    if [ -n $appInId ] && [ $appInId != "null" ]
    then
        echo "PASS"
    else
        echo "FAIL"
    fi

Instead, I'd write:

    case "${appInId-}" in
      '') echo "No applnId" >&2; exit 2;;
      null) echo "applnId is 'null'" >&2; exit 2;;
      *) echo "applnId is valid";; # (if you must)
    esac

I'd omit the last case, though - I'm not a fan of overly chatty programs.


You don't need a self.is_dead. You simply need to block until the thread is complete. For that, we have join():

def stop(self):
    self.is_alive = False
    self.process.join()


There is a problem with vector multiplication in the second loop. You should transpose the second vector before doing multiplication.

F(:,:,t)= [Ax(i,j);Ay(i,j);Az(i,j)]*[Ax(i,j) Ay(i,j) Az(i,j)]';

One of the ways to speed things up is to apply vectorization instead of two for loops, such as with Dyadics.


There is a way without multiple returns and nested if statements.
You have three control flow pathways in your program, related to three states of state_cookie respectively:

cookie is Some and state_cookie.value() == cb.state
cookie is Some and state_cookie.value() != cb.state
cookie is None

For the first, we proceed, whereas for second and third we branch to do the same return. Do the 2. and 3. have anything in common? They cover all except one value.
You may be coming from a language where data types lack expressiveness. Many languages don't have Option at all. In Rust, we have deep operations on Algebraic Data Types like Option.
To postpone comparison and branching until we have all information, we do a map on the Option: req.cookie(STATE_COOKIE_NAME).map(|sc| sc.value()). Then, a simple comparison divides our function into two control flow paths. As an extra, for self-documenting code, we make a short-lived binding for state_cookie_value:
#[get("/callback")]
async fn callback(req: HttpRequest, client: web::Data<BasicClient>, web::Query(cb): web::Query<Callback>) -> Result<HttpResponse> {
    let state_cookie_value = req.cookie(STATE_COOKIE_NAME).map(|sc| sc.value());
    if state_cookie_value != Some(cb.state) {
        return Ok(HttpResponse::BadRequest().finish());
    }

    let token_result = client.exchange_code(AuthorizationCode::new(cb.code)).request(http_client);

    match token_result {
        Ok(token_details) => Ok(handle_success(token_details)),
        Err(token_error) => Ok(handle_error(token_error))
    }
}

This is basically all in this code.
I believe this may obscure the code's meaning for the reader, but you can as well write the match statement as:
Ok(token_result.map_or_else(handle_error, handle_success))


I'm afraid your code is very hard to understand.  Part of the problem is your variable naming: I'm not sure what exactly p_x is and what distinguishes it from the x that's part of the Map object, for example.  It also doesn't help that your comments mostly just describe the behaviour of entirely obvious single lines of code but don't describe any of the unclear aspects of your code, for instance why it is doing what it is doing.

On to more specific comments, this line of code is confusing:

Map.prototype.render(new_x, new_y);

Is there a reason you aren't using this.render(new_x, new_y) here, but instead calling the method directly on the prototype object?  If so, it would be best to explain it with a comment, as this is quite unusual behaviour.  Also, what are new_x and new_y, and why are they calculated in the way they are?  As far as I can see, Map.x and Map.y are never set to anything that has any particularly useful meaning.

In your inner loop in the render method, you repeatedly update this.x and this.y, but the values stored here are never read by code outside of the method, because they are overwritten by the next iteration of the loop before anything else can touch it.  It is unclear why you are doing this, but generally it would be better to only update them once, and to use local variables when you are calculating values for use only within a single method.

You have a number of values in your code that are seemingly related, i.e. 99 and 101 used in two different places.  It may be best to use a variable to store one of these values (I think 100 cells is the size of your map?) and derive one from the other as necessary.

Update after clarification in comments

Having move be part of the Map object when it isn't called in that context is confusing.  Also referring to Map.prototype is unlikely to be what you want to do, as it basically prevents you from ever having more than one Map, thus negating a key benefit of using objects at all.

Here's how I would handle it: I wouldn't declare the event handler as a separate function at all, but instead declare it inline when I set the event handler.  I would also make sure it had a variable in scope that refers to the Map object, so it doesn't need to access the prototype.  Then I'd have it call back to an event-handling function that's actually properly part of the Map object.  Here's what that might look like:

in the inner loop of the render function:

                var map = this;
                cell.addEventListener("click", function () {
                     map.cellClicked (this);
                }, false);
                cell.x = x; cell.y = y;

and the new cellClicked function:

Map.prototype = {
   cellClicked: function (cell) {
      this.render (cell.x - 1, cell.y - 1);
   },


Opening an XML File and Returning the XmlDocument

Here's how I would refactor your code:

An event handler sholdn't return any values, it's better to save the result in a property or a field in this case.

  √ DO use a return type of void for event handlers.
  An event handler can invoke multiple event handling methods, possibly on multiple objects. If event handling methods were allowed to return a value, there would be multiple return values for each event invocation.

Event Design

You shouldn't do too much work inside an event handler, it's better to call a specialized method that can also be reused elsewhere later.
OpenFileDialog needs to be disposed: see Component.Dispose Method which is one of the base class of this dialog.
If you check the if(!openFileDialogXML.ShowDialog()) for a false value and immediately return a default value you can reduce nesting.
If possible it's better to name a class with a noun (e.g. XmlLoader) rather then like a method LoadXml.
Now that the unnecessary nesting is removed you can remove the Stream myStream = null; and put it inside the using.
The last step would be to replace the repeating creation of an empty XmlDocument by a method and call it where necessary. You might want to add some default elements later so now you can do it in only one place. If the XmlDocument is no longer empty you might rename the method to CreateDefaultXmlDocument but it's important that you do it only once. You could forget to adjust the other lines if your code repeates.

class XmlLoader
{
    public XmlDocument XmlDocument { get; private set; }

    private XmlDocument CreateEmptyXmlDocument()
    {
        //  Return an empty XmlDocument if the open file window was closed
        XmlDocument emptyMyStream = new XmlDocument();
        return emptyMyStream;
    }

    public XmlDocument OpenXml()
    {
        using(var openFileDialogXML = new OpenFileDialog())
        {
            openFileDialogXML.InitialDirectory = "C:\\";
            openFileDialogXML.Filter = "XML Files|*.xml";
            openFileDialogXML.RestoreDirectory = true;

            if(!openFileDialogXML.ShowDialog())
            {
               return CreateEmptyXmlDocument();
            }

            //  The stream will hold the results of opening the XML
            using (var myStream = openFileDialogXML.OpenFile())
            {
                try
                {
                    //  Successfully return the XML
                    XmlDocument parsedMyStream = new XmlDocument();
                    parsedMyStream.Load(myStream);
                    return parsedMyStream;
                }
                catch (XmlException ex)
                {
                    MessageBox.Show("The XML could not be read. " + ex);
                    return CreateEmptyXmlDocument();
                }
            }
        }
    }

    public void LoadXML_Window(object sender, System.EventArgs e)
    {
        XmlDocument = OpenXml();
    }
}


Basic HTML structure for three columns of articles

HTML is what's known as a markup language, which means the actual meaning of the elements (whether you choose div or sections) is up to the code to interpret.

Browsers have their own CSS files they apply to every page, so which tag you choose to use for an element doesn't really matter. Except for types like img and video that have special purpose in the browser

That said, using tag names that better suit the purpose increases the readability of your code and improves maintainability for future development.

Standards like HTML5 add more style rules for elements (as well adding more special purpose types like img and a bunch more stuff).

There's not an optimization tradeoff as the CSS engine doesn't treat rules on div different than rules on sections.

  Should I have a header tag inside each article?

Yeah, that's exactly what it's for! Mozilla Developer Network says that the header element is for representing heading elements, specifically even quoting usage designed for a wrapped section's header.

  I heard this is best practice but I feel like this would make the code harder to read

While code readability is arguably a personal thing, I always felt that this kind of layout:

Item

Text

Was a lot harder to understand than something like:

  Item
  <content>
    <photo>

    </photo>
    <description>

Text

    </description>
  </content>

Especially seeing as you can now easily see which closing tag is which.

  Should I keep a line break between different items like sections?

Again, code readability is up to you, do whatever is easier for you to understand.

  in a big HTML file you could have like 200 empty lines making the code way bigger than it has to be. What do people usually do about this?

If you've got that many elements, it might time to use a library (like jQuery, Ember, Angular or React) to manage your data and make the HTML layouts for you.

However for just a normal HTML file, line breaks aren't necessarily bad. Extra lines don't bloat the files, so you don't need to worry too much about the files being bloated.

Like I said before, code readability is an intensely personal thing. While I (and any other reviewers) can take a look at code at tell you how readable it is, you're the one developing it, and it's your creation.


Loading data async with queue. Proper write only locking and scheduling

Instead of keeping track of what's being loaded, you can represent that as a state by wrapping IDataSet into a class:

private sealed class DataSetResult
{
    public volatile IDataSet Result;
}

When an instance of this class is created, start loading the data. You can then just return the value of the Result field - if it is null, the data is still being loaded:

private readonly ConcurrentDictionary<string, Lazy<DataSetResult>> _data;

public IDataSet GetData(string dataId)
{
    var dataSet = _data.GetOrAdd(
        dataId,
        _ => new Lazy<DataSetResult>(
            () =>
            {
                var result = new DataSetResult();
                dataIoAsync.LoadDataAsync(dataParams);
                return result;
            }
        )
    );

    return dataSet.Value.Result;
}

private void DataIoAsync_DataFileLoaded(object sender, DataFileLoadedAsyncEventArgs e)
{
    _data[e.DataId].Value.Result = e.DataSet;
    OnDataFileLoaded(e.DataId);
}

The Lazy<DataSetResult> above ensures that data is retrieved at most once for a given id.

Personally, however, I would prefer to return Task<IDataSet> from this method, as it is really up to the caller to decide whether they want to wait for the result to become available or not. Using Task also allows you to report any exceptions to the client:

private readonly ConcurrentDictionary<string, Lazy<TaskCompletionSource<IDataSet>>> _data;

public Task<IDataSet> GetDataAsync(string dataId)
{
    var dataSet = _data.GetOrAdd(
        dataId,
        _ => new Lazy<TaskCompletionSource<IDataSet>>(
            () =>
            {
                var result = new TaskCompletionSource<IDataSet>();
                dataIoAsync.LoadDataAsync(dataParams);
                return result;
            }
        )
    );

    return dataSet.Value.Task;
}

private void DataIoAsync_DataFileLoaded(object sender, DataFileLoadedAsyncEventArgs e)
{
    _data[e.DataId].Value.TrySetResult(e.DataSet);
    OnDataFileLoaded(e.DataId);
}


Rails form helper to display email fields and their validation errors

I would try this (naming needs improvement):

*_helper.rb:

  def field_wrapper(errors, &block)
    css_classes = %w(form-group floating-label)
    css_classes << 'has-error has-feedback' if errors.any?
    content_tag :div, class: css_classes, &block
  end

  def error_label(form, errors)
    form.label errors.join(', ') if errors.any?
  end

*.html.erb:

 <%= field_wrapper f.object.errors[:to] do %>
      <%= error_label f, f.object.errors[:to] %>
      <%= f.email_field :to, class: "form-control" %>
      <%= f.label :to %>
   <% end %>


Algorithm with byte shifts and BCD calculation

The algorithm seems to be fine, and if it does not fail the tests it should be OK (try to get more test cases though).

Regarding the implementation:

Indentation - not sure if it just the site or you deliberately placed your curly braces the way they are placed, but it they certainly look weird, especially with the array initialization. You should indent when there is a new block, no matter what.
Use var in place of explicit types - makes reading and refactoring easier.
Argument names - In the C# world, the _variable naming conventionally means a private member variable. Even if you choose not to honor that convention, your argument names are very confusing. Instead of 1-2 letter abbreviations you should use descriptive names.
Too long - split into multiple methods. It doesn't matter that they are only called once: descriptive function names will give you a "bird's view" of the algorithm. Also, you should not use Func just because you can; it's cool, but code is better when not cool but clear, so turn that into a normal method.
Explain the padding part in a comment - it is actually a nice solution, but a bit counter-intuitive (my first thought was: why would you convert to string to just convert back?, but it's actually cleaner than filling the padding zeros by hand).
step4.ToList().ToArray() - is a confusing (and half as fast) way of saying step4.Clone(). BTW it wouldn't hurt to just use Lists and avoid the other ToList calls as well.
I would argue that you don't need the try-catch block around the whole method, since the only thing that looks like it could throw is your CRC calls, so you should only handle that part. If anything else throws, it's better if it's ugly and noisy (a.k.a. don't catch it; clients who call your method will get the empty string back and no other indication of failure, which is not really a good practie.
Use XML documentation comments for the method to document purpose, return value, arguments.
Make sure that a public static method is appropriate for your needs. Instead of public, you might want to use internal. And remember, you can't override static methods in derived classes, so you can't take advantage of polymorphism later.


You asked for critique ....

Why are you trying to use an AtomicBoolean as a mutex?  Use a primitive lock, or a Lock if you need more sophisticated behavior.
(Almost) any time you use sleep in an algorithm, you are doing it the wrong way.  In this case, the "wrong way" is a direct consequence of point 1. above.
If you want good performance in a situation where you have multiple producers and consumers, you should avoid doing a notifyAll.  For instance if there are N consumers waiting, and a producer adds a queue entry, then all N consumers will be woken up.  Ideally, only one consumer should be woken.


When two entities are related in many-to-many relationship, neither of them are a parent/root entity nor a dependent/child entity. They are two individual entities totally independent of each other. They are related, but neither of them depends on the other.
At database level a parent/child dependency is mapped through a foreign-key. For a many-to-many relationship there is no foreign-key involved, and the relationship is mapped through a joining table, which we model with a joining entity at code level, (the MovieDirector entity in your example).
So, if Director and Movie are in a many-to-many relationship, then Movie is by no means a parent entity of Director, or vice-versa. Therefore, you should always be able to create a Director entity independent of any information referencing any movie. And from that perspective I see a major flaw in your code - currently you cannot create a Director entity independently, you need a movieId for that (which you shouldn't).
Think about a possible scenario where you might need to select one or more directors while creating a new movie, and that might be the first time some of those directors gets linked with a movie. What I'm trying to imply is, you can always have a director, or want to create one, for whom there is no movie in the database.
The signature of your CreateDirector method should be like -
public Director CreateDirector(Director director)

First setup any related entities (if there is any) before reaching the CreateDirector method -
director.MovieDirectors.Add(new MovieDirector { MovieId = movieId });

and then call for creating the new director -
public Director CreateDirector(Director director)
{
    _repository.Directors.Add(director);
    _repository.SaveChanges();
    return director;
}

Now you can create a director independently or, along with its related entities. I hope that simplifies your current approach too.


Programming Challenge from Kattis: Apparatus

Disclaimer: I won't try and provide a different algorithm to improve the time complexity of the approach. Instead I’ll rather focus on introducing python constructs that will cleanup the code and may help gain speed a bit.
Reading data from standard input
I had trouble running your script from both IDLE and windows command prompt. Neither of them were good at handling sys.stdin as a file. But we can improve things by using the builtin input (raw_input in Python 2) since we just want to read lines one by one.
Converting back and forth between integers and their binary representation
One of the way to improve your computation of oneBite would be to use the divmod builtin. But it is even more easier when using bin and counting the number of '1' in the returned string.
Same when computing digit: the int builtin accept a second argument which is the base in which the number is represented.
Use functions
You could make the code easier to read and understand by using functions: one to parse two lines (one photo) and one to iterate over the whole set of photos and interpret the results.
Functions will also allow you to import your file into an interactive session and test things more easily. If you want to have code at the top-level to be run when invoking your script from the command line, it is recommended to put it under an if __name__ == "__main__" clause.
collections
The last part of your code count the frequency for a certain possibility in a bizarre way. Time for you to learn about collections.Counter.
PEP8

Use snake_case instead of camelCase for your variable names.
Use spaces around most of your operators (frequency > 1, possibilities%2 == 1, possibilities > 0…)
Remove parenthesis around your tests

EAFP
While
    if not (switch in wiring.keys()):
        wiring[switch] = digit
    else:
        wiring[switch] &= digit

is correct, I would first write it
    if switch in wiring:
        wiring[switch] &= digit
    else:
        wiring[switch] = digit

for readability (and less computation) but then change it to
    try:
        wiring[switch] &= digit
    except KeyError:
        wiring[switch] = digit

It is not necessarily faster in this case (it is when failures are much less than success) but I find it clearer.
Putting it all together
In Python 2 use raw_input, xrange and itervalues instead of input, range and values.
from math import factorial
from collections import Counter

def parse_photo(wiring):
    switches = input()
    lights = input()

    if switches.count('1') != lights.count(1):
        return False # invalid data

    # Convert binary value to integer
    lights_value = int(lights, 2)

    for switch, switch_value in enumerate(switches):
        if switch_value == "1":
            try:
                wiring[switch] &= lights_value
            except KeyError:
                wiring[switch] = lights_value

    return True

def wiring_possibilities():
    wiring = {}
    num_switches, num_photos = map(int, input().split())

    for _ in range(num_photos):
        if not parse_photo(wiring):
            return 0

    frequencies = Counter(wiring.values())
    if 0 in frequencies:
        # Same as if 0 in wiring.values()
        return 0

    for possibility, frequency in frequencies.items():
        switched_on_bits = bin(possibility).count('1')
        if switched_on_bits < frequency:
            return 0

    return factorial(num_switches - num_photos) % 1000003

if __name__ == "__main__":
    print(wiring_possibilities())


I prefer the switch statement.  Here are my reasons:

You can move each return statement onto the same line as the case statement to make the switch statement just as short as the ternary version.
The ternary version is harder to read (at least for me) due to the more ? : == and () involved.  This is not a big deal though.
I find it easier to make subtle syntax errors (not compile time errors) with the ternary operator.  For example:

x = y & mask ? 8 : 4;
a = 5 + (b > c) ? b : c;

Of course you can avoid this by using the correct parentheses:

x = (y & mask) ? 8 : 4;
a = 5 + ((b > c) ? b : c);

It's just that sometimes these kind of expressions appear across multiple lines and it gets hard to visualize which part is which.
A compiler might be able to do a better job optimizing a switch statement than the ternary if-else ladder.  For example, if your switch cases are in consecutive order (such as 0..N), then the compiler can use a jump table to simplify the switch into:

// (pseudocode)
offset = jumpTable[index];
goto offset;


type of difference between pointers

pointer_one - pointer_two

The result of this expression is a ptrdiff_t (§6.5.6/9).  Assigning it back to a pointer converts an integer type to a pointer, which IIRC should give you a compiler warning as it can lead to all kind of trouble.

relational operators with pointers

Comparing pointers with relative operators is undefined behavior if the pointers don't point into the same array (§6.5.8/5).

else if(s1>s2) // undefined behavior
{
  return 1;
}
else if(s1<s2) // undefined behavior
{
  return -1;
}

naming

cmpstr isn't really a suitable name for a function that compares the lengths of two strings.

comments

  // if s1 string is equal to s2 string

You don't compare strings for equality.  You (try to) compare their lengths.

Also, your comments should explain why you wrote the code the way you did. Don't tell what the code is doing. With well written code that should be self apparent.

do one thing per function

cmpstr calculates the length of two strings (code duplication!) and then compares these.  That's too much.  Delegate that length calculation to another function: strlen.  Or - for learning purpose only - write your own replacement.

ptrdiff_t vs size_t

Wondered why strlen returns a size_t instead of a ptrdiff_t?  That's because a string might be longer than the maximum difference that can be represented by ptrdiff_t.  Thus end - start may actually be undefined behavior when done with really long strings.  Better keep a size_t counter that you increase while searching for the '\0'.

program output should end with a '\n'

This is only minor, but otherwise it may corrupt the controlling terminal a bit.  Or like in ideone drop the output completely.

printf("%d\n", cmpstr(hello, world));
//        ^^

test your code

You really should!  Every (in an ideal world) piece of code that you write should be tested. You might want to look into TDD (test driven development) and build up good habits from the start.

making it faster

Do you really need to obtain the length of both strings?  Take these two strings as example:

""
"the quick brown fox did something but I don't remember what"

When you start at the first char of each of those, at how many chars do you need to look to determine which string is longer?


A few points:

You don't need to declare the checkbox function within the $(document).ready(), you can do it outside it.
You have some empty CSS rules -- by accident?
$(function() {...}); is a shorthand for $(document).ready(function() {...}); -- you might want to use that if you want
You don't need to do $(y), $(n), because you saved y, n as jQuery objects already
When you make the variables y, n, cx, cbx, you can opt to (at the end of the day, it's personal preference, but makes it clear they are 'special' variables) prepend $ (or jQuery) like var $y = $("#yon"), var $n = $("#non"), and so on..., so you know they're jQuery objects.

With that in mind...:

function checkbox() {
  var $y = $("#yon");
  var $n = $("#non");
  var $cx = $("#chex")
  var $cbx = $("#checkbox");
  var chval = false;
  $(".cspan").click(function() {
    $n.toggleClass("no");
    $y.toggleClass("yes");
    if (chval) {
      $cx.text("\u2716");
      $cbx.prop('checked', false);
      chval = false;
    } else {
      $cx.text("\u2714");
      $cbx.prop('checked', true);
      chval = true;
    }
  });
}

$(function() {
  checkbox();
});
input[type="checkbox"] {
  display: none;
}
input[type="checkbox"] + label span {
  display: inline-block;
  width: 160px;
  height: 60px;
  border-radius: 25px;
  margin: -1px 4px 0 0;
  vertical-align: middle;
  background-color: #ff3a31;
  cursor: pointer;
  transition: background-color 100ms linear;
  position: absolute;
}
input[type="checkbox"]:checked + label span {
  background-color: #00cc66;
  transition: background-color 100ms linear;
}
.checkemb {
  position: relative;
  display: inline-block;
  margin-right: 10px;
  margin-left: 10px;
  font-family: "Arial Black", Gadget, sans-serif;
  color: #ffffff;
}
#chex {
  margin-right: 25px;
  margin-left: 25px;
}
p.yes {
  color: #990800;
  transition: color 100ms linear;
}
p.no {
  color: #008040;
  transition: color 100ms linear;
}

    <input id="checkbx" type="checkbox" />

Yes

&#10006

No


Better alternative to $(this).off("click")

For a handler that only fires once using jQuery you can use .one().

A click handler would look something like:

function notificationMethod(message){
    // do stuff

    // once everything else is setup, attach a click handler to the "Okay" button
    $('#notificationOkay').one("click", unBlockScreen);
}


You can figure out the first parameter of a non-overloaded function pointer pretty easily; I'm not sure but your code looks more complicated than it ought to be.

Unfortunately, your code completely falls down in the presence of overloads and/or templates. Here's the error message:

prog.cc:36:46: error: reference to overloaded function could not be resolved; did you mean to call it?
    using type = extract_function_t<decltype(&Callable::operator()), pick_first>;
                                             ^~~~~~~~~~~~~~~~~~~~~

and here are some types that trigger it:

struct oops1 {
    void operator()(int);
    void operator()(double);
};

struct oops2 {
    void operator()(int);
    void operator()(int) const;
};

void oops3(int);
void oops3(double);

struct oops4
{
    using correct_answer = const std::vector<std::map<int, char>>&;
    template<class T, std::enable_if_t<std::is_same_v<T, const std::vector<std::map<int, char>>>, int> = 0>
        void operator()(T&) {}
};

And here's another error message that I get:

prog.cc:11:1: error: implicit instantiation of undefined template 'pick_first<>'
using pick_first_t = typename pick_first<Args...>::type;
^

with this input:

void oops5(void);

If I were tackling this problem, I would first ask myself what "the type of the first parameter" even means in C++, given that we have function overloading and templates. But then I might try to detect the appropriate type by messing around with

struct ConvertibleToAnything {
    template<class T> operator T() const;
};

and then inspecting f(ConvertibleToAnything{}) and trying to figure out which operator T was getting instantiated.

In the cases where overloading and/or templates rendered the question meaningless, I would try to at least give a nice static_assert error message, if not actually produce a tag type so that is_same_v<deduce_first_parameter_t<oops1>, signature_is_ambiguous_t>.


First, there is a principle you should be reminded:
Never deal with the error you don't know, just pop it up.

Which means, if you can't deal with or don't know about the error passed in the callback, you just pass it to next callback, or throw it(A pattern of CHAIN OF RESPONSIBILITY)!

For the errors you know how to deal with it, you can define a module for error handling and deal with it according to the type of error and log the error for debugging, like the following way.

error-handler.js

var log = require('./log'); // Log module(local or third-party);

function handler(error){
  if(error instanceof error1){
    // log it
    // handler for error1
  }else if(error instanceof error2){
    // log it
    // handler for error2
  }else if ....
};

module.exports = handler;

logic.js

var errorHandler = require('./error-handler');

db.open(function(err, connection){
  if(err){ return errorHandler(err); }
});

For good modules like mongoose will throw their customized Errors.


In order to call each time the garbage function just create a

public function beforeFilter() {
        parent::beforeFilter();
        $this->garbage();

About the new Ticket()
i think it would be okay to change the

$ticketObj->..

to

$this->Ticket->..

Also i think setting your function name's as set is a bad idea because they are built in functions in cakephp


Download, unzip and parse xml into pandas dataframe

You may import itertools and then replace the part

for node in nodes:
    item = {}
    for tag in tag_list:
        if node.find(".//{}".format(tag)) is not None:
            item[tag] = node.find(".//{}".format(tag)).text.strip()
    final_list.append(item)

with

for node, tag in itertools.product(nodes, tag_list):
    if node.find(".//{}".format(tag)) is not None:
        final_list.append({tag: node.find(".//{}".format(tag)).text.strip()})

as itertools.product() creates a cartesian product of your two lists (and so the temporary dictionary item is no longer needed).


If I were to solve this, adding the new code to the switch seems to me like overkill.

I would try writing an application that uses plugins in a searchable directory.
Then you solve each problem in its own plugin and the main program just consists of the logic to find and execute the plugins.

Of course to enhance finding the plugins there some possible designs:

Naming the plugin after the solved problem

Name the plugin file by a given structure so it is obvious which problem is solved:

ep-001.dll
ep-002.dll
...

That has the problem of forbidding user defined names, however it offers efficiency in that you can directly load only the needed plugin if you know the number.

Give the plugin class a problemNumber function

The other solution is to give the plugin class (that you will need anyway for a common interface to query for the solution) a function that returns the problem number.
This allows for arbitrarily named plugins, but also for duplicates and has the disadvantage of loading all plugins that are there to see if the one containing the requested solution is there.

Since you are not that much efficiency bound on this problem I would suggest the second alternative because it has a much nicer OO interface (IMHO).


Since Excel runs via COM, it won't be released from memory until you remove all references to it.  Your example (above) does a pretty good job, but after you say wBook.Close(), you should say wBook = null.  Likewise Excel won't gracefully close-down while your xCel object refers to an instance of Excel.
This article on CodeProject shows the recommended/industry-standard way of closing-down excel. ffwd down to Sections 13 and 14.
http://www.codeproject.com/Articles/404688/Word-Excel-ActiveX-Controls-in-ASP-NET


To reduce duplication, look at what's identical in each line, and what's different. For the different parts, make them a part of a loop, or the arguments to a function. For the identical parts, make them the body of the function/loop. In this case, look at the lines:

Button(master, text="1", command=lambda: self.do_math(1)),
Button(master, text="2", command=lambda: self.do_math(2)),
Button(master, text="3", command=lambda: self.do_math(3)),

The only thing that differs are the text parameter values, and the argument to do_math. Conveniently, they're the same, so this can be a simple loop over a range of numbers. I'm going to use a list comprehension here:

self.number_buttons = [Button(master, text=str(n), command=lambda n: self.do_math(n))
                       for n in range(1, 10)]

And in most cases, that would be fine. Unfortunately though, you're needing to put n inside of a lambda, and that can cause some surprising problems. To fix it, I'm going to use the lambda n=n: . . . fix. If I didn't make this change, the text would be set fine, but each button would end up being passed 19 instead of the correct number.

self.number_buttons = [Button(master, text=str(n), command=lambda n=n: self.do_math(n))
                       for n in range(1, 10)]

modes also has some duplication that can be improved.

modes = {
    "+": self.sum + num,
    "-": self.sum - num,
    "*": self.sum * num,
    "/": self.sum / num
}

self.sum = modes[self.mode]

You're repeating self.sum and num over and over. You can just deal with the data later by mapping to functions instead of the sum. The operator module has functions that correspond to the common operators like + to make this easy:

import operator as op

mode_ops = {
    "+": op.add,
    "-": op.sub,
    "*": op.mul,
    "/": op.truediv
}

f = mode_ops[self.mode]
self.sum = f(self.sum, num)  # Now we only need to specify the data once

This also saves you from computing every possible answer ahead of time. If you ever added an expensive operator, this could save some overhead (although it would be unlikely that that would ever be a major problem).


Getting the program's first argument as a number

There's always multiple ways to solve a problem, but if we keep your function signature unchanged, I'd probably write something like:

use std::env;

fn limit_from_args(mut args: env::Args) -> i32 {
    args.nth(1).and_then(|v| v.parse().ok()).unwrap_or(101)
}

fn main() {}

Notable things with your first solution:

There's no need to specify the String type when collecting; you can just use Vec<_>.
Since only one argument is needed, the code will be more efficient if that's all we look at. If there were thousands of arguments, there's no need to allocate space for 99% of them and then throw that away.
If you did have a slice or a vector, you can combine the range check and getting the value into one call with slice::get. This avoids the extra overhead of checking the index against the range:

match args.get(1) {
    Some(val) => ...,
    None => ...,
}

There's probably no need to specify the type for parse, it should be inferred from the return type.
Since the error codes are repeated, they should probably be extracted to a constant with a meaningful name. Even if they weren't repeated, 101 looks like a magic number.


Copying and comparing two sheets before deleting duplicates

It's poor form to have this much logic in an event procedure. The first step is to move 99% of this code into another module and call it from the event procedure.
Don't activate and select. This slows down your code and makes it bug prone. Use a variable to reference the worksheets and ranges you need instead.
There's no reason to select and paste. The Copy method takes an optional Destination parameter.

Instead of this

Sheets("Sheet1").Range("C:C").Copy
Sheets("Sheet2").Range("M1").Select
ActiveSheet.Paste

Use this

Sheets("Sheet1").Range("C:C").Copy Sheets("Sheet1").Range("M1")

Anytime you turn sheet calculation or screen updating off, you need to use an error handler to make sure it always gets turned back on.
Look into using an ADODB connection to query the workbook instead of working directly with the COM object. It's typically a much, much faster approach.


A few notes on making this look more like idiomatic Ruby:

There's no need to use return unless @observers in every method. You initialize @observers to a known value, which will never be falsy; there is no harm at all in assuming it will still be set later.
Any time you initialize an empty array, iterate a collection and (for each item) append something to the array, you're missing out on a map.

Instead of this...

variables = []
entry[1].each do |symbol|
  variables << instance_variable_get("@#{symbol}")
end
observer.send(entry[0],*variables)

...use this:

variables = entry[1].map { |symbol| instance_variable_get("@#{symbol}") }
observer.send(entry[0],*variables)

The last statement in a method is the return value; get rid of your explicit returns:

def count_observers
  @observers.size
end


A beginner's first Tic Tac Toe implementation

Visuals
You can try
self.values = [["-" for _ in range(3)] for _ in range(3)]

This will let you set up a 3x3 grid without having to draw the whole thing.
Now you can also do
    def show_board(self):
        board_str = "\n".join([ " | ".join(row) for row in grid ])
        print(board_str)

I would also suggest doing away with the show_board function altogether and instead use (for printing)
    def __str__(self):
        return "\n".join([ " | ".join(row) for row in grid ])

and/or (for printing in interactive console)
    def __repr__(self):
        return "\n".join([ " | ".join(row) for row in grid ])

Then you can directly do
xoxo = TicTacToe
print(xoxo)

and inside the class
print(self)

Data Representation and Input
I'm repeating myself here, but it doesn't make sense to have values be a 1-dimensional array. It's a tic-tac-toe board... it should be a 2D 3x3 grid or board. Also you should probably rename the variable values to grid or board.
This will mean taking 2 values as input from user in handle_turn(). I suggest not putting a large string inside input() as it's hard to read. Try instead
print("Enter space separated co-ordinates to pick a square")
print(f"Player {self.player} pick a square: "))
x = int(input())
y = int(input())

Ok, I'll admit this is a little annoying for the players.... maybe you could write the coordinates in the empty cells like
 X  | 1,2 |  O
2,1 |  X  | 1,3
3,1 | 3,2 |  O

(try to do this without writing out the whole starting grid manually, it should be possible using ",".join(), str() and list comprehensions)
Also it should be possible to modify the row/column/diagonals functions with 2D indices like grid[0][0], grid[1][1], grid[2][2], etc. to make it more readable. Due to the way self.grid is stored, the row function can be simplified... but it will look very different from column/diagonal and so it's probably not worth it.


Finding palindromic strings of even length

Notes

Your is_palindrome function has a bug. is_palindrome('1101') returns True.
Be careful with your function names. count_palindromes doesn't count palindromes, it returns the length of the largest one.
substring returns a generator of substrings. It should be plural.
If palindromes is a list of palindromes, you can use a list comprehension to get their respective lengths: [len(p) for p in palindromes].
You don't need to sort a list to find its max: max(palindromes, key=len).
There's also no need to define an empty list and extending it. You can use list(filter(is_palindrome,substring(number))) or [s for s in substring(number) if is_palindrome(s)].

Theory

If you write a generator which iterates over every even substrings in your string in decreasing length, all you need to check is that every digit appears an even number of time.

Code

from collections import Counter

def all_even_substrings(string):
    n = len(string)
    even_n = n + (n % 2)
    for l in range(even_n, 0, -2):
        for i in range(n + 1 - l):
            yield string[i:i + l]

def could_be_palindrome(substring):
    return all(count % 2 == 0 for count in Counter(substring).values())

def largest_possible_palindrome(string):
    return next((s for s in all_even_substrings(string) if could_be_palindrome(s)), None)

print(largest_possible_palindrome('12345354987'))
# 345354
print(largest_possible_palindrome('12334455987'))
# 334455
print(largest_possible_palindrome('123456789'))
# None

It's concise and pretty straightforward. If no palindrome is possible at all, the function returns None.

Substrings examples

Here's an example for all_even_substrings:

print(list(all_even_substrings('1234')))
# ['1234', '12', '23', '34']
print(list(all_even_substrings('12345')))
# ['1234', '2345', '12', '23', '34', '45']

If you ever need every substring:

def all_substrings(string):
    n = len(string) + 1
    for l in range(n, 0, -1):
        for i in range(n - l):
            yield string[i:i + l]

print(list(all_substrings('123')))
# ['123', '12', '23', '1', '2', '3']
print(list(all_substrings('1234')))
# ['1234', '123', '234', '12', '23', '34', '1', '2', '3', '4']


Improving sqlite3 code in swift using c api

A few observations:

The .cachesDirectory is deleted when your device runs low in storage. Are you sure you want to delete your app database in this scenario? Usually we would use .applicationSupportDirectory, which is not deleted when storage runs low and is backed up when you back up your device. But we avoid the use of the .documents folder, because that is reserved for user-facing files.
Also, we would also generally use use the create option of true.

If opening a database failed for any reason, you still need to call sqlite3_close. As the documentation says:

Whether or not an error occurs when it is opened, resources associated with the database connection handle should be released by passing it to sqlite3_close() when it is no longer required.

So I would move the defer out of that if statement. You want to move it out of there, anyway, because defer will run at the end of the current scope (at the end of your if statement in your current implementation), not at the end of the function. But if you move the defer to the right place, that observation is moot.

If a SQL statement fails for any reason, if you are going to print an error, you really should include the sqlite3_errmsg. Without that, it will be exceedingly difficult to debug problems.

I would generally advise using guard in situations where you want to exit upon failure. The compiler will make sure that you properly return when an error condition occurs.
So, pulling that together with the above points, you get something like:
let folder = try! FileManager.default
    .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    .appendingPathComponent("AppData")

try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)

let fileURL = folder.appendingPathComponent("mydb.db")

var database: OpaquePointer?
var result = sqlite3_open(fileURL.path, &database)

defer { sqlite3_close(database) }

guard result == SQLITE_OK else {
    printError(in: database, message: "couldn't open database")
    return
}

result = sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)", nil, nil, nil)
guard result == SQLITE_OK else {
    printError(in: database, message: "couldn't insert into department")
    return
}

result = sqlite3_exec(database, "INSERT OR REPLACE INTO department(id, name) VALUES(0, 'HR'), (1, 'Sales'), (2, 'Accounts'), (3, 'Shipping')", nil, nil, nil)
guard result == SQLITE_OK else {
    printError(in: database, message: "error inserting")
    return
}

Where
func printError(in database: OpaquePointer?, message: String) {
    let error = sqlite3_errmsg(database).flatMap { String(cString: $0) } ?? "Unknown error"
    print(message, error)
}

Usually we do not open and close the database with every method call. We generally open the database once, and leave it open. SQLite is very good about committing changes to the file as you go along, so opening and closing the database for every call is a tad inefficient.

As a broader observation, I would suggest abstracting the SQLite API from this department related SQL. E.g., perhaps
do {
    let database = try openDatabase()
    try database.exec("CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
    try database.exec("INSERT OR REPLACE INTO department(id, name) VALUES(0, 'HR'), (1, 'Sales'), (2, 'Accounts'), (3, 'Shipping')")
} catch {
    print(error)
}

Where:
func openDatabase() throws -> Database {
    let folder = try! FileManager.default
        .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("AppData")

    try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)

    let fileURL = folder.appendingPathComponent("mydb.db")

    let database = Database(fileURL: fileURL)

    try database.open()

    return database
}

Now, the above is using my own personal SQLite database wrapper:
//  Database.swift
//
//  Created by Robert Ryan on 3/8/19.

import Foundation
import SQLite3

private let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)

// MARK: - Database

/// Thin wrapper for SQLite C interface

public class Database {
    // MARK: - Properties

    /// The URL for the database
    let fileURL: URL

    /// The `sqlite3_open` options
    public var options: OpenOptions

    /// A `DateFormatter` for writing dates to the database
    public static var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        return formatter
    }()

    /// The SQLite database pointer
    private var database: OpaquePointer?

    /// Array of prepared statements that have not yet been finalized
    private var openStatements: [Statement] = []

    // MARK: - Initialization

    /// Database initializer
    ///
    /// Note: You must still `open` this database before using it.
    public init(fileURL: URL, options: OpenOptions = .default) {
        self.fileURL = fileURL
        self.options = options
    }

    /// Deinitializer that will finalize any open statements and then close the database if not already closed.
    deinit {
        finalizeStatements()
        try? close()
    }
}

// MARK: - Types

public extension Database {
    enum DatabaseError: Error {
        case failed(ReturnCode, String)
        case unknownType(Any)
        case notOpened
        case noStatementPrepared
        case closeFailed
    }

    struct OpenOptions: OptionSet {
        public let rawValue: Int32

        public static let readOnly     = OpenOptions(rawValue: SQLITE_OPEN_READONLY)
        public static let readWrite    = OpenOptions(rawValue: SQLITE_OPEN_READWRITE)
        public static let create       = OpenOptions(rawValue: SQLITE_OPEN_CREATE)
        public static let noMutex      = OpenOptions(rawValue: SQLITE_OPEN_NOMUTEX)
        public static let fullMutex    = OpenOptions(rawValue: SQLITE_OPEN_FULLMUTEX)
        public static let sharedCache  = OpenOptions(rawValue: SQLITE_OPEN_SHAREDCACHE)
        public static let privateCache = OpenOptions(rawValue: SQLITE_OPEN_PRIVATECACHE)

        public static let `default`:  OpenOptions = [.readWrite, .create]

        public init(rawValue: Int32) {
            self.rawValue = rawValue
        }
    }

    enum ReturnCode: Equatable {
        // non error codes

        case ok
        case done
        case row

        // error codes

        case auth
        case busy
        case cantOpen
        case constraint
        case corrupt
        case empty
        case error
        case fail
        case format
        case full
        case `internal`
        case interrupt
        case ioerr
        case locked
        case mismatch
        case misuse
        case nolfs
        case nomem
        case notadb
        case notfound
        case notice
        case perm
        case `protocol`
        case range
        case readonly
        case schema
        case toobig
        case warning

        case unknown(Int32)

        static func code(for code: Int32) -> ReturnCode {
            switch code {
            case SQLITE_OK:         return .ok
            case SQLITE_DONE:       return .done
            case SQLITE_ROW:        return .row

            case SQLITE_AUTH:       return .auth
            case SQLITE_BUSY:       return .busy
            case SQLITE_CANTOPEN:   return .cantOpen
            case SQLITE_CONSTRAINT: return .constraint
            case SQLITE_CORRUPT:    return .corrupt
            case SQLITE_EMPTY:      return .empty
            case SQLITE_ERROR:      return .error
            case SQLITE_FAIL:       return .fail
            case SQLITE_FORMAT:     return .format
            case SQLITE_FULL:       return .full
            case SQLITE_INTERNAL:   return .internal
            case SQLITE_INTERRUPT:  return .interrupt
            case SQLITE_IOERR:      return .ioerr
            case SQLITE_LOCKED:     return .locked
            case SQLITE_MISMATCH:   return .mismatch
            case SQLITE_MISUSE:     return .misuse
            case SQLITE_NOLFS:      return .nolfs
            case SQLITE_NOMEM:      return .nomem
            case SQLITE_NOTADB:     return .notadb
            case SQLITE_NOTFOUND:   return .notfound
            case SQLITE_NOTICE:     return .notice
            case SQLITE_PERM:       return .perm
            case SQLITE_PROTOCOL:   return .protocol
            case SQLITE_RANGE:      return .range
            case SQLITE_READONLY:   return .readonly
            case SQLITE_SCHEMA:     return .schema
            case SQLITE_TOOBIG:     return .toobig
            case SQLITE_WARNING:    return .warning

            default:                return .unknown(code)
            }
        }
    }
}

// MARK: - Public methods

public extension Database {
    /// Open database
    func open() throws {
        do {
            try call { sqlite3_open_v2(fileURL.path, &database, options.rawValue, nil) }
        } catch {
            try? close()
            throw error
        }
    }

    /// Close database
    func close() throws {
        if database == nil { return }
        finalizeStatements()
        try call {
            defer { database = nil }
            return sqlite3_close(database)
        }
    }

    /// Execute statement
    ///
    /// - Parameter sql: SQL to be performed.
    /// - Throws: SQLite errors.
    func exec(_ sql: String) throws {
        guard database != nil else { throw DatabaseError.notOpened }

        try call { sqlite3_exec(database, sql, nil, nil, nil) }
    }

    /// Prepare SQL
    ///
    /// - Parameters:
    ///   - sql:        SQL to be prepared
    ///   - parameters: Any parameters to be bound to any `?` in the SQL.
    /// - Returns: The prepared statement.
    /// - Throws: SQLite errors.
    func prepare(_ sql: String, parameters: [DatabaseBindable?]? = nil) throws -> Statement {
        guard database != nil else { throw DatabaseError.notOpened }

        var stmt: OpaquePointer?

        try call { sqlite3_prepare_v2(database, sql, -1, &stmt, nil) }

        let statement = Statement(database: self, statement: stmt!)

        openStatements.append(statement)

        try statement.bind(parameters)

        return statement
    }

    /// The `rowid` of the last row inserted
    ///
    /// - Returns: The `rowid`.
    func lastRowId() -> Int64 {
        sqlite3_last_insert_rowid(database)
    }

    /// Returns number of rows changed by last `INSERT`, `UPDATE`, or `DELETE` statement.
    ///
    /// - Returns: Number of rows changed.
    func changes() -> Int32 {
        sqlite3_changes(database)
    }

    /// Returns number of rows changed `INSERT`, `UPDATE`, or `DELETE` statements since the database was opened.
    ///
    /// - Returns: Number of rows changed.
    func totalChanges() -> Int32 {
        sqlite3_total_changes(database)
    }

    /// Finalize a previously prepared statement
    ///
    /// - Parameter statement: The previously prepared statement.
    /// - Throws: SQLite error.
    func finalize(_ statement: Statement) throws {
        guard let index = openStatements.firstIndex(where: { $0.sqlite3_stmt == statement.sqlite3_stmt }) else {
            return
        }

        openStatements.remove(at: index)

        try call {
            defer { statement.sqlite3_stmt = nil }
            return sqlite3_finalize(statement.sqlite3_stmt)
        }
    }

    /// The version of SQLite being used.
    ///
    /// - Returns: Version string.
    func version() -> String? {
        sqlite3_libversion()
            .flatMap { String(cString: $0) }
    }
}

// MARK: Private methods

fileprivate extension Database {
    /// Call block containing SQLite C function
    ///
    /// - Parameter block: Block that returns value from SQLite C function.
    /// - Returns: Returns return value from that C function if it returned `.ok`, `.done`, or `.row`.
    /// - Throws: SQLite error.
    @discardableResult
    func call(block: () -> (Int32)) throws -> Database.ReturnCode {
        let result = Database.ReturnCode.code(for: block())
        switch result {
        case .ok, .done, .row:
            return result

        default:
            let message = String(cString: sqlite3_errmsg(database))
            throw DatabaseError.failed(result, message)
        }
    }

    /// Finalize all open statements (those prepared but not yet finalized).
    func finalizeStatements() {
        for statement in openStatements {
            try? finalize(statement)
        }
    }
}

// MARK: - Statement

/// SQLite statement.
public class Statement {
    public fileprivate(set) var sqlite3_stmt: OpaquePointer?
    private weak var database: Database?

    init(database: Database, statement: OpaquePointer) {
        self.database = database
        self.sqlite3_stmt = statement
    }

    deinit {
        try? database?.finalize(self)
    }
}

// MARK: Public methods

public extension Statement {
    /// Bind array of parameters to `?` placeholders in SQL
    ///
    /// - Parameter parameters: The array of parameters.
    /// - Throws: SQLite error.
    func bind(_ parameters: [DatabaseBindable?]?) throws {
        try parameters?.enumerated().forEach { index, value in
            let offset = Int32(index + 1)
            if let value = value {
                try database?.call { value.bind(to: self, offset: offset) }
            } else {
                try database?.call { sqlite3_bind_null(sqlite3_stmt, offset) }
            }
        }
    }

    @discardableResult
    /// Perform the prepared statement.
    ///
    /// - Returns: The return code if `.done`, `.row` (or `.ok`, which it never can be).
    /// - Throws: The SQLite error if return code is not one of the aforementioned values.
    func step() throws -> Database.ReturnCode {
        guard
            let database = database,
            let statement = sqlite3_stmt
        else {
            throw Database.DatabaseError.notOpened
        }

        return try database.call { sqlite3_step(statement) }
    }

    /// Reset the values bound to this prepared statement.
    ///
    /// Used if you want to bind new values and perform the statement again without re-preparing it.
    ///
    /// - Throws: SQLite error.
    func reset() throws {
        guard let database = database,
            let statement = sqlite3_stmt else { throw Database.DatabaseError.notOpened }

        try database.call { sqlite3_reset(statement) }
    }

    /// Determines if the particular column value is `NULL` or not.
    ///
    /// - Parameter index: The column index number.
    func isNull(index: Int32) -> Bool {
        sqlite3_column_type(sqlite3_stmt, index) == SQLITE_NULL
    }

    /// Retrieve the value returned for a column of the particular `index`.
    ///
    /// - Parameters:
    ///    - type: The type to be returned for the column (e.g. `Int.self`).
    ///    - index: The zero-based column index number.
    /// - Returns: Returns the value found at the specified column index. If the value cannot be converted to that type, it will return `nil`.
    /// - Throws: The SQLite error if return code is not one of the aforementioned values.
    func column<T: DatabaseBindable>(_ type: T.Type, index: Int32) -> T? {
        T(from: self, index: index)
    }

    /// Retrieve the name of the column of the particular `index`.
    ///
    /// - Parameter index: The zero-based column index number.
    /// - Returns: The name of the column or `nil` if it couldn't determine the name.
    func columnName(index: Int32) -> String? {
        sqlite3_column_name(sqlite3_stmt, index)
            .flatMap { String(cString: $0) }
    }

    /// Retrieve the origin name of the column of the particular `index`.
    ///
    /// - Parameter index: The zero-based column index number.
    /// - Returns: The name of the column or `nil` if it couldn't determine the name.
    func columnOriginName(index: Int32) -> String? {
        sqlite3_column_origin_name(sqlite3_stmt, index)
            .flatMap { String(cString: $0) }
    }

    /// Retrieve the name of the table associated with the column of the particular `index`.
    ///
    /// - Parameter index: The zero-based column index number.
    /// - Returns: The name of the column or `nil` if it couldn't determine the name.
    func columnTableName(index: Int32) -> String? {
        sqlite3_column_table_name(sqlite3_stmt, index)
            .flatMap { String(cString: $0) }
    }

    /// Retrieve the name of the table associated with the column of the particular `index`.
    ///
    /// - Parameter index: The zero-based column index number.
    /// - Returns: The name of the column or `nil` if it couldn't determine the name.
    func columnDatabaseName(index: Int32) -> String? {
        sqlite3_column_database_name(sqlite3_stmt, index)
            .flatMap { String(cString: $0) }
    }
}

// MARK: - Data binding protocol

public protocol DatabaseBindable {
    /// Initializer used when returning value from result set of performed SQL `SELECT` statement.
    ///
    /// - Parameters:
    ///   - statement: The prepared and performed SQLite statement.
    ///   - index: The 0-based index for the column being returned.
    init?(from statement: Statement, index: Int32)

    /// When binding a value to a prepared (but not yet performed) SQL statement.
    ///
    /// - Parameters:
    ///   - statement: The prepared SQLite statement to be performed.
    ///   - offset: the 1-based index for the column being bound.
    /// - Returns: The SQLite return code.
    func bind(to statement: Statement, offset: Int32) -> Int32
}

// MARK: Specific type conformances

extension String: DatabaseBindable {
    public init?(from statement: Statement, index: Int32) {
        guard !statement.isNull(index: index), let pointer = sqlite3_column_text(statement.sqlite3_stmt, index) else { return nil }
        self = String(cString: pointer)
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        sqlite3_bind_text(statement.sqlite3_stmt, offset, cString(using: .utf8), -1, SQLITE_TRANSIENT)
    }
}

extension Decimal: DatabaseBindable {
    public init?(from statement: Statement, index: Int32) {
        guard
            !statement.isNull(index: index),
            let string = String(from: statement, index: index),
            let value = Decimal(string: string, locale: Locale(identifier: "en_US_POSIX")) else { return nil }
        self = value
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        var value = self
        let string = NSDecimalString(&value, Locale(identifier: "en_US_POSIX"))
        return sqlite3_bind_text(statement.sqlite3_stmt, offset, string.cString(using: .utf8), -1, SQLITE_TRANSIENT)
    }
}

extension IntegerLiteralType: DatabaseBindable {
    public init?(from statement: Statement, index: Int32) {
        guard !statement.isNull(index: index) else { return nil }
        let value = sqlite3_column_int64(statement.sqlite3_stmt, index)
        self = .init(value)
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        sqlite3_bind_int64(statement.sqlite3_stmt, offset, Int64(self))
    }
}

extension BinaryFloatingPoint {
    public init?(from statement: Statement, index: Int32) {
        guard !statement.isNull(index: index) else { return nil }
        self = Self(sqlite3_column_double(statement.sqlite3_stmt, index))
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        sqlite3_bind_double(statement.sqlite3_stmt, offset, Double(self))
    }
}

extension Data: DatabaseBindable {
    public init?(from statement: Statement, index: Int32) {
        guard !statement.isNull(index: index) else { return nil }

        let count = sqlite3_column_bytes(statement.sqlite3_stmt, index)
        if count == 0 { return nil }

        guard let bytes = sqlite3_column_blob(statement.sqlite3_stmt, index) else { return nil }
        self = Data(bytes: bytes, count: Int(count))
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        withUnsafeBytes { pointer in
            let bytes = pointer.baseAddress
            return sqlite3_bind_blob(statement.sqlite3_stmt, offset, bytes, Int32(count), SQLITE_TRANSIENT)
        }
    }
}

extension Date: DatabaseBindable {
    public init?(from statement: Statement, index: Int32) {
        guard
            !statement.isNull(index: index),
            let pointer = sqlite3_column_text(statement.sqlite3_stmt, index) else { return nil }

        let string = String(cString: pointer)
        guard let date = Database.dateFormatter.date(from: string) else { return nil }

        self = date
    }

    public func bind(to statement: Statement, offset: Int32) -> Int32 {
        let string = Database.dateFormatter.string(from: self)
        return sqlite3_bind_text(statement.sqlite3_stmt, offset, string.cString(using: .utf8), -1, SQLITE_TRANSIENT)
    }
}

Now, that is my personal thin wrapper around the SQLite API, but there are lots of them out there and you probably want to find one that is publicly supported. Or roll your own. But I would advise abstracting the SQLite code away from your app-specific SQL.
Even if you do this (using my wrapper, your own, or some established third-party wrapper), I'd also abstract the “department” repository code out in its own controller. You do not want to entangle your model object and general controller code with any particular storage mechanism. You should be able to change your database API at a future date without impacting your app-specific logic.

When inserting into a database, we often would avoid using string interpolation, but rather bind values to ? placeholders in our SQL using sqlite3_bind_xxx(). Or, using the above SQLite wrapper:
do {
    let database = try openDatabase()
    try database.exec("CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
    let statement = try database.prepare("INSERT OR REPLACE INTO department(id, name) VALUES (?, ?)")
    for (id, string) in [(5, "Bob's Department"), (6, "Susan's Department")] {
        try statement.bind([id, string])
        try statement.step()
        try statement.reset()
    }
} catch {
    print(error)
}

This gets us out of worrying about the presence of apostrophes or other SQLite reserved string literals in our SQL. In the case of this fixed list of departments, it is not much of an issue, but if you start inserting values supplied by the end user, making sure that values are inserted correctly with sqlite3_bind_xxx() functions and ? placeholders in your SQL.

Personally, I would not just open a database with sqlite3_open.

I would use sqlite3_open_v2 with the SQLITE_OPEN_READWRITE option (or the .readWrite option in my wrapper), but not the SQLITE_OPEN_CREATE option (or my .create option).
If open failed, then I would go through the creation process (creating tables, populating them, etc.; or frequently I would put an initialized database in my bundle, and if opening in app support directory failed, then I'd copy from the bundle to app support directory and then open again).

In your simple example, it is not terribly relevant, but as the app/db grows in complexity, you may want to avoid having to write a ton of “create and populate the database” code. It is convenient to have a saved “initial state” database ready and waiting in the bundle. It is your call, though, but just a recommendation.
Either way, it is often preferable to avoiding sqlite3_open, which silently creates a database if it is not there, but use sqlite3_open_v2 without the “create” option, and use the success or failure of that to determine whether you need to initialize the database or not.


Year with the most living (given a list of births and deaths)

The optimal algorithm is about O(n) to generate the count changes per year (and optionally get the first and last year), and about O(m) for enumerating them to find the first year with highest count (where m is preferably the number of years from the first to last year).

var people = [{ birth: 1720, death: 1860 },{ birth: 1720, death: 1860 },{ birth:1803, death: 1809},{ birth: 1730, death: 1810 },{ birth: 1920, death: 1950 },{ birth: 1930, death: 1940 },{ birth: 1940, death: 1990 }, { birth: 1970, death: 2010 }];

var counts = people.reduce((a, v) => (a[v.birth] = (a[v.birth] | 0) + 1,
                                      a[v.death] = (a[v.death] | 0) - 1, a), []);

var maxYear = 0, maxCount = 0, count = 0;
counts.forEach((c, y) => {
  count += c;
  if (maxCount < count) {
    maxCount = count;
    maxYear = y;
  }
});

console.log( maxYear, maxCount );
console.log( { ...counts } );

The above is just a sample, and can be much more efficient with for(;;) loops and starting the second loop from the first year 1720 instead of 0. The count changes can be in either object {} or Array object [] as long as they are enumerated in order from low to high.


Compensating for typos in strings by removing spaces and making uppercase for comparison

You can simplify avoiding reassignement:

def standardizer(str):
    return str.replace("sp_ec_", "sp_etc_").replace(" ", "").upper()

You should use a for loop to avoid repetition in the following lines:

print(str1, standardizer(str1))
print(str2, standardizer(str2))
print(str3, standardizer(str3))
print(str4, standardizer(str4))
print(str5, standardizer(str5))


Caveat: Unicode has been around for over 25 years. Unicode's 110,000 characters are four orders of magnitude more than the 26 under consideration. In the messy real world, any interesting problem involving character processing is highly likely to bump into it..

Data Structures

At scale, the bit by bit data representation is impractical because parsing 110,000 bit integers [or even 256 bit integers representing all of ASCII] is likely to be much harder than the original problem (i.e. implementing consistent 256 bit integer arithmetic is non-trival).

This is not to say that the general problem is overly difficult. To the contrary, it is well understood because it is so common. A common data structure addressing this class of problems is the Hash Table because hash tables have constant time [O(1)] lookup. For large ranges of keys, the overhead of implementing a Hash Table is often overwhelmed by the savings in lookup.

Implementation

Hash Table data structures are available as a robust Java implementation:

Hash Tables are available directly in Java via HashMap.

A pseudo-code implementation:

forEach character in characters
   myHashTable.insert(character, TRUE)

return myHashTable.keys.toArray()

Performance

For special applications an approach such as that described in the question may offer better performance than a generalized approach using HashMap. A possible  alternative in such cases might be Bloom Filters. A field tested Java implementation of Bloom Filters is available via Google's Guava library.


This is a somewhat old question, but I have an alternative that may work for this.  Related to this question, if you turn off the synchronization with the underlying stdio, you can use imbue to set the locale for both wcout and wcin:

#include <locale>
#include <string>
#include <iostream>

int main ()
{
    // this code turns off the sync with stdio
    std::ios_base::sync_with_stdio(false);
    // now create the appropriate locale without setting the global one
    std::locale ru("ru_RU.utf8");
    // use imbue to allow the Russian words to be properly displayed
    std::wcout.imbue(ru);
    // ... and input
    std::wcin.imbue(ru);

    // the rest of the code is essentially unchanged from the original
    std::wstring s(L"привет");
    std::wcout << s << '\n';
    std::wstring u;
    std::wcin >> u;
    s += L' ' + u;
    std::wcout << s << '\n';
 }

Using it in this way means that no custom class is required.


Expression tree in Haskell with support for differentiation

You have a copy-and-paste error here:

eval (Cos a) x =(cos) <$> eval a x
eval (Sin a) x = (cos) <$> eval a x