Logging in with multiple types of info I'm trying to let users log in with multiple columns (e.g. ID, email, phone). If one fails, it checks the next column.

I would like to minimise my if and else statements. Is there better way of doing it?

$email = $request->only('email', 'password');
        $ssn='';$badgenumber='';$ophone='';$fphone='';$pager='';

        if(preg_match("/^[0-9]+$/",$email['email']) == 1 && strlen($email['email']) < 6){
            $ssn = $request->only('ssn', 'password');
            $badgenumber = $request->only('badgenumber', 'password');
        }

        if(preg_match("/^[0-9]+$/",$email['email']) == 1 && strlen($email['email']) > 6){
            $ophone = $request->only('ophone', 'password');
            $fphone = $request->only('fphone', 'password');
            $pager = $request->only('pager', 'password');
        }

        if(filter_var($email['email'],FILTER_VALIDATE_EMAIL) === false)
            $email ='';

        $error = 1;

        try {
            // verify the $email and create a token for the user

            if ($error == 1 && $email) {
                $error = 0;
                if (!$token = JWTAuth::attempt($email)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $ssn) {
                $error = 0;
                if (!$token = JWTAuth::attempt($ssn)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $badgenumber) {
                $error = 0;
                if (!$token = JWTAuth::attempt($badgenumber)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $ophone) {
                $error = 0;
                if (!$token = JWTAuth::attempt($ophone)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $fphone) {
                $error = 0;
                if (!$token = JWTAuth::attempt($fphone)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $pager) {
                $error = 0;
                if (!$token = JWTAuth::attempt($pager)) {
                    $error = 1;
                }
            }

            if($error == 1){
                return response()->json(['error' => 'invalid_credentials'], 401);
            }

        } catch (JWTException $e) {
            // something went wrong
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

Since this is the backend to a login request, I assume that you expect just 2 inputs, the password and one of the others.  So why not use the following:

//gets an array of all inputs: email & pass or ssn & pass or phone & pass...
$credentials = $request->all();

try{
    if(!$token = JWTAuth::attempt($credentials)){
        return response()->json(['error' => 'invalid_credentials'], 401);
    }

} catch (JWTException $e){
    return response()->json(['error' => 'could_not_create_token'], 500);
}

  i would like to minimise my if and else what would you guys recommend?

Hint: If you find yourself doing something over and over and over, you probably need a loop. Since this is a login form and that you expect just 1 variable besides the password, don't have so many vars in your script: $email, $ssn, $pager, badgenumber, ophone, fphone, ssn... just use $identifier.  If you really need to cycle through all possibilities build an array and loop until you find the one the user submitted:

$possibilities = ['email','ssn','badgenumber','ophone'...];
$identifier = '';
foreach ($possibilities as $i){
    if($request->has($i)){
        $identifier = $request->input($i);
        break; //exit the foreach loop b/c we've found the identifier
    }
}
$credentials = [$identifier, $request->input('password')];

Then you can attempt to create the token with those credentials.  Beware I've never used Laravel, but I wrote my answer after going over this helpful page on how to access requests.

Quick sidenote: I notice that you have a check that can be true only if email has length < 6, and another that can be true only if email has length > 6.  What if email has length===6 ?


Changing these two functions into one function I have two functions that are similar. The only differences is that they're using two different models. How can I change them into one function?

 ITagRepository tagRepo = new TagRepository();
 ICategoryRepository catRepo = new CategoryRepository();

public void AddTagsDontExist(string tags)
    {
        var allTags = tagRepo.GetAllQueryAble();
        string[] tag = tags.Split(',');

        foreach (var item in tag)
        {
            if (allTags.Where(e => e.Name.Contains(item)).Count() == 0)
            {
                tagRepo.Add(new Tag
                 {
                     Name = item.ToString(),
                     DateAdded = DateTime.Now,
                     LastModifiedDate = DateTime.Now,
                     IsDeleted = false
                 });
            }
        }
    }

    public void AddCategoriesDontExist(string Categories)
    {
        var allCategory = catRepo.GetAllQueryAble();
        string[] Category = Categories.Split(',');

        foreach (var item in Category)
        {
            if (allCategory.Where(e => e.Name.Contains(item)).Count() == 0)
            {
                catRepo.Add(new Category
                {
                    Name = item.ToString(),
                    DateAdded = DateTime.Now,
                    LastModifiedDate = DateTime.Now,
                    IsDeleted = false
                });
            }
        }
    }

You need to think about the underlying model. Have a think about isA/hasA. Depending on what you conclude...

Are the types defining similar interfaces? You may find that the date info is like a label that both object types have attached to them. (It looks that way.) Define an interface that contains the common names. Have each of the two types implement it. Now you can use just one loop.
Is one of them actually a member of the other? Then define it that way. Your loop will get smaller.

Bottom line is that highly repetitive code should make you think about whether your model is correct.


Generating the largest decent number of given number of digits The Sherlock and the Beast challenge from HackerRank asks to generate the following number with \$n\$ digits for \$T\$ test cases:

  A Decent Number has the following properties: its digits can only be 3's and/or 5's. The number of 3's it contains is divisible by 5. The number of 5's it contains is divisible by 3. If there are more than one such number, we pick the largest one.

My code may not be very optimal. Can you please point out which test cases it may fail, as I may have missed a few conditions? Any suggestions to optimize the code?

using namespace std;
#include<iostream>

int main() {
    int T;
    cin >> T;

    while (T >= 1) {
        int n, flag;
        cin >> n;
        int z = n;

        if(n%5==0){
            for(int r=1;r<=n;r++){
                cout<<"3";
            }cout<<"\n";
        }

        else if(n%5!=0){
        for (int i = 3; i <= n; i += 3) {
            if ((z - i) % 5 == 0) {
                flag = i;
                break;
            }
        }

        if (flag == 0|| (n-flag)%5!=0) {
            cout << "-1"<<"\n";
        }

        else {
            for (int x = 1; x <= flag; x++) {
                cout << "5";
            }
            for (int y = 1; y <= (n - flag); y++) {
                cout << "3";
            }
            cout<<"\n";
        }
        }
        T--;
    }
}

Since you're asking where the code is failing:

Your logic is flawed for at least the case n % 5 == 0 in which case you assume the whole number must always be made of 3's but that is wrong since for example for n = 15 the number consisting of all 5's would be larger and still fulfill the requirements.

Also your code invokes undefined behaviour since flag might be used before it is initialized in the case n % 5 == 0.

Ultimately what you are looking for is a solution to:

3 * f + 5 * t = n

where f is the number of 5's and t is the number of 3's and n is the known length.

One simple way to solve this is to transform it into:

f = n/3 - 5/3 * t

Now all you need to do is to check if there is a solution for t with 0 <= t <= n where f is a whole number which ultimately boils down to finding the smallest t where

n % 3 == (5 * t) % 3

So you have the three cases. Together with the knowledge that 5 % 3 == 2 we can deduce:

n % 3 == 0: (5 * t) % 3 == 0 for t = 0, 3, 6, 9, 12, 15, 18
n % 3 == 1: (5 * t) % 3 == 1 for t = 2, 5, 8, 11, 14, 17, 20
n % 3 == 2: (5 * t) % 3 == 1 for t = 1, 4, 7, 10, 13, 16, 19

Since we're interested in the smallest t (so the resulting number has the maximum number of 5's and is therefor the largest matching one) this leaves you with roughly this pseudo-code algorithm

switch (n % 3):
    case 0: t = 0;
    case 1: t = 2;
    case 2: t = 1;

if (5 * t <= n):
    print "5".repeat(n - 5 * t) + "3".repeat(5 * t)
else
    print "-1"


Dictionary of attributes and values In the code below, I have a dictionary of attributes and values. I am checking to see if the value if an attribute is True, and if so adding the attribute to a list for later processing (it becomes part of a SQL group by).

This code works fine, but I was wondering how it could be more "Pythonic". Note that the col_map dict is actually a lot bigger.

   col_map = {
        'dim_3a_group_checkbox': 'pn_group',
        'dim_3a_family_checkbox': 'pn_family',
        'dim_3a_root_checkbox': 'pn_root',
    }
    # get an object with the attributes (eg:dim_3a_root_checkbox) as True / False
    supply_kpi = self.browse(cr, uid, ids, context=None)[0]
    group_by = []
    for key, value in col_map.iteritems():
        x = getattr(supply_kpi,key)
        if x:   # only add if attribute is True
            group_by.append(value)
    print group_by

Example results

    ['pn_family', 'order_type', 'pn_group', 'categ']

I would do

supply_kpi = self.browse(cr, uid, ids, context=None)[0]
group_by = [col_map[key] for key in col_map if getattr(supply_kpi, key)]

Iterating with list comprehension is much more efficient.
You don't build iteritems list of tuples.


Producing uniform lists in Scala When writing an answer to another question here, I came across the problem of producing lists of integers having a certain total and only consisting of a certain number and an optional rest. So for total 21 and number 5 you would get List(5, 5, 5, 5, 1).

Solving the problem is obviously not hard. However, I have the feeling that it can be written more concisely than this:

def uniformList(sum: Int, num: Int): List[Int] = {
  val rest = sum % num
  List.fill(sum / num)(num) ::: (if (rest == 0) Nil else List(rest))
}

Of course I could inline the rest but I don't think it makes it more readable. I'm not looking for a performant solution but a more concise one. My feeling is that there should be a solution that is as easy to grasp as the concrete example I gave in the first paragraph.

Here are few more ways to produce your uniform lists:

def f0(a: Int, b: Int) = {
  val c = a % b
  val d = a / b
  val n = if (c == 0) d else d + 1
  (1 to n).toList map (i => if (i * b <= a) b else c)
}

def f1(a: Int, b: Int) = {
  val c  = a % b
  val d  = a / b
  val xs = List.fill(d)(b)
  if (c == 0) xs
  else        xs ::: c :: Nil
}

def f2(a: Int, b: Int) = {
  val r = a % b
  val n = a / b
  if (r == 0) List.fill(n)(b)
  else        List.tabulate(n + 1)(i => if ((i + 1) * b <= a) b else r)
}

f0 is a different/interesting way to derive your lists but to my mind is harder to parse that f1
f1 is very similar to what you have already but instead of redundantly concatenating Nil when rest == 0 we simply return the list as is
f2 is quite ugly but utilizes tabulate so I thought I'd include it

You'll notice that in each of the four functions considered so far we calculate rest = sum % nums and then branch based on the result of this calculation. While I can think of other ways to derive a value for rest they aren't as intuitive as the % operator and in the end I think we would still have a conditional statement which decided the final element of the list.

Other than adopting the small change suggested by function f1 I think your code is as concise / understandable as it can be.


Find the size and depth of a tree I have tried to implement two methods, one for finding the size of the tree and the other for finding the height of the tree. Can they be optimized further?

  package trees;
  import java.util.LinkedList;
  import java.util.TreeSet;
public class TreeNodeImpl {

    public TreeNodeImpl left ;
    public TreeNodeImpl right;
    public int Value ;
    public int height=1;

    public TreeNodeImpl newTreeNode(int value){
        TreeNodeImpl newNode = new TreeNodeImpl();
        newNode.Value = value;
        newNode.left = null;
        newNode.right = null ;
        return  newNode;
    }

    public int   recSize(TreeNodeImpl node ){
            if(node == null){
                return 0 ;
            }
            else{
                return( recSize(node.left)+ 1 + recSize(node.right));
            }
    }
    public int recHeight(TreeNodeImpl node){

        if(node==null)
        {
            return 0;
        }
        else {

            if(node.left!=null||node.right!=null){
                height++;
                recHeight(node.left);
                recHeight(node.right);
            }
        return height;
        }
    }

    public static void main(String[] args) {
        TreeNodeImpl node = new TreeNodeImpl();
        node.Value = 6;
        node.left= node.newTreeNode(20);
        node.left.left = node.newTreeNode(30);
        node.right= node.newTreeNode(30);
        node.left.left.right = node.newTreeNode(34);
        node.left.left.left = node.newTreeNode(34);
        int Size = node.recSize(node);
        System.out.println(Size);
        int height = node.recHeight(node);
        System.out.println(height);
    }
}

The formatting is all over the place, which is distracting and makes the code hard to read.

The suffix Impl in TreeNodeImpl is unnecessary, as are the rec prefixes for recSize and recHeight.

It's not clear why newTreeNode should exist; this looks like work that should be done in a constructor.

Neither of the imports java.util.LinkedList and java.util.TreeSet are used and should be removed.

Having recSize and recHeight take a node as a parameter leads to strange-looking code like node.recSize(node).

The biggest problem though is that successive calls to recHeight will return different values.


Creating remote directories in a bash script via ssh (with error trapping) I'd like to create directories on a remote VM, but only if they do not exist. What's more, if creating the directory results in an error (exit status != 0) I'd like the script to exit as well, or at least print an error. Is there a more succinct way to do this than what I have below?

UPDATE: Just to clarify, I want to test -d first so mkdir -p won't produce output about the directory already existing.

#!/bin/bash

mydirs=(/var/www/files /var/www/photos /var/www/info)
for d in ${mydirs[@]}; do
   ssh remotehost "test -d $d"
   res=$?
   test $res -ne 0 && { ssh remotehost "mkdir -p $d"; res=$?; }
   test $res -ne 0 && { echo "error during mkdir on remote"; exit 1; }
done

Running ssh in a loop is not efficient. Since the script is not interactive,
you could pass the entire script to a remote Bash process on stdin,
so that loop will run entirely on the remote server, locally:

ssh remotehost bash << "EOF"
mydirs=(/var/www/files /var/www/photos /var/www/info)
for d in ${mydirs[@]}; do
   test -d $d
   res=$?
   test $res -ne 0 && { mkdir -p $d; res=$?; }
   test $res -ne 0 && { echo "error during mkdir on remote"; exit 1; }
done
EOF

Notice the double-quotes around the here document label, this is to avoid variable interpolation. The entire script is passed to the remote shell literally.

I made only the minimal changes to illustrate the point. Some important improvements are well advised:

All variables used as command line arguments should be double-quoted: "${mydirs[@]}", "$d", and so on.
As a comment mentioned, when using mkdir -p, it's unnecessary to test if the directory exists.
Now that the main operations run in a single process, the pipeline can be simplified.
As another comment mentioned, consider investing in learning a proper system administration tool such as Puppet, Ansible, Chef, or similar.


Handling keyup events with throttle or debounce in Javascript/jQuery In my web application, there is a search input field, and when the user empties all of the text inside the input field, there is an API call made for a default-list of results, which are displayed in a dropdown right underneath the input field.

I'm using the keyup event to try to capture when the user will have completed deleting text, but I've not been able to re-create the desired behavior without using setTimeout().  I've been told to use a throttle or debounce method (no third party modules or plugins, although plain jQuery is ok).

Could someone please give me some advice on how to recreate this code without using setTimeout?  I've been on this for a couple days no with no luck, any help is appreciated!

(function () {
  var desktopInput = document.getElementById('someId');
  var desktopResults = document.getElementsByClassName('someClass')[0];

  function getSuggestedSearchResults(cb) {
    $.ajax({
      url: url,
      data: {},
      timeout: REQ_TIMEOUT,
      xhrFields: {
        withCredentials: true
      },
      success: function (data) {
        cb(data);
      }
    });
  }

  function handleEmptyInputDesktop() {
    if (desktopInput.value === '') {
      setTimeout(function () {
        getSuggestedSearchResults(function (data) {
          var model = transformResults(data);
          var results = nunjucks.render('_fullscreenSearchResults', {
            results: model,
            source: 'suggested'
          });
          desktopResults.innerHTML = results;
        });
      }, 500);
    }
  }

  function init() {
    desktopInput.addEventListener('keyup', handleEmptyInputDesktop);
  }

  init();
})();

Without the setTimeout(), the dropdown menu will disappear if the key isn't pressed long enough on the first stroke that deletes all the text.

I've omitted some extraneous code from this snippet, but I'm happy to give more details if you like.

I ended up using window.requestAnimationFrame and it worked really well, just thought I'd share my solution based on the linked article.

 function requestAnimationTimeout(callback, delay) {
    var dateNow = Date.now;
    var requestAnimation = window.requestAnimationFrame;
    var start = dateNow();
    var stop;

    var timeoutFunc = function () {
      if (dateNow() - start < delay) {
       return stop || requestAnimation(timeoutFunc);
      } else {
       return callback();
      }
    };

    requestAnimation(timeoutFunc);

  }

And then simply use requestAnimationTimeout in place of the native setTimeout.


Checking for legal sudoku boards My problem statement is:

  Write a function to indicate if a given Sudoku board is legal. This function takes a Sudoku board (which you may assume is a N2xN2 2d list of integers, where N is an integer), and returns True if the board is legal, as described above.

And here's my solution:

import time, random

def solve_all(grids, name='', showif=0.0):
    """Attempt to solve a sequence of grids. Report results.
    When showif is a number of seconds, display puzzles that take longer.
    When showif is None, don't display any puzzles."""
    def time_solve(grid):
        start = time.clock()
        values = solve(grid)
        t = time.clock()-start
        ## Display puzzles that take long enough
        if showif is not None and t > showif:
            display(grid_values(grid))
            if values: display(values)
            print '(%.2f seconds)\n' % t
        return (t, solved(values))
    times, results = zip(*[time_solve(grid) for grid in grids])
    N = len(grids)
    if N > 1:
        print "Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max    %.2f secs)." % (
            sum(results), N, name, sum(times)/N, N/sum(times), max(times))

def solved(values):
    "A puzzle is solved if each unit is a permutation of the digits 1 to 9."
    def unitsolved(unit): return set(values[s] for s in unit) == set(digits)
    return values is not False and all(unitsolved(unit) for unit in unitlist)

def from_file(filename, sep='\n'):
    "Parse a file into a list of strings, separated by sep."
    return file(filename).read().strip().split(sep)

def random_puzzle(N=17):
    """Make a random puzzle with N or more assignments. Restart on contradictions.
    Note the resulting puzzle is not guaranteed to be solvable, but empirically
    about 99.8% of them are solvable. Some have multiple solutions."""
    values = dict((s, digits) for s in squares)
    for s in shuffled(squares):
        if not assign(values, s, random.choice(values[s])):
            break
        ds = [values[s] for s in squares if len(values[s]) == 1]
        if len(ds) >= N and len(set(ds)) >= 8:
            return ''.join(values[s] if len(values[s])==1 else '.' for s in squares)
    return random_puzzle(N) ## Give up and make a new puzzle

def shuffled(seq):
    "Return a randomly shuffled copy of the input sequence."
    seq = list(seq)
    random.shuffle(seq)
    return seq

Coding style

Please follow PEP8, the style guide for Python code.
As you read through it, you should recognize several coding style violations in your posted code.
There is also a command line tool called pep8, which can check your entire project and report the violations. You can install it with:

pip install pep8

Strange condition

This looks very strange:

return values is not False and all(unitsolved(unit) for unit in unitlist)

From the posted code it's not clear what is the type of values.
The plural name implies some kind of collection,
but then it can never be False.
As such, this condition doesn't make sense.


Project Euler #45 - Triangular, pentagonal, and hexagonal Project Euler Problem 45

  Triangle, pentagonal, and hexagonal numbers are generated by the
  following formulae:

  Triangle      Tn=n(n+1)/2     1, 3, 6, 10, 15, ... Pentagonal
    Pn=n(3n−1)/2        1, 5, 12, 22, 35, ... Hexagonal     Hn=n(2n−1)      1, 6,
  15, 28, 45, ... It can be verified that T285 = P165 = H143 = 40755.

  Find the next triangle number that is also pentagonal and hexagonal.

My Implementation:

I used a HashSet for fast searching. I got the right answer after experimenting with the size of the HashSet. 100000 worked for me.

void Main()
{
    var pen = Pentagonals(100000);
    var hex = Hexagonals(100000);

    foreach(var n in Triangles()){
        if(pen.Contains(n) && hex.Contains(n) && n > 40755){
            Console.WriteLine(n);
            return;
        }
    }
}

IEnumerable<BigInteger> Triangles()
{
    for(BigInteger n = 1;;n++)
    {
        yield return (n * (n + 1) / 2);
    }
}

HashSet<BigInteger> Pentagonals(int limit)
{
    HashSet<BigInteger> set = new HashSet<BigInteger>();
    for(BigInteger n = 1;n <= limit;n++)
    {
        set.Add(n * (3 *n - 1) / 2);
    }
    return set;
}

HashSet<BigInteger> Hexagonals(int limit)
{
    HashSet<BigInteger> set = new HashSet<BigInteger>();
    for(BigInteger n = 1;n <= limit;n++)
    {
        set.Add(n * (2*n - 1));
    }
    return set;
}

How can I improve this?

This expands my comments on Brythan's answer:

Note: It's written in JavaScript (not C#) since I haven't written C# in years but you should be able to convert it fairly easily.

Answer 1 - Test if successive hexagonal numbers are also triangular and pentagonal

A number \$c\$ is triangular if \$c = t(t + 1)/2\$ (where \$c \in \mathbb{N}\$ and \$t \in \mathbb{N}\$) which can be rewritten as \$0 = t^2 + t -2c\$ and then in terms on \$t\$, using the positive root given by the quadratic formula, as \$t = \frac{-1 + \sqrt{1+8c}}{2}\$.

Similarly, the pentagonal number formula \$c = p(3p-1)/2\$ (where \$c \in \mathbb{N}\$ and \$p \in \mathbb{N}\$) can be rewritten as \$0 = 3p^2 - p - 2c\$ then as \$p = \frac{1 + \sqrt{1+24c}}{6}\$ .

You can then use these to test successive hexagonal numbers to see if the they are also triangular and pentagonal:

function quadraticRoot(a,b,c){
  return ( -b + Math.sqrt( b*b - 4 * a * c ) ) / (2 * a);
}

function isInteger(n){
  return n === Math.round( n );
}

function isTriangularNumber(n){
  return isInteger( quadraticRoot( 1, 1, n*-2) );
}

function isPentagonalNumber(n){
  return isInteger( quadraticRoot( 3,-1, n*-2 ) );
}

function getNextHexagonalNumberWhichIsTriangularAndPentagonal(n){
  var hex;
  while( true ) {
    hex = n * ( 2 * n - 1 );
    if ( isTriangularNumber( hex ) && isPentagonalNumber( hex ) )
    {
      return n;
    }
    ++n;
  }
}

Then:

getNextHexagonalNumberWhichIsTriangularAndPentagonal( 144 );

Gives the answer 27693 as the next hexagonal number that is also triangular and pentagonal.

Answer 2 - Generate successive triangular, pentagonal and hexagonal numbers

function getTriangular(n){
  return n * (n + 1 ) / 2;
}

function getPentagonal(n){
  return n * ( 3 * n - 1 ) / 2;
}

function getHexagonal(n){
  return n * ( 2 * n - 1 );
}

function getNextEqualTriangluarPentagonalHexagonalNumbers(t,p,h){
  var tt = getTriangular(t);
  var pp = getPentagonal(p);
  var hh = getHexagonal(h);
  while ( true ){
    var max = Math.max( tt, pp, hh );
    if ( tt < max ) {
      tt = getTriangular(++t);
    } else if ( pp < max ) {
      pp = getPentagonal(++p);
    } else if ( hh < max ) {
      hh = getHexagonal(++h);
    } else {
      return [t,p,h];
    }
  }
}

Then

getNextEqualTriangluarPentagonalHexagonalNumbers(286,166,144);

Gives the answer [ 55385, 31977, 27693 ] for the next triangular, pentagonal and hexagonal numbers which are identical.


Implement rate limiting by cookie ID I want to develop a simple in-memory web request rate limiting module, I am allowed to have 50 requests from each unique cookie ID every 60 seconds.

I am wondering if the following code is an optimal way of implementing such functionality:

class RateLimiter {

    private static final int MAX_REQUESTS = 50;

    private Map<String, List<Long>> cookieMap = new HashMap<>();

    private boolean isRateLimited(String cookieId) {
      long time = System.currentTimeMillis();
      long oldestTime = time - 60000;
      List<Long> timestamps = cookieMap.getOrDefault(cookieId, new LinkedList<>());
      timestamps.add(0, time);
      int count = 0;
      int tooOldIndex = -1;
      for (int i = 0; i < timestamps.size(); i++) {
          if (timestamps.get(i) >= oldestTime) {
              count++;
          } else {
              tooOldIndex = i;
              break;
          }
      }
      List<Long> newTimestamps = new LinkedList<>();
      // clean up timestamps older than the 60 second window
      for (int i = 0; i < tooOldIndex; i++) {
          newTimestamps.add(timestamps.get(i));
      }
      cookieMap.put(cookieId, newTimestamps);
      if (count >= MAX_REQUESTS) {
         return false;
      } else {
         return true;
      }
  }
}

Accessing elements of a linked list with .get(i) is expensive, because it's an \$O(N)\$ operation compared to \$O(1)\$ of array backed structures. You should avoid doing this, and use an enhanced for-each loop instead, for example:

for (Long currentTimeStamp : timestamps) {
    if (currentTimeStamp  >= oldestTime) {
        newTimestamps.add(currentTimeStamp);
    } else {
        break;
    }
}

If you need the element index, you can add a counting variable "manually" (declared before the loop, and increments in the loop body).


Do I need still to be concerned about favouring str_replace over preg_replace in PHP 7? I have the following piece of code:

$Page = str_replace('-&amp;-', '-[+]-', $Page);
$Page = str_replace('&amp;', '-[+]-', $Page);
$Page = str_replace('-and-', '-[+]-', $Page);
$Page = str_replace('-et-', '-[+]-', $Page);
$Page = str_replace('-und-', '-[+]-', $Page);
$Page = str_replace('-y-', '-[+]-', $Page);
$Page = str_replace('-&-', '-[+]-', $Page);

which I then run many times per page load (perhaps 10 to 40 times).

  N.B. $Page represents a URL fragment - rarely more than 20 characters long.

Am I better off leaving it as it is, or may I, for the purposes of code maintenance, rewrite this code as:

$Page = preg_replace('/(-&-|-&amp;-|&amp;|-and-|-et-|-und-|-y-)/', '-[+]-', $Page);

without suffering a slowdown of one or several hundredths of a second?

(If the slowdown is a matter of milliseconds, I am less bothered).

Background:

I am less familiar with the evolution of PHP than with that of javascript, css etc. so when I see recommendations (long-stated, albeit from the late 2000s and early 2010s) like:

  Avoid preg_replace unless you need to use it and always use
  str_replace instead, which is an order of magnitude faster.

I don't know if that recommendation still has any relevancy for PHP 7.3 in 2020, or whether that recommendation was important to follow in the days of PHP 5, but is less of a concern now (given that PHP 7 is so much faster and more optimised than its predecessor).

Most of such advises are crystal clear bullshit, on so many levels. You need to understand that such recommendations are never a result of some quality research, but just a rephrase of some vague rumor. The internet is full of chimpanzees.

This particular advise didn't make any sense even for PHP5.

That said, a set of consequent function calls apparently should be less efficient than a single call (but again if only it made any real life difference whatsoever).

That said, str_replace accepts array arguments, so it can be

$Page = str_replace(['-&-','-&amp;-','&amp;','-and-','-et-','-und-','-y-'], '-[+]-', $Page);

But you can use whatever version you like, as any difference is unnoticeable. Personally I find preg_replace() approach the cleanest and would prefer that.

As a rule of thumb, do not trust some random pieces of advise from Internet, especially performance-related. It's always just random rubbish. Bother with any optimizations only if your code actually has performance issues. And even in this case do not optimize random irrelevant parts but find the actual bottleneck and optimize it.


LINQ-inspired recursive file search I've been working on a configurable tool that finds files by a certain specification and returns a list. I attempted to approach this in a more LINQ way and tried using appropriate design decisions, all while keeping it reasonably efficient.

Here is my Finder class:

public class Finder
{
    public List<string> Extensions;
    public List<string> TargetDirectories;
    public bool Recursive { get; set; }

    private string _currentPath;
    private List<string> _files = new List<string>();

    public Finder()
    {
        Extensions = new List<string>();
        TargetDirectories = new List<string>();

        _currentPath = Directory.GetCurrentDirectory();
    }

    public string[] GetFiles()
    {
        if (_files.Count != 0)
            return _files.ToArray();
        return new string[0];
    }

    public void Find()
    {
        try
        {
            foreach (var directory in TargetDirectories)
            {
                Search(directory);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

    private void Search(string path)
    {
        var pathPoint = new DirectoryInfo($"{_currentPath}{path}");
        var files = Directory.EnumerateFiles(pathPoint.FullName, "*.*")
            .Where(s => Extensions.Contains(Path.GetExtension(s)))
            .ToList();
        files.ForEach(_files.Add);

        if (Recursive)
        {
            var subDirectories = Directory.GetDirectories(pathPoint.FullName);
            foreach (var subDir in subDirectories)
            {
                Search($"{path}/{new DirectoryInfo(subDir).Name}");
            }
        }
    }
}

And here's the usage:

var finder = new Finder();
finder.Extensions.Add(".cs");
finder.Extensions.Add(".dll");
finder.TargetDirectories.Add("/src");
finder.TargetDirectories.Add("/assembly");
finder.Recursive = true;
finder.Find();

foreach (var file in finder.GetFiles())
{
    Console.WriteLine(file);
}

The Output

It returns all of the files within every folder of /src and /assembly. If I change Recursive to false or omit it, the result will be only the files within the targeted directories. Extensions are also specified to retrieve files only of that type.

Here's what the output looks like:

/long/path/name/src/helloworld.cs
/long/path/name/src/class.cs
/long/path/name/src/subdirectory/anotherclass.cs
/long/path/name/assembly/library.dll

This is the intended return.

Design

I store the directory information so I can scale that information and use fields like Name and FullName. The files for specifically that searched directory are inserted into a list and allocated to a returnable list. The return list, _files, is publicly immutable.

Efficiency

I'm unsure if there's any notable difference between using the LINQ in my Search method or using a for loop for iteration in terms of performance. I also believe there might be a way I can simply use the EnumerateFiles return array without converting to a list then back to an array when using GetFiles().

Any suggestions on how I can improve my class? I'm trying to better my C# knowledge and program; any feedback would be considerably helpful and will assist me in further implementing features.

EDIT:
I am adopting suggestions actively. You can see the (amateur) repository here:
https://github.com/TGibsonn/FastCompile

As someone who's been writing cross-platform tools on .Net Core, this doesn't do what I expect it to do.

finder.TargetDirectories.Add("/src");

I expect that to target a directory named src at the root of the file system. On Linux: /src; on windows C:\src. It would be more clear if the user passed in a relative file path or a complete file path.

Also, please don't concatenate file paths this way.

$"{path}/{new DirectoryInfo(subDir).Name}"

This is terribly error prone. It's hard to get right the first time and it's even harder to refactor later. Always use System.IO.Path.Combine().


C++ class for capturing broadcast window messages In the Windows operating system, some system events are notified via broadcast window messages. DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE are good examples of this. To receive and process these notifications, one need to have a window with an associated window procedure. Given a non-GUI application, this is a burden. So, I'm thinking about encapsulating a simple class for capturing broadcast window messages, and here it comes. The pack comes in one main class CWndMsgReceiver and two helper classes CDummyWndClass and CDummyWnd.

I hope to have my code reviewed, and get some comments and suggestions.

WndMsgReceiver.h

#pragma once
#include <atomic>
#include <thread>
#include <windows.h>

class CDummyWndClass {
public:
  explicit CDummyWndClass(WNDPROC wndproc);
  ~CDummyWndClass();
  operator PCWSTR() const;
private:
  ATOM atom_;
};

class CDummyWnd {
public:
  explicit CDummyWnd(WNDPROC wndproc);
  ~CDummyWnd();
  operator HWND() const;
private:
  CDummyWndClass wndcls_;
  HWND hwnd_;
};

class CWndMsgReceiver {
public:
  explicit CWndMsgReceiver(WNDPROC wndproc);
 ~CWndMsgReceiver();
  operator HWND() const;  // to use with RegisterDeviceNotification
private:
  static void MsgPump(WNDPROC wndproc, std::atomic<HWND>& hwnd);
  std::atomic<HWND> hwnd_;
  std::thread thrd_;
};

WndMsgReceiver.cpp

#include "WndMsgReceiver.h"
#include <cstring>
#include <functional>
#include <utility>

CDummyWndClass::CDummyWndClass(WNDPROC wndproc)
    : atom_(0) {
  HMODULE hmodule = 0;
  GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
                     GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                     (PCWSTR)wndproc, &hmodule);
  WNDCLASSW wndcls = {0, wndproc, 0, 0, (HINSTANCE)hmodule, 0, 0, 0, nullptr,
                      L"{F9F40031-F77E-4A5C-8A6C-30296B823C22}"};
  atom_ = RegisterClassW(&wndcls);
}

CDummyWndClass::~CDummyWndClass() {
  UnregisterClassW((PCWSTR)*this, 0);
}

CDummyWndClass::operator PCWSTR() const {
  PCWSTR p = nullptr;
  std::memcpy(&p, &atom_, sizeof(atom_));
  return p;
}

////////////////////////////////////////////////////////////////////////////////

CDummyWnd::CDummyWnd(WNDPROC wndproc)
    : wndcls_(wndproc)
    , hwnd_(CreateWindowW((PCWSTR)wndcls_, nullptr, 0, 0,
                          0, 0, 0, 0, 0, 0, nullptr)) {
}

CDummyWnd::~CDummyWnd() {
  DestroyWindow(hwnd_);
}

CDummyWnd::operator HWND() const {
  return hwnd_;
}

////////////////////////////////////////////////////////////////////////////////

CWndMsgReceiver::CWndMsgReceiver(WNDPROC wndproc)
    : hwnd_{}
    , thrd_(std::thread(MsgPump, wndproc, std::ref(hwnd_))) {
  do Sleep(0); while (!(HWND)hwnd_);
}

CWndMsgReceiver::~CWndMsgReceiver() {
  PostThreadMessageW(GetThreadId(thrd_.native_handle()), WM_QUIT, 0, 0);
  thrd_.join();
}

CWndMsgReceiver::operator HWND() const {
  return hwnd_;
}

void CWndMsgReceiver::MsgPump(WNDPROC wndproc, std::atomic<HWND>& hwnd) {
  CDummyWnd wnd(wndproc);
  hwnd = wnd;
  MSG msg = {};
  while (GetMessageW(&msg, 0, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessageW(&msg);
  }
}

I haven't worked with WinAPI in years, so I can't help you much with that, but I do have a few concerns regarding style and structure of your code:

What's the meaning of this GUID? Does it have any, or is it just randomly generated?

WNDCLASSW wndcls = {0, wndproc, 0, 0, (HINSTANCE)hmodule, 0, 0, 0, nullptr,
              L"{F9F40031-F77E-4A5C-8A6C-30296B823C22}"};

A comment explaining why this specific value would be nice. Or better, make it a named constant with a self-explanatory name.
You have several instances of C-style casts in the code. Prefer using the C++ cast operators instead. They will give you warnings and diagnostics for potentially dangerous casts.
This looks very obscure:

CDummyWndClass::operator PCWSTR() const {
  PCWSTR p = nullptr;
  std::memcpy(&p, &atom_, sizeof(atom_));
  return p;
}

On my first look, I thought that you were trying to memcpy into a null pointer. The & on p is not easily spotted without a careful look. If you really must do this, then I think a reinterpret_cast would be more clear about your intentions. I did not test this, but something along the lines of the following should do:

CDummyWndClass::operator PCWSTR() const {
    const std::uintptr_t intVal = static_cast<std::uintptr_t>(atom_);
    PCWSTR ptrVal = reinterpret_cast<PCWSTR>(intVal);
    return ptrVal;
}

It would probably look clearer if you'd lay out that loop inside CWndMsgReceiver construtor is a more spaced way, to give it emphasis. Default { } is always good too:

  do Sleep(0); while (!(HWND)hwnd_);

 do {
     Sleep(0);
 } while (!(HWND)hwnd_);

You should also comment that this is not an infinite loop, but that it waits on an independent thread to set the variable.
This might be your personal preference, I for one I'm not a big fan of cast operator overloads. I've seen instances when they can produce some pretty obscure code. IMHO, I think your cast operators would look much nicer as plain Get*() methods.
You don't seem to use the wacky Microsoft prefixes on variable names, though you do use the C prefix for class names. Again, this is a subjective point, but I think your class names would be more readable without it.


Exception handling for a chain of prompts I am trying to make an inputin() function to take all the parameters input for the first time with exception and for individual parameter for the runtime proposition. I am thus looking forward to reducing code size or being a more efficient coder with more pythonic procedures.

""This code is well executed and tested for all possible situations""

import turtle              # 1.  import the modules
#import random

BackGround = 'white'
Numside = 0
Armlen = 0
Turtlecolor = 'blue'
Turtleshape = 'turtle'

def inputin(count = 1, port = 0):
            #counting for resolving runtime error
    global BackGround, Numside, Armlen, Turtlecolor, Turtleshape

    while True :
        try :
            if((port == 0 or port == count) and count == 1):
                count+=1
                BackGround = str(input("Enter the Background Color : "))
            if((port == 0 or port == count) and count == 2):
                count+=1
                Numside = int(input("Enter the No. of Sides : "))
            if((port == 0 or port == count) and count == 3):
                count+=1
                Armlen = int(input("Enter the length of each side : "))
            if((port == 0 or port == count) and count == 4):
                count+=1
                Turtlecolor = str(input("Enter the Turtle Color : "))
            if((port == 0 or port == count) and count == 5):
                count+=1
                Turtleshape = str(input("Enter the Turtle Shape : "))
            port = -1
            break
        except ValueError :
            print("Oops!  That was no valid number.  Try again...")
            count+=-1

#Creating Screen after Everything Is Over

#i am creting this class for adjusting multiple values like a structure.
class Team(object):
    def __init__(self, Numside = 0, Armlen = 0, Turtlecolor = "", Turtleshape = ""):
        self.Numside = Numside
        self.Armlen = Armlen
        self.Turtlecolor = Turtlecolor
        self.Turtleshape = Turtleshape

def screen():
    wn = turtle.Screen()       # 2.  Create a screen

    while True:
        try:
            wn.bgcolor(BackGround)
            break
        except turtle.TurtleGraphicsError as e:
            inputin(1,1)

    wn.exitonclick()

def TurtleCreation():
    lance = turtle.Turtle()
    while True:
        positionInput = 0 #for marking the position of the desired input
        try:
            positionInput = 4
            lance.color(Turtlecolor)
            positionInput = 5
            lance.shape(Turtleshape)
            break
        except turtle.TurtleGraphicsError as f:
            inputin(positionInput,positionInput)
    lance.speed(500)
    lance.penup()
    #lance.goto(-300,200)

inputin()
TurtleCreation()
screen()

#sc = turtle.ScrolledCanvas(master)

#now shifting the turtle to the middle of the system

The whole port and count thing is a total waste of time. If you were stuck with it:

port is redundant, as break is what actually ends the loop;
If port was being used (e.g. while port:) it should be a bool (True/False) rather than an int (1/0);
You shouldn't have whitespace around the = for default argument values (def inputin(count=1, port=0):);
The if conditions should have more space and fewer parentheses: if port == 0 and count == 3:; and
count+=-1 should be count -= 1.

Only two of your inputs actually need to be numbers, yet you wrap the whole thing in try; that block should be as short as you can make it. You can factor out the integer inputs for much cleaner code (see e.g. Asking the user for input until they give a valid response). For the other three inputs the return from input is always a string, so the str calls are totally redundant.

Compare:

def int_input(prompt):
    """Validate integer-only user input."""
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter an integer.")

def input_in():
    """Get required user inputs."""
    background = input("Enter the background color: ")
    num_sides = int_input("Enter the number of sides: ")
    arm_len = int_input("Enter the length of each side: ")
    turtle_color = input("Enter the turtle color: ")
    turtle_shape = input("Enter the turtle shape: ")
    ...

Note the adherence to the style guide and use of docstrings to explain what each function does.

As additional exercises:

Add limits to the integer validation, allowing a minimum and maximum to be set for the function (a negative arm_len wouldn't make much sense, for example);
Create a color_input function to validate the user's color selection, and use it where appropriate; and
Create a shape_input function to do the same for shapes.


Change non-diagonal surrounding elements in a 2-D array I'm a beginner working through an exercise on ruby arrays. Given a two-dimensional array with 0's and/or 1's, it should return an array with the non-diagonal surrounding elements of 1 changed to 1 if they are 0. That is

a = [[1,0,0,0],
     [0,0,0,0],
     [0,0,0,0],
     [0,0,1,0]]

should return

[[1,1,0,0],
 [1,0,0,0],
 [0,0,1,0],
 [0,1,1,1]]

This is what I've come up with. Improvements or comments will be well received.

a = [[1,0,0,0],
     [0,0,0,0],
     [0,0,0,0],
     [0,0,1,0]]

#create a nil-filled placeholder copy of the array
new = Array.new(a.length).map! {|element| element = Array.new(a[0].length)}

#scan original array for 1; map crosses into new array if found
a.each_with_index do |m, n| # n == index of main array
    m.each_with_index do |x, y| # y == index of subarray
        if x == 1
            new[n][y] = 1
            new[n][y+1] = 1 unless (a[n][y+1]).nil? #right
            new[n][y-1] = 1 unless (a[n][y-1]).nil? || y == 0 #left
            new[n-1][y] = 1 unless (a[n-1][y]).nil? || n == 0 #top
            unless n == (a.length - 1)
                new[n+1][y] = 1 unless (a[n+1][y]).nil? || n == (a.size - 1) #bottom
            end
        end
    end
end

#change nil's into 0's
new.each do |element|
  element.map! {|x| x == nil ? x = 0 : x = 1 }
end

Copying the array
You are over-complicating the array copy.  Array.clone will copy the objects of the array (but not the object's objects).  Using it on array of objects might be problematical, but an array of ints will be fine.
new = a.map(&:clone)  # clone each row, return as an array

This line also removes the need of cleaning up your nils at the end
Additional Thoughts
While the logic is largely fine, stylistically your loops could be a little more idiomatic.
Unless you are using older ruby, you should tend to prefer .each.with_index over each_with_index.  They do the same thing but .with_index is a little more functional (programming).
Secondly, in general, try to chose better variable names than m, n, x, y.  You have comments describing what they are, but with better variable names, the code becomes self documenting.  (I've used ix_row and ix_col, but that's my personal naming convention for indexes; feel free to change it, just make sure it's purpose is obvious.)
Finally, you are overthinking your boundary checks as well.  All you need to do is simply check the index.
new.each.with_index do |row, ix_row|
  row.each.with_index do |cell, ix_col|
    if cell == 1
      new[ix_row][ix_col+1] = 1 unless ix_col+1 >= row.length #copy right
      new[ix_row+1][ix_col] = 1 unless ix_row+1 >= new.length # copy down
      new[ix_row][ix_col-1] = 1 unless ix_col.zero? # copy left
      new[ix_row-1][ix_col] = 1 unless ix_row.zero? #copy up
    end
  end
end


Sorting thousands of records I have the following list to sort:

A 0.53
B 0.56
C 0.56
D 0.98
E 0.33

Please note that my list may contains thousands of such type of records. I am sorting my list and put the sorted list into an array as:

  String str="";
        for(String s: mylist){
            str+=s+",";
        }
        String[] sArr = str.split(",");
        String temp="";
        for(int i=0; i<sArr.length;i++) {
            for(int j= i+1; j<sArr.length;j++){
                if(sArr[i].split("\\s")[1].compareToIgnoreCase(sArr[j].split("\\s")[1])<0){
                    temp= sArr[j];
                    sArr[j]= sArr[i];
                    sArr[i]=temp;
                }
            }
        }

       //sArr now contains the sorted list

The problem is that it is taking too long to get sorted when I have thousands of records. Is there any other way to perform the same task efficiently in less time, or is there something wrong with my way of coding?

You should split your code up into different methods (this increases readability and makes it possible to profile your code and find bottlenecks). I would create listToArray (which transforms your list to an array, although this isn't really needed), parseInput (which parses A 0.53 to an integer of 0.53, and if you need the original string, you can wrap this up in an object), and sortArray (which performs the actual sorting).
your way of transforming a list to an array is not very stable (what if there are , in your strings?) It also doesn't seem very performant. Use the standard solution for this.
although I'm not sure why you are even doing this, it seems to just add needless computing time.
you seem to be using bubble sort, which has a very bad performance of O(n^2). You should look into other sorting algorithms such as quicksort.
you perform split("\\s") multiple times on the same elements. It would be better to perform this once at the beginning to save a lot of computing.
have you tried using Collections.sort? I would guess that it will perform better, and the code will definitely be cleaner.
be consistent with your spacing, and use more spaces to increase readability (around =, +, etc.

Using Collections.sort your code would look like this:

    // create test list
    List<String> list = new ArrayList<>();
    list.add("B 0.56");
    list.add("E 0.33");
    list.add("A 0.53");

    // sort the list
    Collections.sort(list, (a, b) -> a.split("\\s")[1].compareToIgnoreCase(b.split("\\s")[1]));

    // print sorted list
    for (String list1 : list) {
        System.out.println(list1);
    }

Result:

E 0.33
A 0.53
B 0.56


N-layered application structure in ASP.NET MVC 5 I've been trying to set up an n-layered application in ASP.NET MVC 5. I've converted my account controller to look like this.

I would like some feedback as to whether this is going in the right direction. What I'm trying to achieve is to off-load my controllers and leave the logic to the service. My Controller should just be doing the routing.

// all services inherit this to expose the DbContext
public class BaseService
{
    protected AppDbContext db = new AppDbContext();
}

interface IAccountService
{
    bool Login(HttpContextBase httpContext, string userName, string password);
    bool Logout(HttpContextBase httpContext, HttpSessionStateBase session);
}

public class AccountService : BaseService, IAccountService
{
    private UserManager<IdentityUser> userManager;

    public AccountService()
    {
        userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
    }

    public bool Login(HttpContextBase httpContext, string userName, string password)
    {
        var user = userManager.Find(userName, password);

        if (user != null) {
            IAuthenticationManager authenticationManager = httpContext.GetOwinContext().Authentication;

            authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            authenticationManager.SignIn(userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie));

            return true;
        }

        return false;
    }

    public void Logout(HttpContextBase httpContext, HttpSessionStateBase session)
    {
        IAuthenticationManager authenticationManager = httpContext.GetOwinContext().Authentication;

        authenticationManager.SignOut();
        session.Clear();
    }
}

public class AccountController : Controller
{
    private readonly IAccountService service;

    public AccountController()
    {
        service = new AccountService();
    }

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Index(IndexViewModel viewModel)
    {
        ActionResult result;

        if (service.Login(HttpContext, viewModel.UserName, viewModel.Password)) {
            result = RedirectToAction("Index", "Home");
        } else {
            result = View(viewModel);
        }

        return result;
    }

    public ActionResult Logout()
    {
        service.Logout(HttpContext, Session);

        return RedirectToAction("Index");
    }
}

It's looking really good.  Some things I might consider that aren't necessary but could help move the code to some better abstractions and hence allow for easier unit testing of features include.

Abstracting your service away from UI related actions by removing the dependency on HttpContextBase.  It looks like all you are using it for is to obtain the IAuthenticationManager so I would pass that into your Login/Logout methods instead.

interface IAccountService
{
    bool Login(IAuthenticationManager authenticationManager, string userName, string password);
    bool Logout(IAuthenticationManager authenticationManager);
}

public bool Login(IAuthenticationManager authenticationManager, string userName, string password)
{
    var user = userManager.Find(userName, password);

    if (user != null) {

        authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        authenticationManager.SignIn(userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie));

        return true;
    }

    return false;
}

public void Logout(IAuthenticationManager authenticationManager)
{
    authenticationManager.SignOut();
    // NOTE:  Now you will have to do the session clear in your controller using this approach
        }

If you were using a DI framework you could consider following the DIP by injecting your service into your controller.  There are many DI frameworks out there (Autofac, Unity, Ninject just to name a few).  This would further abstract your controller away from the service implementation details.

// Account service supplied via Constructor injection
public AccountController(IAccountService accountService)
{
    service = accountService;
}

I noticed you have a base service.  I like this approach but I think I would consider again using Dependency injection (or DI) to provide this to your service so that you can provide another level of abstraction and possibly remove your services need for this.  Hence your base service might turn into something like.

// all services inherit this to expose the DbContext
public abstract class BaseService
{
    protected AppDbContext db { get; private set; }

    protected BaseService(AppDbContext dbContext)
    {
        db = dbContext;
    }
}

public AccountService(AppDbContext dbContext) : base(dbContext)
{
    userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(dbContext));

}

  NOTE:  If concerned that using Dependency injection means this
  wouldn't work, don't be.  Constructor injection is a walk in the park
  for these frameworks.

As your base service is likely to never make sense just by itself I would consider making it an abstract class to enforce implementation of the service through child classes.
In the past I have liked to abstract my dbContext away behind an interface to help with further abstracting my services and provide for a final piece of the abstraction puzzle.  So in your case a simple example of this would be:

interface IDbContext
{
   IDbSet<User> Users { get; set; }
}

class AppDbContext : IDbContext
{

}

By doing this you can now inject your context into your services as an interface.  Hurrah!


Nullable Generics - Implementing SequentialSearchST in C# For learning purposes, I am implementing certain code from Sedgewick & Wayne's Algorithms, Fourth Edition.

Because of language features, a direct translation doesn't seem possible.

For example, I believe the get method in their implementation of SequentialSearchST can return null for both value and reference types because Java boxes/unboxes "value objects" (for lack of a better term) like Integer automatically.

C#, as far as I can tell, does not have an equivalent built in. It also does not appear to be possible to put an all-purpose nullable constraint on a generic type.

At least one other person has tried this, but their implementation does not allow you to store reference types for TValue which prevents you from implementing other Algorithms classes like SeparateChainingHashST.

So, I have decided to throw a runtime error in the static constructor below. Is that about as good as it gets? That is, is there no way to throw a compile time error?

public class SequentialSearchSt<TKey, TValue>
{
    private Node first;

    static SequentialSearchSt()
    {
        if (!default(TValue).Equals(null)) throw new InvalidOperationException("TValue must be a nullable or reference type.");
    }

    private class Node
    {
        public TKey key;
        public TValue val;
        public Node next;

        public Node(TKey key, TValue val, Node next)
        {
            this.key = key;
            this.val = val;
            this.next = next;
        }
    }

    public TValue Get(TKey key)
    {
        for (Node x = first; x != null; x = x.next)
        {
            if (key.Equals(x.key))
            {
                return x.val;
            }
        }
        return default(TValue);
    }

    // more code...
}

Consider removing the requirement that default(TValue) is null, and instead of returning null, throw a KeyNotFoundException:

  The exception that is thrown when the key specified for accessing an element in a collection does not match any key in the collection.

For convenience, you may also want to provide a bool TryGetValue(TKey key, out TValue value) method.

If possible, making SequentialSearchSt<TKey, TValue> implement IDictionary<TKey, TValue> will make using the class easier for any .NET developer.


Basic templating engine in F# using F# syntax I've been working on a rough idea for a templating engine (mostly as a learning project) using the F# syntax. How "correct" is my code in terms of being idiomatic F#? Are there F# features which would make the code simpler? More easily understood?

The template files are loaded at runtime using a script I've not posted here The code is also provided as a gist for easier reading.

Template

#r "program.exe"
open System
open Lib

let intToText i = div [] [Text((sprintf "I is %i" i))]

Template (
    html [] [
        div [("id", "123");("class", "me")] [
            div [] [
                Text "SOME TEXT"
            ]
            div [] [
                Text "SOME MORE TEXT"
            ]
            foreach [1;2;3] intToText
            input [("type", "text"); ("value", "1")]
        ]
    ]
)

Lib

module Lib
open System
open System.Text

type Attributes = (string * string) list

type Element =
    | Tag of (string * Attributes * Element list)
    | TagSelfClosing of (string * Attributes)
    | Collection of (Element list)
    | Text of string

let html (attrs:Attributes) el:Element = Tag("html", attrs, el)
let div (attrs:Attributes) el:Element = Tag("div", attrs, el)
let input (attrs:Attributes) = TagSelfClosing("input", attrs)
let foreach data fn =
    let elems = data |> List.map fn
    Collection(elems)

type Token =
    | OPEN_TAG of (string * Attributes)
    | CLOSE_TAG of string
    | SELF_CLOSING_TAG of (string * Attributes)
    | TEXT of string

let Template el =
    let rec expandTree el output =
        match el with
        | Tag(tagName, attrs, children) ->
            let childContent =
                children
                |> List.fold (fun state item -> state @ (expandTree item [])) []

            let addition = [OPEN_TAG(tagName, attrs)]@childContent@[CLOSE_TAG(tagName)]
            output@addition
        | TagSelfClosing(tagName, attrs) ->
            let addition = [SELF_CLOSING_TAG(tagName, attrs)]
            output@addition
        | Collection(elements) ->
            let collectionContent =
                elements
                |> List.map (fun e -> expandTree e output)
                |> List.fold (fun state item -> state@item) []
            output @ collectionContent
        | Text(string) ->
            output@[TEXT(string)]

    let tokenWriter token =
        let attributeWriter (tuple:string*string) =
            let (name, value) = tuple
            sprintf " %s=\"%s\"" name value

        let foldAttributes attrs =
            attrs
            |> List.map attributeWriter
            |> List.fold (fun state item -> state+item) ""

        match token with
        | OPEN_TAG(name, attrs) ->
            let attributes = foldAttributes attrs
            sprintf "<%s%s>" name attributes
        | CLOSE_TAG(name) -> sprintf "</%s>" name
        | SELF_CLOSING_TAG(name, attrs) ->
            let attributes = foldAttributes attrs
            sprintf "<%s%s />" name attributes
        | TEXT(content) -> sprintf "%s" content

    let expandedTree = expandTree el []
    let content =
        expandedTree
        |> List.map tokenWriter
        |> List.fold (fun state item -> state+item) ""

    printf "%s" content

There are a few suggestions which immediately occur to me:  some are minor changes which could improve the clarity of the code and there is one major change which would shorten the code quite a bit.

The minor changes:

For List.fold you can just pass a function which matches the expected type and not write the full lambda.  With an operator like + it's not obvious, but you can clean up your code a bit using:

attrs
|> List.map (fun (name,value) -> sprintf "%s=\"%s\"" name value)
|> List.fold (+) ""

In the function childContent, I would move the call to expandTree into a List.map, to reduce the amount of nesting and to allow us to clean up the List.fold:

children
|> List.map (fun child -> expandTree child [])
|> List.fold (@) []

With Text(string) you should use a name other than string since that's the name of an existing type and that could cause confusion for someone reading your code.

The major change is that you can combine the tokenWriter and the expandTree into a single function.  At the heart, what you are doing is an in order traversal of a tree to convert your HTML structure into a string:  expandTree does an in order traversal to flatten the tree into a list and then tokenWriter converts those tokens into strings.  You're not gaining much by flattening the tree and then generating the output string; so, you could just use the tree traversal to generate the output string.

Making this change also allows you to remove the Token type, further reducing the overall complexity of your code.

Here's the updated code:

    let Template el =
        let rec elementToString el output =
            let attributesToString attrs =
                attrs
                |> List.map (fun (name,value) -> sprintf "%s=\"%s\"" name value)
                |> List.fold (+) ""

            match el with
            | Tag(tagName, attrs, children) ->
                let attributes = attributesToString attrs
                let tagStr = sprintf "<%s%s>" tagName attributes
                let childContent =
                    children
                    |> List.map (fun item -> elementToString item "" )
                    |> List.fold (+) tagStr
                let closeTagStr = sprintf "</%s>" tagName
                sprintf "%s%s%s" output childContent closeTagStr
            | TagSelfClosing(tagName, attrs) ->
                let attributes = attributesToString attrs
                sprintf "%s<%s%s />" output tagName attributes
            | Collection(elements) ->
                elements
                |> List.map (fun e -> elementToString e output)
                |> List.fold (+) ""
            | Text(text) ->
                sprintf "%s%s" output text

        let expandedTree = elementToString el ""
        let content =
            expandedTree

        printf "%s" content


Two bidirectional Software UARTs with AT89S52 microcontroller I have learned one way to read from a serial port via software UART is via timer interrupts. I have made an implementation of receiving data from one serial port below. I haven't tested it yet because I now also need a way to efficiently transmit data as well without causing bad timings since UART is a timer sensitive protocol. If possible, I want to use one timer to manage both UARTs.

The speed I'm aiming for is 9600bps, and my microcontroller has a crystal speed of 22.1184Mhz. Also, is my code optimized or could I optimize it further so that fewer clock cycles are required for serial processing?

  RX equ P3.0 ;receive bit
  TX equ P3.1 ;xmit bit
  sermode equ 23h ;serial mode.
  SWBUF equ 22h     ;stored data
  SWTBUF equ 24h    ;stored data temporarily
  SWI bit 0h    ;1=received valid data

  org 0000h ;machine start
  ljmp startapp

  org 000Bh ;Timer interrupt
  ljmp timerint

  org 0030h

  timerint:
push PSW
mov C,RX ;get bit asap
push ACC
mov TH0,#0FFh ;reset high timer byte
mov A,sermode
jnz serhalfbit
  ;entered every half bit time if sermode=0
  ;do nothing till bit is zero
  jc nostart
    ;set mode to 1
    inc sermode
    ;set access speed to slow
    mov TL0,#040h
    ;prepare to exit
    sjmp extimerint
  nostart:
serhalfbit:
jz serfullbit
  ;this is entered every full bit time if sermode > 0
  jnb ACC.0,noend
    jnb ACC.3,noend
      ;if sermode=9, reset it...
      mov sermode,#0h
      ;set usable buffer to temporary buffer value
      mov SWBUF,SWTBUF
      ;set SWI to stop bit value. 1=valid data...
      mov SWI,C
      ;set access speed to fast
      mov TL0,#0A0h
    sjmp extimerint
  noend:
  ;if sermode=1 to 8, get bit into a buffer and increment mode
  mov A,SWTBUF
  RRC A
  mov SWTBUF,A
  inc sermode
serfullbit:
extimerint:
;common exit from interrupt
pop ACC
pop PSW
  reti

  startapp:
mov P1,#0FFh        ;reset GPIO
mov P3,#0FFh
mov sermode,#0h ;start at beginning
mov TH0,#0FFh
mov TL0,#0A0h   ;9.6kbps half bit time
mov TMOD,#11h   ;16-bit timers
setb PT0        ;timer 0=high priority
setb TR0        ;timer 0 on
mov IE,#81h         ;en Timer 0 int

bigloop:
; --async function here--
jnb SWI,novalid
  clr SWI
  mov A,SWBUF
  ; A=received serial data
novalid:
sjmp bigloop

You can spare a lot of trouble and cycles by configuring P3.0 as an interrupt source. This way start bit detection would not require constant polling.
I don't see why do you test ACC.0.
sermode is really a baud counter. Consider renaming.
I strongly recommend to sample each baud 3 or 5 times, and signal an error if samples disagree.
For testing the receiver, use a real RS232 part to transmit data. You may also want to set aside a spare pin, let the timer interrupt to toggle it, and observe the waveform on a scope.


Find indices using for loop I should estimate the effect of B fields on particle deflection using \$F=V \times B \times Force\$.

I have a 2D mesh with \$n_x\$ and \$n_y\$ which show the number of points in each direction. \$B\$ is the magnetic field which is a 2D mesh arrays (with dimension \$n_x \times n_y= 1600 \times 900 = 1440000\$) and \$V\$ is the velocity of particles and is a 1D array (with dimension 431605462). I also have two 1D arrays (with the same dimension as the \$V\$ array) which show the x and y coordinates of each particles. I called them grid_pro_x and grid_pro_y.

Since \$V\$ is a 1D array and \$B\$ is a 2D array I can not directly multiply \$V\$ with \$B\$. To solve this issue I created a 2D zero array for the \$V\$ and using 2 for-loops I find particles which stand in each cell of the mesh. I consider the average velocity of all particles as a velocity component of each cell. Because of the large dimensionality of the mesh, if I keep the original dimension, the code needs several days to complete the \$V\$ array since it needs to be repeated 1440000 times. As a solution, I compressed \$V\$ with an optional variable called divider. If I use divider = 10 I guess the code needs 2 days to be finished and if I use divider = 100 the code will be finished in half an hour but now the precision of the results reduces significantly.

You can see the code in the following.

nx,ny= 1600, 900

xmin = -30.0e-6
xmax =  50.0e-6

ymin = -45.0e-6
ymax = 45.0e-6

#### create a 2D  velocity array

divider = 100
m_p= 1.6726219e-27   #  (kg unit)  proton mass

nx_new = nx/divider
ny_new = ny/divider

Vx = np.zeros((ny_new, nx_new))
Vy = np.zeros((ny_new, nx_new))

res_x = (xmax - xmin)/nx_new   # resolution in x direction
res_y = (ymax - ymin)/ny_new   # resolution in y direction

  #   Find corresponding indices

for i in range( 0,ny_new ):
  for j in range(  0,nx_new):

    xx = i*res_x
    yy = j*res_y

##### all particles with different Px confined in a specific cell

    Px_pro_lim = Px_pro[(grid_pro_x >=  xx ) & (grid_pro_x < xx+res_x ) & (grid_pro_y >=  yy ) & (grid_pro_y < yy+res_y ) ]

    Vx[i,j] = np.mean(Px_pro_lim)/m_p
#print 'Vx[i,j]= ' ,Vx[i,j]

If you are trying to make it fast, the last thing to do is drop into Python for-loops.  Keep it all in numpy as much as possible.

The code below maps the particles to the mesh and calculates the mean v for all the particles in each mesh square.  With 400M particles having random x,y, and v on a 1600x900 size mesh, it runs in about 100 seconds on my laptop.

xi = np.digitize(x, np.linspace(xmin, xmax, nx, endpoint=False)) - 1
yi = np.digitize(y, np.linspace(ymin, ymax, ny, endpoint=False)) - 1

flat_index = nx*yi + xi

counts = np.bincount(flat_index)

vsums = np.bincount(flat_index, weights=v)

means = (vsums / counts).reshape(nx,ny)

np.digitize(x, bins) maps values the values in the array x, to ints based on the values in bins.  x < bin[0] maps to 0; bin[0] <= x < bin[1] maps to 1; and so on.  The endpoints=False makes sure the indices go from 1 to 1440000 instead of 1 to 143999; and the -1 shifts it to 0 to 1439999.

np.linspace(start, end, nsteps) divides the range [start, end) in to nstep even intervals.  This is used to define the bins for np.digitize().

nx*yi + xi basically converts the x and y indices to a 1D index from 0 to 1439999, because bincount only works on 1D arrays

np.bincount(z, weights) if weights is omitted, this counts the number of occurrences of each integer in z (like a histogram).  If provided, weights is an array of the same dim as z, the values of the corresponding weights are summed instead of just counting the integers.  So setting weights to v, sums the velocity of each particle in a mesh square.

(sums / counts).reshape(nx,ny) calculates the means and reshapes the result into the 1600x900 mesh.


Testing a template function in GoLang using mocking - making it DRY & easy to follow TL;DR
I'm wondering how to organise test functions using mocks for GoLang drier & easier to follow.
Function
I have a template function that is very similar to ACF's getField:

It take's in a string (field name) & the post ID.
It checks if the ID exists and the obtains the post by ID (the f.store.Posts belongs to the fields struct)
If the post doesn't exist or if the fields could not be unmarshalled it will return an empty string.

func (f *fields) getField(field string, id ...int) interface{} {

    fields := f.fields
    if len(id) > 0 {
        post, err := f.store.Posts.GetById(id[0])
        if err != nil {
            return ""
        }
        var m map[string]interface{}
        if err := json.Unmarshal(*post.Fields, &m); err != nil {
            return ""
        }
        fields = m
    }

    val, found := fields[field]
    if !found {
        return ""
    }

    return val
}

Testing
From the function, presumably I need to test if, The post exists, the json could be unmarshalle or if the field exists.
I have started to use github.com/golang/mock/gomock but am finding it confusing!
In each of the test functions below I create a new controller and mockPost, add assigning the fields Post to it.

func TestGetField(t *testing.T) {
    f, err := helper(`{"text": "content"}`)
    if err != nil {
        t.Error(err)
    }

    if field := f.getField("text"); field == "" {
        t.Errorf(test.Format("content", nil))
    }

    if field := f.getField("wrongval"); field != "" {
        t.Errorf(test.Format("", field))
    }
}

func TestGetField_Post(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    data := []byte(`{"posttext": "postcontent"}`)
    mockPost := domain.Post{
        Id:     2,
        Fields: (*json.RawMessage)(&data),
    }

    posts := mocks.NewMockPostsRepository(controller)
    f.store.Posts = posts
    posts.EXPECT().GetById(2).Return(mockPost, nil)

    field := f.getField("posttext", 2)
    if field != "postcontent" {
        t.Errorf(test.Format("postcontent", field))
    }
}

func TestGetField_No_Post(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    posts := mocks.NewMockPostsRepository(controller)
    var mockErr = fmt.Errorf("No post")
    posts.EXPECT().GetById(gomock.Any()).Return(domain.Post{}, mockErr)
    f.store.Posts = posts

    field := f.getField("text", 1)

    if field != "" {
        t.Errorf(test.Format("", field))
    }
}

func TestGetField_Invalid_JSON(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    data := []byte(`"text "content"`)
    mockPost := domain.Post{
        Id:     1,
        Fields: (*json.RawMessage)(&data),
    }

    posts := mocks.NewMockPostsRepository(controller)
    posts.EXPECT().GetById(1).Return(mockPost, nil)
    f.store.Posts = posts

    field := f.getField("text", 1)
    if field != "" {
        t.Errorf(test.Format("", field))
    }
}

Feedback

Without using the mock package, how would you approach this?
Are there any areas for improvement with the current codebase?
Is there away to consolidate any of the testing methods? It seems quite long winded for such a short function

I don't know exactly what your fields type is, but from the code you've shared, there's a couple of strong recommendations I'd like to make about the code itself, before getting in to the testing aspect.
post, err := f.store.Posts.GetById(id[0])

From this line, and the fact that you're mocking store, I'm deducing your fields constructor looks something like this:
func New(store SomeStoreT) *fields {
    return &fields{
        store: store,
    }
}

Because you're accessing store.Posts directly, the SomeStoreT is going to be the actual type, complete with exposed fields. This means you can't really mock the store type as a whole, you have to ensure that whatever the exported fields are, is safe for concurrent use, and that no other code either on purpose or accidentally assigns anything to said fields. An extreme example would be:
func main () {
    store := storage.New()
    f := fields.New(store)
    store.Posts = nil
    f.GetPosts() // panic
}

It's therefore better to either replace the store dependency with an interface that exposes what you need through getters, so the fields needn't be exported. It'd be as simple as changing the line
post, err := f.store.Posts.GetById(id[0])

to:
post, err := f.store.Posts().GetById(id[0])

Still, there's something that I find a lot more disturbing than this: the use of interface{} and the json.Unmarshal() calls. Your store field has a Posts field. That tells me you know what data you're fetching, or saving. Why would you let code other than the storage layer deal with the marshalling and unmarshalling of that data? Your code should pass around a type that represents a post, and it's the job of the storage layer to handle the marshalling. If you decide JSON isn't the right format, and want to opt for something faster (like a binary format), or you want to switch to a completely different type of DB like Postgres, then you don't want to be forced to change the code throughout your application. You just should be able to swap out you storage adapter, optionally change the tags on the data types, and update the package to handle the new marshalling and be done with it:
package domain

type Post struct {
    ID      int    `json:"id"` // preferred ID in all-caps
    Content string `json:"content"`
}

Then, in the storage package:
package storage

type Posts struct {
    // whatever fields to access the storage used
}

func (p *Posts) GetByID(id int) (*domain.Post, error) {
   record, err := p.db.Get(id) // whatever you need to do here
   if err != nil {
      return nil, err
   }
   ret := domain.Post{}
   if err := json.Unmarshal(record, &ret); err != nil {
       return nil, err
   }
   return &ret, nil
}

So with this, you can change your function in fields to not have to do any unmarshalling at all. It's all handled in the storage. Now, getting a field by string isn't possible with this code, of course. I'm not sure of that's actually a good idea, but that's more of an X-Y problem. You can quite easily implement something that makes getting fields by string ridiculously easy, in fact. All you need to do is create a wrapper type and custom unmarshalling:
package domain

type Post struct {
    PostRecord // embedded struct
    postMap map[string]interface{}
}

type PostRecord struct {
    ID      int    `json:"id"`
    Content string `json:"content"`
}

func (p *Post) UnmarshalJSON(data []byte) error {
    // unmarshal into embedded type
    if err := json.Unmarshal(data, &p.PostRecord); err != nil {
        return err
    }
    if err := json.Unmarshal(data, &p.postMap); err != nil {
        return err
    }
    return nil
}

func (p Post) MarshalJSON() ([]byte, error) {
    return json.Marshal(p.PostRecord) // marshal the embedded type
}

func (p Post) GetField(f string) (interface{}, bool) {
    v, ok := p.postMap[f]
    return v, ok
}

Now your fields function would look something like this:
// you're only ever using `id[0]`, so I don't understand the variadic argument here
// it's also important to note that there's a lot of calls that can error happening here
// and you need to return those errors. It'll make debugging a lot easier
func (f *fields) getField(field string, id int) (interface{}, error) {
    post, err := f.store.Posts().GetByID(id)
    if err != nil {
        return nil, err
    }
    v, ok := post.GetField(field)
    if !ok {
        return nil, errors.New("unknown field for post type")
    }
    return v, nil
}

You'll note that I'm returning nil in case of an error. That's because an empty string is the nil value for a string, but it could just as well be a valid value for an existing record in some cases. It's best to indicate an error by returning said error, and nil for values that are just not defined. If a field doesn't exist, it has no value, and so nil is the only correct thing to return. Of course, the nil value for an int is 0, and an empty string for a string, but your function looks to me like it's written to be non-type-specific. If the Post type had a timestamp field, stored either as time.Time or int64, and you don't return an error, just an empty string, then the caller might do something like this:
tval := fields.getField("timestamp", 123)
ts, ok := tval.(int64)
if !ok {
    return errors.New("invalid timestamp value")
}

Now why is the timestamp value invalid? Becuase the field didn't exist (a typo in the string I passed)? Because the ID doesn't exist? Or because the timestamp field has since been updated to another type? I don't know...
This also assumes that the caller has the sense to check whether the type assertion worked. There's no reason why the caller might just have:
ts := tval.(int64)
and continue to use ts assuming it was the correct value, while in reality it'll default to 0. Write your functions to account for sloppy use. Errors are more likely to be checked than boolean indicators. Return values should be unequivocal when it comes to distinguishing between an error and success. An emtpy string is a perfectly valid return value on success, so don't rely on it to communicate failure.

I'll update this review gradually. I think this is a reasonable amount of information to digest, and get to work with. I've written all of the code snippets above off the cuff, untested, etc... there may be typo's and omissions, so don't assume they're copy-paste ready.

TL;DR answers to your questions

You have to mock dependencies in unit tests. that's what unit tests are/do
I've started this review with some suggestions/recommendations to improve on your code - so yes, there are things that you can do there
with the changes I've proposed, the getFields function is basically a call to the storage package (which is tested separately), and a call on the domain object's GetField function, which is something you unit-test separately. you can still write tests for the function here, but it's just having a mock return either an error or a Post instantce, which you can hard-code in your test. It's far less cumbersome to set up, and test as a result.


Computing a mathematical function in MIPS assembly This code computes the function (3x^2-4x+16) / (5x^2+2x-4). I ran the program and it works, but I am fairly new to assembly language and am not quite sure how to make the most efficient use of the registers.  Does this look ok or is there a better way to do it?

.text
.globl  main

main:
ori      $8, $0, 3         #put x into $8
ori      $9, $0, 3         #puts 3 into $9
ori      $10, $0,  4       #puts 4 into $10
ori      $11, $0, 16       #puts 16 into $11

mult     $8, $8            #Squares x
mflo     $13               #$13 = x^2
mult     $9, $13           #Computes 3x^2
mflo     $14               # $14 = 3x^2
mult     $10, $8           # lo = 4x
mflo     $15               # $9 = 4x
sub      $16, $14,  $15    # $16 = 3x^2 -4x
add      $17, $16,  $11    #$17 = 3x^2 - 4x + 16

ori      $8, $0, 1         #put x into $8
ori      $9, $0, 5         #puts 5 into $9
ori      $10, $0,  2       # put 2 into $10
ori      $11, $0, 4        # puts 4 into $11

mult     $8, $8            #Squares x
mflo     $13               #$13 = x^2
mult     $9, $13           #Computes 5x^2
mflo     $14               # $14 = 5x^2
mult     $10, $8           # lo = 2x
mflo     $15               # $9 = 2x
add      $16, $14,  $15    # $16 = 5x^2 +4x
sub      $18, $16,  $11    #$17 = 5x^2 + 2x - 4

div      $17, $18          #divides 2 functions
mflo     $8                #quotient
mfhi     $9                #remainder
## End of file

There are multiple issues:

first, try to make the program work: These two lines are contradictory

ori      $8, $0, 3         #put x into $8
ori      $8, $0, 1         #put x into $8

Perhaps the real idea is to move a function parameter to $8.

The second thing is redundant calculation:
Instead of squaring x twice, you should be able to

mul $8, $8
mflo $13
mflo $14

To catch the result in two registers.

There's no need to reserve registers for all the immediates, as one can at least add the last coefficients 16 and (-4) with

addi $x, $x, 16

Multiplications with small constants are also often better executed with a series of shifts and adds. Especially here x*4 equals x<<2 and x*2 == x+x, which leads to one less instruction for both operations.


Complex data structure organization in javascript? Upon suggestion in the original question within Stack Overflow, I'm bringing this question here.

Question Explained:

In a website that I built, I used complex multidimensional arrays to organize a multitude of information tables linked to events. I want to know if what I did was a viable efficient solution for the specific situation, or if something else would have made more sense, like using database tables or take an object oriented approach.

This is what I did:

I built a set of dropdown menus with javascript, The first list (category) determined what items where shown on the second list (service). If the user hovered over a category, the correlating services were displayed on the second list. If the user selected a service, a list of items in that service where shown in another part of the page(itemlist). Each item on the itemlist had unique values, prices, and 2 possible types, either check boxes or numerical entries.

Hopefully that will make the following array examples make sense. All you need to know further about these arrays is that they correlate to achieve the above result.

the below array is in image form for your convenience. Stack Overflow refused to keep my formatting, making it unreadable.

There are over 20 copies of this (above) array item with different services.

  ServiceArray[0][0]:
  [0]is the id to be assigned to the element.
  ['1]is text name to be outputted.
  ['2]is a variable name to be assigned.
  ['3]is a key value to be appended to each item so I can call on a correlating value in the first array set.
  ['4]is an example to be listed

the downsides to this approach are obvious. The complex array structures become difficult to manage. When working with the variables, I had to continuously recount each variable to find the array keys. In the end though, i was able to use this approach very dynamically for the drop-downs and service lists. Here are a few examples of the code used to dynamically generate the content with these arrays.

$(".dropdown-service > p").click(function () {
    var thisKey = $(this).data("key");
    $("#ServiceOutput").text($(this).text());
    $(".layer4").append('
');
    for (var i = 0; i < ServiceArray[Category][thisKey][4][1][5].length; i++) {

        var listId = ServiceArray[Category][thisKey][6][1][i][7];
        var listTitle = ServiceArray[Category][thisKey][8][1][i][0];
        var List = "";

        for (var x = 0; x < ServiceArray[Category][thisKey][9][1][i][10].length; x++) {
            var Time = ServiceArray[Category][thisKey][11][1][i][12][x][13];
            var Content = ServiceArray[Category][thisKey][14][1][i][15][x][0];
            var Hours = ServiceArray[Category][thisKey][16][1][i][17][x][18];
            List += '

' + Content + ' ('+ Hours +'Hrs)

';
        }

        $(".layer4").append('

' + listTitle + '

' + List + '

');
    }
    $(".layer4").append('
');
});

So the ultimate question:

Is this method the best for the specific situation, or could I have done something more efficient to save time an effort while achieving the same result?

While there's nothing completely wrong with what you did, if I were the programmer coming in behind you - I would certainly curse your name.  Writing "good" code (to me of course) requires more than meeting the objectives.  Readability and maintainability are just as important.

My concern with your design didn't set in until I saw the sample code to build the menu. Seeing all those brackets and indexes just about melted my brain.  I think if you would use object literals rather than straight arrays then my problems go away as it should then be much more readable and straight forward.


Write your implementation of Ruby's String#count method The task is to write a simplified version of Ruby's String#count method oneself. Simplified because it doesn't have to have the negation and sequence parts of the original.
Here my solution:
def custom_count(string, search_char)
    sum = 0
    seg_string = string.split("")
    seg_char = search_char.split("")

    for i in seg_string
        for j in seg_char
            if i == j
                sum += 1
            end
        end
    end

    sum
end

p custom_count("Hello, World!", "l")    # => 3
p custom_count("Hello, World!", "lo")   # => 5
p custom_count("Hello, World!", "le")   # => 4
p custom_count("Hello, World!", "x")    # => 0
p custom_count("Hello, World!", "w")    # => 0
p custom_count("Hello, World!", "W")    # => 1

Is there a better way to solve the task? Perhaps without using nested loops?

If you can use some ruby String method I would suggest
def custom_count(string, search_char)
  search_char.split("").inject(0) do |count,pattern|
    string.scan(pattern).size + count
  end
end


Calling synchronous code in asynchronous method I'm implementing an interface with the async method Execute. In this I need to call some synchronous code. (removing an item from a dictionary). What would be the best way to go about this?

Alternative 1.

internal class ClearClaimByClaimIdCache : IListenTo<ClaimStatusChangedEvent>
{
        private readonly ICache<Guid, Claim> _cache;

        public ClearClaimByClaimIdCache(ICacheFactory cacheFactory)
        {
            _cache = cacheFactory.GetOrCreateCache<Guid, Claim>("ClaimByClaimId");
        }

        public Task Execute(ClaimStatusChangedEvent @event)
        {
            _cache.Remove(@event.ClaimId);
            return Task.CompletedTask;
        }
}

Alternative 2.

public Task Execute(ClaimStatusChangedEvent @event)
{
    return Task.Run(() => _cache.Remove(@event.ClaimId));
}

Alternative 3.

public async Task Execute(ClaimStatusChangedEvent @event)
{
    await Task.Run(() => _cache.Remove(@event.ClaimId));
}

Or any better way?

If it's really just removing an item from a dictionary (and not e.g. doing synchronous file IO), then Alternative 1 is the best.

When you're using async for scalability (e.g. in ASP.NET), using Task.Run() like this won't help you (since the number of threads used stays the same), it will only hurt you a bit (since Task.Run() has some overhead).

When you're using async for responsiveness (e.g. in GUI applications), using Task.Run() like this can make sense, but only for long-running operations (MS recommendation is operations that can take more than 50 ms). Since dictionary operations shouldn't take long you shouldn't use Task.Run() here either.


Rearrange elements in two-dimensional array spiral order Recently I was asked to write algorithm to rearrange elements in two-dimensional array in spiral order.

Input array:                    Output array:

[  1,  2,  3,  4]           [  1,  2,  3,  4 ]
[  5,  6,  7,  8]    = >    [  8, 12, 11, 10 ]
[  9, 10, 11, 12]           [  9,  5,  6,  7 ]

I came up with the following solution using JavaScript:

(function(){
var Spiralify = function(matrix){
    function isArray(obj){
        return Object.prototype.toString.call(obj) === '[object Array]'
    }

    //Matrix is not specified or not an array
    if( !matrix || !isArray(matrix) ) { console.log('Matrix is not an array'); return; }

    var rows = matrix.length;
    if( rows <= 1 ) return matrix;
    //If first element of matrix is not an array, we cant define amount of columns in matrix, so just wrap it in array and return
    if(!isArray(matrix[0])) return [matrix];

    var cols = matrix[0].length;
    //If rows of the matrix are empty arrays, return null
    if( cols == 0 ) return matrix;

    //If arrays, corresponding to rows, have different amount of elements, return null
    if(matrix.some(function(el){ return el.length != cols; })) { console.log('All rows must have equal amount of columns'); return; }

    //If we have only one column, just transpond the array and wrap it into another array
    if( cols == 1) return [matrix.map(function(i){ return i[0]; })];

    function getUpperCorner(r1,c1,r2,c2)
    {
        for(var i=c1;i<=c2;i++)
            tmpArray.push(matrix[r1][i]);

        for(var j=r1+1;j<=r2;j++)
            tmpArray.push(matrix[j][c2]);

        if(r2-r1 > 0)
            getLowerCorner(r1+1,c1,r2,c2-1);
    }

    function getLowerCorner(r1,c1,r2,c2)
    {
        for(var i=c2;i>=c1;i--)
            tmpArray.push(matrix[r2][i]);

        for(var j=r2-1;j>=r1;j--)
            tmpArray.push(matrix[j][c1]);

        if(r2-r1 > 0)
            getUpperCorner(r1,c1+1,r2-1,c2);
    }

    var tmpArray = [];
    getUpperCorner(0,0,rows-1,cols-1);

    var result = new Array(rows);
    for(var i=0;i<rows;i++)
        result[i] = tmpArray.splice(0,cols);

    return result;
}

var matrix1 = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]];
var matrix2 = [[1,2,3,4,5],[6,7,8],[11,12,13,14,15]];
var matrix3 = [[1,2,3,4]];
var matrix4 = [[1],[2],[3],[4],[5],[6]];
var matrix5 = null;
var matrix6 = 1234;
var matrix7 = [];
var matrix8 = [[],[],[]];
var matrix9 = [1,2,3,4];
var matrix10 = 'Hello';

console.log (Spiralify(matrix1));
console.log (Spiralify(matrix2));
console.log (Spiralify(matrix3));
console.log (Spiralify(matrix4));
console.log (Spiralify(matrix5));
console.log (Spiralify(matrix6));
console.log (Spiralify(matrix7));
console.log (Spiralify(matrix8));
console.log (Spiralify(matrix9));
console.log (Spiralify(matrix10));
})(window);

But this solution was a show-stopper. I'm trying to learn from the defeat and would really appreciate some feedback on why this code is unappropriate.

I'm not sure what exactly about your code made it a "show-stopper." Your use of tmpArray has a bit of a smell to it. There are issues of readability (why does the line for(var i=c1;i<=c2;i++) only have one space in it??). Your core algorithm (getUpperCorner and getLowerCorner) isn't documented and is fairly hard to read.

Personally, though, I would have approached this as a straight recursion problem. So you have the following matrix:

 1  2  3  4
 5  6  7  8
 9 10 11 12

Your "spiral" begins with the the top row, 1 2 3 4. So chop that off and save it.

   1  2  3  4
✂ ┄┄┄┄┄┄┄┄┄┄┄┄
   5  6  7  8
   9 10 11 12

Now you'll notice that the rightmost column of the remaining part, 8 12, is the next part of the spiral. But what if we turn it 90º counter-clockwise?

 5  6  7  8  =>   8 12
 9 10 11 12       7 11
                  6 10
                  5  9

Now 8 12 the top row! Chop it off and repeat:

   8 12
✂ ┄┄┄┄┄┄
   7 11  =>  11 10  9  =>    11 10  9
   6 10       7  6  5     ✂ ┄┄┄┄┄┄┄┄┄┄
   5  9                       7  6  5  =>  5  =>   5
                                           6    ✂ ┄┄┄
                                           7       6  =>  6  7  (end!)
                                                   7

By now you've seen the pattern. To get a matrix's "spiral" you just take off the top row, rotate what's left, then get its spiral, and so on.

Def Spiralify( Matrix )
  If( Matrix has only one row )
    Return( the row )

  Else
    FirstRow     := first row of Matrix
    RestOfMatrix := all of Matrix except the first row

    NextMatrix := RotateLeft( RestOfMatrix )

    NextSpiral := Spiralify( NextMatrix )

    Result := JoinArrays( FirstRow, NextSpiral )

    Return( Result )

RotateLeft will actually make up the most lines of code, but it's just a straightforward nested loop, and the rest basically writes itself.

Update

I had some time to write up an actual implementation. Rather than paste it here you can check it out on jsFiddle.


Pseudoportable C script pattern (See the next iteration.)

From time to time, while working with a command line in *nix family of operating systems, we have to write those scripts doing a rather specific task. Usually we use bash + utility programs to do the job. However, I had to ask myself: how to implement such a script in C? After an invocation of such a script, it should perform the following:

Create a temporary source file \$S\$,
Dump the C code to \$S\$,
Compile \$S\$ to the program \$P\$,
Run \$P\$ passing the arguments to it and caching its exit status,
Remove \$S\$ and \$P\$,
Return the cached exit status of \$P\$.

Code

#! /bin/bash

# Below, XXXX asks for random characters in order to make a unique file name.
# Mac OSX seems to ignore XXXX, yet Ubuntu requires them.

# Create a temporary file name for the source code:
TMP_SOURCE_FILE="$(mktemp -t sourceXXXX).c"
# Create a temporary file name for the executable file:
TMP_PROGRAM_FILE="$(mktemp -t programXXXX)"

# Write the source code into the temporary source file:
cat > $TMP_SOURCE_FILE <<- END_OF_SOURCE
#include <stdio.h>

int main(int argc, char* argv[])
{
    int i;

    puts("Hello, world! I am a pseudoportable C program.");
    for (i = 1; i < argc; ++i)
    {
        printf("Argument %d: %s\n", i, argv[i]);
    }

    return argc - 1;
}
END_OF_SOURCE

# Compile and run:
gcc $TMP_SOURCE_FILE -o $TMP_PROGRAM_FILE
$TMP_PROGRAM_FILE $@
EXIT_STATUS=$?

# Clean the source and the binary:
rm $TMP_SOURCE_FILE
rm $TMP_PROGRAM_FILE

# Delegate the exit status of the C program to calling bash:
exit $EXIT_STATUS

So, what do you think? How can I improve anything? Also, can you come with an example of the situation where this "C script" pattern is more preferable than bash + command line utilities, Python, etc.?

It's not guaranteed that $TMP_PROGRAM_FILE is on the $PATH, so you need to either set the $PATH or use an absolute path for $TMP_PROGRAM_FILE.

You have problems with mktemp.

-t option: It means different things on GNU/Linux mktemp(1) and Mac OS X mktemp(1).

On GNU/Linux:

-t    interpret TEMPLATE as a single file name component,
      relative to a directory: $TMPDIR, if set; else the
      directory specified via -p; else /tmp [deprecated]

On OS X:

mktemp [-t prefix] template …
mktemp -t prefix

    -t prefix
            Generate a template (using the supplied prefix and TMPDIR if set) to create a filename tem-plate. template.
            plate.

Perhaps the confusion is the reason why the GNU/Linux man page indicates that it is deprecated.  I think you just want to run mktemp TEMPLATE without the -t option.
Cleanup: Use trap "rm $TMP_SOURCE_FILE $TMP_PROGRAM_FILE" EXIT as a more robust way to delete the temporary files, in case your script aborts before reaching the rm commands.
.c suffix:  By writing TMP_SOURCE_FILE="$(mktemp -t sourceXXXX).c", you end up getting mktemp to create the file sourceXXXX.  That file does not get cleaned up.  Also, when you do cat > $TMP_SOURCE_FILE, you may be creating sourceXXXX.c, or worse, truncating an existing file.

On GNU/Linux, a remedy would be to use the --suffix .c option.  Unfortunately, the BSD/OS X version doesn't support it.  One workaround is to rename the file after creation using mv -i — which might fail, but at least it's secure.

A better workaround would be to use gcc -x c to tell GCC that it is C source code, without considering the filename extension.

An even better solution would be…
Avoid $TMP_SOURCE_FILE altogether: gcc can take its source code from its standard input!  Use - as the filename.

gcc -o "$TMP_PROGRAM_FILE" -x c - <<- END_OF_SOURCE
…
END_OF_SOURCE