Is it ok to have NaN while comparing fields in JavaScript? I am comparing two integer values, but there is chance of parseInt giving NaN. I would like to know if I need to do any additional checks.

var txtFromCustomerId = document.getElementById(FROMCUSTOMERID_FIELDNAME);
var txtToCustomerId = document.getElementById(TOCUSTOMERID_FIELDNAME);

if (txtFromCustomerId  != null && txtToCustomerId != null) {
    var fromCustomerId = parseInt(txtFromCustomerId.value);
    var toCustomerId = parseInt(txtToCustomerId.value);

    if (fromCustomerId > toCustomerId) { <---There is chance of parseInt giving Nan
        //some other stuff
    }
}

A blank string is not equal to null, therefore it can get through.
parseInt('') returns a NaN.
Always use parseInt() with the radix (the second parameter). In some implementations, it doesn't default to base 10 (decimal).
As much as possible, use string comparison (===, !==, etc). It's best practice.

Instead, check for a blank string. Then instead of parseInt, you can do a +.

var text = *get value*
if(text !== ''){
  var number = +text;
}


Compute the derivative of a function 1.11 Arranging the derivative of a function
  The derivative of any function f (x) at x0 can be estimated according to the following formula:

  Write a program that prints three columns of numbers: x, f (x) and the derivative f '(x) for some simple functions, e.g. sin (x) or arctan(x).

public static class Derrivative
{
    public static double Compute(Func<double, double> f, double x0, double h)
    {
        return (f(x0+h) - f(x0-h)) / (2*h);
    }
}

class Program
{
    static void Main(string[] args)
    {
        const int N = 10;

        Console.WriteLine("Derivative of sin(x)");

        Func<double, double> function = Math.Sin;

        for (int i = 0; i < N; i++)
        {
            Console.WriteLine($"{i}\t{function(i)}\t{Derrivative.Compute(function, i, 0.5)}");
        }

        Console.WriteLine();

        Console.WriteLine("Derivative of arctan(x)");

        function = Math.Atan;

        for (int i = 0; i < N; i++)
        {
            Console.WriteLine($"{i}\t{function(i)}\t{Derrivative.Compute(function, i, 0.5)}");
        }

        Console.ReadLine();
    }
}

Kindly, review this source code.

Separate the for loop to a function printFunction(f, N)

Since you are using a known formula I suggest you use the names in the formula. Meaning i->x
function->f.


Obfuscating iPhone Password If I need to obfuscate an iPhone password that is hardcode (Oauth Client Identifier and Client Secret), would this be a way to do it?

NSString *a = @"a";
NSString *b = @"b";
NSString *c = @"c";
NSString *d = @"d";
NSString *e = @"e";
NSString *f = @"f";
NSString *g = @"g";
NSString *h = @"h";
NSString *i = @"i";
/*    hidden     */
NSString *w = @"w";
NSString *x = @"x";
NSString *y = @"y";
NSString *z = @"z";

NSString *pwd = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@", p,a,s,s,w,o,r,d];

I know obfuscate isn't recommended but after reading this Oauth secrets in mobile apps it seems like the only way.

A slightly better option that takes a little more effort up front but saves a lot of time in the long run, and makes the code more readable (and the obfuscated word harder to crack) would be to follow this pattern...

First, create an NSString class category and fill that category with a readonly property for every character.

@interface NSString (Obfuscater)

@property (readonly) NSString *a;
@property (readonly) NSString *b;
@property (readonly) NSString *c;
// etc...

@end

Now, we write the accessor method, which will follow this pattern:

- (NSString *)a {
    return [self stringByAppendingString:@"a"];
}

And how does this work?

NSString *password = @"".p.a.s.s.w.o.r.d;

This is about the same as nesting stringByAppendingString: several times, with the inner most call being:

[@"" stringByAppendingString:@"p"];

We start with an empty string and append the first character, etc.

Now, this version, compared to the one proposed in the question, is slower, and becomes noticeably more slower with exceptionally long strings, but the obfuscation is better and the working code is more readable.


Retrieving data from files in the folder I am to use VBA code to simply retrieve certain data from all Excel files in certain folder and paste it in working spreadsheet. I am not sure that this is the most efficient (which matters as I would like to learn how to write the most possible efficient codes).

I am using simple copy/paste actions but maybe there are more sophisticated methods (which could help me in the future if for example I would need to get data with certain words in contiguous column in the worksheets, or to order it by date of file creation), or maybe there is better way how to get to the files, or maybe a better to do this and how using forms and tables.

Option Explicit
Sub copydata()
Dim script As Object
Dim catalogue As Object
Dim textfile As Object
Dim loadedfile As Workbook
Dim actualfile As Workbook
Dim path As String
Dim column_index As Integer
path = InputBox("Please input path")
Application.ScreenUpdating = False
Set actualfile = ActiveWorkbook
Set script = CreateObject("Scripting.FileSystemObject")
Set catalogue = script.GetFolder(path)
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
   For Each textfile In catalogue.Files

      Workbooks.Open textfile
      Set loadedfile = ActiveWorkbook
      loadedfile.Worksheets(1).Range("D1:D15").Copy
      column_index = actualfile.Worksheets(1).Range("A5").CurrentRegion.Columns.Count
      actualfile.Worksheets(1).Range("A5").Offset(0, column_index).PasteSpecial
      loadedfile.Close Savechanges:=False

    Next textfile

Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True

End Sub

There is a few things I would fix:

find a better way to grab the path - don't let the user type the path manually as he can easily make a typo and you procedure would fail as you're not currently really checking if the path provided is correct/(exist). Remember not to ever trust user with their input in your programs.

For example, consider this code which shows a box to select the folder (note you can even pass the initial path to it by providing a parameter)

Additionally: If you wanted to point to "My Computer" by default see this workaround on my blog.

Sub Main()

    Dim path As String
    path = GetFolder("") & "\"

    Debug.Print path
End Sub

' strPath is the initial path
Private Function GetFolder(strPath As String) As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = strPath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

Early vs. late binding

I see you are late binding your objects. There are tons of discussions what is better and why so I am not going to judge here all I can see is that all it takes to get intelli-sense and a better performance is adding references to Microsoft Scripting Runtime via the Tools -> References in VBE (Visual Basic Editor).

Now, if you combine the tips from above you could get a little bit revised but better version of you code

Sub Copydata()

    Dim path As String
    path = GetFolder("") & "\"

    Dim script As FileSystemObject
    Set script = New FileSystemObject

    Dim catalogue As Folder
    Set catalogue = script.GetFolder(path)

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.AskToUpdateLinks = False

    Dim textfile As File
    Dim column_index As Integer
    Dim loadedfile As Workbook

    Dim actualfile As Workbook
    Set actualfile = ActiveWorkbook

    For Each textfile In catalogue.Files

        Workbooks.Open textfile
        Set loadedfile = ActiveWorkbook
        loadedfile.Worksheets(1).Range("D1:D15").Copy
        column_index = actualfile.Worksheets(1).Range("A5").CurrentRegion.Columns.Count
        actualfile.Worksheets(1).Range("A5").Offset(0, column_index).PasteSpecial
        loadedfile.Close Savechanges:=False

    Next textfile

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.AskToUpdateLinks = True

End Sub

' strPath is the initial path
Private Function GetFolder(strPath As String) As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = strPath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

Great, so now you probably want to eliminate opening each workbook just to copy data. There are various ways to pull data from opened and closed workbooks (without actually opening them) and I am going to use the ADODB way in your example.

Note, you need to add references to Microsoft ActiveX Data Objects 6.1 Library for this to work but the efficiency should increase a lot because you do not open the files just to get 15 rows out of them.

Let's start with a very simple example:

Assuming there is a folder temp on you C:\ drive and there is a file1.xlsm in it

Sub Pull_Data_from_Excel_with_ADODB()

    Dim cnStr As String
    Dim rs As ADODB.Recordset
    Dim query As String

    Dim fileName As String
    fileName = "C:\temp\file1.xlsm"

    cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=" & fileName & ";" & _
               "Extended Properties=Excel 12.0"

    query = "SELECT * FROM [Sheet1$D1:D15]"

    Set rs = New ADODB.Recordset
    rs.Open query, cnStr, adOpenUnspecified, adLockUnspecified

    Cells.Clear
    Range("A2").CopyFromRecordset rs
    Dim cell As Range, i As Long
    'headers
    With Range("A1").CurrentRegion
        For i = 0 To rs.Fields.Count - 1
            .Cells(1, i + 1).Value = rs.Fields(i).Name
        Next i
        .EntireColumn.AutoFit
    End With
End Sub

See, this does not open the file and allows you to pull the D1:D15 from it.

Now if you slightly modify the code to suit your example you get a fully working and efficient code

Option Explicit

Sub Copydata()

    Dim path As String
    ' retrieve the path to the folder with the files to pull data from
    path = GetFolder("") & "\"

    Dim script As FileSystemObject
    Set script = New FileSystemObject

    Dim catalogue As Folder
    Set catalogue = script.GetFolder(path)

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.AskToUpdateLinks = False

    Dim cnStr As String
    Dim rs As ADODB.Recordset

    Dim query As String
    ' SQL query to pull D1:D15 from Sheet1 in each file
    query = "SELECT * FROM [Sheet1$D1:D15]"

    Dim wbFile As Variant

    ' iterate through the files in the folder user selected
    For Each wbFile In catalogue.Files

        ' upate the connection string with path to each file
        cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=" & wbFile & ";" & _
               "Extended Properties=Excel 12.0"

        ' populate a recordset with D1:D15 from each file
        Set rs = New ADODB.Recordset
        rs.Open query, cnStr, adOpenUnspecified, adLockUnspecified

        ' Copy data from recordset to range in one go
        Range("A5").Offset(0, Range("A5").CurrentRegion.Columns.Count).CopyFromRecordset rs

        ' close the recordset and free memory
        rs.Close
        Set rs = Nothing
    Next wbFile

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.AskToUpdateLinks = True

End Sub

' strPath is the initial path
Private Function GetFolder(strPath As String) As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = strPath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function


Euclidean distance of two matrices I am writing codes to have the Euclidean distance of two matrices and then storing them in a matrix. Could anyone please review this?

a <-matrix(1:2,ncol = 2,nrow = 2)
a
     [,1] [,2]
[1,]    1    1
[2,]    2    2

b <-matrix(3:6,ncol = 2,nrow = 2)
b
     [,1] [,2]
[1,]    3    5
[2,]    4    6

n <-matrix(data = NA)
 for (i in 1:nrow(a)) {
   for (j in 1:nrow(b)) {
    n[i]<-sum(abs(a[i,]-b[j,])^2)
  }
}
n

First let's take a quick look at what your code is doing. Your innermost line of code is:

n[i]<-sum(abs(a[i,]-b[j,])^2)

Due to how you've structured your for loops, this is run for times

with i=1 and j=1, setting n[1] to the squared distance between row 1 with a and row 1 of b,
with i=1 and j=2, overwriting n[1] to the squared distance between row 1 of a and row 2 of b,
with i=2 and j=1, setting n[2] to the squared distance between row 2 of a and row 1 of b, and
with i=2 and j=2, overwriting n[2] to the squared distance between row 2 of a and row 2 of b.

So we end up with n = c(34, 20), the squared distances between each row of a and the last row of b.

It seems most likely to me that you are trying to compute the distances between each pair of points (since your n is structured as a vector). In this case, check out what we accomplish with the following, much simpler code:

(a-b)^2
#      [,1] [,2]
# [1,]    4   16
# [2,]    4   16

The resulting matrix is the squared difference of each element in the two matrices. All we need to do is to sum up the rows:

n <- rowSums((a-b)^2)
n
# [1] 20 20

Or if we wanted the actual distance instead of the squared distance:

n <- sqrt(rowSums((a-b)^2))
n
# [1] 4.472136 4.472136

Note that we dramatically simplified the calculation; a nice side benefit is that this code is much faster than using a for loop in R.


Random exam generator I've written a short Random Exam Generator program.
There are 6 days, 3 time slots per day. One day can not have more than 2 exams. There will be 5 exams in total.

I am fairly new to programming so I would like some feedback on how well this code is written, and if there are any ways to improve it.

var exam_days =
    { 0: 0,
      1: 0,
      2: 0,
      3: 0,
      4: 0,
      5: 0 };

var exam_array = [];

function generateSchedule() {
  for (var i = 0; exam_array.length < 5; i++){
    var time = getRandomInt(0,2);
    var day = getRandomInt(0,5);
    var exam_id = "exam-" + time + day;
    if (dayAvailable(day, exam_days) && uniqueExam(exam_id, exam_array)) {
      exam_days[day] += 1;
      exam_array.push(exam_id);
      document.getElementById(exam_id).style.background = "green";
    }
  }
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function dayAvailable(date, exam_days) {

  if (exam_days[date] < 2) {
      return true;
    }
  return false;
}

function uniqueExam(exam, exam_array)
{
    var count = exam_array.length;
    for (var i = 0; i < count; i++)
    {
        if (exam_array[i] === exam)
          return false;
    }
    return true;
}

Library functions usage

The unique_exam function is basically checking if the exam is in the array or not and returning false if it is not, the includes method is what You need.

return ! exam_array.includes(exam)

Inline

dayAvailable

Should be inlined as it boils down to just one comparison, instead the number of exams per day should be saved as a constant.


Multiple functions to establish a fallback value for a property until not null I have a property (called "Head") that can be set externally. When "Head" is not set, it uses Unity3D's MonoBehaviour functions to try to find the best value for "Head". I started with a nested if, but the nesting was starting to get out of hand.

if (Head == null)
{
    Head = this.GetComponent<Camera>();

    if (Head == null)
    {
        Head = this.GetComponentInChildren<Camera>();

        if (Head == null)
        {
            Head = Camera.main;
        }
    }
}

So I developed a loop:

System.Func<Camera>[] fallbacks = new System.Func<Camera>[]
{
    () => this.GetComponent<Camera>(),
    () => this.GetComponentInChildren<Camera>(),
    () => Camera.main,
};

foreach (var fallback in fallbacks)
{
    if (Head != null)
    {
        break;
    }
    Head = fallback();
}

Would this create too much lambda overhead? Do you think the lambdas even increases readability? Is there a more elegant way to handle multiple fallbacks?

Edit:

RobH helped me discover the Null coalescing doesn't work with Unity3D components.
RobH's extension method workaround worked great with some tweaking. I had to enforce that comparison had to be done through UnityEngine.Object.

public static T IfNullThen<T>(this T obj, Func<T> factory) where T : UnityEngine.Object
{
    return obj != null ? obj : factory();
}

With that extension method my code is now just

Head = Head
    .IfNullThen(() => this.GetComponent<Camera>())
    .IfNullThen(() => this.GetComponentInChildren<Camera>())
    .IfNullThen(() => Camera.main);

This seems to be a textbook case for the null coalescing operator ??

Head = GetComponent<Camera>() ?? GetComponentInChildren<Camera>() ?? Camera.main;

You also (probably) don't need to prefix with this

Edit:

If the null coalescing operator doesn't work (which is a massive shame) why not create an extension method?

public static T IfNullThen<T>(this T obj, Func<T> factory) where T : class
{
    return obj != null ? obj : factory();
    // or
    // return obj == null ? factory() : obj;
}

then you can do:

Head = GetComponent<Camera>().IfNullThen(GetComponentInChildren<Camera>).IfNullThen(() => Camera.main);

Unfortunately I'm on my mac so I don't have a compiler but I think it should work :)


Fetching data from API in JavaScript I'm using Axios to fetch data from an API, and don't know if this is the best way to deal with APIs in ReactJS or not. I want to know if anyone can suggest edits or something to make the code more efficient.

api.js

import axios from 'axios';

export const APIendpoint = axios.create({
    baseURL: 'https://1eb19101-0790-406f-90e0-ee35a2ff2d1f.mock.pstmn.io',
    timeout: 2000
});

matchesAction.js

import {FETCH_MATCHES} from './actionTypes';
import {APIendpoint} from '../api/api';

export const fetchMatches = () => dispatch => {
    const matchInstance = APIendpoint.get('/matches');
    matchInstance.then(response =>
        dispatch({
            type: FETCH_MATCHES,
            payload: response.data
        })
    );
};

It can be done in many ways based on your use case & code structure, but i feel this can be optimal way of structuring.

api/services/index.js

import axios from 'axios';
export {default as MATCHES_API} from "./services/matches.js";

export const CONFIG_API = axios.create({
  baseURL: 'https://1eb19101-0790-406f-90e0-ee35a2ff2d1f.mock.pstmn.io',
  timeout: 2000
});

api/services/matches.js

import CONFIG_API from "api/services";

const ERROR_MSG = "<generic message>";

export const matches = () => {
  return CONFIG_API.get("/matches").then(res => {
  // do some operations on data - if required
    return {success: true, data: res.payload};
  }).catch(err => {
    return {success: false, message: ERROR_MSG || err.message};
  });
};

actions/matchesAction.js

import {FETCH_MATCHES} from './actionTypes';
import {MATCHES_API} from "/api/services";

export const fetchMatches = () => dispatch => {
  matches.then((response) =>
    const {success} = response;
    if (success) {
      dispatch({ type: FETCH_MATCHES, payload});
    } else {
     dispatch({ type: FETCH_MATCHES_FAILED}); /* or show notification */ .
    }
  );
};

Let me know if this works out.


Generic function that accepts both Actions and Func's as parameters I've created a generic try catch I can apply throughout my code so I'm not repeating myself.

private HttpResponseMessage TryCatch(Action action)
{
    return TryCatch(() => { action(); return "ActionToFunc"; });
}

private HttpResponseMessage TryCatch<T>(Func<T> func)
{
    try
    {
        var result = func();

        if (result.ToString() == "ActionToFunc")
        {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        return Request.CreateResponse(HttpStatusCode.OK, result);
    }
    catch (ArgumentNullException)
    {
        return Request.CreateResponse(HttpStatusCode.NotFound);
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }
}

I can call it using:

TryCatch(() => myFunction(parameter));

Is there a better way of doing achieving the same result?

Try to avoid using magic values. This one is a hack to avoid writing 2 methods.

private HttpResponseMessage TryCatch(Action action)
{
    return TryCatch(() => { action(); return "ActionToFunc"; });
}

You are better of splitting your methods. Dispatch error handling to its own method ResolveStatusCode to avoid boiler-plate error handling. In addition, perform argument checks. Since your method is private, I would favor Debug.Assert over ArgumentNullException.

    HttpResponseMessage TryCatch(Action operation)
    {
        try
        {
            Debug.Assert(operation != null, "invalid usage of API");
            operation();
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (Exception error)
        {
            return Request.CreateResponse(ResolveStatusCode(error));
        }
    }

    HttpResponseMessage TryCatch<T>(Func<T> func)
    {
        try
        {
            Debug.Assert(func != null, "invalid usage of API");
            var result = func();
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
        catch (Exception error)
        {
            return Request.CreateResponse(ResolveStatusCode(error));
        }
    }


My own array implementation in C I've been trying to remember old programming concepts like data structures.

My first challenge was about implementing my own array of positive integers:

#include<stdio.h>
#include<stdlib.h>

int* array_initialize(int size) {
    return calloc(size, size * sizeof(int));
}

void array_set(int *array, int index, int value) {
    array += index;
    *array = value;
}

int array_get(int *array, int index) {
    array += index;
    return *array;
}

int array_size(int *array) {
    int size = 0;
    while(*array != 0) {
        size++;
        array++;
    }
    return size;
}

int main() {
    int* array = array_initialize(5);

    array_set(array, 0, 2);
    array_set(array, 1, 4);
    array_set(array, 2, 6);
    array_set(array, 3, 8);
    array_set(array, 4, 10);

    for (int i = 0; i < array_size(array); i++) {
        printf("Index #%d -> %d\n", i, array_get(array, i));
    }
    printf("\nSize: %d\n", array_size(array));

    free(array);

    return 0;
}

Can I call it an array?

Is it a good starting point? What would you change?

Can I implement my custom array with [] to read/write values to my array?

Your array set could be written as *(array + index) = value; and your array get could be written as return *(array + index);.

array[index] could also be written as *(array + index). Those two functions don't do anything you can't already do with [].


Typeahead Talent Buddy Problem is Talent Buddy.

Your task is to

  write a function that prints to the standard output (stdout) for each query the user name that matches the query
  if there are multiple user names matching the query please select the one that is the smallest lexicographically
  all string matches must be case insensitive
  if no match is found for a given query please print "-1"

  Note that your function will receive the following arguments:

  usernames
   - which is an array of strings representing the user names

  queries
   - which is an array of strings representing the queries described above

  Data constraints
   - the length of the array above will not exceed 100,000 entries
   - each name or query string will not exceed 30 characters

  Efficiency constraints

  your function is expected to print the requested result and return in less than 2 seconds

  Example

Input
names: ["james", "jBlank"]
queries: ["j", "jm", "jbl", "JB"]

Output
james
-1
jBlank
jBlank

The above is an example testcase.

My algorithm:

def typeahead(usernames, queries):
        from bisect import bisect_left
        wordlist=sorted(usernames,key=str.lower)
        l_wordlist=map(str.lower,wordlist)
        for i in queries:
            word_fragment=i.lower()
            k=wordlist[bisect_left(l_wordlist, word_fragment): bisect_left(l_wordlist, word_fragment[:-1] + chr(ord(word_fragment[-1])+1))][:1]
            print k[0] if k else  -1

Steps:

Sorted the usernames lexicographically
sorted usernames of small letters(this used in bisect)
using word_fragment i am bisecting the total array

When I profiled my method, I got this testcase:

         250005 function calls in 0.715 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 bisect.py:1(<module>)
        1    0.480    0.480    0.715    0.715 py1.py:24(typeahead)
   100000    0.146    0.000    0.146    0.000 {_bisect.bisect_left}
    50000    0.009    0.000    0.009    0.000 {chr}
        1    0.010    0.010    0.010    0.010 {map}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
    50000    0.013    0.000    0.013    0.000 {method 'lower' of 'str' objects}
    50000    0.006    0.000    0.006    0.000 {ord}
        1    0.050    0.050    0.050    0.050 {sorted}

The problem is that when I run it in the Talent Buddy, it is showing that it takes more than 2 seconds. How can I further optimise my code?

Edit as reference with another question with this testcase. The efficient code provided took the below time:

        147936037 function calls in 52.394 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.002    0.002    0.002    0.002 collections.py:1(<module>)
        1    0.000    0.000    0.000    0.000 collections.py:26(OrderedDict)
        1    0.000    0.000    0.000    0.000 collections.py:381(Counter)
        1    0.000    0.000    0.000    0.000 heapq.py:31(<module>)
        1    0.000    0.000    0.000    0.000 keyword.py:11(<module>)
        1   27.895   27.895   52.394   52.394 py.py:24(typeahead)
   100000    0.014    0.000    0.014    0.000 {method 'append' of 'list' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.002    0.002    0.002    0.002 {method 'join' of 'str' objects}
   100000    0.025    0.000    0.025    0.000 {method 'lower' of 'str' objects}
147736029   24.457    0.000   24.457    0.000 {method 'startswith' of 'str' objects}

def typeahead(usernames, queries):
        from bisect import bisect_left
        wordlist=sorted(usernames,key=str.lower)
        l_wordlist=map(str.lower,wordlist)
        for i in queries:
            word_fragment=i.lower()
            x=bisect_left(l_wordlist, word_fragment)
            try:
                if word_fragment in l_wordlist[x]:
                    print wordlist[x]
                else: print -1
            except: print -1

i have increased it performance by

k=wordlist[bisect_left(l_wordlist, word_fragment): bisect_left(l_wordlist, word_fragment[:-1] + chr(ord(word_fragment[-1])+1))][:1]

there are two bisects functions in above by removing one and converting to below

            x=bisect_left(l_wordlist, word_fragment)
            try:
                if word_fragment in l_wordlist[x]:
                    print wordlist[x]
                else: print -1
            except: print -1

by profiling

 100004 function calls in 0.542 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.329    0.329    0.542    0.542 reducer.py:21(typeahead)
    50000    0.116    0.000    0.116    0.000 {_bisect.bisect_left}
        1    0.013    0.013    0.013    0.013 {map}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
    50000    0.020    0.000    0.020    0.000 {method 'lower' of 'str' objects}
        1    0.063    0.063    0.063    0.063 {sorted}

reduced the system calls by half from 250005 to 100004 did the magic :)


Nested object to hierarchical object list I have a C# type to generate Layer SubLayer:

public class Layer
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Name { get; set; }
}

And simulated a list with a Db class:

public static class Db
    {
        public static IList<Layer> GetLayers()
        {
            return new List<Layer>
                   {
                       new Layer{Id = 1, ParentId = 0, Name = "First Layer" },
                       new Layer{Id = 2, ParentId = 1, Name = "First SubLayer1" },
                       new Layer{Id = 3, ParentId = 1, Name = "First SubLayer2" },
                       new Layer{Id = 4, ParentId = 1, Name = "First SubLayer3" },
                       new Layer{Id = 5, ParentId = 0, Name = "Second Layer" },
                       new Layer{Id = 6, ParentId = 5, Name = "Second SubLayer1" },
                       new Layer{Id = 7, ParentId = 5, Name = "Second SubLayer2" },
                       new Layer{Id = 8, ParentId = 7, Name = "Sub -3" }
                   };
        }
    }

I want to get a serialized JSON object, so I created a service class to generate and changed the Layer class:

public class Layer
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Name { get; set; }
    public IList<Layer> ChildLayers { get; set; }

    public Layer()
    {
        ChildLayers = new List<Layer>();
    }
}

public class LayerService
{
    public IList<Layer> GetLayers()
    {
        IList<Layer> data = Db.GetLayers();

        IList<Layer> hierarcy = new List<Layer>();

        foreach (var layer in data)
        {
            var layer1 = layer;

            var sublayers = data.Where(i => i.ParentId == layer1.Id && i.ParentId !=0);

            var enumerable = sublayers as Layer[] ?? sublayers.ToArray();

            if(enumerable.Any() && layer.ParentId ==0)
                hierarcy.Add(layer);

            foreach (var sublayer in enumerable)
            {
                layer.ChildLayers.Add(sublayer);
            }
        }

        return hierarcy;
    }
}

But this LayerService code is ugly. Is there any practical way with Linq or else? Is there a cleaner way?

var sublayers = data.Where(i => i.ParentId == layer1.Id && i.ParentId !=0);

you should let the operators some room to breathe. Adding a space after = makes your code more readable.

Bug alert

In the above query you are filtering for i.ParentId != 0 and later on you have the condition && layer.ParentId ==0 so your hierarchy wil remain empty.

var enumerable = sublayers as Layer[] ?? sublayers.ToArray();

This makes me just wonder. What sense does it have to convert the IEnumerable<Layer> to an array if the next thing you do is iterating over the items by using a foreach loop ?

var layer1 = layer;

this isn't necessary at all, it is sufficient to use the layer inside linq expression.

You should always use braces {} for single command if statements to make your code less error prone. If you decide to no use them, please don't come back whining that you have a bug you can't find (humour btw.).

Integrating the mentioned points will lead to

public IList<Layer> GetLayers()
{
    IList<Layer> data = Db.GetLayers();

    IList<Layer> hierarcy = new List<Layer>();

    foreach (var layer in data)
    {

        var sublayers = data.Where(i => i.ParentId == layer.Id && i.ParentId != 0);

        if (sublayers.Any())
        {
            hierarcy.Add(layer);
        }
        foreach (var sublayer in sublayers)
        {
            layer.ChildLayers.Add(sublayer);
        }
    }

    return hierarcy;
}

public class Layer
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Name { get; set; }
    public IList<Layer> ChildLayers { get; set; }

    public Layer()
    {
        ChildLayers = new List<Layer>();
    }
}

You shouldn't expose the ChildLayers property setter to the public. If someone comes along setting it to null you would be lost.

You should just change it to

public IList<Layer> ChildLayers { get; private set; }

Otherwise using autoimplemented properties, as long as you don't need validation in the setters , is the way to go.


Highlight strings that match a search term I'm writing a ctrl+f function so to speak in React that allows a user to search for a term in a list of words, and if the term matches any of the words in the list then it highlights it. To do this, I'm currently using document.querySelectorAll to retrieve all of the words in the list and manipulate them (highlight) if there is a match. Because this is React I feel very bad about using the querySelector to grab the words and feel I should be using refs perhaps, but not sure how comparable that is or if that works in this particular scenario. Here is my code:

const HighlightSearchTerm = () => {
  const [searchTerm, setSearchTerm] = React.useState("");

  React.useEffect(() => {
    const regex = new RegExp(searchTerm, "gi");
    const labels = document.querySelectorAll(".label"); // use refs??

    labels.forEach(label => {
      label.innerHTML = label.innerText.replace(regex, match =>
        `<span class="highlight">${match}</span>`
      );
    });
  }, [searchTerm]);

  return (
    <div>
      <input
        type="text"
        value={searchTerm}
        placeholder="Search Labels"
        onChange={event => setSearchTerm(event.target.value)}
      />
    </div>
  );
};

As you can see, implementing it this way has to also call document.querySelectorAll each time the user types a letter or makes a change which isn't very efficient and is causing [Violation] 'setTimeout' handler took <N>ms to appear in the console many times when working with large lists. Instead, I would like to

Not use document.querySelectorAll to retrieve the words in the list (use refs if possible?)
Not fetch the list of words each time I type due to the fact the list won't change once the component is rendered (possibly render them when the component mounts, although it seems I can't do this currently when using querySelector)

Any other optimization suggestions would also be very much appreciated.

Current working example: https://codepen.io/andrewgarrison/pen/eYOWjZB

Rather than extract the Search input in to a different component I would suggest you keep the input and list in the same component.

This way when printing the list you can highlight the search term directly.

const HighlightableList = (props) => {
  const [searchTerm, setSearchTerm] = React.useState("");
  const regex = new RegExp(searchTerm, "gi");

  const items = props.terms.map((term, index) => (
      <div
        className="label"
        key={index}
        dangerouslySetInnerHTML={{
          __html: term.replace(regex, match => `<span class="highlight">${match}</span>`)
        }}
      />
    ));

    return (
      <>
        <input
          type="text"
          value={searchTerm}
          placeholder="Search Labels"
          onChange={event => setSearchTerm(event.target.value)}
        />
        <div className="label-container">
          {items}
        </div>
      </>
    );
}

https://codepen.io/rockingskier/pen/YzKrGNR

Side notes:

Don't make each list item a label. From MDN

  The HTML  element represents a caption for an item in a user interface.

That would suggest that each item in the list has its own user input.  In fact there is only one input (search) and that should really have a label of its own.  I'll let you implement that.

Additionally due the the "list-iness" of the data I have converted it to a ul with each item as an li.


Factory to augment JS classes with validation methods I have some validation classes. To keep things smooth, I create a single class that has those validation classes inside of it. That class will be a singleton, and gets injected into my other classes.

The validation classes have a method that needs to be executed by the depending object. So lets make this clear:

The Matrix class

Gets a validate class injected

and calls validate.validateMatrix().

That method, validateMatrix(), is actually in another class, that validate imports and creates a reference to. The validateMatrix class, for example, looks like this:

export class validateMatrix {
    validateMatrix(props){
       ...
    }
}

The validateclass has a generator for those classes that it needs, and all the validation classes have a method with the exact same name as the class name. That way, I can request the class name and call out to the validate method. That class looks like this:

import {validateString} from './validate/validateString';
import {validateSlider} from './validate/validateSlider';
import {validateCheckbox} from './validate/validateCheckbox';
import {validateRadio} from './validate/validateRadio';
import {validateDatetime} from './validate/validateDatetime';
import {validateMatrix} from './validate/validateMatrix';

export class validate {

    // this is just the library containing all the validators, for easy import.

    constructor(){
        this.classGenerator(
            validateString,
            validateSlider,
            validateCheckbox,
            validateRadio,
            validateMatrix,
            validateDatetime
        );
    }

    classGenerator(...classes){
        // pass in a class with the same method name as class name
        // and that function will be referred from here
        // e.g. this.validateMatrix()

        classes.forEach( (theClass) => {
            let classObj = new theClass();
            this[classObj.constructor.name] = classObj[classObj.constructor.name];
        });
    }
}

Usage:

validate() {
    this.validator.validateMatrix(this.question.properties)
        .then(this.branching.branch());
}

Is this a good way to create a factory method to generate those methods, and keep them hidden in other classes?

Your solution works, and is perfectly functional, but it's bad practice.

What you're describing is the service locator anti-pattern, it means that instead of passing what you need to a function, you pass a magic box that holds what you need and many other things, and it's the responsibility of your consuming class to know this magic box (called a service locator), and be tightly coupled with it, to get the object it really needs. It's a redundant layer of abstraction that only makes things harder instead of easier.

Do you have a Matrix class? Pass it a MatrixValidator with a .validate() method. Have a Checkbox class? Pass it a CheckboxValidator with a .validate() method.

This way, your actual classes don't need to know anything about their validators, they only see an object with a .validate() method, and the .validate() method gets implemented differently for each validator. That's called polymorphism, and it's a powerful tool in your OO arsenal.

Additionally, dynamically adding methods to constructors (a.k.a. classes) is frowned upon, because it makes it hard to read. With the polymorphism method, all of your methods are known at write time, and nothing is added in runtime, which is good for both readability and performance.

Now, you might ask, "who will determine which Validator instance to inject to each of my classes", that would be "the entity that creates your instances", normally, that would be a factory of some sort, otherwise, look up Dependency Injection for a good pattern to follow.


Is this correct usage of the "Decorator" Pattern? I have a model class Product that gets populated from a service DTO object (using AutoMapper).  The service is used to power many different applications and for each one the Product Model might need to behave a bit differently.  After a bit of research I decided the 'Decorator' pattern might be a good choice to accompany these differences.  Here is how I currently have implemented it.

These classes are part of a library that gets included in each of the applications

public class Product
{
    public virtual string ProductName { get; set; }
    public virtual Decimal Price { get; set; }
    public virtual string ImageUrl { get; set; }

    public virtual string GetImageUrl(){
        return ImageUrl;
    }
}

public abstract class ProductDecorator : Product
{
    private Product decoratedProduct; // the product being decorated

    protected ProductDecorator(Product decoratedProduct)
    {
        this.decoratedProduct = decoratedProduct;
    }

    public override string ProductName
    {
        get
        {
            return decoratedProduct.ProductName;
        }
        set
        {
            decoratedProduct.ProductName = value;
        }
    }
    public override decimal Price
    {
        get
        {
            return decoratedProduct.Price;
        }
        set
        {
            decoratedProduct.Price= value;
        }
    }
    public override string ImageUrl
    {
        get
        {
            return decoratedProduct.ImageUrl;
        }
        set
        {
            decoratedProduct.ImageUrl= value;
        }
    }
}

In each application there may be need to slightly change the model.

public class FooProduct : Model.ProductDecorator
{
    public FooProduct (Model.Product product) :base(product){}

    //we want to serve the image through a cdn
    public override string GetImageUrl()
    {
        return string.Format("cnd.network.com?url={0}", HttpUtility.HtmlEncode(ImageUrl));
    }
}

Usage would be something like this:

 FooProduct prod = new FooProduct(productClient.GetProduct(23213));
 Response.Write(prod.GetImageUrl());

This is my first time using this pattern and I'm not sure if I've got it quite right or if it really applies to this scenario.  Are there any foreseeable issues with this solution?

Update

I think I need to explain a little more how I got here.

I created a class library to encapsulate an wcf service.  The library takes the DTO's returned by the service and using AutoMapper, maps the DTO to the Product class.  The issue is that the product model needs to be a bit different for each of the applications consuming the service.  Just using simple inheritance not quite right because a FooProduct needs to pretty much be exactly the same as a Product but just handle the data a bit differently.

// this returns a Product, but for this site I need a FooProduct
var product = Client.GetProduct(232);

This problem is probably a result of bad design in lower layers and from the use of AutoMapper in Client Library.

I think you've misunderstood what decorator pattern is.  As described in Wikipedia

"In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class."

What you are doing is simple inheritance.

You can do this with an interface, but you don't have too.  You have to ask yourself the question "Do I need to use the Product class?"  If you do, then leave it as is, if you don't, make it an interface, or mark it abstract.

I'm going to assume you need it.

Your class definition looks the same:

public class Product
{
    public virtual string ProductName { get; set; }
    public virtual Decimal Price { get; set; }
    public virtual string ImageUrl { get; set; }

    public virtual string GetImageUrl()
    {
        return ImageUrl;
    }
}

You would then inherit from this class for any other class you need:

public class FooProduct : Product
{
    //we want to serve the image through a cdn
    public override string GetImageUrl()
    {
        return string.Format("cnd.network.com?url={0}", HttpUtility.HtmlEncode(ImageUrl));
    }
}

You can now use either class as required:

var productInstance = new Product();

var fooProductInstance = new FooProduct();

The nice part is, you can now pass FooProduct in anywhere a Product is expected:

public void DoSomethingWithProduct(Product product)
{
    // Do some processing
}

Can be called:

processor.DoSomethingWithProduct(product);

or

processor.DoSomethingWithProduct(fooProduct);


LeetCode - Merging piles of stones This is a LeetCode Problem

  You have a pile of stones presented as an array. On each turn you must merge k consecutive piles of stones, starting from any pile you wish. You must continue merging piles until you are left with one pile only. You must do this with minimum overall cost, where the cost is the sum of the ongoing cost plus the sum of all the piles being merged

  If this isn't possible, return -1. If this is possible, return the minimum overall cost

Example

  If k = 2 and the stones = [3,2,4,1]

  Round 1: Merge stones 3 and 2 => Cost = 5, stones = [5, 4, 1]

  Round 2: Merge stones 4 and 1 => Cost = 5 + (4+1) = 10, stones  = [5, 5]

  Round 3: Merge the piles 5 and 5 => Cost 10 + (5+5)= 20, stones = [10]

  The minimum overall cost is 20

My code is below. It runs into issues for large piles of stones such as

  stones = [29, 59, 31, 7, 51, 99, 47, 40, 24, 20, 98, 41, 42, 81, 92, 55]

  k = 2

How do I improve this code to quickly calculate the answer for large piles of stones?

Thank you

def helper(stones, k, count, min_count):
    # Basecase - if only one pile of stones, set minimum count to lowest value of current minimum and new minimum
    if len(stones) == 1:
        min_count = min(count, min_count)
        return min_count
    # Set last index
    last_index = len(stones) - k + 1
    for start in range(last_index):
        new_count = count + sum(stones[start:start + k])
        merged_count = sum(stones[start:start + k])
        new_list = stones[:start] + [merged_count] + stones[start + k:]
        min_count = helper(new_list, k, new_count, min_count)
    return min_count

def merge_stones(stones, k):
    lng = len(stones)
    # Verify if solution is possible
    if lng < k or (lng - 1) % (k - 1) != 0:
        return -1
    # Calculate solution
    minimum = helper(stones, k, 0, 99999999)
    # Return solution
    return minimum

if __name__ == "__main__":
    stones = [3, 2, 4, 1]
    k = 2
    print(merge_stones(stones, k))

Without even doing anything clever regarding the algorithm, this:

    new_count = count + sum(stones[start:start + k])
    merged_count = sum(stones[start:start + k])

can be cleaned up as

    merged_count = sum(stones[start:start + k])
    new_count = merged_count + count


Move debug functions to two DLL's When programming debug functions I am left with 2 options, either put them all within preprocessor blocks so that they don't exist at release runtime, or put them within an if block with a debug flag constant variable (determined at launch) to control their execution. I wanted to write an improved method where in release mode the end user doesn't have access to the functions, but with a special DLL they can use them.

I want to know two things:

Is this more efficient than using a debug flag constant (determined at program launch) variable to control there execution. (e.g. will control flow prediction simply ignore all the calls to these debug functions)
Is this is a good practice. To be precise, would this be frowned upon by developers or horrible for some other reason (like security).

The DLL contains an essentially empty DllMain, here are the important definitions:

#include <iostream>

extern "C" void __cdecl println(const char* str)
{
#ifdef GEN_DEBUG_FUNCS
    std::cout << str << std::endl;
#endif
}

extern "C" int __cdecl test()
{
#ifdef GEN_DEBUG_FUNCS
    return 1;
#else
    return 0;
#endif
}

And on the primary program side of things we have:

The header to hold the function ptrs:

typedef void(__cdecl *f_println)(const char*);
typedef int(__cdecl *f_test)();

#ifdef FPTR_INIT
  #define EXTERN
#else
  #define EXTERN extern
#endif

EXTERN f_println println;
EXTERN f_test test;

/* Used for testing the functions in a CPP file other than main */
void testFuncs();

The CPP file to test the function pointers:

#include "FunctionPtrs.h"
#include <iostream>

void testFuncs()
{
    println("Hello World");
    std::cout << "funci() returned " << test() << std::endl;
}

And finally the Main CPP file which contains the entry-point and function pointer loading:

#include <windows.h>
#include <iostream>
#define FPTR_INIT
#include "FunctionPtrs.h"

int importDeclarations(const bool debug);

int main(int argc, char* argv[])
{
    bool debug = false;
    for(int i = 0; i < argc; ++i)
    {
        if(strcmp(argv[i], "--debug") == 0)
        { debug = true; }
    }

    const int status = importDeclarations(debug);
    if(status) { return status; }

    testFuncs();

    system("pause");

    return EXIT_SUCCESS;
}

int importDeclarations(const bool debug)
{
    const char* path = debug ? "%PATH_TO_DLL%\\debug\\DebugDLL.dll" :
                               "%PATH_TO_DLL%\\release\\DebugDLL.dll";

    const HINSTANCE hGetProcIDDLL = LoadLibrary(path);

    if(!hGetProcIDDLL)
    {
        std::cout << "Could not load the dynamic library." << std::endl;
        return EXIT_FAILURE;
    }

    println = (f_println)GetProcAddress(hGetProcIDDLL, "println");
    test = (f_test)GetProcAddress(hGetProcIDDLL, "test");

    if(!println || !test)
    {
        std::cout << "Could not locate function." << std::endl;
        return EXIT_FAILURE;
    }

    return 0;
}

To answer your question, this is a fine way to do what you're attempting to do. OS vendors will often do something similar where they ship the release versions of their frameworks to end users, and developers can sometimes download debug versions that do more bounds checking and output more verbose messages when given bogus inputs. This allows developers to run additional tests of their own apps to ensure they aren't giving bad values to the OS when calling it.

I also appreciate that now the code can be written inline without a bunch of #ifdef BLAH statements around it or even if (debug) {} statements. I would definitely make sure that calling the release versions which do nothing doesn't slow down any critical inner loops in your processing, though. It's not real likely, but can happen on occasion.

As for a review, I did notice a few really minor things:

You have this line of code in testFuncs():

std::cout << "funci() returned " << test() << std::endl;

What is funci()? Shouldn't the displayed text be "test() returned "? As I say, it's minor, but I was confused while reading it.

I'd also avoid putting an if statement on the same line as its body like you do here:

if(status) { return status; }

When debugging, you'd hit that line, and if status is non-zero the app will suddenly quit when you step over the line. I know if that happened to me, I wouldn't immediately know what had just happened the first time I saw it. Having it on the next line would cause me to step into the body and see that the value is bad. I could then examine what it was before the app quit and the state went away. As I said, very minor, but just thought I'd mention them.


Ideas for simplificaton - Logic to choose which view to load I have a situation where depending on what the value of a uri segment is, my controller will load a different view. Here's what the code looks like in part:

          //which view do we load?
          if (strpos(strtoupper($data['hardwaremodel']),"HP") !== false)
          {
          //hp view should be loaded
          $data['main_content']='hpad';
          }
          elseif (strpos(strtoupper($data['hardwaremodel']),"DELL") !== false)
          {
          $data['main_content']='dellad';
          }
          //load view.
          $this->load->view('includes/template', $data);

For many methods in my controller, I have similar logic. So another method would have the exact same code, but the names of the view would be different dpending on what action the user requested.
So for example, instead of loading the Dell address page above ('dellad') it would load the Dell status page ('dellstatus')

I'm wondering if I change my logic so that all the methods in the controller call a new function that determines what view to load for them will simplify things.

I think the function would have to look something like: (just pseudocode)

 private function loadview($callingfunctionname, $hardwaremodel)
 {
 switch ($callingfunctionname)
 {
     case 'functionA':
           if hardware = dell {
               return "viewabc"
           }
           else {
              return "viewdef"
            }
           break;
     case 'functionB':
           if hardware = dell {
               return "view123"
           }
           else {
              return "view456"
            }
           break;
    }//end switch
   }

But I don't know that it will really simplify things to it this way.  Can you help me improve this code? the other point is that eventually, I will end up with more than 2 hardware types that I have to check for.

Thanks.

Based on your answer, you should put the mapping in an array and create a for each loop. Maybe it would also be a good idea to extract the strtoupper($hardwarename) in a local variable that you don't do it in any if in the worst case. In addition to that you missed to add a default case, which might lead to an error in loading the template. Furthermore you have to move the longer DELL check in front of the shorter otherwise you will never reach this branch.

private function checkhardwarename($hardwarename)
{
    $mapping=array("HP"=>"hp",
                   "DELL%20SF"=>"dell_sf",
                   "DELL"=>"dell");
    $hardwarename=strtoupper($hardwarename);

    foreach ($mapping as $needle=>$viewname)
    {
        if (strpos($hardwarename, $needle) !== false) return $viewname;
    }

    return "default";
}


Winform that exports a datagrid to Excel I've just created a winform that exports a datagrid to Excel. Originally the file was never shown, but I was asked to give the option. So I put in a checkbox and modified the code.

Is my if/else statement at the end enough or should I go about it a different way?

private void buttonExport_Click(object sender, EventArgs e)
{
    try
    {
        //copy contents of grid into clipboard, open new instance of excel, a new workbook and sheet,
        //paste clipboard contents into new sheet.
        copyGrid();
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Microsoft.Office.Interop.Excel.Application();
        xlexcel.Visible = false;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
        xlWorkBook.SaveAs("C:\\Temp\\ItemUpdate.xls", Excel.XlFileFormat.xlExcel5);
        MessageBox.Show("File Save Successfull", "Information", MessageBoxButtons.OK);
        //If box is checked, show the exported file. Otherwise quit Excel.
        if (checkBox1.Checked == true)
        {
            xlexcel.Visible = true;
        }
        else
        {
            xlexcel.Quit();
        }
    }
    catch (SystemException ex)
    {
        MessageBox.Show(ex.ToString());
    }
    //set the Selection Mode back to Cell Select to avoid conflict with sorting mode
    dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;

Yes, I'd say the if..else is enough, but it's a little wordy. Button.Checked is already a Boolean value, so comparing it to true is superfluous. There's also a lot of shortening of code you can do with the judicious use of using directives. Also, I had to do some fancy dancing to make sure Excel itself is truly shut down when it needs to be. Give this a look-see and let me know what you think:

namespace WindowsFormsApplication1
{
    using System;
    using System.IO;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    using Microsoft.Office.Interop.Excel;

    using Application = Microsoft.Office.Interop.Excel.Application;

    public partial class Form1 : Form
    {
        private Application xlExcel;

        private Workbook xlWorkBook;

        public Form1()
        {
            this.InitializeComponent();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                this.QuitExcel();
                this.xlExcel = new Application { Visible = false };
                this.xlWorkBook = this.xlExcel.Workbooks.Add(Missing.Value);

                // Copy contents of grid into clipboard, open new instance of excel, a new workbook and sheet,
                // paste clipboard contents into new sheet.
                this.CopyGrid();

                var xlWorkSheet = (Worksheet)this.xlWorkBook.Worksheets.Item[1];

                try
                {
                    var cr = (Range)xlWorkSheet.Cells[1, 1];

                    try
                    {
                        cr.Select();
                        xlWorkSheet.PasteSpecial(cr, NoHTMLFormatting: true);
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(cr);
                    }

                    this.xlWorkBook.SaveAs(Path.Combine(Path.GetTempPath(), "ItemUpdate.xls"), XlFileFormat.xlExcel5);
                }
                finally
                {
                    Marshal.ReleaseComObject(xlWorkSheet);
                }

                MessageBox.Show("File Save Successful", "Information", MessageBoxButtons.OK);

                // If box is checked, show the exported file. Otherwise quit Excel.
                if (this.checkBox1.Checked)
                {
                    this.xlExcel.Visible = true;
                }
                else
                {
                    this.QuitExcel();
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            // Set the Selection Mode back to Cell Select to avoid conflict with sorting mode.
            this.dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.QuitExcel();
        }

        private void QuitExcel()
        {
            if (this.xlWorkBook != null)
            {
                try
                {
                    this.xlWorkBook.Close();
                    Marshal.ReleaseComObject(this.xlWorkBook);
                }
                catch (COMException)
                {
                }

                this.xlWorkBook = null;
            }

            if (this.xlExcel != null)
            {
                try
                {
                    this.xlExcel.Quit();
                    Marshal.ReleaseComObject(this.xlExcel);
                }
                catch (COMException)
                {
                }

                this.xlExcel = null;
            }
        }

        private void CopyGrid()
        {
            // I'm making this up...
            this.dataGridView1.SelectAll();

            var data = this.dataGridView1.GetClipboardContent();

            if (data != null)
            {
                Clipboard.SetDataObject(data, true);
            }
        }
    }
}


C++ Disposing Textures Recently, I've asked in a code review if my code was causing any pointer related issues. They mentioned that I had problems with my dispose method. Basically, I'm disposing textures from a texture map, by cleaning the texture at the ID given to the method. So I would like to ask you if now, I'm disposing correctly my texture, and if there's a better way to do it.

void TextureManager::freeTexture(std::string id){

    std::map<std::string, SDL_Texture*>::iterator it = m_textureMap.find(id);

    std::cout << "Disposing texture : [ID==" << id << "] [MemoryAdress==" << it->second << "] : \n";

    if (it == m_textureMap.end())
    {
        LOGERROR("ERROR : Invalid ID : cannot dispose texture");
        return;
    }

    SDL_DestroyTexture(it->second);
    std::cout << "--> Destroyed !";

    m_textureMap.erase(id);
    std::cout << " --> Erased from TextureMap !\n\n";
}

Yes, I think it is fine. erase() will get rid of the <key,value> pair indexed by the id.

A tiny optimization here would be calling erase() with the iterator it instead of the id string. This should avoid a second lookup, since the iterator already contains the relevant information map need to remove the item. You can see here that erase() operates on keys or iterators.

Also, pass your id string by const reference, since the method does not need a copy of the string. E.g.:

void TextureManager::freeTexture(const std::string & id) { /* ... */ }
                                 ^^^^^             ^

This is a very long and error prone line:

std::map<std::string, SDL_Texture*>::iterator

You should typedef the map type or use auto if targeting C++11.

Typedefing map somewhere:

// In the header file somewhere...
typedef std::map<std::string, SDL_Texture*> TextureMap;

// Then it is a little simpler to use:
TextureMap::iterator it = map.find(...);

Or just use auto if you can:

auto it = map.find(...);


Reverse Game HackerRank Ruby Solution Problem Statement

  Akash and Akhil are playing a game. They have N balls numbered from 0
  to N−1.         Akhil asks Akash to reverse the position of the balls,
  i.e., to change the order from say, 0,1,2,3 to 3,2,1,0.   He further
  asks Akash to reverse the position of the balls N times, each time
  starting from one position further to the right, till he reaches the
  last ball.    So, Akash has to reverse the positions of the ball
  starting from 0th position, then from 1st position, then from 2nd
  position and so on.

  At the end of the game, Akhil will ask Akash the final position of any
  ball numbered K. Akash will win the game, if he can answer. Help
  Akash.

  Input

  The first line contains an integer \$T\$, i.e., the number of the test
  cases.

  The next \$T\$ lines will contain two integers \$N\$ and \$K\$.

  Output

  Print the final index in array.

  Constraints

  \$1 ≤ T ≤ 50\$
  \$1 ≤ N ≤ 10^5\$
  \$0≤K<N\$

  Sample Input

2
3 1
5 2

  Sample Output

2
4

  Explanation

    For first test case, The rotation will be like this:    0 1 2 -> 2 1 0 -> 2 0 1 -> 2 0 1    So, Index of 1 will be 2.

Solution

test = gets.chomp.to_i
test.times do
   num, numbered = gets.split.map(&:to_i)
   a = []
   elem = 0
   a << elem

  (num-1).times do
   elem += 1
   a << elem
  end

  len = a.length
  final = []
  w = []

 len.times do
  if w.length == 0
   q = a.reverse
  else
   q = w.reverse
  end
  elem = q.shift
  final << elem
  w = q - [elem]
 end

 puts final.index(numbered)
end

My Problem

I could only pass 4 test cases out of 11 since it always timed out for the rest. This is happening because my solution isn't efficient enough.  How can we do it efficiently so that it passes all 11 test cases?

Let's analyze what the problem is saying.

Let's say we start out with the array:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

We then reverse the elements of the array starting at element 0:

9, 8, 7, 6, 5, 4, 3, 2, 1, 0

Then, we reverse all elements except the 0th element:

9, 0, 1, 2, 3, 4, 5, 6, 7, 8

Then we reverse all elements except 0th and 1st element:

9, 0, 8, 7, 6, 5, 4, 3, 2, 1

And so on like so:

9, 0, 8, 1, 2, 3, 4, 5, 6, 7
9, 0, 8, 1, 7, 6, 5, 4, 3, 2
9, 0, 8, 1, 7, 2, 3, 4, 5, 6
9, 0, 8, 1, 7, 2, 6, 5, 4, 3
9, 0, 8, 1, 7, 2, 6, 3, 4, 5

To get the final result:

9, 0, 8, 1, 7, 2, 6, 3, 5, 4

The key thing to note here is that if take every odd-indexed element we get:

9, 8, 7, 6, 5

While every even-indexed element is:

0, 1, 2, 3, 4

So it looks like the final sequence is constructed like this:

Split elements into lower half and upper half
Reverse the order of the upper half
Merge them by taking 1 element from upper half and 1 element from lower half and so on

This is an \$O(n)\$ process with the right implementation

All that remains is to then search the list for the given element (which is \$O(n)\$ in the worst case with a standard implementation), yielding a final computational time complexity of \$O(n)\$. That's it, right? Well it would be, if not for some interesting math.

If we apply some mathematical logic we can get an even faster solution:

Decide if element is in lower half (which will have even indices) or the upper half (which will have odd indices) with a simple comparison to half the length of the array
If element is in lower half: final index will be 1 + 2 * K (as 0 will be in 1st index, 1 will be in 3rd, 2 will be in 5th and so on)
If element is in upper half: final index will be 2 * (N - 1 - K) (as N - 1 will be at 0, N - 2 will be at 2, N - 3 will be at 4 and so on)

This yields an \$O(1)\$ solution! Hurray for Math!

You can also simplify the logic a bit by noticing an interesting fact:

If you wrongly put an element from the upper half into the formula for the lower half and vice versa, an interesting thing happens: the final index will be out of the bounds of the array, and most importantly is greater than the index calculated from the other formula. The proof is left as an exercise, but this allows your entire program to boil down to:

min(1 + 2 * K, 2 * (N - 1 - K)) for every N, K pair

Note: this code ran in .05 sec for each trial under Python3.

Implementations are left as an exercise to the reader.


Simple Python turn based battle game As I mentioned in my bio, I do not code for a living and too old to switch careers but I do enjoy it as a hobby and I am trying to get better. Also trying to get my teenage son more interested. Anyhow, the code below does want I want it to but I am looking for tips to improve it. Any advice would be much appreciated before I add more to it with High Score tables and more functionality.

import random
weapons = ["Sword", "Spell", "Fire"]
shields = ["Armour", "Magic", "Water"]

class Player:
    def __init__(self, name):
        self.name = name
        self.health = 100
        self.weapon = 0
        self.shield = 0

    def damage(self):
        points = random.randint(10, 35)
        self.health -= points

    def selectWeapon(self):
        choice = int(input("Choose your weapon 1-Sword, 2-Spell or 3-Fire:  "))
        self.weapon = choice - 1

    def selectShield(self):
        choice = int(input("Choose your shield 1-Armour, 2-Magic or 3-Water:  "))
        self.shield = choice - 1

# Child class of player with override methods for weapon
# and shield selection
class AiPlayer(Player):
    def __init__(self,name):
        super().__init__(name)

    def selectWeapon(self):
        choice = random.randint(1, 3)
        self.weapon = choice - 1

    def selectShield(self):
        choice = random.randint(1, 3)
        self.shield = choice - 1

class Game:
    def __init__(self):
        self.gameOver = False
        self.round = 0

    def newRound(self):
        self.round += 1
        print("\n***   Round: %d   ***\n" %(self.round))

    # Check if either or both Players is below zero health
    def checkWin(self, player, opponent):
        if player.health < 1 and opponent.health > 0:
            self.gameOver = True
            print("You Lose")
        elif opponent.health < 1 and player.health > 0:
            self.gameOver = True
            print("You Win")
        elif player.health < 1 and ai.health < 1:
            self.gameOver = True
            print("*** Draw ***")

    def displayResult(self, player, opponent):
            print("%s used a %s, %s used a %s Shield\n" %(player.name, weapons[player.weapon], opponent.name, shields[opponent.shield]))
            print("%s caused damage to %s\n" %(player.name, opponent.name))

    def takeTurn(self, player, opponent):

        # Decision Array
        #
        #           Armour|  Magic |  Water
        #           ______|________|_______
        # Sword:    False |  True  |  True
        # Spell:    True  |  False |  True
        # Fire :    True  |  True  |  False

        decisionArray = [[False, True, True], [True, False, True], [True, True, False]]
        if decisionArray[player.weapon][opponent.shield]:
            opponent.damage()
            currentGame.displayResult(player, opponent)
        else:
            print("\n%s used a %s, %s used a %s Shield" %(player.name, weapons[player.weapon], opponent.name, shields[opponent.shield]))
            print("%s blocked %s's attack - No Damage" %(opponent.name, player.name))

# Setup Game Objects
currentGame = Game()
human = Player("Mark")
ai = AiPlayer("Computer")

players = [human, ai]

# Main Game Loop
while not currentGame.gameOver:
    for player in players:
        player.selectWeapon()
        player.selectShield()
    currentGame.newRound()
    currentGame.takeTurn(human, ai)
    currentGame.takeTurn(ai, human)
    print("%s's health = %d" %(human.name, human.health))
    print("%s's health = %d" %(ai.name, ai.health))
    currentGame.checkWin(human, ai)

f-strings

Beginning with Python 3.6, there is a friendlier way of formatting strings. Instead of using "format string" % (tuple_of_args) where the argument and the format codes are separated by significant distance, the arguments are embedded in the string itself, surrounded by {}'s.  The string itself is prefixed with an f.

For example, instead of:

    print("\n***   Round: %d   ***\n" %(self.round))

you can write:

    print(f"\n***   Round: {self.round}   ***\n")

Enumerations

This code doesn't convey a lot of meaning by itself.  It needs to be described by your 7 comment lines.

    decisionArray = [[False, True, True], [True, False, True], [True, True, False]]

Some of the problem stems from indices having semantic meaning.  For example, 1 is Magic.  But 1 is also Spell.  Confusing.

Let's make what is happening a lot clearer.  Let's define enumerations for our weapons and shields:

from enum import Enum

Weapon = Enum("Weapon", "Sword, Spell, Fire")
Shield = Enum("Shield", "Armour, Magic, Water")

Now we have Weapon.Sword, Weapon.Spell, and Weapon.Fire, which conveniently have values 1, 2 and 3 respectively.  We also have Shield.Armour, Shield.Magic and Shield.Water, also with values 1, 2, and 3.

When we have our player select their choice of weapon, we use to store it as the number 0, 1 or 2:

    self.weapon = choice - 1

but now we can store an actual enumeration object, like Weapon.Fire directly.  Conveniently, passing the value 1, 2, or 3 to Weapon(...) will return the corresponding enumeration object:

    self.weapon = Weapon(choice)

Similarly, we can store our shield choice as a Shield enumeration object:

    self.shield = Shield(choice)

The AI is similar, but instead of randint, we can use choice and select a random Weapon and random Shield:

    self.weapon = random.choice(list(Weapon))
    self.shield = random.choice(list(Shield))

But how about that decisionArray?  First of all, that is a lousy name.  What does "decision array" mean?  A Shield will block one (or perhaps more) Weapon attacks.  Let's add a .blocks attribute to our Shield objects:

Shield.Armour.blocks = { Weapon.Sword }
Shield.Magic.blocks = { Weapon.Spell }
Shield.Water.blocks = { Weapon.Fire }

(I'm using a set(), so more that one Weapon can be added.  For example, Shield.Magic could block both { Weapon.Spell, Weapon.Fire } ... after all, it's MAGIC!  Feel free to experiment.)

What would the takeTurn method now look like?

def takeTurn(self, player, opponent):

    if player.weapon not in opponent.shield.blocks:
        # apply damage
    else:
        # damage was blocked

That's pretty straight forward; no table required.  If the weapon is not in the set of things the shield blocks, we apply damage.

PEP-8

PEP 8 is a Style Guide for Python.  It describes things all Python programs should conform to, such as:

variables and function names should be snake_case not mixedCase.

Updated Code

import random
from enum import Enum

Weapon = Enum("Weapon", "Sword, Spell, Fire")
Shield = Enum("Shield", "Armour, Magic, Water")

Shield.Armour.blocks = { Weapon.Sword }
Shield.Magic.blocks = { Weapon.Spell }
Shield.Water.blocks = { Weapon.Fire }

class Player:
    def __init__(self, name):
        self.name = name
        self.health = 100
        self.weapon = None
        self.shield = None

    def damage(self):
        points = random.randint(10, 35)
        self.health -= points

    def select_weapon(self):
        weapons = [f"{weapon.value}-{weapon.name}" for weapon in Weapon]
        weapons = ", ".join(weapons[:-1]) + " or " + weapons[-1]
        choice = int(input(f"Choose your weapon {weapons}:  "))
        self.weapon = Weapon(choice)

    def select_shield(self):
        shields = [f"{shield.value}-{shield.name}" for shield in Shield]
        shields = ", ".join(shields[:-1]) + " or " + shields[-1]
        choice = int(input(f"Choose your shield {shields}:  "))
        self.shield = Shield(choice)

class AiPlayer(Player):

    def select_weapon(self):
        self.weapon = random.choice(list(Weapon))

    def select_shield(self):
        self.shield = random.choice(list(Shield))

class Game:
    def __init__(self):
        self.game_over = False
        self.round = 0

    def new_round(self):
        self.round += 1
        print(f"\n***   Round: {self.round}   ***\n")

    # Check if either or both Players is below zero health
    def check_win(self, player, opponent):
        if player.health < 1 and opponent.health > 0:
            self.game_over = True
            print("You Lose")
        elif opponent.health < 1 and player.health > 0:
            self.game_over = True
            print("You Win")
        elif player.health < 1 and ai.health < 1:
            self.game_over = True
            print("*** Draw ***")

    def display_result(self, player, opponent):
            print(f"{player.name} used a {player.weapon.name}, {opponent.name} used a {opponent.shield.name} Shield\n")
            print(f"{player.name} caused damage to {opponent.name}\n")

    def take_turn(self, player, opponent):

        if player.weapon not in opponent.shield.blocks:
            opponent.damage()
            current_game.display_result(player, opponent)
        else:
            print(f"{player.name} used a {player.weapon.name}, {opponent.name} used a {opponent.shield.name} Shield\n")
            print(f"{opponent.name} blocked {player.name}'s attack - No Damage")

# Setup Game Objects
current_game = Game()
human = Player("Mark")
ai = AiPlayer("Computer")

players = [human, ai]

# Main Game Loop
while not current_game.game_over:
    for player in players:
        player.select_weapon()
        player.select_shield()
    current_game.new_round()
    current_game.take_turn(human, ai)
    current_game.take_turn(ai, human)
    print(f"{human.name}'s health = {human.health}")
    print(f"{ai.name}'s health = {ai.health}")
    current_game.check_win(human, ai)

Notice in this code, if you added additional weapons and/or shields, nothing need be changed other than the Enum(...) declarations and the .blocks = {} lines.  The code itself creates the "1-Armour, 2-Magic or 3-Water" type choice strings, and will properly work with more than 3 choices.


Serializing object graph to proprietary binary file I'm creating a class library to read/write .3di files which are binary files describing 3D models for a video game. This review is for the write/serialization process.

I've mapped the different structures in the .3di file (header, textures, vertices, etc.) to the classes shown below. Each class implements the IBinarySerializable interface and is thus responsible for its own serialization logic. I've omitted many parts of the 3D model here for brevity, but they follow the same pattern.

Clients would use the library by building out a Model object and then calling SaveToFile().

interface IBinarySerializable
{
    byte[] Serialize();
}

public class Model
{
    public ModelHeader Header { get; set; }
    public List<Texture> Textures { get; set; }
    public List<Vertex> Vertices { get; set; }

    public void SaveToFile(string filePath)
    {
        using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
        using (BinaryWriter writer = new BinaryWriter(fileStream))
        {
            writer.Write(Header.Serialize());
            writer.Write(Textures.SelectMany(texture => texture.Serialize()).ToArray());
            writer.Write(Vertices.SelectMany(vertex => vertex.Serialize()).ToArray());
        }
    }
}

public class ModelHeader : IBinarySerializable
{
    public string Name { get; set; }
    public int TextureCount { get; set; }

    public byte[] Serialize()
    {
        using (var buffer = new MemoryStream())
        using (var writer = new BinaryWriter(buffer))
        {
            // Hardcoded values.
            writer.Write(Encoding.ASCII.GetBytes("3DI"));
            writer.Write((byte)8);

            // Header data.
            writer.Write(Encoding.ASCII.GetBytes(Name.PadRight(8, '\0')));
            writer.Write(TextureCount);

            return buffer.ToArray();
        }
    }
}

public class Texture : IBinarySerializable
{
    public string Name { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }

    public byte[] Serialize()
    {
        using (var buffer = new MemoryStream())
        using (var writer = new BinaryWriter(buffer))
        {
            writer.Write(Encoding.ASCII.GetBytes(Name.PadRight(28, '\0')));
            writer.Write(Width);
            writer.Write(Height);

            return buffer.ToArray();
        }
    }
}

public class Vertex : IBinarySerializable
{
    public short X { get; set; }
    public short Y { get; set; }
    public short Z { get; set; }

    public byte[] Serialize()
    {
        using (var buffer = new MemoryStream())
        using (var writer = new BinaryWriter(buffer))
        {
            writer.Write(X);
            writer.Write(Y);
            writer.Write(Z);

            return buffer.ToArray();
        }
    }
}

My Concerns

Since the .3di file schema is proprietary, I don't believe I can use the binary serialization that comes with .NET (e.g., BinaryFormatter) since it adds .NET-specific data to the file. Is that correct?
Should each class be responsible for its own serialization logic? I've considered centralizing all of that logic to a dedicated class, e.g., ModelSerializer, ModelFileWriter, etc. One benefit of that approach is that I wouldn't have to map the file structures to classes so literally.
I repeat this in each Serialize() method:

using (var buffer = new MemoryStream())
using (var writer = new BinaryWriter(buffer))

Should I extract those lines to a helper function and just pass in what I want to do with the writer, e.g., BinaryUtils.Serialize(Action<BinaryWriter> writeAction)?

BinaryFormatter is not adding any extra information. It does not store "here comes a double", this must be stored/handled by the reading algorithm.

But to reproduce a certain byte order, you have to overwrite almost every serializing routine. At the end you gain nothing, comparing to your self-implementation. So it's not the extra-information, it's the order of elements, that might cause trouble when using the given BinaryFormatter.

Each class can be responsible for it's own serialization, if you have only one serialization. If you can always modify your own code, the classes and the serialization never go separate ways to separate libraries, then this might be a good way.

A more sophisticated approach would be a Visitor-pattern. This way you can implement multiple Serializers (Visitors), store in different formats, etc.

One way you have everything concerning a class in the class, the other way you have everything concerning one specific file format in one class. This you have to make up with yourself, it depends on how often you plan to modify or extent anything later on.

Serializing is a streaming process. You create only one Stream ( a File or MemoryStream), don't use one per item, and assemble it later on. You create one Formatter/Writer, and pass this to each item. Each item is storing it's stuff into the output stream. So an item with one property to store, should have one line of code in it's Serializer method.


Shell script for reading /etc/passwd into SQLite I want to read 4 columns, namely UID, GID, username and home directory of specific users from /etc/passwd into an SQLite database. I found this to create many subprocesses, and I'd like to have some improvement suggestions.

#!/bin/sh
db="$PWD/users.db"
users=$(grep -E 'joe|bill|tom' /etc/passwd)
sqlite3 "$db" <<EOF
DROP TABLE Users;
CREATE TABLE Users \
    (UID INTEGER PRIMARY KEY, GID INTEGER, Username TEXT, Home TEXT);
EOF
echo "$users" | while IFS= read -r line
do
    sqlite3 "$db" \
        "INSERT INTO Users VALUES ( \
         $(echo "$line" | cut -d":" -f3),   \
         $(echo "$line" | cut -d":" -f4),   \
        '$(echo "$line" | cut -d":" -f1)',  \
        '$(echo "$line" | cut -d":" -f6)');"
done

Just don't create that many subprocesses. Your objective is to prepare a string of INSERT statements and feed it to one invocation of sqlite3. So drop the whole while read block and do the required text manipulations on the queried passwd entries before passing them off to sqlite3:

#!/bin/sh
db='./users.db'
sqlite3 "$db" <<EOF
DROP TABLE Users;
CREATE TABLE Users \
    (UID INTEGER PRIMARY KEY, GID INTEGER, Username TEXT, Home TEXT);
$(getent passwd 'joe' 'bill' 'tom' | awk -F':' -v quote="'" -v OFS="', '" \
    '{print "INSERT INTO Users VALUES ("quote $3, $4, $1, $6 quote");"}')
EOF

Doing a grep on /etc/passwd has a few drawbacks: the passwd file might not be located in /etc (I don't know of any Unix-like OS for which this is true, though), and it won't have the users that are stored in LDAP/NIS, etc. On the other hand, some systems don't have getent, so this method is not perfect, either. You might want to fall back to grep if getent returns a "command not found".


Universal OpenGL object RAII wrapper class I created a universal OpenGL object RAII wrapper class, that only takes care of object creation and destruction. Here's my code and reasoning behind it:
I first wrote a class that would take glCreate/Delete*() function pointers as constructor arguments, but I quickly realized that's not the right way to go. I'd have to store the glDelete*() function pointer in each object (waste of memory + dereference overhead). Additionally, OpenGL functions have three different forms (see specializations section, further in my code), so that would require 3 different pointer types - ugly. I decided to change my approach.
So, here I am with this template code. As far as I'm concerned, there should be no unnecessary OpenGL call overhead. The class is standard layout, only contains the object ID and there's no virtual stuff involved, so that seems pretty nice. Also, classes wrapping different OpenGL object types cannot be assigned to each other, because template arguments differ.
I'd like to hear your remarks according my code, the class design and the reasoning behind it. Improvement ideas are also welcome.
This is the main code:
/**
    \brief Serves as a RAII wrapper for OpenGL objects
    \note This class provides no OpenGL error checking - this is up to derived classes.
    \template T is object type as in glObjectLabel
*/
template <GLenum T>
class gl_object
{
    public:
        //! Object type used for labeling
        const static GLenum object_type = T;

        inline gl_object( );
        inline explicit gl_object( GLenum target );

        inline ~gl_object( );

        // Deleted copy constructor and copy assignment operator
        gl_object( const gl_object &src ) = delete;
        gl_object &operator=( const gl_object &rhs ) = delete;

        // Move semantics with source invalidation
        gl_object( gl_object &&src );
        gl_object &operator=( gl_object &&rhs );

        //! Allows casting to object's ID (GLuint)
        inline operator GLuint( ) const noexcept;

        //! Returns object's ID
        inline GLuint id( ) const noexcept;

    protected:
        //! The object ID
        GLuint m_id;
};

//! Move constructor with source invalidation
template <GLenum T>
gl_object<T>::gl_object( gl_object<T> &&src ) :
    m_id( src.m_id )
{
    src.m_id = 0;
}

//! Move assignment operator with source invalidation
template <GLenum T>
gl_object<T> &gl_object<T>::operator=( gl_object<T> &&rhs )
{
    // Prevent self-move
    if ( this != &rhs )
    {
        m_id = rhs.m_id;
        rhs.m_id = 0;
    }

    return *this;
}

// Allows cast to GLuint
template <GLenum T>
gl_object<T>::operator GLuint( ) const noexcept
{
    return m_id;
}

// Used for acquiring object's ID
template <GLenum T>
GLuint gl_object<T>::id( ) const noexcept
{
    return m_id;
}

Then, there are many very similar template specializations. Here are the most interesting ones:
// Specializations for GL_BUFFER
template <>
gl_object<GL_BUFFER>::gl_object( )
{
    glCreateBuffers( 1, &m_id );
}

template <>
gl_object<GL_BUFFER>::~gl_object( )
{
    glDeleteBuffers( 1, &m_id );
}

// Specializations for GL_TEXTURE
template <>
gl_object<GL_TEXTURE>::gl_object( GLenum target )
{
    glCreateTextures( target, 1, &m_id );
}

template <>
gl_object<GL_TEXTURE>::~gl_object( )
{
    glDeleteTextures( 1, &m_id );
}

// Specializations for GL_SHADER
template <>
gl_object<GL_SHADER>::gl_object( GLenum type )
{
    m_id = glCreateShader( type );
}

template <>
gl_object<GL_SHADER>::~gl_object( )
{
    glDeleteShader( m_id );
}

// Specializations for GL_PROGRAM
template <>
gl_object<GL_PROGRAM>::gl_object( )
{
    m_id = glCreateProgram( );
}

template <>
gl_object<GL_PROGRAM>::~gl_object( )
{
    glDeleteProgram( m_id );
}

Ensuring you have distinct types
You said this in the comments:

I thought that use of templates instead of a common base class would better emphasize that these objects shouldn't be mixed together (now they are completely distinct types).

Two classes that derive from the same base class are also two distinct types. Furthermore, you can make the constructor of the base class protected, so you cannot instantiate a bare base class, and you can use protected or private inheritance to ensure you cannot get a pointer to the base class from a derived class. For example:
class base {
protected:
    base() = default;
};

class derived: base {
    ...
};

derived foo;      // OK
base bar;         // Error: constructor is protected
base *baz = &foo; // Error: base is inaccessible

The problem with template specialization
Your construction using template specialization has a flaw. The problem is that all member functions you might ever want to use in specializations need to be present in the default template. This is why you have:
template <GLenum T>
class gl_object
{
    ...
    inline gl_object( );
    inline explicit gl_object( GLenum target );
    ...
};

The second constructor that takes the target parameter is only used for gl_object<GL_TEXTURE>, and in fact you must have a target for the texture in order to call glCreateTextures(). The problem is now that I can do the following:
gl_object<GL_BUFFER> buffer(GL_TEXTURE_2D);
gl_object<GL_TEXTURE> texture;

The above statements will compile without errors (but perhaps with a warning), because you promised both constructors would exist. Only the linker will give an error, because there is no implementation of those constructors. But in a large project it might be hard to track down this issue.
You won't have this problem with derived classes, since you have full control over which public member functions (including constructors) each derived class has.
Alternatives without templates
There are two ways to implement this without templates. Either you say that, for example, a gl_texture "is a" gl_object, and use class inheritance, or you say that a gl_texture "has a" gl_name (the OpenGL term for the GLuint identifier given to objects), and use composition. In the first case, you'd structure your code as:
class gl_object {
protected:
    GLuint m_id;

    gl_object() = default;

    // delete copy constructors
    // add move semantics
    // access the ID
};

class gl_buffer: gl_object {
public:
    gl_buffer() {
        glCreateBuffers(1, &m_id);
    }
    ...

    // Enable the default constructor and assignment operator:
    gl_buffer(gl_buffer &&other) = default;
    gl_buffer &operator=(gl_buffer &&other) = default;
};

In the second case, you would write:
class gl_name {
private:
    GLuint m_id;

public:
    // delete copy constructors
    // add move semantics
    // access the ID

    GLuint &get() {
        return m_id;
    }
};

class gl_buffer {
private:
    gl_name m_id;

public:
    gl_buffer() {
        glCreateBuffers(1, &m_id.get());
    }
    ...

    // Enable the default constructor and assignment operator:
    gl_buffer(gl_buffer &&other) = default;
    gl_buffer &operator=(gl_buffer &&other) = default;
};

In the second case, since you deleted the copy constructors for gl_name, classes that use that as a member variable will also no longer be default copy constructable.
The main drawback of either two cases is that you need to implement the move constructors and move assignment operators in each derived class. In this case the default move constructor and move assignment operator would have worked just fine, but they have been implicitly deleted. To re-enable them, just explicitly add the default move constructor and move assignemnt operator.


Optimization code for checking if a list contains any element ID of another list I have the following code:

var sessionsWithError = SessionsFilteredByDate
    .Where(i => i.TrackerId > 0 && i.StatusId == 0)
    .Select(i => i.SessionId);
var sessionsWithErrorFixed = BusinessClient.Instance.Tracker
    .GetAllTrackerAttempts()
    .Select(i => i.SessionId);
var sessionsWithErrorIntersection = sessionsWithError.Intersect(sessionsWithErrorFixed);
var sessionsWithErrorsNotFixed = sessionsWithError.Except(sessionsWithErrorIntersection);

Then I have to create a IEnumerable where I put all the SessionsFilteredByDate where the sessionID is included in sessionsWithErrorsNotFixed, but this operation, since I am using the Any operator, it's slow, apparently \$O(m*n)\$.

How can I achieve this operation with a lower complexity?

SessionsFilteredByDateAndErrors = SessionsFilteredByDate
    .Where(i => sessionsWithErrorsNotFixed.Any(y => y == i.SessionId));

Put the values into a HashSet<T> (see here) as the lookup for that is constant O(1).

var sessionsWithErrorSet = new HashSet<int>(
    SessionsFilteredByDate.Where(i => i.TrackerId > 0 && i.StatusId == 0).Select(i => i.SessionId));

var sessionsWithErrorFixedSet = new HashSet<int>(
    BusinessClient.Instance.Tracker.GetAllTrackerAttempts().Select(i => i.SessionId));

var sessionsWithErrorIntersection = sessionsWithError.IntersectWith(sessionsWithErrorFixed);
var sessionsWithErrorsNotFixed = sessionsWithError.ExceptWith(sessionsWithErrorIntersection);