Relationship design for auto parts store database I'm creating a design database for an autoparts store (this is a project school). For the moment, I'm not sure if the relationship model especially in MODEL, MAKE, BRAND is correct (I really have no experience about this area).

I'm not an expert in this area, so I need some help.

create database AutoParts2

use AutoParts2
go

create table Make
(
MakeID int not null identity(1,1),
Name varchar(50) not null,
constraint PK_Make primary key (MakeID)
)

create table Model
(
ModelID int not null identity(1,1),
MakeID int not null,
Name varchar(50) not null,
constraint PK_Model primary key (ModelID),
constraint FK_Model_Make foreign key (MakeID)
references Make(MakeID)
)

create table [Year]
(
YearID tinyint not null identity(1,1),
Name char(4) not null,
constraint PK_Year primary key (YearID)
)

create table Model2Year
(
Model2YearID int not null identity(1,1),
ModelID int not null,
YearID tinyint not null,
constraint PK_Model2Year primary key (Model2YearID),
constraint FK_Model2Year_Model foreign key (ModelID)
references Model(ModelID),
constraint FK_Model2Year_Year foreign key (YearID)
references [Year](YearID)
)

create table Category
(
CategoryID tinyint not null identity(1,1),
Name varchar(30) not null,
constraint PK_Category primary key (CategoryID)
)

create table Subcategory
(
SubcategoryID tinyint not null identity(1,1),
CategoryID tinyint not null,
Name varchar(30) not null,
constraint PK_Subcategory primary key (SubcategoryID),
constraint FK_Subcategory_Category foreign key (SubcategoryID)
references Category(CategoryID)
)

create table Model2Year2Category
(
Model2Year2CategoryID int not null identity(1,1),
Model2YearID int not null,
CategoryID tinyint not null,
constraint PK_Model2Year2Category primary key (Model2Year2CategoryID),
constraint FK_Model2Year2Category_Model2Year foreign key (Model2YearID)
references Model2Year(Model2YearID),
constraint FK_Model2Year2Category_Category foreign key (CategoryID)
references Category(CategoryID)
)

create table Brand
(
BrandID int not null identity(1,1),
Name varchar(50) not null,
constraint PK_Brand primary key (BrandID)
)

create table Brand2Subcategory
(
Brand2SubcategoryID int not null identity(1,1),
BrandID int not null,
SubcategoryID int not null,
constraint PK_Brand2Subcategory primary key (Brand2SubcategoryID),
constraint FK_Brand2Subcategory_Brand foreign key (BrandID)
references Brand(BrandID),
constraint FK_Brand2Subcategory_Subcategory foreign key (SubcategoryID)
references Subcategory(SubcategoryID)
)

create table Part
(
PartID int not null identity(1,1),
Name varchar(50) not null,
BrandID int not null,
PartNumber varchar(50) not null,
Description varchar(200),
constraint PK_Part primary key (PartID),
constraint FK_Part_Brand foreign key (BrandID)
references Brand(BrandID)
)

create table Model2Year2Part
(
Model2Year2PartID int not null identity(1,1),
Model2YearID int not null,
PartID int not null,
constraint PK_Model2Year2Part primary key (Model2Year2PartID),
constraint FK_Model2Year2Part_Model2Year foreign key (Model2YearID)
references Model2Year(Model2YearID),
constraint FK_Model2Year2Part_Part foreign key (PartID)
references Part(PartID)
)

create table Brand2Subcategory2Part
(
Brand2Subcategory2PartID int not null identity(1,1),
Brand2SubcategoryID int not null,
PartID int not null,
constraint PK_Brand2Subcategory2Part primary key (Brand2Subcategory2PartID),
constraint FK_Brand2Subcategory2Part_Brand2Subcategory foreign key (Brand2SubcategoryID)
references Brand2Subcategory(Brand2SubcategoryID),
constraint FK_Brand2Subcategory2Part_Part foreign key (PartID)
references Part(PartID)
)

You have all the tables you need and you have the many-to-many relationships correct, I think.

I'd suggest that you add a Parent field to Category and then create a hierarchy of categories instead of having a Category table with a single Subcategory table.

create table Category(
    CategoryId int not null identity(1,1),
    ParentCategoryId int null,
    CategoryName nvarchar(100) not null,
    primary key (CategoryId))

As a point of style, I'd name the many-to-many tables with underscores instead of numbers, i.e. Model_Year_Part.

Note that I used nvarchar instead of varchar.

If you ask a question on StackExchange for a school project, don't forget the citation if you use the answers! It's okay to ask but never to plagiarise.


Running xinput to change touchpad settings I am looking for some feedback on the code below, mainly for efficiency or mechanism correctness (like eval vs. subprocess). I am also curious if .find() is the best mechanism to use here. I am not familiar with regex, so my crutch (or benefit, depending) is using .find() over learning a sublanguage like regex.

import subprocess

get_device_id = subprocess.Popen(["xinput", "list", "SynPS/2 Synaptics TouchPad"], stdout=subprocess.PIPE)
gdi_str = str(get_device_id.stdout.read())
gdi_id_find = (gdi_str[gdi_str.find('id='):])
gdi_len = 3
gdi = (gdi_id_find[gdi_len:5])
if gdi.isdigit():
    device_id = gdi
else:
    pass

get_prop_id = subprocess.Popen(["xinput", "list-props", "15"], stdout=subprocess.PIPE)
r = str(get_prop_id.stdout.read())

if "2 Synaptics TouchPad" in r:
    b = (r[r.find('libinput Tapping Enabled ('):])
    bLen = len('libinput Tapping Enabled (')
    b = (b[bLen:b.find(')')])
    if b.isdigit():
        prop_id = b
    else:
        pass

subprocess.run(["xinput", "set-prop", device_id, prop_id, "1"])

This code parses the output of:

xinput list SynPS/2 Synaptics TouchPad

to get a numerical device ID, in this case 15:

SynPS/2 Synaptics TouchPad                      id=15   [slave  pointer  (2)]

The code then runs:

xinput list-props 15   # 15 is our parsed id

and parses this output:

Device 'SynPS/2 Synaptics TouchPad':
Device Enabled (147):   1
Coordinate Transformation Matrix (149): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
libinput Tapping Enabled (300): 0
libinput Tapping Enabled Default (301): 0
libinput Tapping Drag Enabled (302):    1
libinput Tapping Drag Enabled Default (303):    1
libinput Tapping Drag Lock Enabled (304):       0
libinput Tapping Drag Lock Enabled Default (305):       0
libinput Tapping Button Mapping Enabled (306):  1, 0
libinput Tapping Button Mapping Default (307):  1, 0
libinput Natural Scrolling Enabled (282):       0
libinput Natural Scrolling Enabled Default (283):       0
libinput Disable While Typing Enabled (308):    1
libinput Disable While Typing Enabled Default (309):    1
libinput Scroll Methods Available (286):        1, 1, 0
libinput Scroll Method Enabled (287):   1, 0, 0
libinput Scroll Method Enabled Default (288):   1, 0, 0
libinput Click Methods Available (310): 1, 1
libinput Click Method Enabled (311):    1, 0
libinput Click Method Enabled Default (312):    1, 0
libinput Middle Emulation Enabled (291):        0
libinput Middle Emulation Enabled Default (292):        0
libinput Accel Speed (293):     0.000000
libinput Accel Speed Default (294):     0.000000
libinput Left Handed Enabled (298):     0
libinput Left Handed Enabled Default (299):     0
libinput Send Events Modes Available (267):     1, 1
libinput Send Events Mode Enabled (268):        0, 0
libinput Send Events Mode Enabled Default (269):        0, 0
Device Node (270):      "/dev/input/event10"
Device Product ID (271):        2, 7
libinput Drag Lock Buttons (284):       <no items>
libinput Horizontal Scroll Enabled (285):       1

for the purposes of getting the prop-id for "libinput Tapping Enabled", in this case 300:

libinput Tapping Enabled (300): 0

Once the value is established, the code does a basic check for .isdigit() and if True, presents the values to:

subprocess.run(["xinput", "set-prop", device_id, prop_id, "1"])

Which ultimately sets the value to 1:

libinput Tapping Enabled (300): 1

There's no need for a redundant pass after your if; these can be deleted:

else:
    pass

xinput --list and xinput --list-props aren't long-running commands.  It's simpler to subprocess.run() them, with standard output redirected to a variable:

get_device_id = subprocess.run(["xinput", "list",
                                "SynPS/2 Synaptics TouchPad"],
                               capture_output=True)
if get_device_id.returncode != 0
    sys.exit(get_device_id.returncode)
gdi_str = get_device_id.stdout

I don't believe that first command is actually required - xinput --list-props is quite happy to accept a device name instead of a property:

xinput --list-props 'SynPS/2 Synaptics TouchPad'


Checking CSS code for best practices when mimicking I'm currently looking to try learn CSS properly and I'm looking to recreate the following image using CSS:

Now I've managed to recreate the image (sort of) what I am looking to know though is based on my code what am I doing wrong/what would be the best practice. Many solutions fix a problem I want to know if my solution is reasonable.

is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's

Testing

Here is the CSS image:

Here is my CSS

Well, no, actually. That's your HTML - it just happens to have some style attributes. Which it shouldn't have.

So step one, separate CSS and HTML. Use a <style> element in the <head> element, or better yet, include the CSS from a separate file. Don't inline your styling.

But for experiment purposes, you could try re-making your code as a jsfiddle or jsbin (both for your own sake, and to make it easier for reviewers later). Put HTML in the HTML panel, and CSS in the CSS panel, and play around with it.

And you should be using more semantic (i.e. meaningful) markup. You have a lot of div elements, but a div is a purposefully meaningless element used mostly for grouping other, more specific, elements.

The point is that when just reading the HTML, I can't tell what it represents. It could be anything since it's almost all div elements. Yet in the picture I see things that should probably be links or buttons, headings or spans, and maybe forms and images.

Here's an analogy to illustrate the idea of "semantic markup": Imagine for a moment that you're writing a book: the HTML elements form your outline. Right now, that outline would say:

Text
Text
Text
Text

Ok, sure, a book consists of text, but that's not a very useful outline.

A more useful book outline would say something like

Title
Introduction
Main body (likely divided into chapters or sections)
Summary and conclusion

That's what HTML is meant to do: Mark up information so as to reveal and codify its structure. Hence, the tags you use matter a great deal. And it makes it easier to apply CSS, since you've now grouped content in a logical manner. You can style things based on what they are; headings, paragraphs, images, etc.. You want all your links to be red? Just change the style for a elements, and you're done. The HTML stays the same, since the links are still links - the CSS just makes them look different, but doesn't (shouldn't) change their meaning.

That said, there of course aren't pre-existing elements for everything you can think of, and often you want some headings to look one way, and other to look a different way, even though they're all headings. That's when class names and sometimes IDs come in, since they allow you to further specify things.

When I look at that first image, I see a structure (outline) like

div.dialog
  header
    img.thumbnail
    h1
    h2 (update: an h2 isn't really correct here, see comments)

  div.body (maybe it's actually an image?)

  footer
    p
    div.actions
      a.favorite
      a.share
    form
      button
      button

I've given the containing element a dialog class, because it looks sort of like a dialog box to me. And yes, it's a div because there's no HTML element that captures the idea of a "dialog". That's when div comes in handy, since you can apply your own meaning (semantics) to it using an ID and/or a class name.

But it might not be a dialog box; it might be a cell in a grid view. In that case the class name should reflect that and be called grid-cell or something (update: actually, no it probably shouldn't - see comments). And perhaps the element should be an article. Again, pick an element and, if necessary, an ID and/or class name to describe what something is (not how it looks, or how it behaves).

Now, I'm not saying that the structure above is correct (as you can see, a few things have already been brought up in the comments), but that's how it mapped out in my head. If I were to start actually coding it, I'd probably end up changing a bunch of things.

For instance, footer probably isn't quite the right element to use, since it really contains more important stuff. Yet is it the "body" then? I don't know, but you've got to start somewhere, and then iterate, iterate until the CSS and the HTML each look clean and semantic separately, and together produce the desired result.

I know I haven't actually tackled the styling you've written, but that's because I find that less important than getting the overall approach right first.


Hackerrank ransomnote This is the question; https://www.hackerrank.com/challenges/ctci-ransom-note/problem

I have solved this hacker rank challenge but i feel like the complexity is pretty inefficient because i use two nested loops which causes my program to run in quadratic time, i guess... I am sure there there is a better solution. Can someone tell me a better solution than what i have done. I'd also appreciate if i could get any feedback regarding my coding style or if there should be made any improvement to make it look more readable, better etc. Thank you.

function checkMagazine(magazine, note) {
  let isRansom=true
  note=note.split(' ')
  magazine=magazine.split(' ')

  for(let i of note){
    if(isRansom===false){
      console.log('No')
      return false;
    }
    else{
      for(let j of magazine){
        if(i===j){
          var index=magazine.indexOf(j)
          if(index>-1){
            magazine.splice(index,1)
          }
          isRansom=true;
          break;
        }
        else{
          isRansom=false;
        }
      }
    }
  }

  if(isRansom){
    return true
  }
}

checkMagazine('give me one grand today night','give me one grand today')

Having a look at the HackerRank problem, the title is implying a HashTable might be a nice data structure to use for this problem ("Hash Tables: Ransom Note"). You might want to look up more about the theory, some examples in JS, (and even more/reference). JS objects can also be used as HashMaps, with a discussion of the pros and cons of this in other SO answers.

Essentially, with a (Hash)Map we can associate keys of some type, with values of the same or another type. Such as mapping strings -> integers. Setting and looking up a value in a map is in constant O(1) time, whereas with an array, looking for a value (indexOf()) is in linear O(n) time. Using Map, the problem could be reduced to linear complexity. (Additionally, splice is an 'expensive' O(n) operation to remove an element from an array in JS).

Here is an idea / some pseudocode of how you might use a Map to solve the problem by mapping each word (string) to the count of how many occurrences we have of that word (integer).

map is an initially empty map

for every word in magazine:
    if word not in map:
        add word to map with count 1
    else:
        increment count of word in map

for every word in note:
    if word not in map or count of word in map = 0:
        show "No."
        return
    else:
        decrement count of word in map (word has been used)

show "Yes."
return

Ignoring the hashtables for a moment, your code is a bit unnecessarily complicated in places. We don't actually need two nested for-loops. Only one that goes through all words in note and removes them from magazine array as we use them up. This removes the need for all the nested if- conditions and the boolean flag isRansom. Finally, if you have something that looks like at the end of a function:

if(someBooleanValue) {
    return true;
}

This can be replaced by:

return someBooleanValue;

Check also the parameter and return types of the function: in the HackerRank problem, magazine and note are already string arrays, and the function is not expected to return a boolean value, merely print to the console. With that in mind, here is how it could be done:

function checkMagazine(magazine, note) {
    for (let word of note) {
        let i = magazine.indexOf(word);

        if (i == -1) {
            console.log("No")
            return;
        }
        magazine.splice(i, 1);
    }

    console.log('Yes');
}

Note that despite there being no nested for-loops, it is still quadratic in complexity due to the outer loop (for every word in note), and the linear complexity of splice and indexOf inside this loop.


Turning an Integer into an array of ints My goal here is pretty simple, I want to turn a number like 12435987234 into an array of integers in reverse order.  So that would look like:

[4,3,2,7,8,9,5,3,4,2,1]

I want to do this without changing the number to a string and back.  Really, I don't want to convert it at all but I'm open to hearing ideas around this.

I've found one way to do in ruby via #divmod but suspect there is a more perfomant way.

# turns 1234 into
# [4,3,2,1]
def reversed_digits(val)
  quot = val
  results = []
  while quot > 0 do
    quot, remainder = quot.divmod(10)
    results << remainder
  end
  results
end

puts reversed_digits(1234)
=> [4,3,2,1]

I don't think your algorithm can be improved in speed. I'd propose a different implementation, though, a more shorter recursive function:

def reversed_digits(num, base: 10)
  quotient, remainder = num.divmod(base)
  [remainder] + (quotient == 0 ? [] : reversed_digits(quotient, base: base))
end


How can I convert this to a generic method? I have this code I used to to pull data from our IBM i into .NET into an object so it is easy to work with (avoiding DataTables).

How can I make it better?
How can I convert all/most of this into a generic reusable method?

Here is an example of a method I have written:

public Customer GetUtilityBillCustomer(int id)
{
    #region SQL Statement
    StringBuilder sb = new StringBuilder();
    sb.Append("SELECT ACUSTN, AWEBPN, ANAME, AADD1, AADD2, ACITY, ASTATE, AZIP5, AZIP4, AEMADR, ALOCAT, ");
    sb.Append("(TRIM(WTMETER.MADRSN) || ' ' || TRIM(WTMETER.MADRSA) || ' ' || TRIM(WTMETER.MADRSX)) AS SERVICEADDR, ");
    sb.Append("(AARR1 + AARR2 + AARR3) AS BALANCE ");
    sb.Append("FROM WTCUST, WTMETER ");
    sb.Append("WHERE ALOCAT = MLOCAT AND ACUSTN = @custnumber1 ");
    sb.Append("UNION ");
    sb.Append("SELECT FCUSTN, FWEBPN, FNAME, FADD1, FADD2, FCITY, FSTATE, FZIP5, FZIP4, FEMADR, FLOCAT, ");
    sb.Append("(TRIM(WTMETER.MADRSN) || ' ' || TRIM(WTMETER.MADRSA) || ' ' || TRIM(WTMETER.MADRSX)) AS SERVICEADDR, WTFINAL.FAMTDU AS BALANCE ");
    sb.Append("FROM WTFINAL, WTMETER ");
    sb.Append("WHERE FLOCAT = MLOCAT AND FCUSTN = @custnumber2");
    #endregion

    DataTable dt = new DataTable();
    using (iDB2Connection conn = new iDB2Connection(_connString))
    {
        using (iDB2Command cmd = new iDB2Command(sb.ToString(), conn))
        {
            conn.Open();
            cmd.Parameters.Add("@custnumber1", iDB2DbType.iDB2Decimal).Value = id;
            cmd.Parameters.Add("@custnumber2", iDB2DbType.iDB2Decimal).Value = id;
            using (iDB2DataAdapter da = new iDB2DataAdapter(cmd)) { da.Fill(dt); }
            conn.Close();
        }
    }

    #region Fill object from DataTable
    var customer = (from i in dt.AsEnumerable()
                    select new Customer
                    {
                        Id = i.Field<int>("ACUSTN"),
                        Pin = i.Field<int>("AWEBPN"),
                        Name = i.Field<string>("ANAME").Trim(),
                        Address1 = i.Field<string>("AADD1").Trim(),
                        Address2 = i.Field<string>("AADD1").Trim(),
                        City = i.Field<string>("ACITY").Trim(),
                        State = i.Field<string>("ASTATE").Trim(),
                        Zip5 = i.Field<string>("AZIP5").Trim(),
                        Zip4 = i.Field<string>("AZIP4").Trim(),
                        LocationNumber = i.Field<int>("ALOCAT"),
                        ServiceAddress = i.Field<string>("SERVICEADDR").Trim(),
                        BalanceDue = i.Field<decimal>("BALANCE"),
                        Email = i.Field<string>("AEMADR")
                    }).SingleOrDefault();
    #endregion

    return customer;
}

I am thinking along the lines of:

public static DataTable GetData(string connString, string sqlStatement)
{
    DataTable dt = new DataTable();

    using (iDB2Connection conn = new iDB2Connection(connString))
    {
        using (iDB2Command cmd = new iDB2Command(sqlStatement, conn))
        {
            conn.Open();
            cmd.Parameters.Add("@custnumber1", iDB2DbType.iDB2Decimal).Value = id;
            cmd.Parameters.Add("@custnumber2", iDB2DbType.iDB2Decimal).Value = id;
            using (iDB2DataAdapter da = new iDB2DataAdapter(cmd)) { da.Fill(dt); }
            conn.Close();
         }
    }

    return dt;
}

But how do I pass in an unknown list of parameters and parameter types? Would I use an array of objects? Other thoughts?

You could receive a lambda that adds parameters.

public static DataTable GetData(string connString, string sqlStatement, Action<iDB2ParameterCollection> addParameters)
{
    DataTable dt = new DataTable();

    using (iDB2Connection conn = new iDB2Connection(connString))
    {
        using (iDB2Command cmd = new iDB2Command(sqlStatement, conn))
        {
            conn.Open();
            if(addParameters != null) {
                addParameters(cmd.Parameters);
            }
            using (iDB2DataAdapter da = new iDB2DataAdapter(cmd)) { da.Fill(dt); }
            conn.Close();
         }
    }

    return dt;
}

//...
GetData(connStr, sqlStatement, parameters => {
        parameters.Add("@custnumber1", iDB2DbType.iDB2Decimal).Value = id;
        parameters.Add("@custnumber2", iDB2DbType.iDB2Decimal).Value = id;
    });

Edit: I suggest reading about the different delegates: Action; Func; Predicate.
https://stackoverflow.com/questions/566860/delegates-predicate-action-func

In a nutshell:

Action does something;
Func is the same as an Action, but with a return value;
Predicate<T> is the same as Func<T, bool> but a bit more semantically significant.


Opening links in a new tab or window I've got a lot of links (150+) in an href (here I can only post 2) and I want them to be opened in a new tab or window. I've got this piece of code that works, but before I add it to my website and before I add it to a lot of articles of mine (250+), I want to make sure the syntax of the code is 100% correct. Also, do I need the
?

test

test

The code itself is fine, though I would flip it, first html, then the javascript (without the window.onload).

AN example to explain why: If you have a huge image and a slow connection the loading takes say 5 seconds. These 5 seconds all your anchors don't have the target="_blank" and if a user clicks they still leave your website.

I would not use this method meself (unless I have to) .
If you use AJAX to load content with anchors, those anchors will not have the target="_blank" either. This will require a bit more advances problem solving. If you want some links to be ignored, you can't with the current code. There are more small problems that will pop up which are all to minor to sum up here, but in the end are all just very ennoying.

I recommend that you do not rely on this method. Just take some time and update the content. I assume you have that in a datase, just FIND() and REPLACE(). Make it permanent.


AM/PM to 24 hour time conversion I recently joined the website www.hackerrank.com for programming challenges, and one of them was a time conversion from 12 hour to 24 hour. Rather than using the Date class, I decided to write the code for it, and in the end I came up with this:

String time = new Scanner(System.in).nextLine();
String suffix = time.substring(time.length()-2);
time = time.replace(suffix, "");
String[] hms = time.split(":");
if (suffix.equals("PM")) {
    hms[0] = String.valueOf(Integer.parseInt(hms[0])+12);
    hms[0] = hms[0].equals("24") ? "12" : hms[0];
}
else if (suffix.equals("AM")) {
    hms[0] = hms[0].equals("12") ? "00" : hms[0];
}
System.out.println(String.join(":", hms));

And the code passed all the test cases proposed by the website. Is there any way that my code can be improved?

It's not clear how many digits the output is supposed to have.  For midnight, you output "00", but for 1 am to 9 am, you echo the hour, which may or may not have a leading zero.

Taking the last two characters as the suffix, then doing time.replace(suffix, ""), feels like a fragile operation.  Consider treating this as a pattern-matching exercise instead, and using a regular expression.  Since the pattern also describes the valid input strings, you get input validation for free.

private static final Pattern TIME12 = Pattern.compile(
    "(?<h>0?\\d|11|12):(?<ms>[0-5]\\d:[0-6]\\d)\\s*(?<ampm>[AP]M)"
);

public static String time24(String time12) {
    Matcher m = TIME12.matcher(time12);
    if (!m.matches()) throw new IllegalArgumentException();

    int h = "12".equals(m.group("h")) ? 0 : Integer.parseInt(m.group("h"));
    if ("PM".equals(m.group("ampm"))) h += 12;
    return String.format("%02d:%s", h, m.group("ms"));
}


Log Likelihood Calculations for Censored Data in R I am calculating the log-likelihood of data that have some observations censored. For uncensored "a" clusters, the likelihood calculates P(Y=y). For censored "b" clusters, it calculates that Y is at least size Y, P(Y≥y). So the likelihood is L=mult[P(Y=y)P(Y≥y)].

The below code is my working, actual-in-use code that calculates this log likelihood based on censorship status. However, when in place with several other functions, it is extremely slow since it has to iterate through each row in the dataset (datasets are usually several thousand rows long, and maximization runs through several thousands of iterations of R and k values).

My hope is that someone will know of an alternative way to approach this that will increase performance. I am (obviously) not an expert coder.

new_likelihood <- function(Y,R,k) {
  p_function <- function(y,n){ #Create a dummy function to use in for loop
     exp(log(n)-log(y)+lgamma(k*y+y-n)-(lgamma(k*y)+lgamma(y-n+1))+(y-n)*log(R/k)-(k*y+y-n)*log(1+R/k))
    }
  liks_a <- numeric(nrow(Y)) # initialize vector of logliks for `a` clusters
  liks_b <- numeric(nrow(Y)) # initialize vector of logliks for `b` clusters

  #Loop through each row of the data
  for(i in 1:nrow(Y)){
    y <- Y[i,1]
    n <- Y[i,2]
    c <- Y[i,3]

      if (c==0){ #For uncensored, apply regular PDF
        liks_a[i] <- log(p_function(y,n))
      } #outputs a value of 0 in liks_a[i] if c=1, so doesnt affect sum(log(liks))

      if(c==1){ #for censored, sum to do 1-(sum(Y-1))
        liks_b[i] <- log(1-sum(p_function(1:(y-1),n)))
      } #outputs a value of 0 if in liks_b[i] if c=0, so doesnt affect sum(log(liks))
  }
  sumliks <- sum(liks_a,liks_b)
  return(sumliks)
}

# Example data
Y_censor0 <- cbind(c(3,2,2,10,1,1),c(1,1,1,1,1,1),c(0,0,0,0,0,0)) # 3-column data w/ no one censored
Y_censor1 <- cbind(c(3,2,2,10,1,1),c(1,1,1,1,1,1),c(0,0,1,1,0,0)) # 3-column data with some censored

# Test
new_likelihood(Y_censor0,0.9,0.25)
new_likelihood(Y_censor1,0.9,0.25)
```

Your function p_function is vectorized and that is nice. There's a little difficulty for the sum though.
Below is the improved code that takes advantage of the vectorization. I also replaced log(1+x) with log1p(x), which is better for a small |x|. And I replaced the stuff with the lgamma functions with some stuff with the lbeta function.
new_likelihood2 <- function(Y, R, k) {

  p_function <- function(y, n){
    exp(log(n) - log(y) - lbeta(k*y, y-n+1) - log(k*y+y-n) + (y-n)*log(R/k) - (k*y+y-n)*log1p(R/k))
  }

  p_function_sum <- function(y, n){
      vapply(
        seq_along(y), function(i) sum(p_function(1:(y[i]-1), n[i])), numeric(1)
      )
  }

  uncensored <- Y[, 3] == 0
  Yuncensored <- Y[uncensored, 1:2]
  Ycensored   <- Y[!uncensored, 1:2]
  liks_a <- log(p_function(Yuncensored[, 1], Yuncensored[, 2]))
  liks_b <- log1p(-p_function_sum(Ycensored[, 1], Ycensored[, 2]))

  sum(liks_a, liks_b)
}


Managing a wish list from an API I have a class that I use to manage a list to/from an API in Swift. Using a clean code approach, I'm wondering if, how, and why I should change it when I have a class that uses it for just one or two functions.

Here's the class:

import Foundation

protocol ApiWishListManagerDelegate
{
    func didFailWishList(failError: NSError?)
    func didGetWishList()
    func didAddToWishList()
    func didUpdate()
    func didDelete()
}

class ApiMyAccountWishListManager: ApiController
{
    // MARK: - Vars
    var delegateWishList: ApiWishListManagerDelegate?

    // MARK: - Inits

    override init()
    {
        super.init()
    }

    init(delegateWishList: ApiWishListManagerDelegate)
    {
        super.init()
        self.delegateWishList = delegateWishList
    }

    // MARK: - Functions

    func addToWishList(productId: Int)
    {
        var dataToPost = NSDictionary(objects: [productId], forKeys: ["pid"])
        post(MakeURL.addToWishList(), postData: dataToPost, callBack: parseAddToWishList)
    }

    func parseAddToWishList(data: NSData?, response: NSURLResponse, error: NSError?)
    {
        if let jsonResultDictionary = convertOnSuccessAPI(response, data: data!)
        {
            self.delegateWishList!.didAddToWishList()
            return
        }
        self.delegateWishList!.didFailWishList(error)
    }

    func readItems()
    {
        get(MakeURL.getWishList(), queryString: "", https: true, callBack: parseReadItems)
    }

    func parseReadItems(data: NSData?, response: NSURLResponse, error: NSError?)
    {
        if let jsonResultDictionary = convertOnSuccessAPI(response, data: data!)
        {
            MyAccountDataCache.sharedInstance.saveWishList(jsonResultDictionary)
            self.delegateWishList!.didGetWishList()
            return
        }
        self.delegateWishList!.didFailWishList(error)
    }

    func updateItemQuantity(productId: Int, quantity: Int, folderId: Int)
    {
        var dataToPost = NSDictionary(objects: [productId, quantity, folderId], forKeys: ["pid", "prodQty", "srcFolderID"])
        post(MakeURL.chageQuantity(), postData: dataToPost, callBack: parseUpdateItemQuantity)
    }

    func parseUpdateItemQuantity(data: NSData?, response: NSURLResponse, error: NSError?)
    {
        if wasCallSuccessfulAPI(response) && data?.length == 0
        {
            self.delegateWishList!.didUpdate()
            return
        }
        self.delegateWishList!.didFailWishList(error)
    }

    func deleteItemFromFolder(productId: Int, folderId: Int = 0)
    {
        var dataToPost = NSDictionary(objects: [productId, folderId], forKeys: ["pid", "srcFolderID"])
        put(MakeURL.removeProduct(), postData: dataToPost, queryString: "", callBack: parseDeleteItemFromFolder)
    }

    func parseDeleteItemFromFolder(data: NSData?, response: NSURLResponse, error: NSError?)
    {
        if let jsonResultDictionary = convertOnSuccessAPI(response, data: data!)
        {
            self.delegateWishList!.didDelete()
            return
        }
        self.delegateWishList!.didFailWishList(error)
    }
}

The main question is when a class is using this manager, for something like just getting the wishlist, we have a set of empty delegates like this:

    // MARK: - ApiWishListManager

    func didFailWishList(failError: NSError?)
    {
        hideSpinner()
    }

    func didGetWishList()
    {
        mainTableView.reloadData()
        hideSpinner()
    }

    func didAddToWishList()
    {
    }

    func didUpdate()
    {
    }

    func didDelete()
    {
    }

The add, update and delete are just sitting there never to be used.  I know about making them optional, using @objc, but I don't really want to add all the extra code that goes with checking if the delegate is setup before calling each one.  I've tried adding delegates within the same class, but I think that just starts looking too ugly and makes extra code for the classes that need all of the functions of this one manager.

We should definitely go ahead and use @objc and make the methods optional that make sense to be optional.

In Swift, it's actually not nearly as bad to check whether or not a delegate is set up or responds to a selector.  In Objective-C, it was a big if statement.  In Swift, we can use optional chaining.

Suppose that didUpdate is an optional method.  Calling it on our delegate then looks like this:

self.delegate?.didUpdate?()

The only difference here is the ? before the parenthesis.

What this line of code says is basically:

if delegate is not nil and if delegate responds to selector "didUpdate"
    call "didUpdate" on delegate
else
    do nothing

The other important thing here is that we need to be sure that we're making our reference to the delegate a weak reference, which can only be done if our protocol is specified as @objc.  In almost every case, the object acting as our delegate is already holding a strong reference to the class that needs the delegate.  If this class also holds a strong reference back to the delegate (which you're currently doing), we've creating a retain cycle.  The memory can never be released without annoying setting each other's reference to the other to be nil... and the hard part is often times figuring out when to do that.

So, let's make our protocol be an @objc protocol and use a weak reference to our delegate, and then use optional chaining to take care of the optional methods.


Is decimal, hexadecimal, octadecimal, binary converter efficient? I have made a method which takes two parameters: the value to convert and the base. Based upon those two parameters my method is adjusted (with several helper methods) to change the desired decimal number to a number with a different base.

Is this code practical and clean? If not, what should I change to make it better?

public String baseConversion(int base, int value){
    String finalResult = "";
    String tempResult = "";
    int countLength = 0, countFit = 0; // countLength counts the length of the tempResult string in order to know how many '0' to add. countFit counts how many times the tempValue fits into the current parameter 'value'
    int placeValue; // Records the place value. ex 245: '2' is in the hundreds place value
    int tempValue = 0;

    while (value > 0){
        placeValue = 1;
        // calculates the highest power that fits in the value (takes desired base into account)
        while (value > placeValue){
            placeValue*=base;
            countLength++;
        }
        if (value!=placeValue){
            countLength--; // subtract to account for the value in the tempResult that is not '0'
            placeValue/=base; // divide back as the previous while loop went one placeValue higher than needed in order to break out
        }
        //figures out how many times the placeValue can fit into the value
        while (tempValue+placeValue <= value){
            tempValue+=placeValue;
            countFit++;
        }
        if (base==16){
            tempResult += numConverter(countFit);
        }
        if (base==8 || base == 2 || base == 10){
            tempResult += String.valueOf(countFit);
        }
        // adds zeros to the rest of the string
        while (countLength > 0){
            tempResult+="0";
            countLength--;
        }

        // takes the current tempResult and combines with previous. ex combine 10000 with 100 = 10100
        finalResult = combineResults(finalResult, tempResult);

        value -= tempValue;
        countFit=0;
        tempValue=0;
        tempResult="";
    }
    return finalResult;
}

Helper methods:

private String numConverter(int number){
    // only for hexadecimal
    if(number == 10){
        return "A";
    }else if (number == 11){
        return "B";
    }else if (number == 12){
        return "C";
    }else if (number == 13){
        return "D";
    }else if(number == 14){
        return "E";
    }else if (number == 15){
        return "F";
    }else {
        return String.valueOf(number);
    }
}

private String combineResults(String a, String b){
    String result = "";
    int indexA = 0, indexB = 0;
    int aTempLength = a.length(), bTempLength = b.length();
    if (a.length() > b.length()){
        while (aTempLength > bTempLength){
            result+=a.charAt(indexA);
            indexA++;
            aTempLength--;
        }
    }else {
        while (bTempLength > aTempLength){
            result+=b.charAt(indexB);
            indexB++;
            bTempLength--;
        }
    }
    while (aTempLength > 0){
        if (String.valueOf(a.charAt(indexA)).equals("0")){
            result+=b.charAt(indexB);
            indexA++;
            indexB++;
        }else {
            result+=a.charAt(indexA);
            indexA++;
            indexB++;
        }
        aTempLength--;
    }
    return result;
}

Disclaimer: I'm new here, so this might not be the type of review people give, but I'm trying to match it as best as I can.

Formatting

A comment explaining the purpose of combineResults(String a, String b) next to the method would be helpful.  (Yes, there's one in the main method, but documentation next to the helpers is good, too.)

The same could be said for numConverter(int number)...

Other than that, indentation looks good, braces look fine, etc.  :)

Algorithm

In general: You should be passing around StringBuilders or StringBuffers (or chars) instead of Strings.  The former are mutable, while the latter isn't mutable.  This will save some performance.  (e.g. appending is better on memory with the builders and buffers, rather than with raw Strings.)

Main Algorithm

Ok...  You took kinda an odd approach to converting bases.  Rather than using all those while loops, you should focus on determining the next least significant digit by using the modulus operator followed by division.

For example, in pseudocode:

while(number > 0) {
  nextDigit = number % base; //Get the next digit using modulo
  number /= base;
  // prepend nextDigit to result String Buffer
}

This makes the combineResults() method unneeded, as prepend is built-in to the StringBuilder.

NumConverter

In the spirit of StringBuilders vs. String, this should return a char rather than a String.

Your current code assumes that the only number ever fed to this method will be less than 16.  This could be a problem if it's a larger library, or if you want to expand the bases to more than hexadecimal.

You could use a switch/case construct instead of the else if's...

Or, if you really want to shorten the code, you could do something like (note: this also implements the char return instead of String):

char numConverter(int digit) {
   if (num >= 16 || num < 0) //If we're not given a valid digit
     return 0; //Let the output know somehow...  could throw an exception instead.
   else if (digit <= 10) //If we're dealing with a "normal" digit
     return ((char)num + '0'); //... return the numeric equivalent
   else //We're in extended digit range: we need letters!
     return ((char)digit + 'A' - 10); //Return hex equivalent of 10-15 (A-F)
}


Code to multiply matrices together I've got a short algorithm used in my code to multiply two matrices and put them into a destination Matrix. I decided to use the temporary array t_elements, which allows the user to make one of the input matrices the output matrix as well.

Usually I like to save optimization for later, but this code is going to be called often, so I was wondering if anyone could suggest ways to make it faster.

#include <vector>

struct Matrix{
    std::vector<std::vector<float>> elements;
    int height;
    int width;

    Matrix(int w, int h)
    {
        width = w;
        height = h;

        for (int i = 0; i < height; i++) {
            elements.push_back(std::vector<float>());

            for (int j = 0; j < width; j++) {
                elements[i].emplace_back(0.0f);
            }
        }
    }

    float get_element(int x, int y) const { return elements[y][x]; }

    void set_element(int x, int y, float value) { elements[y][x] = value; }
};

void dot(Matrix const& left, Matrix const& right, Matrix& dest)
{
    float t_elements[right.width][left.height];

    for (int i = 0; i < left.height; i++) {
        for (int j = 0; j < right.width; j++) {
            float elementVal = 0;

            for (int k = 0; k < left.width; k++)
                elementVal += (left.get_element(k, i) * right.get_element(j, k));

            t_elements[j][i] = elementVal;
        }
    }

    for (int i = 0; i < dest.width; i++)
        for (int j = 0; j < dest.height; j++)
            dest.set_element(i, j, t_elements[i][j]);
}

int main()
{
    Matrix m1 = Matrix(3,3);
    Matrix m2 = Matrix(3,3);
    Matrix m3 = Matrix(3,3);

    dot(m1, m2, m3);

    return 0;
}

Both of the other answers make some very good points, especially when it comes to replacing vector. Two dimensional vectors are particularly iffy because the whole lump of memory will not be contiguous. If you access elements[y][x] you first have to look in elements[y] for the address of the inner vector, and then have to look into that inner vector. By contrast if you have an array that is say, 4x4, the compiler would typically internally have a single 1D array of length 16. Then to get elements[2][2] it might just grab the entry in offset 11 (i.e. 2*4+3)

There are (at least) three distinct performance advantages associated with this when you think about low level hardware.

You don't waste time chasing pointers to find which bit of memory you need.
Having the values that you're working with all be close together gives you nice cache locality.
This simplifies the code within the key loops, giving the compiler a better chance of automatically vectorizing your code.

Snowbody mentions templating your Matrix so that you could have different primitive types in it (A matrix of ints or of doubles or whatever). I would further suggest templating your matrix to specify the sizes. Comparing with how std::array is done, where you might have std::array<int, 3>;, you could have matrix<float, 3, 3>. (In fact it would be necessary if you wanted your internal data storage to be a std::array as vnp suggests.)

This again gives the compiler more guarantees about your program ahead of time, which again means it has a better chance of doing helpful optimisations. For example a classic optimisation that compilers might do is "Loop unrolling", whereby they actually rewrite

for (int i = 0; i < 3; ++i) {
    doSomething();
}

as

doSomething();
doSomething();
doSomething();

They can do this because they know ahead of time how many iterations of the loop to expect, and calculate whether duplicating the machine code is justified by getting rid of the loop overhead.

As well as probably helping performance, this opens the door to writing compile time checks for your program. For example you could get the compiler to stop you from accidentally adding a 4x4 matrix to a 2x2 matrix, just like it would stop you from adding a double and a string.

Finally, because this information is known at compile time it does not need to be stored or accessed during the running of the program. Instead of i < dest.width the compiler would be writing machine code for i < 3. (But, importantly, you would still not have to write i < 3 which is inflexible and harder to understand than width.)

Modern optimisers have their own cost models to decide when to inline methods, but sensible hints still wouldn't go amiss. I'd suggest that get_element and set_element are particularly good candidates for inlining.

I actually disagree with vnp about directly accessing elements, although I do agree that the current getter and setter aren't any better. The advantages of using such methods are that they give you opportunity to

add precondition and postcondition checks, such as requiring that the indices are within bounds.
mess with the internal representation, such as the aforementioned storing your data in a 1D array and directly indexing it as if it was a 2D one. (If for some reason you didn't trust the compiler to do that indexing for you.)

Note that

float t_elements[right.width][left.height];

Is not legal c++, because c++ requires that array size (for stack arrays) must be a constant expression. You do have the option of using new, in which case you must remember to delete[]

I would also suggest, though this strays away from performance questions, that doing some error checking would be sensible. If you don't want to include sizes in the templates as above, it's still worth a basic check that you're not multiplying a 2x5 matrix by a 3x4 one.

Please note that all of the above is based on some theoretical understanding of the sorts of machine code that compilers can write. It is not based on empirical profiling of your code with a representative set of test data, which should be your first move when looking to optimise anything. (Closely followed of course by questioning whether there might be a suitable third party library that has already done all the hard work for you.)


GetCommonBaseClass: Readabiliy and Functionality I have two pieces of they which do almost the same thing. They both return the most common base class of two types. They differ in two aspect:

If one of the arguments is null, code A returns null and code B returns object.
If one of the arguments is an interface type, code A returns null and code B returns object.

My two questions for you:

Which code is more readable?
When it comes down to those differences, should the code:

a. return null.
b. return object.
c. throw an exception?

Code A:

    /// <summary>
    /// Returns the most common type of two types.
    /// If no common type can be found, null is returned.
    /// </summary>
    static public Type GetCommonBaseClass(Type a, Type b)
    {
        if ((a == null) || (b ==null))
            return null;
        if (a.IsInterface || b.IsInterface)
            return null;
        if (a.IsAssignableFrom(b))
            return a;
        while (true)
        {
            if (b.IsAssignableFrom(a))
                return b;
            b = b.BaseType;
        }
    }

    /// <summary>
    /// Returns the most common type of one or more types.
    /// If no common type can be found, null is returned.
    /// </summary>
    static public Type GetCommonBaseClass(params Type[] types)
    {
        if ((types == null) || (types.Length == 0))
            return null;
        Type type = types[0];
        for (int i = 0; i < types.Length; i++)
            type = GetCommonBaseClass(type, types[i]);
        return type;
    }

Code B:

    /// <summary> Finds the most derived common base class of all the provided types, or System.Object if there is no common base class  </summary>
    public static Type CommonBaseClass(params Type[] types)
    {
        if(ReferenceEquals(types,null)) return typeof(object);
        types = types.Where(x => !ReferenceEquals(x,null)).Distinct().ToArray();
        switch (types.Length)
        {
            case 0: return typeof(object);
            case 1: return types[0].IsInterface ? typeof(object): types[0];
            default:
                IEnumerable<IEnumerable<Type>> hierarchies = types.Select(ClassHierarchy).OrderBy(x => x.Count());
                Queue<Type> smallest = new Queue<Type>(hierarchies.First().Reverse());
                hierarchies = hierarchies.Skip(1);
                do
                {
                    int maxPossible = smallest.Count;
                    hierarchies = hierarchies.Select(each => each.Take(maxPossible));
                    Type candidate = smallest.Dequeue();
                    if (hierarchies.All(each => each.Last() == candidate))
                        return candidate;
                } while (smallest.Count > 1);
                return typeof(object);
        }
    }

    ///<summary>Gets the class hierarchy of the provided type, in order of derivation, e.g. : (System.Object,CustomBaseType,CustomConcreteType,...), or the singleton of System.Object type if the provided type is an interface or null </summary>
    public static IEnumerable<Type> ClassHierarchy(this Type type)
    {
        if (type == null || type.IsInterface) type = typeof(object);
        var stack = new Stack<Type>();
        do
        {
            stack.Push(type);
            type = type.BaseType;
        } while (type != null);
        return stack;

    }

I think that code A is quite a lot simpler, so it's also more readable. It's quite clear what GetCommonBaseClass(Type a, Type b) is supposed to do and GetCommonBaseClass(params Type[] types) is also quite straightforward.
On the other hand, CommonBaseClass(params Type[] types) in Code B is much more complicated, it's hard to see what's actually going on in all that code.

Also, in code A, GetCommonBaseClass(params Type[] types) could be simplified even more by using something like types.Aggregate(GetCommonBaseClass).

Regarding the edge cases, I think that, null inputs should cause an ArgumentNullException to be thrown. (Or not, if null is really a valid value.) With interfaces, I think the correct behavior depends on your requirements. If you don't know, I think the safest choice is to throw an exception. It's trivial to allow interfaces later on, if that's needed. On the other hand, adding a restriction could cause a issues with older code that uses your method.


PHP MVC model structure Just looking for some feedback for one of my models I have for a project. I'm pretty happy with it but I was wondering if anyone had any optimization suggestions.

class ContactModel
{
    public function __construct($db)
    {
        try {
            $this->db = $db;
        } catch (PDOException $e) {
            exit('Database connection could not be established.');
        }
    }

    public function getBlastRecipients()
    {
        $sql = "SELECT Email FROM Contact WHERE Blast=?";
        $query = $this->db->prepare($sql);
        $query->execute(array('1'));
        return $query->fetchAll();
    }

    public function getBOLRecipients($custpoid)
    {
        $sql = "SELECT [CustPOID]
                          ,[POShipToRef]
                          ,cp.CarrId
                          ,cp.LoadID
                          ,c.CarrDesc
                          ,ct.Email
                          ,ct.ContactId
                      FROM [Sales].[dbo].[CustPO] as cp
                      LEFT OUTER JOIN Load as ld
                      on ld.LoadID = cp.LoadID
                      LEFT OUTER JOIN Carrier as c
                      on c.CarrId = cp.CarrId
                      LEFT OUTER JOIN Contact as ct
                      on c.CarrId = ct.CarrierId
                       WHERE CustPOID=?";
        $query = $this->db->prepare($sql);
        $query->execute(array($custpoid));
        return $query->fetchAll();
    }

    public function getDeliveryRequestEmailAddresses($custpoid)
    {
        //If a ShipToID is set, we want to return all email addresses associated with that customer, otherwise just return whatever email addresses are associated with the BillToID
        $sql = "SELECT
                       CASE
                        WHEN cp.CustShipToID IS NOT NULL THEN
                       c.Email
                       ELSE
                       cy.Email
                       END as Email
                         FROM CustPO cp
                         LEFT OUTER JOIN Contact as c
                         on cp.CustBillToID = c.CustId
                         LEFT OUTER JOIN Contact as cy
                         on cp.CustShipToID = c.CustId
                         WHERE CustPOID=?";
        $query = $this->db->prepare($sql);
        $query->execute(array($custpoid));
        return $query->fetchAll();
    }

    public function getEmailAddress($contact_id)
    {
        $sql = "Select Email FROM Contact WHERE ContactId=?";
        $query = $this->db->prepare($sql);
        $query->execute(array($contact_id));
        return $query->fetch();
    }
}

I just have a couple of small points:

Exiting in Constructor

You shouldn't just exit in a constructor, but throw an exception instead. But in this case, the only statement in the try block is an assignment, so there isn't really anything that can go wrong. You should just remove the entire try-catch block.

Naming

Your naming is somewhat inconsistent. For methods you use camelCase, and for parameters you either use all lowercase (which you should always avoid), or under_score. At the very least custpoid should be custpoId.

I would also use somewhat more descriptive names inside the queries. Having c, cp, cy, as well as ct all in one query is a bit confusing.

SQL Style

Your SQL statements are also a bit inconsistent. If you write SQL keywords in all uppercase, do it always (see for example as, on, and Select).


Bruteforce MD5 Password cracker I just started learning Go, and I wanted to created a project to learn more about concurrency in go. I heard about Go's lightweight threads, so I wanted to give them a try.

This program uses backtracking to brute-force a list of passwords loaded from a file. It tries from password of length 2 and go ahead until all passwords are been found.

It works well until password length doesn't come to 6: then my RAM will get full. I've already optimized my code in some ways e.g. in the first iteration of the program I used to create a chan for every thread, and every thread would wait for the spawned thread to terminate. Now it has a barrier.

I would need some suggestion about my code and spatial optimization tips.

package main

import (
"fmt"
"io/ioutil"
"strings"
"sync"
"log"
"time"
"crypto/md5"
)

var alfabeto = []rune {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'}

func compute(prefix int, n int, a string, wgFather *sync.WaitGroup){
    defer wgFather.Done()

    if prefix == n-1 {
        for _, d := range alfabeto {
            password := fmt.Sprintf("%s%c", a, d)

            if searchPassword(password) {
                if len(passwords) == 0{
                    return
                }
            }
        }
    }else {
        for i := range alfabeto{
            wgFather.Add(1)
            go compute(prefix+1, n, fmt.Sprintf("%s%c", a, alfabeto[i]), wgFather)
        }
    }
}

var passwords []string

func main(){

    if loadPasswords() {
        return
    }
    fmt.Println("File with passwords loaded. We're gonna crack", len(passwords),"passwords!")
    start := time.Now()
    cont := 2
    for len(passwords) > 0  {
            fmt.Println("Searching for passwords at length: ", cont)

            var wg sync.WaitGroup
            wg.Add(1)
            go compute(0, cont, "", &wg)
            wg.Wait()
            cont++
        }

    elapsed := time.Since(start)
    fmt.Println("Password's file cracked in:", elapsed)

}

func searchPassword(pass string) bool{
    hash := fmt.Sprintf("%x", md5.Sum([]byte(pass)))
    for i, value := range passwords{
        if strings.Compare(hash, value) == 0{
            // Password found!
            fmt.Println("Find Password:", pass, " with hash:", hash)
            passwords = append(passwords[:i], passwords[i+1:]...)
            return true
        }
    }
    return false
}

func loadPasswords() bool{
    stream, err := ioutil.ReadFile("file.txt")
    if err != nil{
        log.Fatal(err)
        return true
    }
    readstring := string(stream)

    passwords= strings.Split(readstring, "\n")
    return false
}

This is my password's file, file.txt:

56cc213a6303180cbab6a3da15108751
b1c9b44a9a0a65615f21834aee53594b
4b855fcca0a7140f60dd8259d1a0f1ad
14db43821fb74030ac6e8bdf662646d5
93eea5a9dfb14219e8e9d51ab1ae2b82
b0804ec967f48520697662a204f5fe72
ab6d50d5a9ecafd6fd429d38877837ca
168908dd3227b8358eababa07fcaf091
3cf4046014cbdfaa7ea8e6904ab04608
02c77002a0c646684b3325959fe147b2
f38fef4c0e4988792723c29a0bd3ca98
f3abb86bd34cf4d52698f14c0da1dc60
e842795b282293fd61bc294c49edb12b
c4fdb9019bcca7e82296952ba3e1895b
8dc01b0de0431cb7eced92277c1f04c7
bbebde933d57f88406bc530e5df0df3a
44fd79ea712293e5b5a7b51aceb6c0a7
56eb473ffd7429b00eb136c80664be30
875a8ec1acd2fa9f02ca152974dfd904
23ba6002aa3583a61db26e957b1fbe43
dcaa9fd4f23aaf0c29f540becf35b46f
98f740d68822f4209674ca9f23c20abe
a079350a0e30d9f293f6acaea80bb015
c44ab68f3a5ef32c8dfbbaa1daa86f98
6057b96acf9d41c1ca26a8923d970404
daa10b9d19015cf1cbf4bb53cf135b61
b29533fb6f81a9dbf8eae44b05ce8f49
22b35da29d5fa740fab4cb83ccb820aa
11cff46e84b6cae9951ea65eb5716d9e
9dd8ecec47e0c96bb189038fdb35bf16
e03a5f28b2349d6735adf6f528a7f18c
6057b96acf9d41c1ca26a8923d970404

First let's mention a bug / issue:

Your passwords variable is accessed (read and modified) from multiple goroutines without any syncronization: this is a race condition!

Primary problem

Your memory problem arises from launching a tremendous amount of goroutines. For example when you call compute() with n = 6 (to try passwords with a length of 6), it will create:

36^5 = pow(36, 5) = 60466176

(36 is the length of your alphabet; 5 is the prefix value for the condition prefix == n-1 when compute() stops spawning new goroutines)

60 million goroutines!

Goroutines are lightweight, but not that lightweight! Even if managing 1 goroutine would cost only 1 KB memory (it has its own stack etc.), this would require 60 GB memory! Understandable you run out of it. Your code spawns goroutines at a much quicker rate than they complete. (It should be noted that nothing in your code prevents spawning these new goroutines before any would be completed, so this is kind of worst case but still...)

An easy fix!

But the good news is that there is a really easy fix to this tremendous number of goroutines: simply do not spawn many goroutines.

A trivial way to limit spawning goroutines is that when you would spawn them, bind it to a condition to keep them at bay. For example launch 36 goroutines to process passwords starting with the different letters, but after that let 1 goroutine try all the combinations with that starting letter.

We can test this "first letter" condition by comparing prefix to 0:

for i := range alfabeto {
    wgFather.Add(1)
    if prefix == 0 {
        go compute(prefix+1, n, fmt.Sprintf("%s%c", a, alfabeto[i]), wgFather)
    } else {
        compute(prefix+1, n, fmt.Sprintf("%s%c", a, alfabeto[i]), wgFather)
    }
}

By inserting this condition and the else branch just calling compute() on the same goroutine, you keep your goroutine number and memory usage at bay! But still, you utilize multiple goroutines and multiple CPU cores.

There is a minor "downside": you have no control how these 36 goroutines finish compared to each other, there may be a "relaxed" period when only 1 or 2 goroutines are running and others are finished, in this relaxed period CPU utilization will not be 100%. More formally CPU utilization will be < 100% if # of goroutines is less than # of CPU cores.

Optimization tips

Here are some optimization tips:

You do unnecessary round-trips: you build potential passwords as string, then when your searchPassword() function computes its MD5, it has to convert it to []byte. Best would be to build password in a []byte. Go stores strings as UTF-8 encoded sequences (see blog post Strings, bytes, runes and characters in Go for details), and all your alphabet letters map to bytes one-to-one in UTF-8 encoding, so you could just use their byte value for faster building.
In your searchPassword() when you have the MD5 of the potential password, you always iterate over all crackable MD5 strings and you compare to all. This is a waste, you could sort the crackable MD5 values and use binary search to find if the potential is in it (sorting and binary search is implemented in the sort package). Or even better: you could build a map from the crackable MD5 strings, and just check if the candidate is in the map (now this check would be O(1) complexity instead of O(log n) of the binary search).
It is also an unnecessary round-trip to convert a calculated MD5 to string in order to check if it is a crackable one. Best would be to convert the crackable MD5 values to a byte array (note: array and not slice), and when you have the MD5 of a potential password as an array, you can check if it is a crackable one without converting it to string. Arrays are comparable in Go (unlike slices!), so you could also build a map from the MD5 arrays to check if a potential MD5 is in the map.
Also note that your algorithm generates passwords multiple times. For example if you want to check passwords with a length of 3, these 3-letter passwords are essentially all the 2-letter passwords +1. But you don't make use of this, you always generate all passwords with a given length from "scratch".

Utilizing these tips would speed up your algorithm big time; not just because we got rid of lots of needless computation / conversion, but also because much less "garbage" will be generated for the GC.

Alternative

An alternative way of implementing this brute-force cracker would be to use the producer-consumer pattern. You could have a designated producer goroutine that would generate the possible passwords, and send them on a channel. You could have a fixed pool of consumer goroutines (e.g. 5 of them) which would loop over the channel on which generated passwords are delivered, and each would do the same: receive passwords, hash them (MD5) and check if it matches a crackable one.

The producer goroutine could simply close the channel when all combinations were generated, properly signalling producers that no more passwords will be coming. The for ... range construct on a channel handles the "close" event and terminates properly.

This would result in a clean design, would result in fixed number of goroutines, and it would always utilize 100% CPU. It also has the advantage that it can be "throttled" with the proper selection of the channel capacity (buffered channel) and the number of consumer goroutines.

Here is how this producer-consumer could look like in Go if someone wants to play with it (also note that I elaborated this with full examples and much deeper explanation in StackOverflow question Is this an idiomatic worker thread pool in Go?):

var wg sync.WaitGroup

func produce(ch chan<- []byte) {
    // Now generate all passwords:
    for {
        if noMore { // If no more passwords
            close(ch)
            break
        }
        pass := ...   // Here generate next password
        ch <- pass    // send it for processing
    }
}

func consume(ch <-chan []byte) {
    defer wg.Done()
    for pass := range ch {
        // Hash, check
    }
}

func main() {
    ch := make(chan []byte, 100) // Buffered channel

    // Start consumers:
    for i := 0; i < 5; i++ { // 5 consumers
        wg.Add(1)
        go consume(ch)
    }

    // Start producing: we can run this in the main goroutine
    produce(ch)

    wg.Wait() // Wait all consumers to finish processing passwords
}

This blog post is an excellent introduction to parallel computation in Go using goroutines and channels:

Go Concurrency Patterns: Pipelines and cancellation

Further optimization tip

Now if you go with this producer-consumer goroutine model, another optimization becomes available.

The md5.Sum() function (which takes a []byte and returns the MD5 checksum of its content) always creates a new, internal md5.digest value which is used to do the MD5 hashing. Then it is discarded.

Now if we have a small, fixed pool of consumer goroutines, we can now create and it is profitable to create a designated MD5 hasher for each with the md5.New() function. To what end? We can use the returned hasher (which is of type hash.Hash) to compute MD5 hashes, but what's cool is that we can reuse it to compute hashes of multiple byte slices.

hash.Hash implements io.Writer so we can write any []byte into it of which we want to compute the MD5 hash, and it also has a Hash.Sum() method which returns the MD5 hash, giving the option to not create a new array return value which will hold the calculated MD5, but we can pass our slice to it in which we want the result. We can also create prepared arrays ([16]byte) and slice them to obtain a slice []byte, and do this for all of the consumer goroutines. As a result, we can further suppress "memory-garbage" generation and reduce GC work. Once we queried the MD5 sum of a password, we can simply call Hash.Reset() to re-initiaze the hasher for the next password.


Cryptographically Secure Pin Generator using RNGCryptoServiceProvider In my system I have a SMS authentication. Users input their user-id and get sent an SMS with a 5 digit pin number they input in a website to log in. The pin has a lifetime of a few minutes.

This pin number needs to be fairly secure so hackers can't try to guess the pin.

I would like to get some comments about my approach and code.

Here is my Code:

public class PinGenerator : IPinGenerator
{
    public string GetPin()
    {
        var rand = GetRandomNumber();

        return (rand %99999).ToString().PadRight(5, '0');
    }

    private int GetRandomNumber()
    {
        using (var crypto = new RNGCryptoServiceProvider())
        {
            byte[] data = new byte[4];

            crypto.GetBytes(data);

            return Math.Abs(BitConverter.ToInt32(data, 0));
        }
    }
}

Use unsigned integers to avoid the Abs related issues
RightPad is incorrect, since shorter integers need leading zeros. Either use LeftPad or simply ToString("D5")
A bigger integer will reduce the bias.

Thus I'd rewrite the relevant code as:

byte[] buffer = new byte[sizeof(UInt64)];
cryptoRng.GetBytes(buffer);
var num = BitConverter.ToUInt64(buffer, 0);
var pin = num % 100000;
return pin.ToString("D5");


Merge into an object from two different API calls I'm working on an app to compare SDKS (their churn and acquisiton rates). I have created an API with two separate endpoints.
The first, compares one sdk to ther other and spits out that data for each sdk.
The second, simply gets general information about a single sdk.
I'm merging these objects into one, so that all information regarding a single SDK can be found.
Problems I previously had, and might still come up (hopefully fixed by now): When setting the object at the end with setAllSdksInfo(objCopy) there was a problem in which it would not set it ok.
I'm also getting an ESLint warning which states "Function declared in a loop contains unsafe references to variable(s) 'objCopy', 'objCopy', 'objCopy', 'objCopy', 'objCopy', 'objCopy', 'objCopy'" but that doesn't seem to be causing any problems.
import React, { useEffect } from "react";
import MatrixSquare from "./MatrixSquare";

function Matrix({ selectedSdks, allSdksInfo, setAllSdksInfo, showMatrix, setShowMatrix }) {

  useEffect(() => {
    (async () => {
      const selectedSdksKeys = Object.keys(selectedSdks);
      if (!selectedSdksKeys.length) return;

      setShowMatrix(false);

      let comparedCount = 0;

      const notComparedKeys = [];

      selectedSdksKeys.forEach((key, i) => {
        for (let j = i + 1; j < selectedSdksKeys.length; j++) {
          if ( allSdksInfo?.[key]?.["churned_to"]?.hasOwnProperty( selectedSdksKeys[j])) {
            comparedCount += 1;
            if (comparedCount === 3) {
              setShowMatrix(true);
            }
          } else {
            notComparedKeys.push([key, selectedSdksKeys[j]]);
          }
        }
      });

      let objCopy = Object.assign({}, allSdksInfo);

      for (let i = 0; i < notComparedKeys.length; i++) {
        await fetch( `/api/sdk/churn?sdk1_id=${notComparedKeys[i][0]}&sdk2_id=${notComparedKeys[i][1]}`)
          .then((res) => res.json())
          .then((res) => {
            const copyPreviousObj = Object.assign({}, objCopy);
            objCopy = { ...objCopy, ...res };
            const resKeys = Object.keys(res);

            resKeys.forEach((key) => {
              const new_churned_to = objCopy[key]["churned_to"];
              const new_acquired_from = objCopy[key]["acquired_from"];

              if (copyPreviousObj[key]) {
                objCopy[key]["churned_to"] = {
                  ...new_churned_to,
                  ...copyPreviousObj[key]["churned_to"],
                };
                objCopy[key]["acquired_from"] = {
                  ...new_acquired_from,
                  ...copyPreviousObj[key]["acquired_from"],
                };
              }
            });
          });
      }

      selectedSdksKeys.forEach(async (id, i) => {
        if (allSdksInfo[id]?.["num_installed_apps"]) return;
        const res = await fetch(`/api/sdk/general_info?sdk_id=${id}`);
        const data = await res.json();
        objCopy[id]["num_installed_apps"] = data["num_installed_apps"];
        objCopy[id]["acquired_total"] = data["acquired_total"];
        objCopy[id]["churned_total"] = data["churned_total"];
      });

      setAllSdksInfo(objCopy);
      setShowMatrix(true);
    })();
  }, [selectedSdks]);

I beleive the issue with

When setting the object at the end with setAllSdksInfo(objCopy) there
was a problem in which it would not set it ok.

Is because Object.assign is not doing what you're expecting it to do, it does not create a deep copy of the source object
TLDR;
When you modify a nested property of the copied object, it will affect the original one, one way of creating a deep copy of the object is JSON.parse(JSON.stringify(obj)) :

const obj_original = {
  a: {
    b: {
      c: 'hello'
    }
  }
}

const obj_copy = Object.assign({}, obj_original);

const deep_copy = JSON.parse(JSON.stringify(obj_original));

obj_original.a.b.c = 'test';

console.log(obj_original); // { a: { b: { c: 'test' } } }
console.log(obj_copy); // { a: { b: { c: 'test' } } }
console.log(deep_copy); // { a: { b: { c: 'hello' } } }

Keep it DRY :
instead of objCopy[id]["churned_total"] = data["churned_total"]; you could use destructuring assignment to avoid repeating :
selectedSdksKeys.forEach(async (id, i) => {
  if (allSdksInfo[id]?.num_installed_apps) return;

  const res = await fetch(`/api/sdk/general_info?sdk_id=${id}`);

  const { num_installed_apps, acquired_total, churned_total } = await res.json();;

  objCopy[id] = {
    ...objCopy[id],
    num_installed_apps,
    acquired_total,
    churned_total
  }
});


Refusing to use a common template engine As the title says, I refuse to use a common template engine. I have my reasons, so instead of doing this:

test

{CommonParam}

I do this:

function listBlock($array){
echo '
';
foreach($array as $foo){
echo '
' . '' . $foo['text'] .
';
}
echo '
'
}

// now we'd call listBlock($myarray)

My question is quite simple... as I'm actually developing my own custom framework, I know it's a bit difficult to maintain this code, but it works great. Is this a good practice?

Answer courtesy of JC

In MVC Frameworks, you will often find this question answered a multitude of ways. Here are two principles that I attempt to live by, with regards to this.

Separate business logic from presentation logic. If the function in question takes input from another source, and simply does some formatting on it, then it is similar to the view helpers used in most MVC frameworks, and thus is separated from any business logic that processed the input to the function. However, if the function itself is doing logic based upon its input to determine other things about the data, other then simply how to display it, you wind up with a situation where if you have more then one case down the road, this function will begin to grow substantially, and eventually may become impossible to understand, or inefficient.
Data processed by the system should be usable in many forms. If your data might be needed for other uses, beyond display, then you may later on find yourself having to refactor, or even duplicate the code, when you realize that you need 'Ted Developer' in 'Developer, Ted', 'Ted Developer' and 'Ted' forms, and your function only returns one of the three.


WhenAll for .NET 3.5 I am trying to write a version of Task.WhenAll for .NET 3.5 using the "Task Parallel Library for .NET 3.5". This is what I came up with. Is there a better way of doing this?

    public static Task WhenAll(IEnumerable<Task> tasks)
    {
        var tcs = new TaskCompletionSource<object>();

        var remainingTasks = tasks.ToList();
        int count = remainingTasks.Count();
        var exceptions = new List<Exception>();

        foreach (var task in remainingTasks)
        {
            task.ContinueWith(t =>
            {
                if (Interlocked.Decrement(ref count) == 0)
                {
                    foreach (var task1 in remainingTasks)
                    {
                        if (task1.IsFaulted)
                        {
                            exceptions.Add(task1.Exception);
                        }
                    }

                    if (exceptions.Any())
                    {
                        tcs.SetException(new AggregateException(exceptions));
                    }
                    else
                    {
                        tcs.SetResult(null);
                    }
                }
            });
        }

        return tcs.Task;
    }

int count = remainingTasks.Count();

Since remainingTasks is a List, you can use the Count property here.

var exceptions = new List<Exception>();

This variable should be declared where it's used: in the if Interlocked.Decrement block.

if (task1.IsFaulted)

This means you're treating canceled tasks the same as successfully completed ones. Instead, you can check whether Exception is null.

You could also rewrite the inner foreach using LINQ:

var exceptions = remainingTasks
    .Select(task => task.Exception)
    .Where(e => e != null)
    .ToList();


Convert JSON to a different format (nested json) This is really not a question. I was looking up this solution but couldn't find it anywhere. Thought of posting it here so it may save someone's time.

Here was my issue: I had a JSON coming from server which was not nested. Lets take example of Movies:

var movies = [
  {"name":"Ice Age 3", "language":"English", "year":"2012"},
  {"name":"Ice Age 3", "language":"French", "year":"2011"},
  {"name":"Ice Age 3", "language":"German", "year":"2013"}
];

Now effectively speaking, there is no need for server to return it like this, however this was my case and since I was using jquery-template I wanted to have it as a nested JSON object. Something like this:

var movies = [{
    "name": "Ice Age 3",
    "details": [
        {"language": "English", "year": "2012"},
        {"language": "French", "year": "2011"},
        {"language": "German", "year": "2013"}
    ]
}];

Here is the code which I wrote to convert it:

function convert(arr) {
    var convertedArray = [];

    $(arr).each(function () {
        var found = false;
        for (var i = 0; i < convertedArray.length; i++) {
            if (convertedArray[i].name === this.name) {
                found = true;
                convertedArray[i].details.push({
                    "language": this.language,
                    "year": this.year
                });
                break;
            }
        }
        if (!found) {
            convertedArray.push({
                "name": this.name,
                "details": [{
                    "language": this.language,
                    "year": this.year
                }]
            });
        }
    });

    return convertedArray;
}

I am sure there would be a better approach for this. But for me it worked.

var found = false;

Using flag is not good practice.

This is better solution:

var movies = [
  {"name":"Ice Age 3", "language":"English", "year":"2012"},
  {"name":"Ice Age 3", "language":"French", "year":"2011"},
  {"name":"Ice Age 3", "language":"German", "year":"2013"},
  {"name":"Ice Age 4", "language":"German", "year":"2013"}
];

function convert(arr) {
    return $.map(unique(arr), function(name){
        return {
            name: name,
            details: $.grep(arr, function(item){
                return item.name == name
            })
        }
    });
}

function unique(arr) {
    var result = [];
    $.map(arr, function(item){
        if ($.inArray(item.name, result))
            result.push(item.name);
    })
    return result;
}

console.log(convert(movies));


Find and replace strings in the first column of data Not a professional coder, but my current hospital position is allowing me to code some workarounds for our abysmal EHR system. The following is part of my Python project to visualize laboratory data.
The following code snippet works, but I haven't figured out a way with list comprehensions or np.where to streamline it and potentially improve performance. I haven't found any posts yet to answer this, including among those suggested during question submission.
This code tests tuple[0] in a list of tuples (test_and_value) comprising (lab test names, test values), searching for misspelled lab test names and replacing them with standardized lab test names.
Common misspellings and their replacement terms live in another list of tuples (chem_fix) to preserve the order in which they are checked. Some word fragments of misspellings are used in lieu of full words, therefore testing cannot be a simple == statement.
Final product is a list of tuples, test_and_value_f, with correctly spelled lab tests.
Pertinent code excerpts:
chem_fix = [('A/G RATIO', 'A:G RATIO'), ('ALK', 'ALKALINE PHOSPHATASE'), ('ALT', 'ALT'), ('AST', 'AST'), ('BILI', 'BILIRUBIN,TOTAL'), ('BLIL', 'BILIRUBIN,TOTAL'), ('BUN/CREAT', 'BUN/CREAT RATIO'), ('BUN', 'BLOOD UREA NITROGEN'), ('CARBON', 'CO2'), ('GLOB', 'GLOBULIN'), ('RANDOM', 'GLUCOSE'), ('PROTEIN', 'TOTAL PROTEIN')]
fix_terms = [x[0] for x in chem_fix]

test_and_value_f = []
replaced = False
for lab_test, value in test_and_value:
    for count, term_needing_fix in enumerate(fix_terms):
        if term_needing_fix in lab_test:
            test_and_value_f.append((chem_fix[count][1], value))
            replaced = True
            break
    if replaced == False:
        test_and_value_f.append((lab_test, value))
    else:
        replaced = False

Sample test_and_value input: [('GLUCOSE', '77'), ('BUN', '14'), ('CREATININE', '1.4'), ('CALCULATED BUN/CREAT', '10'), ('SODIUM', '142'), ('POTASSIUM', '3.7'), ('CHLORIDE', '100'), ('CARBON DIOXIDE', '30'), ('CALCIUM', '8.9'), ('PROTEIN, TOTAL', '6.5'), ('ALBUMIN', '3.4'), ('CALCULATED GLOBIN', '3.1'), ('CALCULATED A/G RATIO', '1.1'), ('BILIRUBIN, TOTAL', '0.7'), ('ALKALINE PHOSPHATASE', '59'), ('SGOT (AST)', '3')]
Sample test_and_value_f output: [('GLUCOSE', '77'), ('BLOOD UREA NITROGEN', '14'), ('CREATININE', '1.4'), ('BUN/CREAT RATIO', '10'), ('SODIUM', '142'), ('POTASSIUM', '3.7'), ('CHLORIDE', '100'), ('CO2', '30'), ('CALCIUM', '8.9'), ('TOTAL PROTEIN', '6.5'), ('ALBUMIN', '3.4'), ('GLOBULIN', '3.1'), ('A:G RATIO', '1.1'), ('BILIRUBIN,TOTAL', '0.7'), ('ALKALINE PHOSPHATASE', '59'), ('AST', '3')]
Is there a more efficient way to do this?

You could use a dictionary instead of a list of tuples for chem_fix, and then you could get rid of fix_terms. Then you could use search from the re module in the list comprehension and then look up any matches in the dictionary. And you can use walrus operator to store whatever is returned from search since first you have to make sure it’s not None. Here’s an example of that:
# there’s already a function called “compile”
# “import re” used so it doesn’t get overwritten
pattern = re.compile('|'.join(chem_fix))
pattern_search = pattern.search # method will be looked up faster
test_and_value_f = [
    (
        chem_fix[m.group(0)]
        if (m := pattern_search(lab_test)) is not None
        else lab_test,
        value
    )
    for lab_test, value in test_and_value
]


Finding questions to answer In light of the recent "SQL frenzy" of sorts in The 2nd Monitor, I decided to take a stab at writing my own SEDE query. Essentially, what it does is find questions that could be answered based on the following parameters.

-- @MinQuestionVotes - The minimum amount of votes on a question.
-- @MaxQuestionAnswers - The maximum amount of answers to a question.
-- @QuestionTags - The tags that should be on the questions.

At the moment, I feel that those parameters are necessary for finding possible questions to answer, but if you feel that one isn't needed, just mention it. Anyways, here's the code, and here's the SEDE query link.

-- User parameters for finding questions. Here is
-- a brief description of what each parameter does.

  -- @MinQuestionVotes - The minimum amount of votes on a question.
  -- @MaxQuestionAnswers - The maximum amount of answers to a question.
  -- @QuestionTags - The tags that should be on the questions.
DECLARE @MinQuestionVotes INT = ##MinQuestionVotes##;
DECLARE @MaxQuestionAnswers INT = ##MaxQuestionAnswers##;
DECLARE @QuestionTags NVARCHAR(150) = ##QuestionTag1##;

-- SELECT the final results. Data is filtered based
-- on the following conditions.

  -- ClosedDate  IS EQUAL TO              null
  -- PostTypeId  IS EQUAL TO              question
  -- Score       GREATER THAN OR EQUAL TO @MinQuestionVotes
  -- AnswerCount LESS THAN OR EQUAL TO    @MaxQuestionAnswers
  -- Tags        CONTAIN                  @QuestionTags
SELECT
    Posts.Id AS [Post Link]
  , OwnerUserId AS [User Link]
  , Posts.Score
  , Posts.Tags
  , Posts.ViewCount
  , Posts.AnswerCount
  FROM Posts
    INNER JOIN PostTags ON Posts.Id = PostTags.PostId
    INNER JOIN Tags ON PostTags.TagId = Tags.Id
  WHERE
    Posts.PostTypeId = 1 AND
    Posts.ClosedDate IS NULL AND
    Posts.Score >= @MinQuestionVotes AND
    Posts.AnswerCount <= @MaxQuestionAnswers AND
    Tags.TagName LIKE CONCAT('%', @QuestionTags, '%');

Finally, here's an example of possible inputs. When entering into the QuestionTags field, you need to surround your tags with single quotes, like this: 'python'.

@MinQuestionVotes:   1
@MaxQuestionAnswers: 0
@QuestionTags:       'python'

First, your comments:

They're structured well, but, the content could be improved:

-- SELECT the final results. Data is filtered based
   ^^^^^^^^^^^^^^^^^^^^^^^^^
-- on the following conditions.

You're not really SELECTing the final results, you SELECT them based on the conditions, you don't SELECT them and then filter them.

Your declaration DECLARE @QuestionTags NVARCHAR(150) = ##QuestionTag1## is a little confusing:
Tags is plural, but then the variable you ask for input is Tag1 (singular)?

You ask for input like ##MinQuestionVotes##, but there's no reason to abbreviate, it could really just be:
##MinimumQuestionVotes##. Same things applies to the other two.

Finally, CONCAT('%', @QuestionTags, '%') is good, but you could really just:
'%' + @QuestionTags + '%' instead.

You could even build the tag string with the ' attached so the user doesn't need to input.

Other than that, your code looks really clean and nice. Good Work!


Validation Error Handling - DRY Pattern Implementation The Country, State and City functions accepts the Integer as Parameter and returns the relevant error code if the validation fails in ValidateNotExist Class.

Therefore, I have enhanced the ValidateNotExist class with a slight different implementation (using switch) and named it as ValidateNotExistImproved.

But I think, the entire code can be improved further. Can someone help me figure out what mistakes am I doing and how can I improve it?

The entire code is provided with a little explanation for every class.

NotExistErrorCodeConfig

  Error codes configuration.

public static class NotExistErrorCodeConfig
{
    public const string Country = "COUNTRY_NOT_EXIST";
    public const string State = "STATE_NOT_EXIST";
    public const string City = "CITY_NOT_EXIST";
}

EntityTypeEnum

  Enum Configuration, this is being used in the ValidateNotExistImproved class.

public enum EntityTypeEnum
{
    Country = 1,
    State = 2,
    City = 3
}

ExistsHelper

  The actual logic is implemented and it has dedicated functions.

public static class ExistsHelper
{
    public static bool Country(int id)
    {
        return (id > 10) ? true : false;
    }

    public static bool State(int id)
    {
        return (id > 10) ? true : false;
    }

    public static bool City(int id)
    {
        return (id > 10) ? true : false;
    }
}

ValidateNotExist

  A helper class, the implementation calls this class. This class is responsible to check the value and return the relevant error message.

public static class ValidateNotExist
{
    public static string Country(int id)
    {
        return (!ExistsHelper.Country(id)) ? NotExistErrorCodeConfig.Country : string.Empty;
    }

    public static string State(int id)
    {
        return (!ExistsHelper.State(id)) ? NotExistErrorCodeConfig.State : string.Empty;
    }

    public static string City(int id)
    {
        return (!ExistsHelper.City(id)) ? NotExistErrorCodeConfig.City : string.Empty;
    }
}

ValidateNotExistImproved

  I have combined the three functions into single function but using Switch statement. This is supposed to be improved version of ValidateNotExist.

public class ValidateNotExistImproved
{
    public static string Validate(EntityTypeEnum type, int id)
    {
        string errorCode = string.Empty;

        switch (type)
        {
            case EntityTypeEnum.Country:
                errorCode = (!ExistsHelper.Country(id)) ? NotExistErrorCodeConfig.Country : string.Empty;
                break;

            case EntityTypeEnum.State:
                errorCode = (!ExistsHelper.State(id)) ? NotExistErrorCodeConfig.State : string.Empty;
                break;

            case EntityTypeEnum.City:
                errorCode = (!ExistsHelper.City(id)) ? NotExistErrorCodeConfig.City : string.Empty;
                break;

            default:
                break;
        }

        return errorCode;
    }
}

ImplementationClass

  The actual implementation class, it returns the same error code.

public class ImplementationClass
{
    public ImplementationClass()
    {
        var error = ValidateNotExist.Country(2);                                         //Throws an error COUNTRY_NOT_EXIST
        var extendedError = ValidateNotExistImproved.Validate(EntityTypeEnum.Country, 2);        //Throws an error COUNTRY_NOT_EXIST

        Console.WriteLine(error);
        Console.WriteLine(extendedError);
        Console.ReadKey();
    }
}

public static class ExistsHelper
{
    public static bool Country(int id)
    {
        return (id > 10) ? true : false;
    }

    public static bool State(int id)
    {
        return (id > 10) ? true : false;
    }

    public static bool City(int id)
    {
        return (id > 10) ? true : false;
    }
}

The usage of a ternary here is senseless, you can just return the evaluated condition like so
public static class ExistsHelper
{
    public static bool Country(int id)
    {
        return (id > 10);
    }

    public static bool State(int id)
    {
        return (id > 10);
    }

    public static bool City(int id)
    {
        return (id > 10);
    }
}

but looking at it, it seems it doesn't matter what "type"  you are validating because they all have the same condition. You could simply use only one method and extract the magic number 10 into a meaningful constant.

ValidateNotExistImproved
Here you are using a ternary as well which isn't needed because a simple if statement would be enough and more readable like so
public static string Validate(EntityTypeEnum type, int id)
{
    switch (type)
    {
        case EntityTypeEnum.Country:
            if (!ExistsHelper.Country(id))
            {
                return NotExistErrorCodeConfig.Country;
            }
            break;

        case EntityTypeEnum.State:
            if (!ExistsHelper.State(id))
            {
                return NotExistErrorCodeConfig.State;
            }
            break;

        case EntityTypeEnum.City:
            if (!ExistsHelper.City(id))
            {
                return NotExistErrorCodeConfig.City ;
            }
            break;
    }

    return string.Empty;
}


SQL Stored Procedure Get Distinct and Update The idea is to show how many times a user (by EmployeeID) is in the TblTableList and then update the TblTableStatusCount

I have been learning Fetch this week so wanted to ensure I have gone down the right path and this is a small database, can/should I use this for any size?

Code:

USE [database]
        GO

        SET ANSI_NULLS ON
        GO
        SET QUOTED_IDENTIFIER ON
        GO
        Alter PROCEDURE [dbo].[spSummary]
            -- Add the parameters for the stored procedure here

        AS

        BEGIN

        DECLARE @StatusTotal AS Int
        DECLARE @Status0 AS Int
        DECLARE @Status1 AS Int
        DECLARE @Status2 AS Int
        DECLARE @Status3 AS Int

        --Cursor to loop through
        DECLARE @EmployeeID  AS NvarChar(10);
        DECLARE propCurs CURSOR FOR
        SELECT  EmployeeID FROM [TblTableList]

        --Open Loop Code
        OPEN propCurs;
        FETCH NEXT FROM propCurs INTO @EmployeeID
        WHILE @@FETCH_STATUS = 0
        --Now do repeated code

          BEGIN

         --   SELECT @StatusTotal = COUNT(ID) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID
            --SELECT @Status0 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '0'
            --SELECT @Status1 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '1'
            --SELECT @Status2 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '2'
            --SELECT @Status3 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '3'

        with cnt as (
           SELECT
             1 as cntAll
             , case WHEN CurrentAlertStatus = '0' then 1 else 0  end as cnt1
             , case WHEN CurrentAlertStatus = '1' then 1 else 0  end as cnt2
             , case WHEN CurrentAlertStatus = '2' then 1 else 0  end as cnt3
              , case WHEN CurrentAlertStatus = '3' then 1 else 0  end as cnt4
           from [TblTableCountFrom] where EmployeeID = @EmployeeID
        )
        SELECT @StatusTotal = sum(cntAll),
          @Status0  = sum(cnt1),
          @Status1  = sum(cnt2),
          @Status2  = sum(cnt3),
          @Status3  = sum(cnt4)
          FROM cnt;
            -- Check if ID Exists

            --HERE NEED TO CHECK IF EXISTS OR SHOULD I WIPE THE TABLE AT THE START?
            IF EXISTS (SELECT EmployeeID FROM [TblTableCount] WHERE @EmployeeID = EmployeeID)

                UPDATE [TblTableCountFrom]Count
                SET StatusTotalCount = @StatusTotal, Status0 = @Status0, Status1 = @Status1, Status2 = @Status2, Status3 = @Status3
                WHERE EmployeeID = @EmployeeID
              Else
                INSERT INTO [TblTableCount]
                (EmployeeID, StatusTotalCount, Status0, Status1 , Status2, Status3) VALUES (@EmployeeID, @StatusTotal,@Status0, @Status1, @Status2,@Status3 )

            END

            -- Now we bookend the loop code

            FETCH NEXT FROM propCurs INTO @EmployeeID

        END

        --Tidy up and close loop code
        CLOSE propCurs;
        DEALLOCATE propCurs;

Consistency

You have this:

    with cnt as (
       SELECT
         1 as cntAll
         , case WHEN CurrentAlertStatus = '0' then 1 else 0  end as cnt1
         , case WHEN CurrentAlertStatus = '1' then 1 else 0  end as cnt2
         , case WHEN CurrentAlertStatus = '2' then 1 else 0  end as cnt3
         , case WHEN CurrentAlertStatus = '3' then 1 else 0  end as cnt4
       from [TblTableCountFrom] where EmployeeID = @EmployeeID

And this:

    SELECT @StatusTotal = sum(cntAll),
      @Status0  = sum(cnt1),
      @Status1  = sum(cnt2),
      @Status2  = sum(cnt3),
      @Status3  = sum(cnt4)
      FROM cnt;

While both styles of formatting are perfectly acceptable, it's better to sick with the same throughout your code for readability.

Same for this:

    DECLARE @StatusTotal AS Int

And this:

    DECLARE @EmployeeID  AS NvarChar(10);

It works with or without a semicolon in this case, try to stick to one method.

The elephant in the room

Cursors are very slow. Especially using a bunch of variables with it. I understand you were experimenting with a function of SQL you are new to, and that's great. We all do that, play with our shiny new toy.

However, for something that's production and that will get called regularly, efficiency is key. Your clients won't care how cool your code looks, especially if it takes longer to run.

It is very rare that you actually need a cursor. Think about it this way. If you have 100 employees in your table, then it is running the query 100 times instead of once. Imagine 5000 or 50000 employees how long this would take.

I commented out all sections I think you could safely dispense with for better efficiency:

    USE [database]
    GO
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    Alter PROCEDURE [dbo].[spSummary]
        -- Add the parameters for the stored procedure here
    AS
    BEGIN

    DECLARE @StatusTotal AS Int
    DECLARE @Status0 AS Int
    DECLARE @Status1 AS Int
    DECLARE @Status2 AS Int
    DECLARE @Status3 AS Int

    --Cursor to loop through
    DECLARE @EmployeeID  AS NvarChar(10);

    /* DECLARE propCurs CURSOR FOR
    SELECT  EmployeeID FROM [TblTableList]

    --Open Loop Code
    OPEN propCurs;
    FETCH NEXT FROM propCurs INTO @EmployeeID
    WHILE @@FETCH_STATUS = 0
    --Now do repeated code

      BEGIN */

     -- SELECT @StatusTotal = COUNT(ID) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID
     -- SELECT @Status0 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '0'
     -- SELECT @Status1 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '1'
     -- SELECT @Status2 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '2'
     -- SELECT @Status3 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '3'

    with cnt as (
       SELECT
         1 as cntAll
         , case WHEN CurrentAlertStatus = '0' then 1 else 0  end as cnt1
         , case WHEN CurrentAlertStatus = '1' then 1 else 0  end as cnt2
         , case WHEN CurrentAlertStatus = '2' then 1 else 0  end as cnt3
         , case WHEN CurrentAlertStatus = '3' then 1 else 0  end as cnt4
       from [TblTableCountFrom] where EmployeeID = @EmployeeID
    )
    SELECT @StatusTotal = sum(cntAll),
      @Status0  = sum(cnt1),
      @Status1  = sum(cnt2),
      @Status2  = sum(cnt3),
      @Status3  = sum(cnt4)
      FROM cnt;
        -- Check if ID Exists

        --HERE NEED TO CHECK IF EXISTS OR SHOULD I WIPE THE TABLE AT THE START?
        IF EXISTS (SELECT EmployeeID FROM [TblTableCount] WHERE @EmployeeID = EmployeeID)

            UPDATE [TblTableCountFrom]Count
            SET StatusTotalCount = @StatusTotal, Status0 = @Status0, Status1 = @Status1, Status2 = @Status2, Status3 = @Status3
            WHERE EmployeeID = @EmployeeID
          Else
            INSERT INTO [TblTableCount]
            (EmployeeID, StatusTotalCount, Status0, Status1 , Status2, Status3) VALUES (@EmployeeID, @StatusTotal,@Status0, @Status1, @Status2,@Status3 )

        /* END

        -- Now we bookend the loop code

        FETCH NEXT FROM propCurs INTO @EmployeeID */

    END

    --Tidy up and close loop code
    /* CLOSE propCurs;
    DEALLOCATE propCurs; */

Also!

Do what @ckuhn203 said about a view.