texts: Constructor to transform an Outlook contact into a Dynamics CRM contact

texts:
This is my constructor to transform an Outlook contact into a Dynamics CRM contact:

public Contact(ContactItem contactItem)
{
    LogicalName = EntityLogicalName;
    FirstName = contactItem.FirstName;
    LastName = contactItem.LastName;
    //if no last name, use the first name
    if (String.IsNullOrEmpty(LastName))
    {
        LastName = contactItem.FirstName;
        //if no First name, use the Full Name.
        if (String.IsNullOrEmpty(LastName))
        {
            LastName = contactItem.FullName;
            //if no last name or first name, use the company name
            if (String.IsNullOrEmpty(LastName))
            {
                LastName = contactItem.CompanyName;
                //If no last name, no first name and no company name, use the email address.
                if (String.IsNullOrEmpty(LastName))
                {
                    LastName = contactItem.Email1Address;
                    //if no Last name, no first name, no company name, no email address, default to naam niet bekend.
                    if (String.IsNullOrEmpty(LastName))
                    {
                        LastName = @"Naam niet bekend";
                    }
                }
            }
        }
        else
        {
            FirstName = "";
        }
    }

    Address1_City = contactItem.BusinessAddressCity;
    Address1_Country = contactItem.BusinessAddressCountry;
    Address1_Line1 = contactItem.BusinessAddressStreet;
    Address1_PostalCode = contactItem.BusinessAddressPostalCode;
    Telephone1 = contactItem.BusinessTelephoneNumber;
    Telephone2 = contactItem.HomeTelephoneNumber;
    Fax = contactItem.BusinessFaxNumber;
    Address2_Line1 = contactItem.HomeAddressStreet;
    Address2_City = contactItem.HomeAddressCity;
    Address2_PostalCode = contactItem.HomeAddressPostalCode;
    Address2_Country = contactItem.HomeAddressCountry;
    EMailAddress1 = contactItem.Email1Address;
    EMailAddress2 = contactItem.Email2Address;
    EMailAddress3 = contactItem.Email3Address;
}

As you can see, I got 5 nested ifs to determine what I should use for LastName. I don't like how it looks, but the only other option I can see is putting them in sequence instead of nested. However, that would mean that instead of usually having only 1-3 ifs, it would be forced into doing 5 ifs every single time. during tests with 1800 records, it already felt noticeably slower if it got to the literal string.

Is there some really easy way (or some really obscure way) of doing this which I missed?


texts: Getting time since Unix epoch on both Windows NT and *NIX systems

texts:
The following snippet of C includes implementations for both Windows NT and POSIX-compliant systems to get the time (with microsecond resolution) since the Unix epoch. In the case of Windows NT, the time is registered as 100-nanosecond ticks since the NT epoch (1/1/1601), so it requires a bit of conversion.

I feel like this is the best solution I could've come up with, but it still feels a bit clunky. See if you can help:

#if defined(__unix__) || defined(unix) || defined(__unix) || defined(__CYGWIN__)
#include <sys/time.h>
static struct timeval lnm_current_time;
#elif defined(_WIN32) || defined(__WINDOWS__)
#include <windows.h>
#include <sysinfoapi.h>
static FILETIME lnm_win32_filetime;
#else
#error lognestmonster: Neither Windows NT nor a POSIX-compliant system were detected.\
        Implement your own system time functions or compile on a compliant system.
#endif

uint64_t lnm_getus(void) {
    uint64_t us;
#if defined(__unix__) || defined(unix) || defined(__unix) || defined(__CYGWIN__)
    gettimeofday(&lnm_current_time, NULL);
    us = (lnm_current_time.tv_sec*1000000+lnm_current_time.tv_usec);
#elif defined(_WIN32) || defined(__WINDOWS__)
    // get system time in ticks
    GetSystemTimeAsFileTime(&lnm_win32_filetime);
    // load time from two 32-bit words into one 64-bit integer
    us = lnm_win32_filetime.dwHighDateTime;
    us = us << 32;
    us |= lnm_win32_filetime.dwLowDateTime;
    // convert to microseconds
    us /= 10;
    // convert from time since Windows NT epoch to time since Unix epoch
    us -= 11644473600000000ULL;
#endif
    return us;
}
```


texts: TapeEquilibrium implementation does not satisfy all requirements

texts:
The Codility's TapeEquilibrium problem asks:

  Given an array \$A\$ with length \$N\$, indexed starting from 0, find an equilibrium index \$P\$, such that

  $$\left| \sum_{i=0}^{P-1} a_i - \sum_{i=P}^{N-1} a_i \right|$$

  is minimized.  Assume that \$2 \le N \le 100000\$ and that \$-1000 \le a_i \le 1000\$.  Elements of input arrays can be modified.

Here is my solution:

 public int solution(int[] A)
 {
        // write your code in C# 5.0 with .NET 4.5 (Mono)
        List<int> list = A.Cast<int>().ToList();
        int temp = 0;
        int sum = list.Sum();
        List<int> result = new List<int>();
        foreach (int i in list)
        {
             temp = temp + i;
             result.Add(Math.Abs(  ( sum - temp) - temp));

        }
        return  result.Min();
    }

How can I make it better?  I only got 83%.


texts:
I need feedback on my Bootstrap for the MVC architecture that I follow.
I load the routes via yaml. Here is an example:

feed:
    path: /{controller}/{action}{slash}
    requirements:
        id: "[1-9][0-9]*"
        slash: "[/]{0,1}"
    methods: [GET,POST]

#Explore Controller
explore:
    path: /{controller}{slash}
    requirements:
        id: "[1-9][0-9]*"
        slash: "[/]{0,1}"
    methods: [GET,POST]

And here is my Bootstrap class:

class Bootstrap
{

    public function __construct()
    {
        $request = Request::createFromGlobals();
        $locator = new FileLocator(__DIR__ . '/../../../config');

        // DI container
        $container = new DependencyInjection\ContainerBuilder;

        $loader = new DependencyInjection\Loader\YamlFileLoader($container, $locator);
        $loader->load('config-development.yml');

        $container->compile();

        // routing
        $loader = new Routing\Loader\YamlFileLoader($locator);
        $context = new Routing\RequestContext();
        $context->fromRequest($request);
        $matcher = new Routing\Matcher\UrlMatcher(
            $loader->load('routing.yml'),
            $context
        );

        try{
            $parameters = $matcher->match($request->getPathInfo());

            foreach ($parameters as $key => $value) {
                $request->attributes->set($key, $value);
            }

            $command = $request->getMethod() . $request->get('action');
            $resource = "controller.{$request->get('controller')}";

            $controller = $container->get($resource);
            $data = $controller->{$command}($request);

        }catch(\Error $e){
            $data = [
                'status'=>404,
                'message'=>'Not found',
                'info'=>$e->getMessage()
            ];
        }catch(\Symfony\Component\Routing\Exception\MethodNotAllowedException $e){
            $data = [
                'status'=>404,
                'message'=>'Not found',
                'info'=>$e->getMessage()
            ];
        }catch(ResourceNotFoundException $e){
            $data = [
                'status'=>404,
                'message'=>'Not found',
                'info'=>$e->getMessage()
            ];
        }

        if(is_array($data)){
            $response = new JsonResponse($data);
        }else{
            $response = new Response($data);
        }

        //Set cors headers
        $response->headers->set('Access-Control-Allow-Origin', '*');
        $response->headers->set('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
        $response->headers->set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
        $response->headers->set('Access-Control-Allow-Credentials', 'true');

        $response->send();
    }

I load the controllers and services via yaml. I'm interested if you would change anything and if you see any possible issues that this kind of structure might have.

I'm seeking for improvements in my code.


texts:
I'm trying to automate entity reading in my yesod application.

This is what I have:

withEntity
  :: ( PersistEntity a
     , YesodPersistBackend site ~ PersistEntityBackend a
     , PersistStore (YesodPersistBackend site)
     , YesodPersist site )
  => String
  -> Key a
  -> (Entity a -> ExceptT Text (HandlerT site IO) b)
  -> ExceptT Text (HandlerT site IO) b
withEntity what key f =
  do mrec <- lift . runDB . get $ key
     case mrec of
       Nothing  -> throwError . pack $ "unknown " ++ what
       Just rec -> f (Entity key rec)

Users of my application may send a request for data in DB using integer ID instead of Key a. So I have a wrapper around withEntity:

withEntitySql
  :: ( PersistEntityBackend a ~ SqlBackend
     , ToBackendKey SqlBackend a )
  => String
  -> Int64
  -> (Entity a -> ExceptT Text (HandlerT App IO) b)
  -> ExceptT Text (HandlerT App IO) b
withEntitySql what key f = withEntity what (toSqlKey key) f

This way I can write functions specifying error messages when record doesn't exist:

withA
  :: Int64
  -> (Entity A -> ExceptT Text (HandlerT App IO) a)
  -> ExceptT Text (HandlerT App IO) a
withA =
  withEntitySql "A"

withB
  :: Int64
  -> (Entity B -> ExceptT Text (HandlerT App IO) a)
  -> ExceptT Text (HandlerT App IO) a
withB =
  withEntitySql "B"

I can combine this functions with each other:

withA aId $ \ ea ->
  withB bId $ \ eb -> do
    ...

On the top level in handler for route I wrap the result of runExceptT into json object so client can see if something went wrong with his request.

I don't like that I have to write a function for each entity I'm working with in order to specify error message. I'm not sure how to improve withEntity to determine error message by itself.


texts:
This question is the adaptation of this question in C++. (I'm the author of that code as well).

The code:

#include <bits/stdc++.h>

std::string bf_interpreter(std::string code){
    long long int ptr = 0;

    std::vector<int> values = {0};
    long long int length = 1;

    std::vector<int> brackets;

    std::string result = "";

    for(unsigned long long int index = 0; index < code.size(); index++){
        while(length <= ptr){
            length++;
            values.push_back(0);
        }

        char character = code[index];

        switch(character){
            case '>': ptr++; break;
            case '<': ptr--; break;

            case '+': values[ptr] = (values[ptr] + 1) % 256; break;
            case '-': values[ptr] = (values[ptr] - 1) % 256; break;

            case '[':
                brackets.push_back(index);
                break;

            case ']':
                if(values[ptr] == 0)
                    brackets.pop_back();
                else
                    index = brackets[brackets.size() - 1];

                break;

            case '.':
                result += (char)values[ptr];
                break;

            case ',':
                char input; std::cin >> input;
                values[ptr] = (int)input;
                break;
        }
    }

    return result;
}

int main()
{
    std::string s;

    std::cin >> s;

    std::cout << bf_interpreter(s);
}

I'm quite a beginner in C++, so please excuse me if I'm not following any standard conventions.


texts:
I'm displaying a conflict marker for each actor for each day, if the current day is in their conflicts:

  <template v-for="actor in cast">
    <template v-for="conflict in actor.conflicts">

    </template>
  </template>

This works, but it just feels like a lot of code (despite it already being a dozen or so lines shorter than how I was doing it before using Vue JS).

Here's my Vue.js:

new Vue({
  el: '#schedule-builder',

  data: {

    cast: [
      {{ cast_list }}
          {
            actor: {
              id: "{{ actor_id }}",
              name: "{{ actor_name or 'TBD' }}",
            },
            conflicts: [
              {{ conflict_calendar }}
                { datestamp: "{{ value }}" },
              {{ /conflict_calendar }}
            ],
          },
      {{ /cast_list }}
    ],

    next_three_months: [
      {
        datestamp: '{{ now | format:Y-m-d }}',
      },
      {{ loop times="90" }}
        {
          datestamp: '{{ now | modify_date:+1 day | format:Y-m-d }}',
        },
      {{ /loop }}
    ],


texts: A little bash function, assigning attributes

texts:
This function checks if an attribute has been passed and if not, asks user for input.

I'm new in bash scripting and would like to get some feedback. Is it okay or should I refactor this code somehow to make it more concise?

#!/usr/bin/env bash

fn() {
    if [ -z "$1" ]; then
        read -p "username:" username
    else
        username=$1
    fi

    echo "username is $username"
}


texts: Programming Language Identification in JS

texts:
This is a RegExp exercice from HackerRank. Basically, I have to write a program (I chose JavaScript) that receives a program as an input (string) and tries to identify the programming language used. We're only concerned by 3 languages: C, Java or Python.

function processData(input) {
   console.log(identifyLanguage(input));
}

var identifyLanguage = function (code) {
    if (isJava(code))
        return 'Java';
    else if (isC(code))
        return 'C';
    else if (isPython(code))
        return 'Python';
    else return 'C';
}

var isC = function(input) {
    const cPreprocessor = /#(include.*?>|define.*)/g;
    const cStruct = /\b(typedef.*?;|struct.*?(?=\s*?\{))/g;
    const cPointers = /\b\w+\s*->\s*\w+\b/g;
    const cFunctionPointerReturn = /[a-zA-Z]+\s+\*\s+([a-zA-Z_]\w*)\s*\([a-zA-Z]*\s*([a-zA-Z_]\w*)\)\s*\{/g;
    const cFunctionPointerArg = /[a-zA-Z]+\s*\*?\s*([a-zA-Z_]\w*)\(.*[a-zA-Z]+\s*\*\s*([a-zA-Z_]\w*).*\)\s*\{/g;
    return cPreprocessor.test(input) || cStruct.test(input) || cPointers.test(input) ||
           cFunctionPointerArg.test(input) || cFunctionPointerReturn.test(input);
}

var isPython = function (input) {
    const pythonKeywords = /(class|def|if|while|else|for).*:/g;
    const pythonLists = /\[((\d+|("|').+\3),)*(\d+|("|').+\5)\]/g;
    const pythonPrint = /\bprint(\s*("|').+\2|\(.*\))/g;
    const pythonBoolean = /True|False/g;
    return pythonKeywords.test(input) || pythonLists.test(input) ||
           pythonPrint.test(input) || pythonBoolean.test(input);
}

var isJava = function(input) {
    const javaImport = /\bimport\s*.*?;/g;
    const javaClass = /(public|private)?\s*class.*?\{/g;
    return javaImport.test(input) || javaClass.test(input);
}

I can't say I'm satisfied with this, although it passes all the test cases, but It feels kinda ugly, non-DRY and amateurish. What can I do to improve it?

Update

The previous code updated after the suggestions provided in the chosen answer by Joseph :

var langPatterns = {
    C: [
        /#(include.*?>|define.*)/g, //cPreprocessor
        /\b(typedef.*?;|struct.*?(?=\s*?\{))/g, //cStruct
        /\b\w+\s*->\s*\w+\b/g, //cPointers
        /[a-zA-Z]+\s+\*\s+([a-zA-Z_]\w*)\s*\([a-zA-Z]*\s*([a-zA-Z_]\w*)\)\s*\{/g, //cFunctionPointerReturn
        /[a-zA-Z]+\s*\*?\s*([a-zA-Z_]\w*)\(.*[a-zA-Z]+\s*\*\s*([a-zA-Z_]\w*).*\)\s*\{/g //cFunctionPointerArg
    ],
    Java: [
        /\bimport\s*.*?;/g, //javaImport
        /(public|private)?\s*class.*?\{/g //javaClass
    ],
    Python: [
        /(class|def|if|while|else|for).*:/g, //pythonKeywords
        /\[((\d+|("|').+\3),)*(\d+|("|').+\5)\]/g, //pythonLists
        /\bprint(\s*("|').+\2|\(.*\))/g, //pythonPrint
        ///True|False/g //pythonBoolean
    ],
}

var identifyLanguage2 = function (code) {
    return Object.keys(langPatterns).find(lang =>
        langPatterns[lang].some(pattern =>
            pattern.test(code)));
}


texts:
For me as a complete newbie to the world of C++, getters and setters are a rather confusing topic. There seems to be a wide range of opinions on what constitutes a sound use of getters and setters. In this particular post I'm most interested in finding a good way of using getters and setters in a memory-safe way.

I hacked up a little example. Consider this epic tale of a king and his magic sword:

#include <iostream>
#include <string>

using std::string;

class Weapon {
  private:
    string name;
  public:
    Weapon(string n = "rusty sword") : name(n) {
      std::cout << "weapon '" << name << "' constructed" << std::endl;
    }
    string getName(){
      return name;
    }
    ~Weapon(){
      std::cout << "weapon '" << name << "' destroyed" << std::endl;
    }
};

class Hero {
  private:
    string name;
    Weapon weapon;
  public:
    Hero(string n) : name(n) {
      std::cout << "hero '" << name << "' constructed" << std::endl;
      describeWeapon();
    }
    void describeWeapon() {
      std::cout << name << " now swings " << weapon.getName() << std::endl;
    }
    void setWeapon(Weapon w) {
      weapon = w;
      describeWeapon();
    }
    ~Hero() {
      std::cout << "hero '" << name << "' destroyed" << std::endl;
    }
};

int main() {
  Hero h = Hero("Arthur");
  Weapon ex = Weapon("Excalibur");
  h.setWeapon(ex);
  std::cout << "Ok, now all objects will go out of scope" << std::endl;
  return 0;
}

This code yields the following output:

// our hero is given a rather modest sword to start with
weapon 'rusty sword' constructed
hero 'Arthur' constructed
Arthur now swings rusty sword

// Excalibur is created in the main scope
weapon 'Excalibur' constructed
Arthur now swings Excalibur   // since we passed the object by value, Arthur now actually owns a COPY of the original Excalibur.
weapon 'Excalibur' destroyed  // This is strange! Who got destroyed here?

Ok, now all objects will go out of scope
weapon 'Excalibur' destroyed  // Here, Arthurs copy is being destroyed.
hero 'Arthur' destroyed       // Arthur himself bites the dust.
weapon 'Excalibur' destroyed  // And finally, the original sword leaves this world.

Now, there are a few obvious problems in this piece of code:

For one, it is not ideal that we have the original Excalibur in the main-scope, while Arthur is only passed a copy. But what would be a better solution? Passing a pointer to Excalibur comes to mind, but is that the right way to go here?
It also seems like just overwriting Arthur's old weapon with the new one passed in the setter causes some erratic behaviour. Consider the last line in the second paragraph of the output: here, allegedly Excalibur gets destroyed, while I believe that it is much rather the rusty old sword that Arthur owned originally that gets demolished.

The vast majority of literature about getters and setters deals with primitives, so any help on best practices for passing objects (or pointers or references to objects) into setters would be highly appreciated!


texts: Building a parent/child tree relationship

texts:
I have a problem: build a tree relationship parent/child like this one:

Can you review this piece of code please since I am convinced it could be improved?

struct item {
    char value;
    std::list<item*> children;
};

I write a comparison function for a sort :

bool compareChild(const item *first, const item *second)
{
    return ( first->value < second->value );
}

a function to get the parent:

item *getTopParent(const char src_data[][2], int len)
{
    for (int i = 0; i < len; ++i)
    {
        if (src_data[i][0] == '\0')
        {
            item* head = new item;
            head->value = src_data[i][1];
            return head;
        }
    }
    return NULL;
}

Two functions to push the children:

bool PushChildren(const char src_data[][2], int len, item *parent)
{
    bool parentGotChildren = false;

    for (int i = 0; i < len; ++i)
    {
        if (src_data[i][0] == parent->value)
        {
            item* child = new item;
            child->value = src_data[i][1];
            parent->children.push_back(child);
            parentGotChildren = true;
        }
    }
    parent->children.sort(compareChild);

    return parentGotChildren;
}

bool PushChildrenforAParent(const char src_data[][2], item *parent, int len)
{
    bool hasGotAChild = true;
    std::list<item*>::iterator itchild = parent->children.begin();
    std::list<item*>::iterator childLast = parent->children.end();

    while (hasGotAChild && (itchild != childLast))
    {
        hasGotAChild = PushChildren( src_data, len, *itchild);
        if (hasGotAChild)
        {
            hasGotAChild = PushChildrenforAParent( src_data, *itchild, len);
        }
        ++itchild;
    }
    return hasGotAChild;
}

A function to initialise the "tree":

item* initialize_tree(const char src_data[][2], int len)
{
    bool hasTopParentGotAChild = false;
    //initialisation of the head
    item *head = getTopParent( src_data, len);

    if (head != NULL)
    {
        hasTopParentGotAChild = PushChildren( src_data, len, head);

        if (head != NULL)
        {
            if (hasTopParentGotAChild)
            {
                PushChildrenforAParent(src_data, head, len);
            }
            return head;
        }
        else
        {
            return NULL;
        }
    }
    return NULL;
}


texts:
I am not a DBA nor do I play one on TV.

My application is retrieving information from Facebook and storing it into our own database.  I want to retrieve the Location Post information of Id and AuthorId.  AuthorId is a foreign key to another table.  I was told by a DBA that foreign keys should always use internal unique identifiers because you can never rely on external unique identifiers.  So I created the following table structure...

CREATE TABLE tblAuthor
(
    [MyAuthorId] INT NOT NULL PRIMARY KEY IDENTITY
    [FacebookAuthorId] BIGINT NOT NULL
    ...Additional Facebook information...
)

CREATE TABLE tblLocationPost
(
    [MyLocationPostId] INT NOT NULL PRIMARY KEY IDENTITY,
    [FacebookLocationPostId] BIGINT NOT NULL,
    [MyAuthorId] INT NOT NULL,
    ...Additional Facebook information...
    CONSTRAINT [FK_tblLocationPost_Author] FOREIGN KEY (MyAuthorId) REFERENCES tblAuthor(MyAuthorId)
)

The data I get back from Facebook when querying Location Post is LocationPostId and AuthorId.  So I have created the following stored procedure to insert/update the LocationPost information in the database...

CREATE PROCEDURE [dbo].[LocationPost_Save]
@facebookLocationPostId bigint,
@facebookAuthorId bigint
AS
BEGIN
     DECLARE @myAuthorId INT
     DECLARE @IdentityColumn TABLE ( IdentityId int )

     BEGIN TRANSACTION

     /* Locate out internal unique id using facebooks unique author id, insert it if necessary */
     IF EXISTS (SELECT * FROM tblAuthor WHERE FacebookAuthorId = @facebookAuthorId)
     BEGIN
         SELECT @myAuthorId = MyAuthorId FROM tblAuthor WHERE FacebookAuthorId = @facebookAuthorId
     END
     ELSE
     BEGIN
         INSERT INTO tblAuthor (FacebookAuthorId) VALUES (@facebookAuthorId)
         SELECT @myAuthorId = SCOPE_IDENTITY()
     END

     /* Insert/Update one row in LocationPost */
     MERGE tblLocationPost lp
     USING (SELECT @facebookId as FacebookId) fb
     ON (lp.FacebookId = fb.FacebookId)
     WHEN MATCHED THEN
         UPDATE SET
             MyAuthorId = @myAuthorId,
             ...Additional data...
     WHEN NOT MATCHED THEN
         INSERT
             (FacebookLocationPostId, MyAuthorId, ...Additional Columns...)
         VALUES
             (@facebookLocationPostId, @myAuthorId, ...Additional Values...)
     OUTPUT INSERTED.MyLocationPostId INTO @IdentityColumn;

     COMMIT TRANSACTION

     /* Return the identify column of Inserted/Updated row */
     SELECT IdentityId FROM @IdentityColumn
END

Is this the correct pattern to use for this scenerio or is there a better approach?
Is the MERGE command the appropriate approach to Insert/Update a record (I am using SQL Server 2008)?
Do I really need to put my own Author Unique Id in the LocationPost table, or can I simplify this by putting the Facebook Unique Id?


texts: Matrix OOP implementation using C++11 and C++14

texts:
I know that other people already did the same already,
but I'm learning C++ (C++11/14) coming from C (I'm reading Programming: Principles and Practice Using C++, by Bjarne Stroustrup), and this is my OOP implementation of a matrix (N by M size).

At the moment it doesn't use template for generic types and uses double, and all it does is represent a matrix, but doesn't implement any calculation function members yet.
I'm using the C++ PIMPL idiom (using C++11's unique_ptr and C++14's make_unique), and the subscript [] operator overload.

I'd like to know if I'm using a good programming pattern (or a bad antipattern) and in the correct C++ way of doing things (ex. program structure, files and organization, types etc...). Please if you can keep it simple, as I'm still missing parts of the language I haven't learned yet.

File main.cpp:

#include <iostream>
#include <memory>

#include "Matrix.hpp"

using namespace std;
using namespace zgt;

constexpr size_t num_elements{ 3};

/*
 Outputs:
 1, 2, 3
 4, 5, 6
 7, 8, 9
 */
int main() {
    Matrix m{ num_elements }; // Squared matrix

    double inc{ 1 };
    for (size_t i{ 0 }; i < num_elements; i++) {
        for (size_t j{ 0 }; j < num_elements; j++) {
            m[i][j] = inc++;
        }
    }

    for (size_t i{ 0 }; i < num_elements; i++) {
        for (size_t j{ 0 }; j < num_elements; j++) {
            if (j == 0) {
                cout << m[i][j];
            } else {
                cout << ", " << m[i][j];
            }
        }

        cout << endl;
    }

    return 0;
}

File Matrix.cpp:

#include "Matrix.hpp"

using namespace std;
using namespace zgt;

struct Matrix::_impl {
    unique_ptr<unique_ptr<MatrixRow>[]> _m;

    _impl(size_t rows, size_t cols): _m(make_unique<unique_ptr<MatrixRow>[]>(rows)) {
        for (size_t i{ 0 }; i < cols; i++) {
            _m[i] = make_unique<MatrixRow>(cols);
        }
    }
};

MatrixRow& Matrix::operator[](size_t index) {
    return *(pimpl->_m[index]);
}

Matrix::Matrix(size_t rows, size_t cols) : pimpl(make_unique<_impl>(rows, cols)) {}
Matrix::Matrix(size_t size) : Matrix::Matrix(size, size) {}
Matrix::~Matrix() = default;

File Matrix.hpp:

#ifndef Matrix_hpp
#define Matrix_hpp

#include <iostream>
#include <memory>

#include "MatrixRow.hpp"

namespace zgt {
    class Matrix{
        struct _impl;
        std::unique_ptr<_impl> pimpl;
    public:
        Matrix(size_t rows, size_t cols);
        Matrix(size_t size); // [size][size]
        ~Matrix();

        MatrixRow& operator[](size_t index);
    };
}

#endif

File MatrixRow.cpp

#include "MatrixRow.hpp"

using namespace std;
using namespace zgt;

struct MatrixRow::_impl {
    unique_ptr<double[]> _v;

    _impl(size_t cols): _v(make_unique<double[]>(cols)) {}
};

double& MatrixRow::operator[](size_t index) {
    return pimpl->_v[index];
}

MatrixRow::MatrixRow(size_t cols) : pimpl(make_unique<_impl>(cols)) {}
MatrixRow::~MatrixRow() = default;

File MatrixRow.hpp:

#ifndef MatrixRow_hpp
#define MatrixRow_hpp

#include <iostream>
#include <memory>

namespace zgt {
    class MatrixRow{
        struct _impl;
        std::unique_ptr<_impl> pimpl;
    public:
        MatrixRow(size_t cols);
        ~MatrixRow();

        double& operator[](size_t index);
    };
}

#endif


texts: Replace first occurrence of pattern in file

texts:
Here's my attempt to replace first occurrence of pattern in file with spaces. Effectively deleting it, and hopefully will allow me to "delete" it in a large file, without rewriting it.

#define MAX_LINE_LENGTH
int removeFirstOccurenceInFile(const char* fileName, const char* pattern) {
  FILE* f = fopen(fileName,"r+");
  if (f == NULL) {
     perror("Can't open input file");
     return 0;
  }
  char buf[MAX_LINE_LENGTH] = {'\0'};
  char spaces[MAX_LINE_LENGTH];

  int unreadBytes = 0;
  char* patInBuf = NULL;
  while (1) {
    if (patInBuf != NULL) break;
    unreadBytes += strlen(buf);
    if (fgets(buf,sizeof(buf),f) == NULL) break;
    patInBuf = strstr(buf,pattern);
  }
  if (patInBuf == NULL) {
    fprintf(stderr,"No '%s' found in '%s'\n",pattern,fileName);
    fclose(f);
    return 0;
  }
  int delFrom = patInBuf-buf;

  memset(spaces,' ',delFrom);
  fseek(f,unreadBytes+delFrom, SEEK_SET);
  fwrite(spaces,1,strlen(pattern),f);

  fclose(f);
  return 1;
}

I'm not sure about the error handling. I considered using goto instead of the usual error handling:

  if (patInBuf == NULL) {
    fprintf(stderr,"No '%s' found in '%s'\n",pattern,fileName);
    retval = -1;
    goto cleanup;
  }
...
cleanup:
  fclose(f);
  return retval;

Are there other problems? Will that indeed be efficient?


texts: Find nth Fibonacci Number, using iteration and recursion

texts:
I'm a beginner programmer and I came upon this problem which is to find the nth number in the Fibonacci series.

I used to solve the problem using a for loop; today I learned about recursion but there is a problem: when I pass 40 or 41 to the recursive function, it takes a bit of time to calculate it, while in the iterative method it would instantly give me the answers.

I have these questions:

Why do most people (on the Internet) recommend using recursion?   Because it's simpler and easier to write the program?  (Logically I thought that we should write it in a way that is fast and simple)
Here are the 2 methods that a beginner like me can handle writing at the moment.  Is there a better way than these two methods?  And are these methods complex?

Here is the recursive method:

    #include <iostream>
    using namespace std;

    unsigned long long fibonacci(unsigned long long n);

    unsigned long long fibonacci(unsigned long long n){
        if(n<=1)
            return n;                                //base case
        return fibonacci(n-1) + fibonacci(n-2);      //recursive case
    }

    int main(){
        unsigned int a {};
        cout << "Enter number: ";
        cin >> a;
        cout << fibonacci(a) << endl;
        return 0;
    }

And here is the iterative (looping) method:

#include <iostream>
using namespace std;
int main() {
    int n{};
    unsigned long long t1{0}, t2{1};
    unsigned long long sum{};
    cout << "Enter the number of terms: ";
    cin >> n;
    cout << "Fibonacci Series: ";
    for (int i{2}; i < n; ++i) {
        sum = t1 + t2;
        t1 = t2;
        t2 = sum;
    }
    cout << t2;
    return 0;
}

Note: I know that using namespace std is a bad idea but I have also tried the same thing without the namespace and still I get the delay, so I did it here because it's easy to understand.

Edit1: First of all I would like to thank everyone who commented and answered my question...To be honest I didn't think that this question would bring a lot of attention to the community so I appreciate the time you put on this and it means a lot to me.

Edit2: Let me demonstrate some of the things that might have been a little odd to you.

Q: What do you mean by better when you say if there is a better way than these two methods?
A: By better, I meant that the code shall be simple and also takes less time to execute or perform the calculations

Q: What do you mean when you say most people (on the internet) use recursion?
A: I've seen code out there that uses recursion to solve problems.  The two common problems I've seen are Fibonacci and Factorial of a number. For factorial, I have also tried both methods (iteration and recursion) but I didn't get a delay for both of them when I type large numbers like 40 or 50. The common problem I saw with recursion is that eventually, you may run out of memory space because it is calling itself multiple times which results in a stack overflow (because stack as a part of memory will be filled). Although this problem doesn't occur in this example. So this raises another question here:

When should we use recursion?


texts: Fetching and displaying the provisioning status of a phone number

texts:
I have the following function:

def dnd_return(number,my_timeout):
    try:
        r =requests.get("https://dndcheck.p.mashape.com/index.php?mobilenos= {}".format(number), timeout =my_timeout)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as err:
        return "Error fetching DND info"
    else:
        return r.text

Then I have the following route:

@app.route('/track_mobile_numbers', methods=['POST','GET'])
def mobile():
    if request.method == 'POST':
        if request.form.get("number", "") != "":
            number = request.form['number']
            number = number.replace(" ","")
            number = number.replace('+91', '')
            number = number.strip()
            strnumber = number
            dnd_list = []
            if len(number) == 10:
                try:
                    dnd_dump = dnd_return(number,9)
                    json_dump = json.loads(dnd_dump)
                    j = json_dump[0]

                    if j['DND_status'] != "deactivated" and j['DND_status'] != "off":
                        dnd_list.append("DND status : "+j['DND_status'])
                        dnd_list.append("Date of Activation : "+j['activation_date'])
                        dnd_list.append("Preference : "+j['current_preference'])

                    else:
                        dnd_list.append("DND status : "+j['DND_status'])
                except Exception as e:
                    dnd_list.append(e)
            else:
                dnd_list.append("The number should contain 10 digits")

            number = number[:4]
            try:
                number = int(number)
                num = mobileNumbers.query.filter_by(number = number).first()
                return render_template('mobilenumbers.html',
                                        strnumber = "Mobile number : " + strnumber,
                                        operator = "Operator : " + num.operator,
                                        state = "State : " + num.state,
                                        dnd = dnd_list
                                      )
            except Exception as err:
                return render_template('mobilenumbers.html',
                                        error = err
                                      )
        else:
            return render_template('mobilenumbers.html',
                                    error = "Please enter a valid number"
                                  )
    else:
        return render_template('mobilenumbers.html')

Is there a better way to do this? Can you recommend improvements to this code?


texts: Multiple similar methods to compute the average student grade

texts:
I have bunch of similar methods in different classes to average student grades.

In the Student class:

public double getAverageGrade() throws NoGradesForStudentException {
    double sum = 0;
    int totalGrades = 0;
    ArrayList<Subject> studentSubjects = getStudentSubjects();
    for(Subject subject : studentSubjects) {
        try {
            sum += getAverageGradeInSubject(subject);
            totalGrades++;
        }
        catch(NoGradesInSubjectException e) {
            //everything is okey
        }
    }
    if (totalGrades == 0) {
        throw new NoGradesForStudentException("Student does not have any grades yet");
    } else {
        return sum/totalGrades;
    }
}

In the GroupOfCourses class:

public double getAverageGrade() throws NoGradesInCourseException {
    double gradeSum = 0;
    double studentsWithGrades = 0;
    for(Student student : getStudents()) {
        try {
            gradeSum += student.getAverageGrade();
            studentsWithGrades++;
        }
        catch (NoGradesForStudentException e) {
            //viss kartiba, ja izmet so iznemumu
        }
    }
    if (studentsWithGrades != 0) {
        return gradeSum/studentsWithGrades;
    } else {
        throw new NoGradesInCourseException("There are no grades in course.");
    }
}

This one is in the main and user input is mingled with the logic. But the logic is the same as in previous examples.

private static void calculateSubjectAvgGrade() {
    ArrayList<Subject> allSubjects = Main.getSubjectsInAllCourses();

    for(int index = 0; index < allSubjects.size(); index++) {
        System.out.println(index + ". " + allSubjects.get(index).getTitle());
    }
    System.out.print("Izvelieties prieksmetu ievodot ta numuru: ");
    int number = Input.consoleIntIn();

    double sum = 0;
    int subjectsWithGrade = 0;
    for (Course course : Main.courses) {
        try {
            sum += course.getAverageGradeInSubject(allSubjects.get(number));
            subjectsWithGrade++;
        }
        catch(NoGradesInSubjectException e) {
            //viss ok
        }
    }
    double avg = subjectsWithGrade != 0 ? sum/subjectsWithGrade : 0;
    System.out.println("Prieksmeta videja atzime ir: " + avg);
}

I was wondering is there a way I could create one function and call it in those methods? It would look something like this:

public double getAvarageGrade() throws NoGradesException {
     return function(studentSubjects, "Student does not have any grades yet");
}

I'm asking this because I have lot of methods in different classes that duplicate their logic.

I'm using Java 8.


texts: Working and calculating with geographic positions

texts:
I was thinking about how to implement a GPS navigation for my quadcopter.  I was writing some functions to calculate the angle between two positions (from home point to the target).

I'd like a review of this code.  I am not very sure whether I was calculating the geographic position right.

/*
 * Geographic calculations
 */
float UAVNav::width_of_merid_m(const float fLat_deg) {
  float fdX_m = _2PI * _RADIUS_EARTH_m * cos(ToRad(fLat_deg) );
  fdX_m /= 360.f;
  return fdX_m;
}

float UAVNav::dist_2_equat_m(const float fLat_deg) {
  return (_PERIMETER_EARTH_m / 360.f) * fLat_deg;
}

float UAVNav::dist_2_greenw_m(const float fLat_deg, const float fLon_deg) {
  return width_of_merid_m(fLat_deg) * fLon_deg;
}

float UAVNav::home_2_target_deg() {
  const float fMod = 10000000.f;
  GPSPosition target = m_pReceiver->m_Waypoint;
  GPSData home = m_pHalBoard->get_gps();

  float fLatHome_deg = home.latitude / fMod;
  float fLonHome_deg = home.longitude / fMod;

  float fLatTarg_deg = target.latitude / fMod;
  float fLonTarg_deg = target.longitude / fMod;

  float fXHome = dist_2_greenw_m(fLatHome_deg, fLonHome_deg);
  float fYHome = dist_2_equat_m(fLatHome_deg);

  float fXTarg = dist_2_greenw_m(fLatTarg_deg, fLonTarg_deg);
  float fYTarg = dist_2_equat_m(fLatTarg_deg);

  float dX = fXTarg - fXHome;
  float dY = fYTarg - fYHome;

  // Calculate the angle to the destination direction
  // NOTE: Here the system is inverted by 90° to align the magnetic north to 0°
  m_fDestin_deg = ToDeg(atan2((float)dX, (float)dY) );
  return m_fDestin_deg;
}


texts:
I'm fairly new to C and wanted a general review of this code. It's a solution to this problem.

  You and your \$K-1\$ friends want to buy \$N\$ flowers. Flower number \$i\$ has
  cost \$c_i\$. Unfortunately the seller does not want just one customer to
  buy a lot of flowers, so he tries to change the price of flowers for
  customers who have already bought some flowers. More precisely, if a
  customer has already bought \$x\$ flowers, he should pay \$(x+1)*c_i\$ dollars
  to buy flower number \$i\$.

  You and your \$K-1\$ friends want to buy all \$N\$ flowers in such a way that
  you spend the least amount of money. You can buy the flowers in any
  order.

  Input:

  The first line of input contains two integers \$N\$ and \$K\$ (\$K \le N\$). The
  next line contains \$N\$ space separated positive integers \$c_1,c_2,\dotsc,c_N\$.

  Output:

  Print the minimum amount of money you (and your friends) have to pay
  in order to buy all \$N\$ flowers.

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

int comp_desc(const void * a, const void * b)
{
    int * aPtr = (int*)a;
    int * bPtr = (int*)b;
    return *bPtr - *aPtr;
}

int main()
{
    int flowersNeeded, numFriends, i;
    scanf("%d %d", &flowersNeeded, &numFriends);
    getchar();
    int flowerCosts[100];
    memset(flowerCosts, 0, sizeof(flowerCosts));
    for (i = 0; i < flowersNeeded; ++i)
    {
        scanf("%d", &flowerCosts[i]);
    }
    qsort(flowerCosts, flowersNeeded, sizeof(int), comp_desc);
    int flowersBought = 0;
    int moneySpent = 0;
    int multiplier = 1;
    for (i = 0; i < flowersNeeded; ++i)
    {
        moneySpent += flowerCosts[i] * multiplier;
        multiplier = (++flowersBought / numFriends) + 1;
    }
    printf("%d\n", moneySpent);
    return 0;
}


texts:
I'm trying to learn C++ having come from a C/Assembly background.  I thought one of the first tools I'd make as a project is a "directory tally" program:

It will count all the files in the current directory
If the user specifies, it will count all the folders in the current directory too
If the user specifies, it will count all the files in subdirectories as well (and folders if the user specifies)

Given that most of my academic, professional, and personal programming projects have involved C instead of C++ I'm pretty sure that my code is not idiomatic C++ (yet), but I have used guidelines like use std::(w)string over (w)char(_t) * strings, use the STL as much as possible, etc.

I'm wondering if I can get feedback on:

Is it obvious from looking at my code that I come from a C background?
What can I do to make this program look more like idiomatic C++?
The usual code review stuff, things I could write more clearly or bad things I'm doing that I should avoid.

#include <iostream>
#include <filesystem>

namespace fs = std::experimental::filesystem;

bool __cdecl recur_flag(std::wstring arg)
{
    if (arg.length() < 2) return false;
    return ((arg.at(0) == L'-' || arg.at(0) == L'/') && (arg.at(1) == L'r' || arg.at(1) == L'R'));
}

bool __cdecl dir_flag(std::wstring arg)
{
    if (arg.length() < 2) return false;
    return ((arg.at(0) == L'-' || arg.at(0) == L'/') && (arg.at(1) == L'd' || arg.at(1) == L'D'));
}

bool __cdecl help_flag(std::wstring arg)
{
    if (arg.length() < 2) return false;
    return ((arg.at(0) == L'-' || arg.at(0) == L'/') && (arg.at(1) == L'?'));
}

int __cdecl wmain(int argc, wchar_t *argv[])
{
    bool recur = false, dircount = false;
    unsigned long long count = 0;

    recur = ((argc >= 2) && (recur_flag(std::wstring(argv[1])))) || ((argc >= 3) && (recur_flag(std::wstring(argv[2]))));

    dircount = ((argc >= 2) && (dir_flag(std::wstring(argv[1])))) || ((argc >= 3) && (dir_flag(std::wstring(argv[2]))));

    if ((argc >= 2) && (help_flag(std::wstring(argv[1]))) || (argc >= 3) && (help_flag(std::wstring(argv[2]))))
    {
        std::wcout << L"Usage: dircount /R /D /?" << std::endl << L"\t/R Recursive - count files in current directory and subdirectories" << std::endl <<
            L"\t/D Include directories when counting files" << std::endl << L"\t/? Display this help message" << std::endl << std::endl;
        return 0;
    }

    if (recur)
    {
        for (auto &p : fs::recursive_directory_iterator(fs::current_path()))
        {
            if (fs::is_directory(p))
            {
                if (dircount) count++;
            }
            else count++;
        }
    }
    else
    {
            for (auto &p : fs::directory_iterator(fs::current_path()))
            {
                if (fs::is_directory(p))
                {
                    if (dircount) count++;
                }
                else count++;
            }
    }

    std::wcout << L"There are " << count << L" items in the current directory"; if (recur) std::wcout << L" tree"; std::wcout << std::endl;

    return 0;
}


texts: Unit testing F# code without using an existing test library (MSTest, xUnit, etc.)

texts:
I know I can probably use MSTest (I'm under Linux without an IDE so maybe not?) or another unit testing library, but for a small project I decided to write my own unit tests without resorting to a framework (for fun and for learning).

Right now, I have only one type of assert and one test but I would like a code review to improve my code now to make sure I am on the right track.

module Tests

// modules under test
open HeightMap
open MidpointDisplacement

// assert functions
let assertAreEqual expected actual =
    printf "... "
    if expected <> actual then printfn "%s" ("Test failed, expected " + expected.ToString() + ", actual " + actual.ToString())
    else printfn "Test passed"

// tests
let testNewHeightMapReturnZeroInitializedHm () =
    let hm = newHeightMap 5
    let result = hm.Map |> Array.sum
    assertAreEqual 0.0 result

// tests included in run
let testsToRun =
    [
        ("test newHeightMap will return a 0 initialized height map",
         testNewHeightMapReturnZeroInitializedHm)
    ]

// test runner
let runSingleTest test =
    let testName, testFunction = test
    printf "%s" testName
    testFunction()

let runTests =
    testsToRun |> List.map runSingleTest |> ignore
    printfn "%s" "Ran all tests."

One thing that bugs me is that I there is some redundancy by specifying the test function and then including it in a list inside a tuple.


texts: Parsing and formatting a time two ways (perfectionistic approach)

texts:
I'm still not satisfied by the readability of the code. The wanted behavior which would be self descriptive would sound like: "I've two fields; one is for the date and one for the hour. This two fields should be in a UserControl of which I have two instances, one is for the event time and one is for the event end time."

My personal opinion is all the extra code is something which is specific to C# syntax, and not to my purpose. Handling null, exceptions, conversions between dates and strings makes me to write that extra code and a developer could get confused and wonder on what was the purpose of that solution. The only thing which is at a functional level in this code is an assignment.

The String.Format is an example of what I mean... it's a really mean solution. Now that every approach tries to separate Model, View and Controllers, I'm mixing the solution I found to to fill a gap of conversion and the code wrote to make the behavior I needed.

Which solution would you use?

First formulation

public override void OnEventTimeChanged()
{
    DateTime eventDateWithTime;
    TimeSpan eventTime;

    if (TimeSpan.TryParse(EventTime, out eventTime))
    {
        eventDateWithTime = (EventDate.Date + eventTime);
        CultureInfo cultureInfo = Thread.CurrentThread.CurrentUICulture;
        EndTime = String.Format(cultureInfo, "{0:HH:mm}", eventDateWithTime);
        EndDate = eventDateWithTime;
    }
}

Second formulation

public override void OnEventTimeChanged()
{
    CultureInfo cultureInfo = Thread.CurrentThread.CurrentUICulture;

    TimeSpan eventTime;
    if (!TimeSpan.TryParse(EventTime, out eventTime)) return;

    DateTime eventDateWithTime = (EventDate.Date + eventTime);
    string eventTimeString = String.Format(cultureInfo, "{0:HH:mm}", eventDateWithTime);

    EndTime = eventTimeString;
    EndDate = eventDateWithTime;
}


texts:
Please have a through look my custom implementation of generic repository pattern and suggest anything I may be lacking.

I am using a generic interface with 6 methods
I'll be using a repository class for each entity type (e.g UserRepository, ProductRepository, StoreRepository) which are not only going to implement the generic interface but also can add additional methods as per the need with respect to each repository class. for example:

UserRepository can add a new method named as CountUsers() which gets called from controller.
ProductRepository can add a new method named as GetExpiredProducts() which gets called from controller.

I am declaring IGenericRepository<User> in UserController, similarly in other controllers and using repositoryPattern.

Generic Repository Interface

public interface IGenericRepository<T> : IDisposable where T : class
{
    IEnumerable<T> SelectAll();
    T SelectByID(object id);
    void Insert(T obj);
    void Update(T obj);
    void Delete(object id);
    void Save();
}

Implementation of Generic Repository Interface

public class UserRepository : IGenericRepository<User>
{
    private ModelDBEntities dataContext = null;
    public UserRepository()
    {
        this.dataContext = new ModelDBEntities();
    }
    public UserRepository(ModelDBEntities dataContext)
    {
        this.dataContext = dataContext;
    }

    public IEnumerable<User> SelectAll()
    {
        return dataContext.Users;
    }
    public User SelectByID(object argId)
    {
        long userId = long.Parse(argId.ToString());
        return dataContext.Users.Single(u => u.UserId == userId);
    }
    public void Insert(User obj)
    {
       dataContext.Users.AddObject(obj);
    }
    public void Update(User obj)
    {
        if (obj.EntityState == EntityState.Detached)
            dataContext.Users.Attach(obj);
        dataContext.ObjectStateManager.ChangeObjectState(obj, System.Data.EntityState.Modified);
    }
    public void Delete(object argUserId)
    {
        long userId = long.Parse(argUserId.ToString());
        dataContext.Users.Single(u => u.UserId == userId).Status = "inactive";
    }
    public void Save()
    {
        dataContext.SaveChanges();
    }

    private bool disposed = false;
    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                dataContext.Dispose();
            }
        }
        this.disposed = true;
    }
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

My User Controller

public class UserController : Controller
{
    private IGenericRepository<User> _repositoryUser = null;
    public UserController()
    {
        _repositoryUser = new UserRepository();
    }
    public UserController(IGenericRepository<User> repository)
    {
        _repositoryUser = repository;
    }

    [HttpPost]
    public JsonResult SubmitHandler(User argUser)
    {
        if (ModelState.IsValid)
        {
            _repositoryUser.Insert(argUser);
            _repositoryUser.Save();
            return Json("success");
        }
        else
            return Json("failure");
    }
    public ActionResult Delete(object Id)
    {
            if (Id != null && Id.ToString().Trim().Length > 0)
            {
                int param = int.Parse(Id.ToString());
                _repositoryUser.Delete(Id as object);
                _repositoryUser.Save();
                return View("User", _repositoryUser.SelectAll());
            }
            else
                return View("404");
    }
}


texts: Maximum depth or height of a Binary tree

texts:
The Following function is supposed to calculate the maximum depth or height of a Binary tree
        the number of nodes along the longest path from the root node down to the farthest leaf node.

please comment as if it was a 15 minute coding interview. coding style and efficiency.

this was given to you

public class BinaryTreeNode
{
    public BinaryTreeNode Left { get; set; }
    public BinaryTreeNode Right { get; set; }
    public int Value { get; set; }

}

please comment on the unit tests as well.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
    [TestClass]
    public class MaxTreeDepth
    {
        //     0
        //   1    2
        //  3
        [TestMethod]
        public void GetMaxTreeDepthTest()
        {
            BinaryTreeNode root = new BinaryTreeNode
            {
                Value = 0,
                Left = new BinaryTreeNode {Value = 1},
                Right = new BinaryTreeNode {Value = 2}
            };
            root.Left.Right = new BinaryTreeNode {Value = 3};

            int result = GetMaxTreeDepth(root);
            Assert.AreEqual(3,result);
        }

        //     0

        [TestMethod]
        public void GetMaxTreeDepthTestOneNode()
        {
            BinaryTreeNode root = new BinaryTreeNode
            {
                Value = 0,
            };

            int result = GetMaxTreeDepth(root);
            Assert.AreEqual(1, result);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void GetMaxTreeDepthTestNull()
        {
            BinaryTreeNode root = null;
            int result = GetMaxTreeDepth(root);
        }

        private int GetMaxTreeDepth(BinaryTreeNode root)
        {
            if (root == null)
            {
                throw new ArgumentNullException();
            }
            int depth = 0;
            return GetMaxHelper(root, depth);
        }

        private int GetMaxHelper(BinaryTreeNode root, int depth)
        {
            if (root == null)
            {
                return depth;
            }

            return Math.Max( GetMaxHelper(root.Right, depth+1),  GetMaxHelper(root.Left, depth+1));
        }
    }
}


texts:
I've written a quick little helper for event & call debounce/throttling. Since I'm at home and none of my regular code review friends are on-line I figured I'd turn to the great folks here! Would love any feedback you might have.

/**
 * debounce
 * @param {integer} milliseconds This param indicates the number of milliseconds
 *     to wait after the last call before calling the original function .
 * @return {function} This returns a function that when called will wait the
 *     indicated number of milliseconds after the last call before
 *     calling the original function.
 */
Function.prototype.debounce = function (milliseconds) {
    var baseFunction = this,
        timer = null,
        wait = milliseconds;

    return function () {
        var self = this,
            args = arguments;

        function complete() {
            baseFunction.apply(self, args);
            timer = null;
        }

        if (timer) {
            clearTimeout(timer);
        }

        timer = setTimeout(complete, wait);
    };
};

/**
* throttle
* @param {integer} milliseconds This param indicates the number of milliseconds
*     to wait between calls before calling the original function.
* @return {function} This returns a function that when called will wait the
*     indicated number of milliseconds between calls before
*     calling the original function.
*/
Function.prototype.throttle = function (milliseconds) {
    var baseFunction = this,
        lastEventTimestamp = null,
        limit = milliseconds;

    return function () {
        var self = this,
            args = arguments,
            now = Date.now();

        if (!lastEventTimestamp || now - lastEventTimestamp >= limit) {
            lastEventTimestamp = now;
            baseFunction.apply(self, args);
        }
    };
};

To help understand what the point of these helpers are I've prepared this demo: http://jsfiddle.net/zR5jV/1/

GitHub project can be found here: https://github.com/m-gagne/limit.js


texts:
I'm trying to read data from an array. I manage to get the information I want but my code is extremely inefficiently written.

My array looks like this:

var arTab:Array = new Array();
arTab[0] = new Array(2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012);
var promilleTab:Array = new Array();
promilleTab[0] = new Array(9631, 8593, 8363, 8128, 8514, 8534, 8560, 8146, 8241, 8019,         8759);
var forerkortTab:Array = new Array();
forerkortTab[0] = new Array(13481, 12785, 12585, 12492, 13470, 14181, 14622, 14082, 14287, 13640, 14180);
var hastighetTab:Array = new Array();
hastighetTab[0] = new Array(9863, 12217, 14920, 14929, 15425, 18010, 15909, 14197, 13276, 11158, 12264);
var trafikklovenTab:Array = new Array();
trafikklovenTab[0] = new Array(18862, 19196, 20101, 20026, 21381, 21845, 20005, 19446, 20900, 19346, 20265);

I am using combo boxes to pick a year from the "arTab" array and another to pick the felony done.(the 3 other arrays)

What I am doing right now looks something like this:

function skrivUt(Event:MouseEvent)
{
    if(bruddListe == 1)
    {
        if(arListe == 1)
        {
            txtSvar.text = "I " + arTab[0][0] + " ble det anmeldt " + promilleTab[0][0] + " for promillekjøring";
        }
        if(arListe == 2)
        {
            txtSvar.text = "I " + arTab[0][1] + " ble det anmeldt " + promilleTab[0][1] + " for promillekjøring";
        }
        if(arListe == 3)
        {
            txtSvar.text = "I " + arTab[0][2] + " ble det anmeldt " + promilleTab[0][2] + " for promillekjøring";
        }
    {
{

This is just a small example but the list goes on because I have to do 11 results for all the 4 combo choices.

Is there any way I can write this in a shorter and more efficient way?


texts: How to Make Strongly-typed References to Web.Config?

texts:
Let's say I have a configuration file with a property in it:

<add key="LoadedCode" value="L" />

I know I can reference this using the ConfigurationManager:

System.Configuration.ConfigurationManager.AppSettings["LoadedCode"];

This has some drawbacks.  It can get bulky when it gets used in multiple locations.  I lose support for refactoring and "Find All References" because I'm using an item in the AppSettings collection.  I don't have strong-typing in cases where the config setting isn't a string.  So I wrap it into a static property in a static class:

public static string LoadedCode
{
    get { return System.Configuration.ConfigurationManager.AppSettings["LoadedCode"]; }
}

Great so far.  Now I want to use this on multiple pages and this leads me to my conundrum.  Should I reference this static property everywhere, or should each page have its own local wrapper?

On the one hand, a local wrapper pushes all uses on the page through a single point which can be modified without impacting other pages if needed.  On the other hand, it adds a layer of indirection to the dependency chain and it looks a bit like overkill.

Is there a best practice for this type of behavior, or am I simply over-thinking things?


texts:
I am relatively new to JavaScript/jQuery, and cobbled together a script. Essentially, the script sets individual timers on specific DOM elements, and then recursively applies timed functions to them. The functions actually apply a "flip" effect to a div, showing a front and back, and then do different things on each side. The references to "Vague" are from Vague.js, and external library I didn't write that provides a blur effect to elements. The script works, but writing working code and writing good code are two separate things.

$(document).ready( function() {
    $('.flipper').each(function(e) {
        var flipper = new myFlipper($(this));
    })
});

var myFlipper = function (flipper) {
    //console.log(flipper);
    this.flipper = flipper;
    this.image = flipper.find('img');
    this.blurStatus = true;
    this.flipStatus = true;
    this.Vague = this.image.Vague ({
        intensity: 8,
        forceSVGUrl: false
    });
    this.blurContext = $.proxy(this.myBlur, this);
    this.flipContext = $.proxy(this.myFlip, this);
    // $(this.image).on("click", this.blurContext);
    var randomNumber = Math.floor(Math.random()*10);
    var timer = randomNumber * 1000;
    setTimeout(this.blurContext, timer);
}

myFlipper.prototype.myBlur = function(e) {
    console.log(this.flipContext);
    if(this.blurStatus) {
        this.Vague.blur();
        this.blurStatus = false;
        this.flipper.find('.caption').animate({opacity: 1.0}, 3000);
        setTimeout(this.flipContext,5000);
    } else {
        this.Vague.unblur();
        this.blurStatus = true;
    }
}

myFlipper.prototype.myFlip = function(e) {
    console.log(this.flipper.attr("class"));
    console.log(this.flipStatus);
    if (this.flipStatus) {
        this.flipper.addClass('hover');
        this.flipper.find('.caption').animate({opacity: 0.0}, 1000);
        this.blurContext();
        this.flipStatus = false;
        setTimeout(this.flipContext, 20000);
    } else {
        this.flipper.removeClass('hover');
        this.flipStatus = true;
        setTimeout(this.blurContext,5000);
    }
}

Here is the JSFiddle of the whole thing.


texts:
Now FizzBuzz itself isn't a big challenge but I agree that it can be a good tool to see if someone can code or not.  I wanted to practice my LINQ a little bit so here's my single line FizzBuzz solution.

Enumerable.Range(1,100).Select(
                        n =>
                        (n % 15 == 0) ? "FizzBuzz" :
                        (n % 3 == 0) ? "Fizz" :
                        (n % 5 == 0) ? "Buzz" :
                        n.ToString())
                        .ToList()
                        .ForEach(Console.WriteLine);


texts:
I've implemented Caesar Cipher with two sample functions, Is my code readable I tried to make it understandable as I can , any comment is appreciated.
I am planning to do a Vigenère Cipher soon.

import string
def cipherencryprt (word , key ):
    word.lower()
    encryptedstring = ""
    for i in word :
        charvalue = ord(i) +key
        if ( charvalue > 122):
            charvalue = ord('a') + (charvalue -123)
            encryptedstring += chr(charvalue)

        else:
            encryptedstring += chr(charvalue)
    return encryptedstring

def cipherdecrypt(word , key ) :
    word.lower()
    decryptstring = ""
    for i in word :
        charvalue = ord(i ) - key
        if ( charvalue < 97 ):
            charvalue = ord('z') - (96-charvalue)
            decryptstring += chr(charvalue)
        else: decryptstring+= chr(charvalue)
    return decryptstring

if __name__ == "__main__" :
    print(cipherencryprt('omar', 4))
    print(decrypt(cipherencryprt('omar', 4),4))


texts:
i've implemented a waiter service in Angular for syncronice multiple calls to one async function and i want to know if there exists a simplier way of atchiving the same result or if it's over engineered
the code
import {Injectable} from '@angular/core';

export class PromiseRef {
  resolve: (any?: any) => any;
  reject: (any?: any) => any;
}

class ExecutionQueue {
  promises = new Set<PromiseRef>();
  lock: boolean = false;

  constructor() {
  }

  hasPromises(): boolean {
    return !!this.promises.size;
  }

  clearQueue() {
    this.lock = false;
    this.promises.clear();
  }

  add(promiseRef: PromiseRef) {
    this.promises.add(promiseRef);
  }

  remove(promiseRef: PromiseRef) {
    this.promises.delete(promiseRef);
  }
}

@Injectable({providedIn: 'root'})
export class WaiterService {

  private executionQueues = new Map<string, ExecutionQueue>();

  constructor() {
  }

  isLocked(queueName: string): boolean {
    return this.getQueue(queueName).lock;
  }

  lockQueue(queueName: string): Promise<PromiseRef> {
    return new Promise<PromiseRef>(
      (resolve, reject) => {
        const queue = this.getQueue(queueName);

        const promiseRef = new PromiseRef();

        promiseRef.resolve = resolve;
        promiseRef.reject = reject;

        if (!queue.lock) {
          queue.lock = true;
          promiseRef.resolve(promiseRef);
        } else {
          this.addToExecutionQueue(queueName, promiseRef);
        }
      }
    );
  }

  async unlockQueue(queueName: string) {
    const queue = this.getQueue(queueName);
    queue.lock = false;
    const iterator = queue.promises.values();
    const nextValue = iterator.next();

    if (nextValue.done) {
      return;
    }

    const promiseRef = nextValue.value;
    queue.remove(promiseRef);

    const newRef = await this.lockQueue(queueName);
    promiseRef.resolve(newRef);
  }

  addToExecutionQueue(queueName: string, promiseRef: PromiseRef) {
    const queue = this.getQueue(queueName);
    queue.add(promiseRef);
  }

  private getQueue(queueName: string) {
    let queue = this.executionQueues.get(queueName);

    if (!queue) {
      queue = new ExecutionQueue();
      this.executionQueues.set(queueName, queue);
    }

    return queue;
  }
}

then you should use it like this
async someFn() {
  await this.waiterService.lockQueue('a_queue');

  try {
    // do async stuff
  } finally {
    this.waiterService.unlockQueue('a_queue');
  }
}


texts:
This is a part of my Factorio mod Visual Signals.

This code takes a numeric value as input and returns a string for the value, for example:

-12 --> -12
1 --> 1
50 --> 50
999 --> 999
1500 --> 1.5k
24999 --> 24.9k
123456 --> 123k
1234567 --> 1.2M
12345678 --> 12M
123456789 --> 123M
1234567890 --> 1.2G
and so on...

The idea is to replicate the same way Factorio show signals in the circuit network.

The code works by determining a prefix, which simply is a potential minus sign. It then determines the middle part (the numbers and potential comma separator to use) and the suffix (the letter at the end).

The code seems to work perfectly fine and now I simply wonder: Can I improve this code somehow?

local suffixChars = { "", "k", "M", "G", "T", "P", "E" }

function CountString(count)
  local absValue = math.abs(count)
  local prefix = ""
  if count < 0 then
    prefix = "-"
  end
  local suffix = 1
  while absValue >= 1000 do
    absValue = absValue / 1000
    suffix = suffix + 1
  end

  local str = tostring(absValue)
  if absValue < 10 then
    return prefix .. string.sub(str, 1, 3) .. suffixChars[suffix]
  end
  if absValue < 100 then
    return prefix .. string.sub(str, 1, 2) .. suffixChars[suffix]
  end
  return prefix .. string.sub(str, 1, 3) .. suffixChars[suffix]
end


texts: How to pass pre-generated values to an anonymous function to speed up a fit?

texts:
In Matlab I am using the combination of fit and fittype function (from the curve fitting toolbox) to fit a signal using an anonymous function.

My issue is that, this anonymous function use the integral function of matlab, and this is extremely time consuming. I am therefore trying to get rid of this function inside the anonymous function.

An amazing improvement would be to pre-calculate these integral and pass it to the fit function, but I do not know how to do this.

I tried to define the vector that contain these integration values and pass it to the fit by defining it as 'dependent' or 'problem' variable in fittype but that did not do the trick. I also tried concatenating the coordinate and the result of this integral. When doing a two column vector it tried to fit a surface (which it is not the case). When concatenating in a one column vector it complain that the data set and the coordinate system should be the same size.

As an alternative I also tried using sum and trapz instead of integral but fittype told me that then the function did not fulfill the criteria of an anonymous function.

I am running short on ideas and on ways to ask search engines for new ideas and would welcome all new point of view on how to solve this.

For curious peoples here is the original anonymous function I am using:

function [ y ] = zeusEquation(varargin)
    psi0=varargin{1};% in radian
    a1 = varargin{2};% parameter to be fitted
    a2 = varargin{3};%parameter to be fitted
    a3 = varargin{4};% average of background signal/ offset in gray level
    a4 = varargin{5};% slope on the signal background
    a5 = varargin{6};% decentering of the signal (in meter)
    a6 = varargin{7};% width of the signal in radian
    x = varargin{8};%Coordinate system in meter!!!!
    y = zeros(size(x));

    %fundamental bloc equation needed
    sinIntegral = @(t) 2.*sin(t)./(pi.*t);
    u = @(f, e, x) f.*abs(x-e);

    %Actual signal calculation
    for i = 1:max(size(x))
        if u(a6,a5,x(i))~=0
            y(i) = a3...
             +a4.*(x(i)-a5)...
             +(1-integral(sinIntegral,0,u(a6,a5,x(i))))...
             .*(a1.*sign(x(i)-a5).*sin(psi0)-...
             (1-a2).*integral(sinIntegral,0,u(a6,a5,x(i))).*(1-cos(psi0)));
        else
            y(i) = a3+a4.*(x(i)-a5);
        end
    end
end

Note: I cross asked this question on mathwork.


texts:
I recently read the book clean code by Robert C. Martin and I'm trying to apply his style of writing methods to the FizzBuzz programming example.

So far I have two "public" methods called: start and parseNumber, that respectively start the FizzBuzz program or parse a single number according to the FizzBuzz principle.

class FizzBuzz(object):

    def start(self, end_number):
        return ",".join(self._parse_numbers(end_number))

    def _parse_numbers(self, end_number):
        number_list = []
        for number in range(1, end_number+1):
            number_list.append(self.parse_number(number))
        return number_list

    def parse_number(self, number):
        if self._is_number_divisible_by_five_and_three(number):
            return "FizzBuzz"
        elif self._is_number_divisible_by_three(number):
            return "Fizz"
        elif self._is_number_divisible_by_five(number):
            return "Buzz"
        else:
            return str(number)

    def _is_number_divisible_by_five_and_three(self, number):
        return number % 15 == 0

    def _is_number_divisible_by_three(self, number):
        return number % 3 == 0

    def _is_number_divisible_by_five(self, number):
        return number % 5 == 0

I'm happy with the last 3 methods that are clearly doing one thing. But the _parse_numbers and parse_number methods can be improved, I just don't know how to do that.


texts: SHA256 password hash generation and verification

texts:
I would like to optimise this code. It seems a bit verbose, particularly with the 'elseif' that doesn't do anything.

This code either:

takes a plain text password, generates a salt, and returns them both OR
takes a plain text password and a salt with which to encrypt the password, and returns them both (even though the salt has already been supplied).

class Member extends ActiveRecord\Model {

private function process_password($password, $salt = '') {
    /**
     * Process a password to encrypt it for storage or verification.
     * @param string - plain text password for processing.
     * @access private
     * @return array Containing the encrypted password and the salt.
     */

    //Check if the salt has been supplied. If not, generate one.
    if (!$salt) {
        $salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
    } elseif ($salt && strlen($salt) == 64)  {
        //Do nothing, the salt has already been supplied here.
    } else {
        log_message('info', 'Supplied password to process_password() was not the correct 64-byte length.');
        return false;
    }

    $hashed_password = hash('sha256', $password.$salt);

    return array('password' => $hashed_password, 'salt' => $salt);

}
}


texts: Dim Hero & Add Background to Nav on scroll

texts:
I have followed a tutorial that initially was for adding a 'sticky' nav. I adapted this slightly so it adds a background to the Nav when the page scroll reaches the top-third point of the hero area.

I then added a similar function that dims the hero area once the scroll gets to the midway point of the hero.

Both functions work in terms of displaying the expected results, but I am questioning the need for two almost identical functions and event listeners.

Could these be combined into one, complete function?

const hero = document.querySelector("#heroArea");
// Finds the top third of the element by adding the top of the element to the height of the element then divide by 3
const bottomOfNav = hero.offsetHeight / 3;
const middleHero = hero.offsetHeight / 2;

function fixNav() {
  // If the window position is greater or equal to the bottom of the nav
  if (window.scrollY >= bottomOfNav) {
    // Adds a class to the body tag
    document.body.classList.add("fixed-nav");
  } else {
    document.body.classList.remove("fixed-nav");
  }
}

window.addEventListener("scroll", fixNav);

function dimHero() {
  if (window.scrollY >= middleHero) {
    document.body.classList.add("dim-hero");
  } else {
    document.body.classList.remove("dim-hero");
  }
}

window.addEventListener("scroll", dimHero);
* {
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}

nav {
  position: fixed;
  width: 100%;
  left: 0;
  right: 0;
  color: #fff;
  padding: 15px;
  text-align: center;
  text-transform: uppercase;
  font-family: sans-serif;
  transition: .3s;
}

.fixed-nav nav {
  background: #333;
}

.hero {
  height: 100vh;
  background: black;
  opacity: 1;
  transition: .3s;
}

.dim-hero .hero {
  opacity: 0;
}

.text-block {
  height: 50vh;
  background: #555;
  color: #fff;
  font-size: 30px;
  text-align: center;
  padding: 40px;
}

.text-block-two {
  background: #333;
}

  Navigation

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eos ipsum et, omnis sit vero ab doloremque quia dolores mollitia. Doloremque maxime dolores quo eius ea. Ad, reiciendis minus. Dolorum, hic.

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eos ipsum et, omnis sit vero ab doloremque quia dolores mollitia. Doloremque maxime dolores quo eius ea. Ad, reiciendis minus. Dolorum, hic.


texts:
I'm a newcomer to C++, from C#. I wrote a program that prints an ASCII checkerboard with a side length of the number passed to it (link to original Code Golf question).

stdafx.h

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

#include <iostream>
#include <sstream>
#include <string>

Checkers.cpp

#include "stdafx.h"

using std::cin;
using std::cout;
using std::endl;
using std::stoi;
using std::string;
using std::stringstream;

string header(int num);

template <bool white>
string body(const string &head, int num);

template <bool white>
stringstream& append_body(stringstream &stream, int rem, int approx);

int _tmain(int argc, _TCHAR* argv[])
{
    int num;

    if (argc == 1 || ((num = stoi(argv[1])) < 0))
    {
        cout << "Usage: ./Checkers [nonnegative int]" << endl;
        return 1;
    }

    switch (num)
    {
    case 0:
        return 0;
    case 1:
        cout << "+--+" << endl << "|  |" << endl << \
            "|  |" << endl << "+--+" << endl;
        return 0;
    }

    int rem = num % 2;
    int approx = num - rem;

    const string& head = header(num);
    string& wtail = body<true>(head, num);
    string& btail = body<false>(head, num);

    string& block = wtail + btail;

    stringstream stream;

    for (int i = 0; i < approx / 2; i++)
        cout << block;

    if (rem == 1)
        cout << wtail;

    cout << head << endl;

#ifdef _DEBUG
    cin.get();
#endif
}

string header(int num)
{
    string result;

    for (int i = 0; i < num; i++)
        result += "+--";

    return result + '+';
}

template <bool white>
string body(const string &head, int num)
{
    int rem = num % 2;
    int approx = num - rem;

    stringstream stream;
    stream << head << endl;

    append_body<white>(stream, rem, approx) << endl;
    append_body<white>(stream, rem, approx) << endl;

    return stream.str();
}

template <bool white>
stringstream& append_body(stringstream &stream, int rem, int approx)
{
    const char *const block =
        white ? "|  |##" : "|##|  ";

    for (int i = 0; i < approx / 2; i++)
        stream << block;

    stream << '|';

    if (rem == 1)
        stream << (white ? "  |" : "##|");

    return stream; // not a local so this is OK
}

Questions:

I intentionally had a little fun optimizing prematurely here, i.e. generating the header ("+--+") and body ("|##|  |") strings only once instead of every loop. What could I do to increase readability without getting rid of each-loop optimizations like this?
When is it okay to use non-type template parameters, like I did in body? This means that you always have to rewrite your code when you want to offer a non-template alternative, correct?


texts: Properly mark up multiple person using schema.org microdata

texts:
I am creating a radio episode that will have multiple conductors (usually 1 to 3): inside a loop I am associating those conductors to director providing also the url linking to their respective conductors page:

    Conducted by

    start loop...

            {{name}}}

        <meta itemprop="jobTitle" content="Conductor">

    end loop....

but I am not sure if I am doing it well and I feel I could have done multiple mistakes:

The way I define the multiple person
How I am associating the url
The jobTitle (I expect this to better specify the director in some way)
span inside span (trying to have conductors on one line and inside an heading for better semantically specify that they important to the radio episode)


texts:
I just handed in my first assessed coursework for my Computer Science degree. Part of it was to take in a date (dd mm yyyy) between 1900 and 2100 and output the ordinal date. My function to do that is below.

I’m new to C - I’ve used Python, JavaScript and more recently Pascal, so I might be approaching this from the wrong direction, and there could be a more traditional method I should be using.

Any suggestions to make this more standard with C guidelines would be great - in addition to other algorithms I could have used.

int monthToDays(int day, int month, int year) {
  int monthLengths[11] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30}; // only 11 long because january -> 0 not 31

  monthLengths[1] = monthLengths[1] + checkIsLeap(year); //increase febuaray by 1 if it's a leap year

  int iMonth = 0;
  int totalDays = day;
                          // reduce by 1 because array is 0 indexed
  for (iMonth = 0; iMonth < month - 1; iMonth++) {
    totalDays = totalDays + monthLengths[iMonth];
  }

  return totalDays;
}

int checkIsLeap(int year) {

  int leap = 0;

  if (year % 4 == 0) {
    leap = 1;
    if (year % 100 == 0) {
      leap = 0;
      if (year % 400 == 0) {
        leap = 1;
      }
    }
  }

  return leap;
}


texts: What would be a better way of adding the functionality to "add" a student?

texts:
I have the following Student class:

class Student {
    public $user_id;
    public $name;

    public function __construct($user_id) {
        $info = $this->studentInfo($user_id);
        $this->name = $info['name'];
        $this->is_instructor = $info['is_instructor'];
        $this->user_id = $info['id'];
    }

    public function studentInfo($id) {
        global $db;

        $u = mysql_fetch_array(mysql_query("SELECT * FROM $db[students] WHERE id='$id'"));
        if($u) {
             return $u;
        }
    }

    public function getCoursesByInstructor() {
        global $db;

        return mysql_query("SELECT courses.*, course_types.name FROM $db[courses] as courses
                            JOIN $db[course_types] as course_types ON courses.course_type_id=course_types.id
                            WHERE instructor_id='$this->user_id'");
    }
}

Ideally, I'd do:

$u = new Student(1);
$courses = $u->getCoursesByInstructor();

Does anyone have any critiques on this class? Also, how would you recommend me adding functionality to "add" a student?


texts: Sort, & find out duplicates and missing elements in an array

texts:
this code is for return duplicates after sorted them, and also to
  return the missed value between the limits of the given array, it's
  executed correctly, but i need to optimize it so it excecute in less
  time than it execute can any one help?

function findDupsMiss(arr) {
    // your code here
    var noDuplicates = [];
    var missedNum;
    var duplicates = [];
    var sortedDuplicates =[]

arr.forEach((el, i) => {
 if(noDuplicates.includes(el) == false){
   noDuplicates.push(el)
 }
})
var sortedArr = noDuplicates.sort((a,b) => a-b);
for(var i=0 ; i<sortedArr.length -1 ; i++){
  if((sortedArr[i]+1) !== sortedArr[i+1]){
    missedNum = sortedArr[i] + 1
   }
}
arr.forEach( el => {
  if(arr.indexOf(el) != arr.lastIndexOf(el)){
    duplicates.push(el)
  }
})
duplicates.forEach(el => {
  if(sortedDuplicates.includes(el) == false){
   sortedDuplicates.push(el)
 }
})

var lastdup = sortedDuplicates.sort((a,b) => a-b);
return [missedNum , lastdup]

}
findDupsMiss([10,9,8,9,6,1,2,4,3,2,5,5,3])


texts: Test a single-line file for punctuation and newline

texts:
I have written the following program to read from a file (entire input in single line) and check for:

ASCII punctuation characters
a final newline

import re
file_name=input("Please enter the file name ")
with open(file_name, 'r') as fp:
    context=fp.read()
    regex = re.compile('[@_!#$%^&*()<>?/\|} {~]')
    if regex.search(context) is None:
        print("No special character found")
    else:
        print("Special character found")
    for x in range(0,len(context)-1):
        if (context[x].isspace())==True:
            print("spaces found in the file at ", x)
            break
        else:
            pass
        #print("No space found")
    for x in range(0, len(context)-1):
        if context[x]=='\n' or context[x]=='"':
            print("Yes new line is there at", x)
            break
        else:
            pass
        #print("No new line ")


texts: Excel VBA macro loops through 20-28 sheets taken from filenames in cells and pastes them to the main workbook

texts:
My apologies for a "repost", my original post was only partial and confusing. Here is a better snippet. This runs fairly slow (30 seconds or so) cycling through 20 workbooks. Any suggestions for improvement would be appreciated; I have left out my dimming of variables at the beginning, as well as my error handling portions, as those all work just fine.

For even MORE details, the user enters file paths into a column of up to 28 filepaths, and then the adjacent column derives the file name from the path. This macro, once initiated via a command button, begins cycling through all those filepaths, opening the document, copying and pasting it to the main workbook, until it reaches an empty cell in the column, to which then it stops.

There are also a few other small parts in there, like updating the last modified date when the button is clicked, as well as taking information from the first opened sheet to let the user know (on the main page) what kind of information is being pulled or has been pulled. Additionally, I often include frequent status bar updates for my impatient users who don't like staring at a spinning cursor without being told what's going on.

Private Sub CommandButton19_Click()

Application.DisplayStatusBar = True
Application.ScreenUpdating = False 'run faster
Application.DisplayAlerts = False 'prevents clipboard prompt
Application.Cursor = xlWait

On Error GoTo HandleIt

    Dim RangeDifferentiator As Integer
    Dim i As Long
    Dim SheettoCopyLoop
    Dim FileToCopyLoop
    Dim FileNameLoop

For i = 1 To 28 'start loop (28 because the last row being used is 34. If we need more rows this needs to change)

    RangeDifferentiator = i + 5
    Sheets("Admin").Select
    SheettoCopyLoop = Range("D" & RangeDifferentiator)
    FileToCopyLoop = Range("E" & RangeDifferentiator)
    FileNameLoop = Range("F" & RangeDifferentiator)

If FileToCopyLoop <> "" Then

    Application.StatusBar = "Pulling data for " & SheettoCopyLoop & "..." 'let's us know which one it's pulling
    Sheets(SheettoCopyLoop).Cells.ClearContents
    Workbooks.Open Filename:= _
        FileToCopyLoop
    'Needs optimizing
    Sheets("Summary").Cells.Copy

    'Establishes if this is a MTD or YTD file and up to what month it's pulling
    If i = 1 Then
        Workbooks("YTD File.xlsm").Sheets("SM Summaries").Range("C2").Value = ActiveWorkbook.Sheets("Summary").Range("C6").Value
        Workbooks("YTD File.xlsm").Sheets("SM Summaries").Range("C4").Value = ActiveWorkbook.Sheets("Summary").Range("C5").Value
    End If

    'Needs optimizing
    Windows("YTD File.xlsm").Activate
    Sheets(SheettoCopyLoop).Select
    Sheets(SheettoCopyLoop).Range("A1").Select
    ActiveSheet.Paste
    ActiveSheet.Range("A1").Select
    Windows(FileNameLoop).Close
    Sheets("Admin").Select
    Range("A1").Select

Else
Application.StatusBar = "READY"
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.Cursor = xlDefault
'Show last modified date on admin page for the user
Workbooks("YTD File.xlsm").Sheets("Admin").Range("F1").Value = "Last modified: " & Date
MsgBox "Data pull complete!", vbInformation, "Success!"
Exit Sub
End If

Next i
Exit Sub

'The following is all error handling to help show what went wrong and where
HandleIt:
If SheettoCopyLoop <> "" Then
errorhandler = MsgBox("Oops! An error has occured on page " & SheettoCopyLoop & ". Check to make sure file exists/file path is correct.", vbExclamation, "Error!")
Application.StatusBar = "Error occured on page " & SheettoCopyLoop 'Show where error occured on status bar if applicable
Else
errorhandler = MsgBox("Oops! An unknown error has occured.", vbCritical, "Error!")
Application.StatusBar = "Unknown error"
End If
Worksheets("Admin").Activate
Range("H7").Select
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.Cursor = xlDefault
Exit Sub
End Sub


texts:
I was doing container with most water question in Leetcode for which I wrote this algorithm

Question link: https://leetcode.com/problems/container-with-most-water

Question:

  Given n non-negative integers a1, a2, ..., an , where each represents
  a point at coordinate (i, ai). n vertical lines are drawn such that
  the two endpoints of line i is at (i, ai) and (i, 0). Find two lines,
  which together with x-axis forms a container, such that the container
  contains the most water.

  Note: You may not slant the container and n is at least 2.

Input: [1,8,6,2,5,4,8,3,7]

/**
 * @param {number[]} height
 * @return {number}
 */

var maxArea = function(height) {
    let currentHighest=0
    while(height.length) {
        const num = height.shift()
        let j=0
        while(j<height.length) {
            const lowerNum = Math.min(num, height[j])
            const distance = j+1
            const area = distance * lowerNum
            currentHighest = Math.max(currentHighest,  area)
            j++
        }
    }
    return currentHighest
};

but it appears so this code isn't opimized, Can someone help me in optimizng the above code?


texts:
I am trying to expose a simple struct via FFI. Is this the best way to do it?

I am not 100% sure about the get_text function. This is taking the string out of the struct and cloning it before returning a pointer to it. I suspect this is going to leak. Whats the best idiomatic way around this? Do I need to provide a free_string function? Is there a way to just return a pointer into the Rust string?

use std::mem;
use std::os::raw::{c_char, c_void};
use std::ffi;

#[derive(Debug)]
pub struct SomeData {
    text : String,
    number : usize,
}

#[no_mangle]
/// Make the structure. Box it to stick on the heap and return a pointer to it.
/// This absolves Rust from having to deal with the memory, so it is the callers
/// responsibility to free it by calling drop_data.
pub extern "C" fn make_some_data (text: *const c_char, number: usize) -> *mut c_void {
    let cstr = unsafe {
        assert!(!text.is_null());
        ffi::CStr::from_ptr(text)
    };

    let data = cstr.to_str().ok().map(|utf8_str| {
        Box::into_raw(Box::new(SomeData {
            text: String::from(utf8_str),
            number,
        }))
    }).unwrap();

    data as *mut c_void
}

#[no_mangle]
/// Returns the text field of the struct.
pub extern "C" fn get_text(data: *mut c_void) -> *mut c_char {
    let data = unsafe {
        assert!(!data.is_null());
        Box::from_raw(data as *mut SomeData)
    };
    let text = data.text.clone();
    mem::forget(data);
    ffi::CString::new(text).unwrap().into_raw()
}

#[no_mangle]
/// Returns the number field of the struct.
pub extern "C" fn get_number(data: *mut c_void) -> usize {
    let data = unsafe {
        assert!(!data.is_null());
        Box::from_raw(data as *mut SomeData)
    };
    let number = data.number;
    mem::forget(data);
    number
}

#[no_mangle]
/// Frees the memory.
pub extern "C" fn drop_data (data: *mut c_void) {
   mem::drop(data);
}


texts: Block Allocation in Fixed-Size Block Allocator

texts:
The following routine is the block-allocation procedure in a fixed-size allocator being written for library use. It is designed to be accessed from C++ (the un-mangled symbol name is void * Superblock::alloc_block()). The performance of this routine is the critical to the library; and I, with almost no prior experience in assembly, am looking for suggestions about performance and also any holes in the logic. It seems to be working correctly right now, but I'm worried about edge cases.

Execution context: written for x86_64 System V abi, full allocator may be found here: https://github.com/cmura81/experimental-allocator.

alloc_sb_alloc_block.s:

.globl __ZN10Superblock11alloc_blockEv

// 'this is passed in %rdi
// Variables:
//    this->beginning = 0(%rdi) +8
//    this->last_privately_freed_block = 8(%rdi) +8
//    this->last_publicly_freed_block = 16(%rdi) +8
//    this->block_size = 24(%rdi) +2
//    this->free_blocks = 26(%rdi) +2
//    this->max_blocks = 28(%rdi) +2

__ZN10Superblock11alloc_blockEv:
  xorq %rcx, %rcx
  // this->beginning -> rsi
  movq 0(%rdi), %rsi
  // allocated_block = this->last_privately_freed_block
  movq 8(%rdi), %rax
  // if this->last_privately_freed_block == NULL
  testq %rax, %rax
  jz __ZN10Superblock11alloc_blockEv.i_pubchalloc
  // this->free_blocks--
  decw 26(%rdi)

  // Move 2 bytes from rax into edx
  movzwl (%rax), %edx
  notw %dx
  jz __ZN10Superblock11alloc_blockEv.i_nbi_ffff
  notw %dx
  movslq %edx, %rcx
  // this->last_privately_freed_block = this->beginning + next_block_index
  addq %rcx, %rsi
  movq %rsi, 8(%rdi)

  ret
__ZN10Superblock11alloc_blockEv.i_nbi_ffff:
  movq $0, 8(%rdi)
  ret
__ZN10Superblock11alloc_blockEv.i_pubchalloc:
  movq 16(%rdi), %rax
  // if this->last_publicly_freed_block == NULL
  testq %rax, %rax
  jz __ZN10Superblock11alloc_blockEv.i_noalloc
  // this->free_blocks--
  decw 26(%rdi)

  // if *(uint16_t)(this->last_publicly_freed_block + next_block_index) == 0xFFFF
  movzwl (%rax), %edx
  notw %dx
  jz __ZN10Superblock11alloc_blockEv.i_pubnbi_ffff
  notw %dx
  movslq %edx, %rcx
  // this->last_privately_freed_block = this->beginning + next_block_index
  addq %rcx, %rsi
  movq %rsi, 16(%rdi)
  ret
__ZN10Superblock11alloc_blockEv.i_pubnbi_ffff:
  movq $0, 8(%rdi)
  ret
__ZN10Superblock11alloc_blockEv.i_noalloc:
  movq $0, %rax
  ret


texts: Checking if a Chess space has been attacked

texts:
I have this list of at least seven else-if. When their condition is met, I change the same boolean is_attacked to true. This should be simple but I can't figure out in what way I can achieve the same in a more readable way.

if(request_is_attacked){
    if(as_knight){
        if(piece_abs_val==2){//knight
            is_attacked=true;
        }
    }else if(piece_abs_val==6){//king
        if(i==0){
            is_attacked=true;
        }
    }else if(piece_abs_val==5){//queen
        is_attacked=true;
    }else if(piece_direction%2){
        if(piece_abs_val==4){//rook
            is_attacked=true;
        }
    }else if(piece_abs_val==3){//bishop
        is_attacked=true;
    }else if(i==0 && piece_abs_val==1){
        if(piece_val!=-1){//w_pawn
            if(piece_direction==4 || piece_direction==6){
                is_attacked=true;
            }
        }else{//b_pawn
            if(piece_direction==2 || piece_direction==8){
                is_attacked=true;
            }
        }
    }
}

For more context, this is happening inside a loop (hence the i), when the i is the first it means it is one square apart (i==0), so Pawns and Kings use this, but this information shouldn't matter much.

Also, when piece_direction%2 is true, we are moving in a + (that's why I check for Rooks), else it means we are in moving x direction, so I proceed to check for Bishops and Pawns.


texts:
I have implemented to following generic factory in C++11 using smart pointers and I would like to get some feedback about it.

(Please note that I can't use C++14)

Due to company policies I have to change the names of the business objects.

class Car{};
class Taxi : public Car{};
class Police : public Car{};

class CarFactory {

public:
    enum CarName {TaxiName, PoliceName};

    std::unique_ptr<Car> getCar(CarName sa) {
        if (d_carMap.find(sa) == d_carMap.end()) {
            d_carMap[sa] = std::move(createCar(sa));
        }
        return std::move(d_carMap[sa]);
    }

private:
    std::unordered_map<CarName,
                       std::unique_ptr<Car>,
                       std::hash<int>> d_carMap; //hash is for enum

    std::unique_ptr<Car> createCar(CarName sa) {

        if (sa == CarName::TaxiName){
          return std::unique_ptr<Car>(new Taxi());
        } else if (sa == CarName::PoliceName) {
          return std::unique_ptr<Car>(new Police());
        }

        return nullptr; //no car found for provided argument.
    }

};

Which of the moves are actually needed here?
What happens to the unique_ptrs, if this factory is used in a multi threading environment?
Is std::unique_ptr<Car>(new Taxi()); really the best way of instantiating a smart pointer in C++11 (which doesn't have make_unique)?
Should the enum be a class, even if I can't use std::hash on it?
Where would you define the enum? In a separate header file? In the same
header, outside of the class (but in a namespace)?
How should the unit test look like?

I wrote the following test which actually fails on the indicated line:

TEST(CarFactoryTest, retrieveTaxi) {

    CarFactory sf;

    auto Car = sf.getCar(CarFactory::CarName::TaxiName);
    if (!Car) {
        FAIL();
    }

    if (dynamic_cast<Taxi*>(Car.get()) == nullptr) {
        FAIL();
    }

    //this time get it from the map
    Car = sf.getCar(CarFactory::CarName::TaxiName);
    if (!Car) {
        FAIL(); //Test fails here!
    }

    if (dynamic_cast<Taxi *>(Car.get()) == nullptr) {
        FAIL();
    }
}


texts: Making change using the smallest possible number of coins

texts:
I have written code based on the Greedy Algorithm. The example can be found here.

  Problem: Make a change of a given amount using the smallest possible number of coins.

  Coins available are:

  dollars (100 cents)
  quarters (25 cents)
  dimes (10 cents)
  nickels (5 cents)
  pennies (1 cent)

This outputs an array of coins:

<?php

function makeChange($amount) {
    $c = array(100, 25, 10, 5, 1);
    $sol = array();
    $sum = 0;
    $i = 0;
    $ele = $c['0'];
    while ($sum != $amount) {
        $sum = $sum + $ele;
        if ($sum > $amount) {
            $sum = $sum - $ele;
            $i++;
            $ele = $c[$i];
            continue;
        }
        $sol[] = $ele;
    }
    return $sol;
}

$amount = 356;
$sol = makeChange($amount);
print_r($sol);
?>

Can this become more optimized?


texts: Subclassed Python Counter for a more visually user-friendly __str__() method, for anagrams

texts:
I wrote a Counter subclass suitable for anagrams, with a more visually user-friendly __str__() method using alphabetic ordering and Unicode superscripts(/subscripts) for letter-counts, so you can compare at-a-glance if two phrases are anagrams or not:

c1 = LetterCounter("PRESIDENTTRUMP")
print(c1)
D¹ E² I¹ M¹ N¹ P² R² S¹ T² U¹

Code below. My questions:

translating integer to superscript(/subscript) is really clunky. Anything more compact?
Counter.items() actually returns a view. It would be more elegant if it was similarly possible to define sorted_items() as a view instead of taking sorted(list(self.items()))
leave the subscript code in even though it's not currently used
applying .format() to a variable-length list of tuples is a pain, can't just use *args.

'{0[0]}{0[1]}'.format(x for x in value_count) fails with 'generator' object is not subscriptable
'{0[0]}{0[1]} '.format([x for x in value_count]) is wrong, the format is outside the list comprehension.
[ '{0[0]}{0[1]} '.format(x) for x in value_count ] won't allow us  call LetterCounter.int_to_superscript() on only the second item of each tuple.
any more elegant approaches?

in general we're supposed to override __str__() not __repr__(), but if we don't care about pickling why not just override __repr__(), then we can directly see the object just by typing its name, don't need print?
after I independently wrote this I found Printing subscript in python
it seems more friendly for general use/reposting to enter Unicode literals in source as '\u2070' rather than '⁰'

Code:

import collections

class LetterCounter(collections.Counter):

    subscript_digits   = ''.join([chr(0x2080 + d) for d in range(10)])
    superscript_digits = ''.join(['\u2070','\u00b9','\u00b2','\u00b3','\u2074','\u2075','\u2076','\u2077','\u2078','\u2079'])
    trans_to_superscript = str.maketrans("0123456789", superscript_digits)
    trans_to_subscript   = str.maketrans("0123456789", subscript_digits)

    @classmethod
    def int_to_superscript(cls, n):
        return str(n).translate(cls.trans_to_superscript)
    @classmethod
    def int_to_subscript(cls, n):
        return str(n).translate(cls.trans_to_subscript)

    def __str__(self):
        value_count = sorted(list(self.items()))
        return ' '.join( '{}{}'.format(x[0], LetterCounter.int_to_superscript(x[1])) for x in value_count )

# Test code
c1, c2 = LetterCounter("PRESIDENTTRUMP") , LetterCounter("MRPUTINSREDPET")
print(c1)
D¹ E² I¹ M¹ N¹ P² R² S¹ T² U¹


texts: SICP - exercise 2.5 - Represent pairs of nonnegative integers

texts:
Exercise 2.5.  Show that we can represent pairs of nonnegative
  integers using only numbers and arithmetic operations if we represent
  the pair a and b as the integer that is the product 2^a*3^b.
  Give the corresponding definitions of the procedures cons, car,
  and cdr.

There are already two solutions for this exercise on this site. However, I believe mine is different, for its order of growth of number of steps is Θ(log(n)), rather than Θ(n).

While my solution would presumably runs faster when number becomes incredibly large, but is it necessary to exchange so much elegance for efficiency? Also, I've used primitive procedure log and gcd, which I assume have Θ(1) and Θ(log(n)) order of growth respectively. Am I right? Would the use of them slow down my program?

Please give me your advice.

;;; Exercise 2.5
;;; ============

(define (cons x y)
  (* (expt 2 x)
     (expt 3 y)))

; return a power of b that is bigger than z
(define (bpf b z)
  (define (iter p)
    (if (> p z)
      p
      (iter (square p))))
  (iter b))

(define (car z)
  (inexact->exact (/ (log (gcd z (bpf 2 z)))
                     (log 2))))

(define (cdr z)
  (inexact->exact (/ (log (gcd z (bpf 3 z)))
                     (log 3))))

(define x 12)
(define y 16)
(define z (cons x y))

(car z)
;Value: 12
(cdr z)
;Value: 16

Note: As @Renzo kindly pointed in his comment below, you might have to use (inexact->exact (round (/ (log ... in order to make my code work in your Lisp implementation. Sorry for the inconvenience.