Presenting user with options and executing a function based on user choice in Javascript I'm currently creating a text based game where the user navigates through the game via buttons and i'm trying to improve on my code because i'm pretty sure it could be alot better, the following is some code which i wrote to give the user some options (via html buttons) and then check what their selection is in order to execute the correct function.
class Room {

    constructor(description, options) {

        this.description = description;
        this.options = options;

    }
}

 var f1hallway = new Room("You see two rooms", ["Room 1", "Room 2"]);

 var f1room1 = new Room("You find a letter on a table", ["Read it", "Exit"]);

 var f1room2 = new Room("Nothing of interest here", ["Exit"]);

    whichArea = function(areaSelected) {

                selectedArea = areaSelected;
                areaSelected();

              }

    function presentChoices(options) {

              choices.innerHTML = "";

         for (var x = 0; x < options.length; x++) {

            choiceButton = document.createElement("button");
            choiceButton.setAttribute("class", "choice-button");
            choices.appendChild(choiceButton);
            choiceButton.innerHTML = options[x];
            selectedChoiceIndex = x;
            choiceButton.setAttribute("id", x);

             choiceButton.onclick = function() {

                selectedChoice = this.innerHTML;
                chosenOptionId = this.id;
                whichArea(selectedArea);

             }

        }

    }

function f1hallwayFunc() {

        mainText.innerHTML = f1hallway.description;
        choices.innerHTML = "";
        presentChoices(f1hallway.options);

        if (chosenOptionId == 0) {

            chosenOptionId = null;
            whichArea(f1roomOneFunc);

        }

        else if (chosenOptionId == 1) {

            chosenOptionId = null;
            whichArea(f1roomTwoFunc);

        }

function f1roomOneFunc() {

    mainText.innerHTML = f1room1.description;
    presentChoices(f1room1.options);

     if (chosenOptionId == 0) {

        chosenOptionId = null;
        mainTextWrap.innerHTML = "You start reading the letter";

    }

    else if (chosenOptionId == 1) {

        chosenOptionId = null;
        whichArea(f1hallwayFunc);
        mainText.innerHTML = "You exit the room and return to the hallway";

    }

}

function f1roomTwoFunc() {

    mainText.innerHTML = f1room2.description;
    presentChoices(f1room2.options);

     if (chosenOptionId == 0) {

        chosenOptionId = null;
        whichArea(f1hallwayFunc);
        mainText.innerHTML = "You exit the room and return to the hallway";

    }

}

The code works fine but seems like a mess at the same time, each area that the user ends up in goes through this same process, can someone please tell me how this could be written better and any best practices i'm missing? I'm still quite new to programming and would appreciate any help, thanks!

I think a good way to approach this would be to integrate all the data (descriptions, options, and additional room choices) into an object indexed by room number or step name (since multiple things can be done in a single room). Starting at the first room, parse the data for that room to display the description and choices appropriately, and continue recursively whenever a new choice is made. Doing it this way means that, to set up the rooms, you only need to change around the object room numbers and strings instead of writing convoluted JavaScript logic.
For example, for the hallway and 2 rooms, you could have:
const steps = {
  hallway: {
    desc: 'You see two rooms',
    choices: ['Room 1', 'Room 2']
  },
  'Room 2': {
    desc: 'Nothing of interest here',
    // when the choice description and JS step name are not the same,
    // separate them
    choices: [{ desc: 'Exit', target: 'hallway' }]
  },
  'Room 1': {
    desc: 'You find a letter on the table',
    choices: [
      { desc: 'Read it', target: 'readLetter' },
      { desc: 'Exit', target: 'hallway', onChoiceDesc: 'You exit the room and return to the hallway' }
    ]
  },
  readLetter: {
    // ...
  },
};

Whenever a new step runs, if the choice that was just chosen had a onChoiceDesc property, display that. Otherwise, display the desc of the new step onto the page. Iterate through each choice to add a button, a button description, and a click handler.
To conditionally display a choice depending on program state, add a function to the choice object. Eg, if, after reading the letter, something becomes available in the hallway, you could add the following:
choices: ['Room 1', 'Room 2', { desc: 'Room 3', target: 'Room 3', showIf: () => hasReadLetter }]

readLetter: {
  desc: 'You start reading the letter. The letter informs you that Room 3 exists',
  choices: [
    { desc: 'Exit', target: 'hallway', onChoiceFn: () => hasReadLetter = true }
  ]
}

where onChoice gets invoked when the button is clicked (in addition to the default behavior of re-rendering the hallway step). (Make sure to have declared a hasReadLetter variable outside.)
That's the general idea - leave the manipulation of the DOM to the other code that parses through the steps object, while writing the meat of the game inside the steps object.

Although you'll probably be ditching most of it, some suggestions regarding your current code:
Classes are good for tying together data with methods related to the data. If all you have is plain data, a class doesn't help you. In your case, unless you were planning on adding methods later, using a plain object would make more sense for the Rooms.
Use consistent indentation so that you (and other readers of the code) can pick up on the { } blocks at a glance. Ideally, use an IDE that indents code properly and automatically. For example, this:
}
 var f1hallway = new Room("You see two rooms", ["Room 1", "Room 2"]);
    whichArea = function(areaSelected) {
                selectedArea = areaSelected;

should be
}
var f1hallway = new Room("You see two rooms", ["Room 1", "Room 2"]);
whichArea = function(areaSelected) {
    selectedArea = areaSelected;

Declare variables before using them - if you don't, you'll either be implicitly assigning to the global object (which is inelegant), or an error will be thrown if running in strict mode (and strict mode is recommended). Not declaring a variable before using it is a not-uncommon source of bugs when one finds that the variable isn't scoped as one expected it to be. The whichArea = should be let whichArea =.
Use modern syntax If you're going to write in ES6+ (which you are with the class, and as you should), never use var, it has too many gotchas to be worth using nowadays - use const instead when declaring variables, or use let when you have to reassign the variable.
Prefer IDL properties over setAttribute when feasible - IDL properties are usually more concise and easier to read and write. These two:
choiceButton.setAttribute("class", "choice-button");
choiceButton.setAttribute("id", x);

can be
choiceButton.className = "choice-button";
choiceButton.id = x;

(though, neither of those should be necessary at all: to target the button with CSS, you should be able to do .choices > button, by giving the parent a class name instead. Dynamic IDs are quite a code smell too - to get the index inside a click handler, either check the child's index in an array of all siblings, or use a data attribute, or a Map - but not an ID. Or, even better, in this case, just use the closure in the click handler over the index being iterated over.)
Prefer .textContent over .innerHTML unless you're deliberately setting text content; .textContent is faster, safer, and more semantically appropriate.
Prefer strict equality - loose equality with == and != has a whole bunch of weird coercion rules that neither you nor others who happen to read the code should have to have memorized to understand what's going on. Use === and !== instead.


Efficiently find all the Pythagorean triplets where all numbers less than 1000 How can I make this code run faster:
for a in range(1,1001):
    for b in range(1, 1001):
        for c in range(1, 1001):
            if pow(a, 2) + pow(b, 2) == pow(c, 2):
                print(str(a) + "," + str(b) + "," + str(c))

Some optimizations and style suggestions:

After finding a solution you can break:
for a in range(1,1001):
    for b in range(1, 1001):
        for c in range(1, 1001):
            if pow(a, 2) + pow(b, 2) == pow(c, 2):
                print(str(a) + "," + str(b) + "," + str(c))
                break

Use ** which is faster than pow, or just multiply for itself a*a.
Use Python formatter to print the result: print(f"{a},{b},{c}").
Calculate c as \$c=sqrt(a^2+b^2)\$:
for a in range(1,1001):
    for b in range(1, 1001):
        c = int(math.sqrt(a ** 2 + b ** 2))
        if a ** 2 + b ** 2 == c ** 2 and c < 1001:
            print(f"{a},{b},{c}")

The solution now takes \$O(n^2)\$ instead of \$O(n^3)\$.
Instead of checking if a ** 2 + b ** 2 == c ** 2:, it's enough verifying that c is an integer:
for a in range(1,1001):
  for b in range(1, 1001):
      c = math.sqrt(a ** 2 + b ** 2)
      if c.is_integer() and c < 1001:
          print(f"{a},{b},{int(c)}")

As already said, you can also start the second for-loop from a to avoid duplicated solutions.
Put everything into a function:
def triplets(n):
  for a in range(1, n):
      for b in range(a, n):
          c = math.sqrt(a * a + b * b)
          if c.is_integer() and c <= n:
              print(f"{a},{b},{int(c)}")
triplets(1000)

Runtime on my machine:
Original: 868.27 seconds (~15 minutes)
Improved: 0.27 seconds

EDIT:
Since this question got a lot of attention I wanted to add a couple of notes:

This early answer was for OP's original problem that I interpreted as "find all the triplets in a reasonable amount of time".
There are definitely more efficient (and advanced) solutions than this one. If you are interested in finding out more, have a look at other excellent answers on this thread.
As noted in the comments, the runtime in my answer is a rough calculation. Find a better benchmark on @Stefan's answer.


Login program in Python I wrote this login program as part of my project for school. Should I use my implementation of a login program, or is there some standardized patterns of login programs, like the ones in encryption where we use made packages instead of writing our own?

Also, please correct me if am doing anything wrong or if there is a faster and more elegant way.

users = []

"""
    Look of data.txt

    john|mckinly|tree|ssap321
    elie|rose|sweet|pass123

"""

def loadData():
    with open('data.txt','r') as data:
        for line in data:
            user = makeUser(line)
            users.append(user)
    return True

def saveData():
    with open('data.txt','w') as data:
        for user in users:
            print(user['name']+'|'+user['surname']+'|'+user['username']+'|'+user['password'],file = data)

def makeUser(line):
    name, surname, username, password = line.split('|')
    if password[-1:] == '\n':
        password = password[:-1]
    return {'name':name,
            'surname':surname,
            'username':username,
            'password':password
            }

def register():
    name = input('Name:')
    surname = input('Surname:')
    while True:
        username = input('Username:')
        if checkLen(username):
            break

    while True:
        password = input('Password:')
        if checkLen(password):
            break
    users.append({'name':name,'surname':surname,'username':username,'password':password})

def checkLen(info):
    if len(info) > 0:
        return True
    else:
        print('Can\'t be blank!')

def login(state):
    while state:
        username = input('Username:')
        password = input('Password:')
        for user in users:
            if user['username'] == username and user['password'] == password:
                print('You are logged in.')
                state = False
                break
        else:
            print('Wrong input.')

def main():
    state = loadData()

    print('1) Login')
    print('2) Register')
    print('x - Exit')
    choice = input('>')

    while choice not in ['1','2','x']:
        choice = input('>')

    if choice == '1':
        login(state)
    elif choice == '2':
        register()
        main()
    elif choice == 'x':
        saveData()
        quit()

        if __name__ == '__main__':
    main()

The biggest problem you currently have is keeping the passwords in plain text - use a one-way irreversible hash function, like argon2 or bcrypt.

Going even further, you should not be doing it yourself and instead trust something stable that have already proved itself of being mature and safe - like passlib library.

If you know that user authentication part is going to become more complicated, think about using a specialized User Directory like LDAP or Active Directory - there is a third-party ldap package that you can use for your client implementation.

Also, when a password is entered, the input should be hidden - there is a getpass module specifically for this kind of use case. Also, look into getuser() function for the login prompt.

There are also different third-party libraries, like click or cement that might help in making building the CLI apps easier. Explore the other CLI libraries at the awesome-python list.


Tail-recursive call vs looping for a Poker app I'm developing a Poker app. It is almost done, and I'm looking for improvement. One of the things I wonder is whether I should change how I perform iterations. I currently iterate by using tail-recursive calls. However, a friend of mine suggested that I use a while loop instead because loops don't require stack space.

private async Task Turns()
    {
        _turns = ReturnTurns();
        GC.KeepAlive(Updates);
        if (!Player.FoldTurn && Player.Chips > 0)
        {
            if (Player.Turn)
            {
                SetPlayerStuff(true);
                Call -= Player.PreviousCall;
                _up = int.MaxValue;
                _turnCount++;
                Bot1.Turn = true;
                _restart = true;
            }
        }
        if (!Player.Turn)
        {
            await Flip(0);
        }
        if (Player.FoldTurn || !Player.Turn || Player.Chips <= 0)
        {
            Call = TempCall;
            if (StatusLabels[Player.EnumCasted].Contains(RepetitiveVariables.Fold))
            {
                Bot1.Turn = true;
            }
            SetPlayerStuff(false);
            Bot1 = (Bot)await RotateTurns(Bot1, Bot1.EnumCasted);
            Bot2 = (Bot)await RotateTurns(Bot2, Bot2.EnumCasted);
            Bot3 = (Bot)await RotateTurns(Bot3, Bot3.EnumCasted);
            Bot4 = (Bot)await RotateTurns(Bot4, Bot4.EnumCasted);
            Bot5 = (Bot)await RotateTurns(Bot5, Bot5.EnumCasted);
            _restart = false;
        }
        if (!_restart)
        {
            await Turns();
        }
    }

That's how I think it should look like with a while loop:

    private async Task Turns()
    {
        while (true)
        {
            _turns = ReturnTurns();
            GC.KeepAlive(Updates);
            if (!Player.FoldTurn && Player.Chips > 0)
            {
                if (Player.Turn)
                {
                    SetPlayerStuff(true);
                    Call -= Player.PreviousCall;
                    _up = int.MaxValue;
                    _turnCount++;
                    Bot1.Turn = true;
                    _restart = true;
                }
            }
            if (!Player.Turn)
            {
                await Flip(0);
            }
            if (Player.FoldTurn || !Player.Turn || Player.Chips <= 0)
            {
                Call = TempCall;
                if (StatusLabels[Player.EnumCasted].Contains(RepetitiveVariables.Fold))
                {
                    Bot1.Turn = true;
                }
                SetPlayerStuff(false);
                Bot1 = (Bot) await RotateTurns(Bot1, Bot1.EnumCasted);
                Bot2 = (Bot) await RotateTurns(Bot2, Bot2.EnumCasted);
                Bot3 = (Bot) await RotateTurns(Bot3, Bot3.EnumCasted);
                Bot4 = (Bot) await RotateTurns(Bot4, Bot4.EnumCasted);
                Bot5 = (Bot) await RotateTurns(Bot5, Bot5.EnumCasted);
                _restart = false;
            }
            if (!_restart)
            {
                continue;
            }
            break;
        }
    }

GC.KeepAlive(Updates);

Do you really need to do this? Objects are not collected as long there is a valid reference to them meaning that Updates should always be avaiable if you are not replacing the reference. If you are replacing the reference it means that you are not keeping you object alive long enough for the current game which sounds leaky.

Bot1 = (Bot)RotateTurns(Bot1, Bot1.EnumCasted);

RotateTurns should be an instance method on Bot and should not be present on the current scope. And once again you are replacing the object reference.
The bots should be alive at least as long as a game instance.

It would be better to keep a list of all bots so you could iterate on them.

foreach(var bot in _bots){
    await bot.RotateTurns();
}

if (!_restart)
{
    continue;
}
break;

The !_restart condition could be placed on the while. Also consider to keep this a method variable instead of a field.

while(!_restart)


Component functions - static vs. OO? I'm writing a small PHP framework to help me develop Web applications. The framework is split into numerous components, each of which are automatically loaded according to the configuration settings. This is my component base class:

class Component {
    public static void init() {}
}

When I create new components, I extend them from Component. For example, I have an Authenticator component that handles user login, logout and some other related functions. Here's an example of the code:

class Authenticator extends Component {
     public static void login($u, $p) {}
     public static void logout() {}
     ...
}

As you can see my methods are static, so when it comes time to use the component, I can easily call the component's functions using Authenticator::METHOD() in the scope of my controller class. There is no need to create an instance of the components since they are in a static context.

But should I make them more OO (eg: make the methods non-static) using DI or some other means? What would be the advantages of this? And considering how I have several components, how would I do this without making things overly complex?

The OO equivalent of this is one of:

interface Component {
   public function init();
}

class Authenticator implements Component {
}

// OR

abstract class Component {
   abstract public function init();
}

class Authenticator extends Component {
}

Yes, you will have to create objects without using static.  Its really not so bad though.

What are the benefits?  I created my own framework that is pure OO.  So here is an example of what OO code looks like with dependency injection.  I'll describe what it does afterwards so that you get an idea of some of the benefits.

<?php
class Page_XML_Site_Locations extends Page_XML_Site
{
   public function contentMain()
   {
      $model = $this->app->getModelDB(
         'Model_DB_Joint',
         array('Table_Name'       => 'Location',
               'Table_References' => $this->app->getTableReferences(
                  array('References' => array(
                           'Image_List_ID' => array(
                              'Child_Field' => 'List_ID',
                              'References'  => array(
                                 'Image_ID' => array(
                                    'Child_Field' => 'ID',
                                    'Table_Name'  => 'Image')),
                              'Table_Name'  => 'Image_List'),
                           'Map_ID'        => array(
                              'Child_Field'  => 'Map_ID',
                              'Table_Name'   => 'Map')),
                        'Table_Name' => 'Location'))));

      $processing = $this->app->getProcessingNone();
      $settings = $this->app->getSettings();

      $data = $this->app->getData(
         array('Image_List_ID' => $this->app->getNew(
                  'Data_Image_List',
                  array('Dir'         => $settings['Web']['DB_Storage'] .
                        'img/location/',
                        'Empty_Image' => $settings['Web']['No_Photo'],
                        'Formats'     => array('W_Min'),
                        'Image'       => $this->app->getShared('Image'),
                        'Image_Sizes' => $this->app->getShared('Image_Sizes'),
                        'References' => array(
                           'Image_ID' => $this->app->getData()),
                        'Translator'  => $this->tr)),
               'Map_ID'        => $this->app->getNew(
                  'Data_Map',
                  array('References' => array(),
                        'Sensor'     => 'false',
                        'Size'       => '320x320'))));

      $view = $this->app->getView('View_XML_Locations',
                                  array('Data'         => $data,
                                        'Image_Format' => 'W_Min'));

      $controller = $this->app->getController();
      $controller->execute();
   }
}
// EOF

$this->app is my application container responsible for creating and retrieving resources.  It is a dependency injection container.  There are no calls to new or evil getInstance singletons.  All of the objects are managed via the container.

Distinct objects are created (model, processing, settings, data, view, controller).  They stand alone (except data which is only created for injection into the view).  I don't have to worry about their interface to each other.  It is all handled by my event manager and controller.  The objects each handle their own area.  The Model gets joint data from its referenced tables.  The processing handles any POST or GET requests.  Everything does its job (which produces a list of stores in the correct language with their details, images and maps for finding them).  There is nothing complex to worry about with who is calling who.

That is the top level view.  What did I have to do to complete that page?

Model, Processing, Settings, Controller - Nothing, that is straight from the framework.
Data_Image_List - calculate the image file name from the DB table and constructor settings.
Data_Map - calculate the google static map string from the DB table and constructor settings.
View - This is where most of the work goes.  Loop through the data, writing the elements.

If you don't like the look of the code that I use with my framework then you should probably ignore my suggestions.

What will your Authenticator component do?  How tightly will it be coupled to the rest of your system?  Can it stand alone allowing you to kepp all your logic for each part of your system distinct?


Use of a regex stored inside a YAML file I installed settingslogic and in the configuration file I put the regex for the email as follows:

#config/settings.yml
defaults: &defaults

  email_regex: /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i

development:
  <<: *defaults
  # neat_setting: 800

test:
  <<: *defaults

production:
  <<: *defaults

That I load in devise configuration in this way:

#config/initializers/devise.rb
  # Regex to use to validate the email address
  # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i
  config.email_regexp = eval Settings.email_regex

It works, but what do you think about that eval? Is it the correct way to convert a string to a regex?

If you want to use a regexp in a yaml file you need to use !ruby/regexp

#config/settings.yml
defaults: &defaults

  email_regex: !ruby/regexp '/^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i'

Edit:
 The solution proposed by Mike Bethany is very similar to the yaml implementation.

You can take a look to what is used in Ruby 1.9.2 here (search for "!ruby/regexp"):
https://github.com/tenderlove/psych/blob/master/lib/psych/visitors/to_ruby.rb

PS (and OT): I think, like Mike Bethany, that this basic functionality belong to the Regexp class not yaml, and need to be moved to a Regexp method. What do you think?


Access an associative array value given an array of keys in PHP I have an object which stores an app configuration in an associative array, as this:

[
  'Database' =>
    [
      'DB_SERVER' => 'localhost'
      'DB_NAME' => 'adbname'
      'DB_USER' => 'theuser'
      'DB_PASS' => 'thepass'
    ]
]

And a function, get(), which receives a variable number of arguments and returns the configuration value for this parameters. For example, Config::get('Database','DB_PASS') will return 'thepass'.

This is an excerpt of the code:

class Config
{
    protected static $values;

    ...

    public static function get()
    {
        $val = &self::$values;
        $argList = func_get_args();
        for ($i = 0; $i < count($argList); $i++) {
            $val = &$val[$argList[$i]];
            if(empty($val)) break;
        }
        return (is_null($val)?"":$val);
    }
}

Is there a more elegant / efficient way of accessing the value?

This seems alright, but you could use foreach, and checking and returning can be simpler:

class Config
{
    protected static $values;

    ...

    public static function get()
    {
        $val = &self::$values;
        foreach(func_get_args() as $argument)
        {
          $val = &$val[$argument];
          if(empty($val)) return "";
        }
        return $val;
    }
}

I would call this more elegant, but it's not more efficient. (I did not test the code.)


i18n translator using Jinja2 I'm learning to Jinja2 and what's important in this case isn't speed but i18n translations and functionality. With Python 2.7, Jinja2 and not Django seems to preferred way to go, so I'm rewriting much of my project to use Jinja2 templates. We already had plenty of translations in .mo and .po files and wanted to keep use of those and we also want to make use of django's translation package. I found a way to use the Django translation libraries with Jinja2.

Could you review this code and comment if I can use it this way? My SDK is Google App Engine.

import jinja2
from django.utils import translation
from django.utils.translation import gettext, ngettext, ugettext, ungettext, get_language, activate
class DjangoTranslator(object):

    def __init__(self):
        self.gettext = gettext
        self.ngettext = ngettext
        self.ugettext = ugettext
        self.ungettext = ungettext
from jinja2 import Environment, FileSystemLoader
class DjangoEnvironment(jinja2.Environment):

    def get_translator(self, context):
        return DjangoTranslator()

jinja_environment = DjangoEnvironment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.i18n'])
jinja_environment.install_gettext_translations(translation)

I don't know jinja but I can give a few generic python pointers:

Generally, its considered best to put all imports at the top of the file not scattered throughout
Rather then importing a bunch of stuff to use once, use self.gettext = translation.gettext etc
Why empty lines after class, but nowhere else? I'd but a blank line before the start of a class and not inside.


Yet another binary search Code review my binary search! It isn't supposed to be superfast or anything. It's optimized for clarity and only sorts arrays of pointers. Also in the same style is my quicksort code review question: Yet another quicksort.

/*
  used as the base case of bsearch.
*/
static void const* misc_bsearch_linear(void const** A, void const** Z, void const* K, bool (*cmp)(void const*, void const*))
{
  /*
    burn forward while *A < K. if there is anything left, it will have
    to be that *A >= K.
  */
  while ((A < Z) && cmp(*A, K)) A++;

  /*
    if there is nothing left, we're done.
  */
  if (!(A < Z)) return NULL;

  /*
    now we know *A >= K.
  */
  {
    if (cmp(K, *A)) {
      /* when K < *A */
      /* this means *A > K, so no dice */
      return NULL;
    } else {
      /* when K >= *A */
      /* this means *A == K, so return it */
      return *A;
    }
  }
}

static void const* misc_bsearch_internal(void const** A, void const** Z, void const* K, bool (*cmp)(void const*, void const*))
{
  /*
    must stop loop when there are 3 or fewer elements, otherwise it
    could go on forever in the bottom case.
  */
  while ((Z - A) > 3) {
    void const** M = (A + ((Z - A) >> 1));

    if (cmp(*M, K)) {
      /* when *M < K */
      A = M + 1;
    } else {
      /* when *M >= K */
      Z = M + 1;
    }
  }

  /*
    we're down to at most 3 elements, to downgrade to linear search to
    finish up.
  */
  return misc_bsearch_linear(A, Z, K, cmp);
}

/*
  cmp should return true iff [arg1] < [arg2] (strictly).
*/
static INLINE void const* misc_bsearch(void const** A, uintptr_t L, void const* K, bool (*cmp)(void const*, void const*))
{
  return misc_bsearch_internal(A, (A + L), K, cmp);
}

#define MISC_BSEARCH_VARIANT(s, t)                                   \
  static INLINE t* misc_bsearch_##s(t** A, uintptr_t L, t const* K, bool (*cmp)(t const*, t const*)) \
  {                                                                  \
    return ((t*)(misc_bsearch(((void const**)(A)), L, K, ((bool (*)(void const*, void const*))(cmp))))); \
  }

Clarity

Reformat to the presentation width.  Rather than incur slider bars,...

static void const* misc_bsearch_internal(void const** A, void const** Z, void const* K, bool (*cmp)(void const*, void const*))

... wrap code

    static void const* misc_bsearch_internal(void const** A, void const** Z,
        void const* K, bool (*cmp)(void const*, void const*))

One letter argument names convey little,.  Use more expressive names

// static void const* misc_bsearch_linear(void const** A,
//    void const** Z, void const* K, bool (*cmp)(void const*, void const*))
static void const* misc_bsearch_linear(void const** First,
    void const** Last, void const* Key, bool (*cmp)(void const*, void const*))

const void * and void const * are the same, yet the one used by OP does not match the one used by the C standard.  When looking for clarity, recommend following the standard's practice.
It is not stated if bool cmp() functions return true or false on match.  For clarity, that should be detailed.  OTOH. I eventually found it.  For clarity, that should be detailed more obviously - at the top.

// cmp should return true iff [arg1] < [arg2] (strictly).

Missing include.h files.  I'd expect at least something for NULL and <stdint.h> the the optional types intptr_t / uintptr_t.
A sample usage (commented) of the entry function misc_bsearch() would be helpful.  As it is, it is unclear how to use the function set.

Wider use

The compare functions used by the standard C library qsort() use a int cmp(....).  As this code uses a bool cmp(....), the same function is not usable directly in the other.  Consider changing this code change to use int cmp(....).

Limitation

"only sorts arrays of pointers."  --> Op's code handles pointers to objects.  Pointers to functions may be wider than void *.


Exception handling with null check in java //not an elf file. try PE parser
        PE pe=PEParser.parse(path);
        if(pe!=null)
        {
            PESignature ps =pe.getSignature();
            if(ps==null||!ps.isValid())
            {
                //What is it?
                Toast.makeText(this,"The file seems that it is neither an Elf file or PE file!",3).show();
                throw new IOException(e);
            }
        }
        else
        {
            //What is it?
            Toast.makeText(this,"The file seems that it is neither an Elf file or PE file!",3).show();
            throw new IOException(e);
        }

How can I organize the above code, so that

 //What is it?
          Toast.makeText(this,"The file seems that it is neither an Elf file or PE file!",3).show();
          throw new IOException(e);

Appears  only once, or just be better-looking(easy to read)?

Summary

Please comment or advise on organizing the if statements.

Your business logic is getting muddled with your error-checking logic. I would recommend extracting your "null-to-Exception" conversions into different methods, so they don't appear here.

Ideally, PEParser.parse() and PE.getSignature() would not return null values, and would instead throw an exception directly if they encountered an issue. If you have the option to change these methods, I would do so. Otherwise, I would recommend wrapping them in methods that will convert null return values to exceptions, like so:

PE GetPEFromPath(String path)
{
    PE pe = PEParser.parse(path);
    if (pe == null)
    {
        throw new IOException();
    }
    return pe;
}

PESignature GetSignatureFromPE(PE pe)
{
    PESignature ps = pe.getSignature();
    if (ps == null || !ps.isValid())
    {
        throw new IOException();
    }
    return ps;
}

These methods should return a valid object, or throw an exception - no other options. This way, we can write our business logic in a try block with no null-check interruptions, and if something fails, we will move gracefully to the catch block.

Now, we can transform your given code snippet into something more readable:

//not an elf file. try PE parser
try
{
    PE pe = GetPEFromPath(path);
    PESignature ps = GetSignatureFromPE(pe);
}
catch (IOException e)
{
    Toast.makeText(this, "The file seems that it is neither an Elf file or PE file!", 3).show();
    throw e;
}


Is there a better or more compact way of adding items in treeview using LINQ? I am using the following code to add nodes in a treeview. Is there a better or more compact way of doing this by using LINQ?

foreach (Plan plan in this.IncomingPlan.Plans)
{
    foreach (Document doc in plan.Documents.Where(d => d.Name.Equals(this.DocumentName, StringComparison.OrdinalIgnoreCase)))
    {
        foreach (Author author in doc.Authors)
        {
            TreeNode treeNode = new TreeNode()
            {
                Text = author.Name,
                Type = NodeType.ParentNode,
                Tag = author
            };

            foreach (Book book in author.Books)
            {
                treeNode.Nodes.Add(new TreeNode()
                {
                    Text = book.Name,
                    Type = NodeType.ChildNode,
                    Tag = book
                });
            }

            this.treeView.Nodes.Add(treeNode);
        }
    }
}

Looks perfectly fine to me. That's the first time I've looked at your code and I was able to see quickly what it does.

There is no need to overly-compact things if it is going to make it a pain for someone else to understand in future.


merge sort implementation 7 Please look at the above code

#include<stdio.h>
#include<stdlib.h>
void mergesort(int *,int ,int);
void merge1(int *,int ,int ,int);

int main()
{
int low=0,high,n,i,a[100];

  printf("Enter the lenght of array\n");
  scanf("%d",&n);
  high =n-1;
  printf("Enter the array that you want to sort\n");

  for(i=low;i<=high;i++)
  {
    scanf("%d",&a[i]);
  }

  mergesort(a,low,high);
  printf("The sorted array is \n");

  for(i=low;i<=high;i++)
  {
    printf("%d-",a[i]);
  }
  printf("MERGE sorted");
  return 0;
}

void mergesort(int a[],int low,int high)

{

  int mid;
  if(low<high)
 {
    mid=(low+high)/2;
    mergesort(a,low,mid);
    mergesort(a,mid+1,high);
    merge1(a,low,mid,high);
 }

}

 void merge1(int a[],int low,int mid,int high)
{
    int i=low,j=mid+1,new_array[100],k=low,m;

      while(i<=mid && j<=high)
   {
     if(a[i]<a[j])
     {
       new_array[k]=a[i];
       i++;
       k++;
     }
    else
    {
       new_array[k]=a[j];
       j++;
       k++;

    }
   }

        while(i<=mid)
       {
       new_array[k]=a[i];
       i++;k++;
       }

       while(j<=high)
      {
       new_array[k]=a[j];
       j++;
       k++;
      }

      for(m=low;m<=high;m++)
     {
         a[m]=new_array[m];
     }

}

Actually, I implemented merge sort and it is working fine but I want much better code than this . Can anyone  make this code much better?

Coding conventions

It is more customary to put one space character before and after a binary operator. So instead of a=1, you should write a = 1.
int low=0,high,n,i,a[100]; This is not easy to read, so instead, declare each variable on its own row:

    int low = 0;
    int high;
    .
    .
    .

Implementation

new_array[100] This substantially limits your implementation. Of course, in C, you can always overflow it, but it may rewrite relevant data or terminate your program altogether in case your process references a memory location it may not.
mid=(low+high)/2; This is a minor nitpick, yet some people suggest writing mid = low + (high - low) / 2. That may avoid overflowing low + high in some (super rare) cases.

General comments

Otherwise, your implementation looks reasonable as you don't write an if hell some novices tend to.

Summa summarum

After mainly correcting the style issues, you may come out with something like this:

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

void merge(int* a, int low, int mid, int high)
{
    int i = low;
    int j = mid + 1;
    int k = 0;
    int m;

    int* new_array = malloc(sizeof(int) * (high - low + 1));

    while (i <= mid && j <= high)
    {
        if (a[i] < a[j])
        {
            new_array[k++] = a[i++];
        }
        else
        {
            new_array[k++] = a[j++];
        }
    }

    while (i <= mid)
    {
        new_array[k++] = a[i++];
    }

    while (j <= high)
    {
        new_array[k++] = a[j++];
    }

    for (m = low, k = 0; m <= high; m++, k++)
    {
        a[m] = new_array[k];
    }

    free(new_array);
}

void my_mergesort(int a[], int low, int high)
{
    int mid;

    if (low < high)
    {
        mid= low + (high - low) / 2;
        my_mergesort(a, low, mid);
        my_mergesort(a, mid + 1, high);
        merge(a, low, mid, high);
    }
}

int main()
{
    int high;
    int n;
    int i;
    int a[100];

    printf("Enter the lenght of array\n");
    scanf("%d",&n);
    high = n;

    printf("Enter the array that you want to sort\n");

    for(i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
    }

    my_mergesort(a, 0, n - 1);

    printf("The sorted array is \n");

    for (i = 0; i < n; i++)
    {
        printf("%d ",a[i]);
    }

    puts("\n");
    return 0;
}

Hope that helps.


Implementation of a Kennel I need a code review for the following question:

  Using C++ object oriented design, provide the implementation of Kennel
  so that:

  The method AddCat() adds a Cat to the Kennel, providing its name.
  The method AddDog() adds a Dog to the Kennel, providing its name.
  The method RollCall() prints the Animal's name and sound to stdout:

  Cats identify themselves by printing "Meow" to stdout.
  Dogs identify themselves by printing "Woof" to stdout.

Kennel .h

    #pragma once
    #ifndef KENNEL_H
    #define KENNEL_H

    #include <string>
    #include <iostream>
    #include <vector>

    class Kennel
    {

    public:
        Kennel() { };
        virtual ~Kennel();
        void AddCat(const std::string & name);
        void AddDog(const std::string & name);
        void RollCall();
        virtual void makeSound(std::string name) { }

    private:
        std::vector <Kennel*> KennelList;
    protected:
        std::string name;

    };

    //Dog inherits Kennel
    class Dog :public Kennel
    {
    public:
        Dog(std::string dogName)
        {
            name = dogName;
        }
        ~Dog() { };
        void makeSound(std::string name)
        {
            std::cout << name << " says Woof" << std::endl;
        };
    };

    //Cat inherits Kennel
    class Cat :public Kennel
    {
    public:
        Cat(std::string catName)
        {
            name = catName;
        }
        ~Cat() { };
        void makeSound(std::string name)
        {
            std::cout << name << " says Meow" << std::endl;
        };
    };

    #endif

Kennel.cpp

    #include "Kennel.h"

    Kennel::~Kennel()
    {
        for (auto i : KennelList)
        {
            delete i;
        }
    }

    void Kennel::AddCat(const std::string & name)
    {
        KennelList.push_back(new Cat(name));
    }

    void Kennel::AddDog(const std::string & name)
    {
        KennelList.push_back(new Dog(name));
    }

    void Kennel::RollCall()
    {
        for (unsigned int i = 0; i < KennelList.size(); ++i)
        {
            KennelList[i]->makeSound(KennelList[i]->name);
        }
    }

main

#include "Kennel.h"
    int main()
    {
    Kennel kennel;

    kennel.AddCat("Garfield");
    kennel.AddDog("Odie");
    kennel.AddDog("Pluto");
    kennel.AddCat("Felix");
    kennel.AddCat("Sylvester");
    kennel.AddCat("Scratchy");
    kennel.AddDog("Scooby Doo");
    kennel.AddCat("Puss in Boots");
    kennel.AddDog("Goofy");
    kennel.AddDog("Old Yeller");

    kennel.RollCall();
}

Think of the phrase : public to mean "is a".

A dog is not a kennel, nor is a cat, so Dog and Cat should not inherit from Kennel. You need a class called Animal. Cats and dogs are animals, so Cat and Dog should derive from Animal. Animals are contained in a kennel.


Use up all characters to form words Task:

  Given a dictionary of words, and a set of characters, judge if all the
  characters can form the words from the dictionary, without any
  characters left.  For example, given the dictionary {hello, world, is,
  my, first, program}, if the characters set is "iiifrssst", you should
  return 'true' because you can form {is, is, first} from the set; if
  the character set is "eiifrsst", you should return 'false' because you
  cannot use all the characters from the set.

  P.S. there may be tens of thousands of words in the dictionary, and
  the chars set length could be up to hundreds, so I really need some
  efficient algorithm.

Source: http://www.careercup.com/question?id=5841660122497024

Here is my solution in Python:

from collections import Counter
from itertools import combinations_with_replacement
import copy

# Check if word can be made up with the characters in char_count
def valid_word(word):
    # build character count for word
    word_char_count = Counter(word)

    # check if character count for word
    for char in word_char_count.keys():
        if char not in char_count or word_char_count[char] > char_count[char]:
            return False

    return True

# Only return words that can be made up from characters with char_set
def prune_words(words):
    res = []
    for word in words:
        if valid_word(word):
            res.append(word)

    return res

def main(words, char_set):
    global char_count
    char_count = Counter(char_set)  # count character occurrences

    # Prune words that cannot possible be made from the set of characters
    words = prune_words(words)
    words_len = [len(word) for word in words]

    # Maximum number of r with generating combinations
    max_r = len(char_set) / min(words_len)

    # Generate permutations with the valid words
    for r in range(1, max_r + 1):
        for comb in combinations_with_replacement(words, r):
            # If the total length of the combination matches length of char_set,
            # do further checks
            if sum(map(len, comb)) == len(char_set):
                temp_count = copy.deepcopy(char_count)

                # Subtract char count of each word in combination from char_set
                for word in comb:
                    temp_count.subtract(word)

                # If the remaining count are all zero, then we have found an
                # answer
                if all([count == 0 for count in temp_count.values()]):
                    print comb
                    return True

    return False

if __name__ == '__main__':
    print main(['hello', 'world', 'is', 'my', 'first', 'program'],
               'iiifrssst')

What improvements can be made to my code (e.g. algorithmic speed, make it more 'Python', style, etc etc)?  Happy to hear any constructive comments!

Since "the chars set length could be up to hundreds", it can easily contain enough letters to form any word in an English dictionary. In such a case prune_words would not prune any words. This makes me think the pruning is an example of premature optimization.
Instead of using Counter to check a match, I believe it would be faster to compare sorted lists of characters, i.e. compare sorted("".join(comb)) to a pre-computed sorted(char_set).
Copying a Counter by Counter(char_count) is faster than by copy.deepcopy.
To check if all counts are zeros you don't need the list comprehension as you can simply use if not any(temp_count.itervalues())
You check lots of combinations that are the wrong length. Even though the length check is the first thing inside the loop, it would be better to generate the combinations in a way that allows you to back off when the combined length exceeds the length of char_set. I would use recursion to explore the combinations.
A more clever approach might be found from representing the dictionary as a prefix tree.


Replacing all keys found in a dictionary for its value in a list I have a file that is written DOS format and I need to replace some characters into others. I created a dictionary for that purposes, and now I have to read everyline from my stream and replace my values as I go.

I created this piece of code in C#, however, I highly doubt that this is the way to go, since I figure that C# dictionary class must have a simpler way to this probably common operation. Any feedback is greatly appreciated !

public Dictionary<char, string> Chars { get; set; } = new Dictionary<char, string>();

    // Called in my constructor
    public void CreateDictionnary()
    {
        Chars.Add('\u001b', " ");
        Chars.Add('\u0000', " ");
        // Multiple other characters that I have to replace
    }

public List<string> ReplaceSpecialCharacters(List<string> lines)
    {
        var result = new List<string>();

        foreach (var line in lines)
        {
            string newLine = string.Empty;

            foreach (var @char in line)
            {
                string replacedChar = @char.ToString();
                bool keyFound = false;

                foreach (var entry in Chars)
                {
                    if (keyFound)
                        continue;

                    if (@char == entry.Key)
                    {
                        replacedChar = entry.Value;
                        keyFound = true;
                    }
                }

                newLine += replacedChar;
            }

            result.Add(newLine);
        }

        return result;
    }

The main suggestion I'd make is to use Dictionary<char,char>.  This allows to work with char collections and convert them to strings rather than continuously concatenating strings.

This also allows you to leverage LINQ to do the replacement and shorten your code tremendously.

It could look like this:

public Dictionary<char, char> Chars { get; set; } = new Dictionary<char, char>();

// Called in my constructor
public void CreateDictionnary()
{
    Chars.Add('\u001b', ' ');
    Chars.Add('\u0000', ' ');
    // Multiple other characters that I have to replace
}
public List<string> ReplaceSpecialCharacters(List<string> lines)
{
    for(int i = 0; i < lines.Count; ++i)
    {
        lines[i] = new string(lines[i].Select(x => Chars.ContainsKey(x) ? Chars[x] : x).ToArray());
    }
    return lines;
}

Incidentally this lowers the complexity from O(n²m),the total number of characters squared times the number of entries in the dictionary, to O(n²).  Which since you're dealing with strings is probably about the best you can get.  If you want it better, storing the data as char arrays instead of strings allows the replacement to be in-place instead of creating new strings.  This could be done in O(n) complexity.


Account disabled and deleted functions I have the following functions that for the most part are utilizing much of the same code (except for the actual message). What are the possibilities, if there are any, for combining / reducing these functions so that there isn't so much redundancy?

    // ACCOUNT DISABLED FUNCTION

    function accountDisabled() {
        if (!$('.accountautologoff').length) {

            $('.content').append('
Your account has been disabled
Contact the system administrator
');

            $('body').addClass('disabled');
            $('html').removeClass('loading');
            $('.accountautologoff').hide().fadeTo(600, 1, 'swing');
            $(document).bind('mousewheel', function (e) { e.preventDefault(); });
            $('.content-home, .content-search').fadeTo(600, 0.5, 'swing');
        };
    };

    // ACCOUNT DELETED FUNCTION

    function accountDeleted() {
        if (!$('.accountautologoff').length) {

            $('.content').append('
Your account has been removed
Contact the system administrator
');

            $('body').addClass('disabled');
            $('html').removeClass('loading');
            $('.accountautologoff').hide().fadeTo(600, 1, 'swing');
            $(document).bind('mousewheel', function (e) { e.preventDefault(); });
            $('.content-home, .content-search').fadeTo(600, 0.5, 'swing');
    };
};

You could start by actually trying to combine them yourself. :/ we appreciate code reviews but honestly this was a copy and paste job.

function accountDeactivate(msg) {
  if (!$('.accountautologoff').length) {
    $('.content').append('
' + msg +'
');
    $('body').addClass('disabled');
    $('html').removeClass('loading');
    $('.accountautologoff').hide().fadeTo(600, 1, 'swing');
    $(document).bind('mousewheel', function (e) { e.preventDefault(); });
    $('.content-home, .content-search').fadeTo(600, 0.5, 'swing');
  };
}


Convert flat object keys to hierarchical one While responding to a SO question, I wrote the following method to convert a flat key structure to a hierarchical one as given below

In

{
   property1: 'value1',
   property2.property3: 'value2',
   property2.property7: 'value4',
   property4.property5.property6: 'value3',

}

Out

{
    property1: 'value1',
    property2: {
        property3: 'value2',
        property7: 'value4'
    },
    property4: {
        property5: {
            property6: 'value3'
        }
    }
}

Converter:

function convert(obj) {
    var res = {}, i, j, splits, ref, key;
    for (i in obj) {
        if (obj.hasOwnProperty(i)) {
            splits = i.split('.');
            ref = res;
            for (j = 0; j < splits.length; j++) {
                key = splits[j];
                if (j == splits.length - 1) {
                    ref[key] = obj[i];
                } else {
                    ref = ref[key] = ref[key] || {};
                }
            }
        };
    }
    return res;
}

Can this be improved?

Demo: Fiddle

The main complexity of this function arises from using a plain for-in loop to loop over object keys - this adds two extra indentation levels instead of just one level if one were to use a higher-level looping construct. So I would use some library function or create something like:

function eachKeyValue(obj, fun) {
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            fun(i, obj[i]);
        }
    }
}

Within this loop, there's another low-level for-loop, which I would again replace, say... with an Array.forEach method.

Now, in your code the loop goes over all the parts of the key, checking each time whether it's the last part. Instead of this, I would first remove the last part, loop over all the other parts to ensure all these are initialized, and then simply assign the value to the last position.

With some additional improvements to variable names, I would write it as such:

function convert(obj) {
    var result = {};
    eachKeyValue(obj, function(namespace, value) {
        var parts = namespace.split(".");
        var last = parts.pop();
        var node = result;
        parts.forEach(function(key) {
            node = node[key] = node[key] || {};
        });
        node[last] = value;
    });
    return result;
}

This code has just 2 levels of nesting compared to the original 4.


Dynamic way to use string/array as index of object in javascript I've got a structure of files and folders in a directory structured like the "example_object" I describe below. I also have paths of each of the files as strings.

So my solution is to split the path into an array, and then use the array to index the object as described in the function below. The length of the array will vary as I don't know how many levels of folders there will be.

Whilst what I've written below works, and I guess is only 4 lines, I see a lot of users get anxious about using "eval". It also seems an indirect method to get the job done. Any improvements/alternate ways to do this?

function change_object_using_path_string(this_object,this_path,new_value){
  var array_as_index = this_path.split("/");
  array_as_index = "['"+array_as_index.join("']['")+"']";
  var code_to_eval = this_object+array_as_index+"='"+new_value+"'";
  eval(code_to_eval);
}

The above function is what I'm actually using in my script. The below code reflects the structure of the inputs I would put into the above function:

// NOTE: I'm only inputting "example_object" into 'change_object_using_path_string' as a string to facilitate the eval solution I'm using. I would prefer a solution which directly inputs example_object into the function.

example_object = {
  folder_1_name:{
    folder_2_name:{
      folder_3_name:{
        'file.txt':'this file content'
      }
    }
  }
}
example_path = "folder_1_name/folder_2_name/folder_3_name/file.txt";

change_object_using_path_string("example_object",example_path,"new content instead");

Yes, it's fairly straightforward to do this without using eval. For example, a statement like obj['a']['b']['c']['d'] = 'value'; can be rewritten as a series of smaller steps:

var temp = obj;
temp = temp['a'];      // member access
temp = temp['b'];      // member access
temp = temp['c'];      // member access
temp['d'] = 'value';   // assignment

Now, it shouldn't be too hard to see how those member access statements can be rolled into a loop, if you have an array of indexes (which you do).

A few other notes:

It's good to see descriptive names, but change_object_using_path_string strikes me as a bit too long and unwieldy. What about something like set_path_value?
You may want to use some more spacing between function parameters (param1,param2 vs param1, param2) and operators (a+b vs a + b). This makes individual parts stand out more, making the code a little easier to read.


Making Math vector implementation using java Below is the Code.

package Calculation;
public class Vector
{
    double x;
    double y;
    double z;
   /**Constructor to create a null vector i.e. 0i+0j+0k*/
    public Vector()
    {
        this.x=0;
        this.y=0;
        this.z=0;
    }
    /**Constructor to create a vector with the given values of i,j and k*/
    public Vector(double x,double y,double z)
    {
        this.x=x;
        this.y=y;
        this.z=z;
    }
    /**Return the string notation of the Vector */
    public String getCompleteStringNotation()
    {
        String not=this.x+"i^+"+this.y+"j^+"+this.z+"k^";
        return not;
    }
 /**Return the string notation of the Vector.Reduced it if any of x,y and z are integers */
    public String getReducedStringNotation()
    {
        String not="";
        if(this.x!=0)
        {
            if(this.x==(int)this.x)
                not=not+(int)this.x+"i^+";
            else
                not=not+this.x+"i^+";
        }
        if(this.y!=0)
        {
            if(this.y==(int)this.y)
                not=not+(int)this.y+"j^+";
            else
                not=not+this.y+"j^+";
        }

        if(this.z!=0)
        {
            if(this.z==(int)this.z)
                not=not+(int)this.z+"k^";
            else
                not=not+this.z+"k^";
        }

            if(not.equals(""))
            return null;

            if(not.charAt(not.length()-1)=='+')
            not=not+"\b";

        return not;
    }
  /**Gives the length of the vector*/
    public double modulus()
    {
        double mod=Math.sqrt(Math.hypot(x,Math.hypot(y,z)));
        return mod;
    }
/**Check if two vectors are parallel or not*/
    public boolean isParallel(Vector v)
    {
        double xr=this.x/v.x;
        double yr=this.y/v.y;
        double zr=this.z/v.z;
        if(xr==yr&&yr==zr&&zr==xr)
            return true;
        else
            return false;
    }
  /**Returns the unit vector in the direction of the Calling vector object*/
    public Vector getUnitVector()
    {
        double mod=this.modulus();
        Vector unit=new Vector(this.x/mod,this.y/mod,this.z/mod);
        return unit;
    }
   /**Computes and return the dot product between two vector*/
    public double dotProduct(Vector v)
    {
        double res=this.x*v.x+this.y*v.y+this.z*v.z;
        return res;
    }
  /**Compute and returns the angle between two vectors in radians*/
    public double angleBetween(Vector v)
    {
        double dotPro=this.dotProduct(v);
        double modObj=this.modulus();
        double modV=v.modulus();
        double angle=Math.acos(dotPro/(modObj*modV));
        return angle;
    }
   /**Computes and returns the cross product of the two vector*/
    public Vector crossProduct(Vector v)
    {
        double resx=(this.y*v.z)-(v.y*this.z);
        double resy=-((this.x*v.z)-(v.x*this.z));
        double resz=(this.x*v.y)-(v.x*this.y);
        Vector res=new Vector(resx,resy,resz);
        return res;
    }

}

And now some questions.

  1. In my stringNotation methods i could not write i cap.Mean to say i(and at the top of it ^) similarly with j and k.

  2. How to implement hashcode and equals function.

  3. Any other guide will also be entertained.

Question 1 not exactly the right place to ask here I think. Perhaps aks that one as a question on StackOverflow instead? For the i it's possible by directly putting in the î (type ^ first then i to make it 1 character, also works for ê û ô and â, not directly possible in standard character sets for j or k as far as I know).
Unless if you want to just use an alternative notation. For example printing (x,y,z) instead of the xî yj zk. But that would be trivial to implement yourself once you do decide to do it like that.

For question 2 I suggest you get yourself a good IDE (for example IntelliJ or Eclipse) and have it generate an equals and hashcode function for you. Doing that correctly can be tricky.

The code you have now looks pretty good as is.

The only big issue I have is the package visibility of the x y and z fields. The default best practice would be to make them private and provide getters to access them if needed. Also only provide setters if it makes sense to change the values (usually not the case).

Alternatively you might want to access the fields often in which case calling getters could become annoying. In that case I would suggest making the class immutable and provide public access the the fields.

public class Vector {
    public final double x;
    public final double y;
    public final double z;

Immutability is a nice property to have, especially if you want to use the class in a multithreaded environment. (Even if you make the fields private it's still a good idea to make them final as well).

A last smaller issue I want to mention is to always use braces to prevent silly mistakes. Especially if these silly mistakes can take hours to find.

lastly some minor nitpicks

the usual java convention says to put the opening bracket on the same line. For example:

 public String getReducedStringNotation() {
    String not="";
    if(this.x!=0) {
        if(this.x==(int)this.x) {
            not=not+(int)this.x+"i^+";
        } else {
            not=not+this.x+"i^+";
        }
    }

The good thing is that you were consistent, so not really a complaint here.

You don't need this variable here:

public double modulus() {
    double mod=Math.sqrt(Math.hypot(x,Math.hypot(y,z)));
    return mod;
}

You can directly return it return Math.sqrt(Math.hypot(x,Math.hypot(y,z)))

Also, should this be

public double modulus() {
    return Math.sqrt(x*x + y*y + z*z);
}

instead?

The following line could also be a direct return statement:

    if(xr==yr&&yr==zr&&zr==xr)
        return true;
    else
        return false;

replace it with:

return xr==yr && yr==zr && zr==xr;

not the best variable name. I would prefer notation or result in most cases.

More specifically to actually understand what this does:

    if(not.equals(""))
    return null;

Which brings me to my last nitpick. Wouldn't it be better to return that empty string here? NullPointerExceptions are one of the most annoying thing to deal with in Java. I prefer some minor "huh?" moments when there was an empty string where I would expect a Vector over my program crashing with a NPE.


Feedback on simple Merge algorithm I am writing a simple merge algorithm in Haskell. I wanted to add simple logging, hence am using the Writer Monad to include logging.

type ArrayWithLogging a = WriterT [String] Identity [a]

merge :: (Show a, Ord a) => ArrayWithLogging a -> ArrayWithLogging a -> ArrayWithLogging a
merge al bl = do
    a <- al
    b <- bl
    case (a, b) of
        ([], b') -> tell ["Returning " ++ show b'] >> return b'
        (a', []) -> tell ["Returning " ++ show a'] >> return a'
        (a'@(x:xs), b'@(y:ys)) -> if (x <= y)
                                    then tell ["Min " ++ show x ++ " merging " ++ show xs ++ " with " ++ show b]
                                        >> ((merge (return xs) (return b')) >>= \z -> return (x : z))
                                  else tell ["Min " ++ show y ++ " merging " ++ show a ++ " with " ++ show ys]
                                        >> ((merge (return a') (return ys)) >>= \z -> return (y : z))

I feel there are too many returns inside the monadic context. Is this style correct?

Let's start simple. First of all, your code seems fine. However, as you've noticed yourself, there's an abundance of returns. Several of them don't seem necessary, so let us inspect some patterns:

((merge (return a') (return ys)) >>= \z -> return (y : z))

The pattern x >>= \z -> return (f z) is the same as fmap f x. That already reduces the number of returns by two:

type ArrayWithLogging a = WriterT [String] Identity [a]

merge :: (Show a, Ord a) => ArrayWithLogging a -> ArrayWithLogging a -> ArrayWithLogging a
merge al bl = do
    a <- al
    b <- bl
    case (a, b) of
        ([], b') -> tell ["Returning " ++ show b'] >> return b'
        (a', []) -> tell ["Returning " ++ show a'] >> return a'
        (a'@(x:xs), b'@(y:ys)) -> if (x <= y)
                                    then tell ["Min " ++ show x ++ " merging " ++ show xs ++ " with " ++ show b]
                                        >> fmap (x:) (merge (return xs) (return b'))
                                    else tell ["Min " ++ show y ++ " merging " ++ show a ++ " with " ++ show ys]
                                        >> fmap (y:) (merge (return a') (return ys))

Now, for the next step, let's get rid of the WriterT monad in the first two arguments. There's no reason for that, and it further removes the return:

merge :: (Show a, Ord a) => [a] -> [a] -> ArrayWithLogging a
merge a b = do
    case (a, b) of
        ([], b') -> tell ["Returning " ++ show b'] >> return b'
        (a', []) -> tell ["Returning " ++ show a'] >> return a'
        (a'@(x:xs), b'@(y:ys)) -> if (x <= y)
                                    then tell ["Min " ++ show x ++ " merging " ++ show xs ++ " with " ++ show b]
                                        >> fmap (x:) (merge xs b')
                                    else tell ["Min " ++ show y ++ " merging " ++ show a ++ " with " ++ show ys]
                                        >> fmap (y:) (merge a' ys)

We can still get the old variant by using the following merge':

merge' a1 b1 =
  a <- a1
  b <- b1
  merge a b

Now that we've reduced function pretty far (but didn't lose any functionality!), we can go ahead and change some indentation to make our intend more clear. Furthermore, let us also introduce a small helper called message:

merge :: (Show a, Ord a) => [a] -> [a] -> ArrayWithLogging a
merge a b = do
    case (a, b) of
        ([], b') -> tell ["Returning " ++ show b'] >> return b'
        (a', []) -> tell ["Returning " ++ show a'] >> return a'
        (a'@(x:xs), b'@(y:ys)) ->
            if (x <= y)
                then message x xs b  >> fmap (x:) (merge xs b')
                else message y a  ys >> fmap (y:) (merge a' ys)
  where
   message e ls rs = tell ["Min " ++ show e ++ " merging " ++ show ls ++ " with " ++ show rs]

OK, let's reiterate our steps:

We changed x >>= \z -> (f z) to fmap f x
We changed the arguments into their non-monad variant
We introduced another function to keep the old behaviour (if necessary)
We changed the indentation to make sure that it looks nicer.
We introduced a small helper to make sure that we don't repeat ourselves.

And those are all the non-opinionated (well, except the last one) changes I'd recommend to you. In my personal opinion, the function gets even a little bit nicer if we use pattern matching on the arguments:

type ArrayWithLogging a = WriterT [String] Identity [a]

merge :: (Show a, Ord a) => [a] -> [a] -> ArrayWithLogging a
merge a        []     = tell ["Returning " ++ show a] >> return a
merge []       b      = tell ["Returning " ++ show b] >> return b
merge a@(x:xs) b@(y:ys)
  | x <= y    = message x xs b  >> fmap (x:) (merge xs b)
  | otherwise = message y a  ys >> fmap (y:) (merge a ys)
  where
    message e ls rs = tell ["Min " ++ show e ++ " merging " ++ show ls ++ " with " ++ show rs]

merge' :: (Show a, Ord a) => ArrayWithLogging a-> ArrayWithLogging a-> ArrayWithLogging a
merge' a b = do
   a1 <- a
   b1 <- b
   merge a1 b1


Coroutine-based two-in-one properties Over the holidays I played around with coroutines and their use as two-in-one getter and setter methods:
#! /usr/bin/env python3
#  coroproperty.py - Coroutine-based two-in-one properties.
#
#  Copyright (C) 2020 Richard Neumann <mail at richard dash neumann period de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""Coroutine-based two-in-one decorator."""

from contextlib import suppress
from math import pi, sqrt
from typing import Any, Callable

def coroproperty(method: Callable) -> property:
    """Single decorator for getter and setter methods."""

    def getter(self) -> Any:
        """Property getter function."""
        coro = method(self)
        value = next(coro)
        coro.close()
        return value

    def setter(self, value: Any):
        """Property setter function."""
        coro = method(self)
        next(coro)
        next(coro)

        with suppress(StopIteration):
            coro.send(value)

    return property(getter, setter)

class Circle:
    """Information about a circle."""

    def __init__(self, radius: float):
        """Initializes the circle with its radius."""
        self.radius = radius

    @coroproperty
    def diameter(self):
        """Gets and sets the diameter."""
        yield self.radius * 2
        self.radius = (yield) / 2

    @coroproperty
    def circumference(self):
        """Gets and sets the circumference."""
        yield self.diameter * pi
        self.diameter = (yield) / pi

    @coroproperty
    def area(self):
        """Gets and sets the area."""
        yield pow(self.radius, 2) * pi
        self.radius = sqrt((yield) / pi)

The downsides I already discovered are, that each set access implies that an unused get is performed before. Furthermore, these decorators are significantly slower than a "classical" property with separate getter and setter methods:
Coro get: 0.2394869327545166
Classic get: 0.09408378601074219
Ratio coro / classic: 2.5454644515174247
Coro set: 0.7087152004241943
Classic set: 0.10921454429626465
Ratio coro / classic: 6.489201644257868

What other side-effects could arise when using these kind of properties?
Note that this code is not intended for use in productive environments, but is of academic interest only.

The proper way to prime a generator for accepting values is to send an initial None value.
Yield will simultaneously return a value to the caller, and accept a value sent from the caller.
Using those two facts, you could rewrite the code like:
...

def coroproperty(method: Callable) -> property:

    ...

    def setter(self, value: Any) -> None:
        coro = method(self)
        coro.send(None)
        with suppress(StopIteration):
            coro.send(value)

    ...

class Circle:

    ...

    @coroproperty
    def diameter(self):
        self.radius = (yield self.radius * 2) / 2

    ...

Side-effects
Wasted time and computation.  Setting the diameter, circumference and/or area first involves computing those quantities, which is unnecessary.
You could circumvent that by accepting a new value before returning the value.
    @coroproperty
    def diameter(self):
        diameter = yield None
        if diameter is not None:
           self.radius = diameter / 2
        else:
           yield self.radius * 2

The getter would need to call next(coro) twice, ignoring the first returned value: None.
If you desired a property which could store None, you'd need to create and use your own sentinel value.

Assignment to diameter, even if not changing the value, will change the radius.  In this example, it is changed from an int to a float:
>>> c.radius = 100
>>> c.radius
100
>>> c.diameter = c.diameter
>>> c.radius
100.0

Add in sqrt, and multiplication & division by π, and accuracy can be lost:
>>> c.radius = 1_000_000_000_000
>>> c.area = c.area
>>> c.radius
999999999999.9999


Reimplementing Python's enum.auto() for compatibility In Python >= 3.6 there is an enum.auto() function.

The auto() function can be used like this:

import enum
from enum import auto

class Fruits(enum.Enum):
  APPLE = auto()
  ORANGE = auto()
  BANANA = auto()

I want to use it, but i cannot be sure if i am on Python >= 3.6 so I implemented it like this:

import enum

try:
  from enum import auto
except ImportError:
  __my_enum_auto_id = 0
  def auto() -> int:
    global __my_enum_auto_id
    i = __my_enum_auto_id
    __my_enum_auto_id += 1
    return i

class Fruits(enum.Enum):
  APPLE = auto()
  ORANGE = auto()
  BANANA = auto()

It works afaik, but it seems ugly to me. Any suggestions on how to improove it/make it better? or is it ok?

Is there some side effect I may have overlooked?

The easiest solution would be to use the aenum1 library, which is drop-in compatible with the stdlib and also has some advanced features not found in the stdlib.  It also works in Python versions 2.7 and 3.3+.

1 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.


Sieve of Eratosthenes in C# Just because I've never written a real Sieve of Eratosthenes, I decided I should probably write one just to make sure I know what it is.  I'd like (constructive) criticism on best practices, potential problems, and anything else you see fit:

static int GetNthPrime(int n)
{
    List<int> primes = new List<int>() { 2, 3 };

    int potentialPrime = 5;

    while (primes.Count < n)
    {
        int squareRootPotentialPrime = (int)Math.Sqrt(potentialPrime);

        for (int i = 1; i < primes.Count; i++)
        {
            if (potentialPrime % primes[i] == 0)
            {
                break;
            }

            if (primes[i] > squareRootPotentialPrime)
            {
                primes.Add(potentialPrime);
                break;
            }
        }
        potentialPrime += primes[0];
    }

    return primes[n - 1];
}

What you have written, is not exactly the Sieve of Erathostenes.
When doing the sieve, you don't do any divisions; you just step through all the numbers and cross off multiples.
The sieve doesn't find the n'th prime, but rather all primes up to a limit.
This is an example of how to do the sieve. It's a very basic version.

public static IEnumerable<int> SieveOfErathostenes(int upperLimit)
{
    //BitArray works just like a bool[] but takes up a lot less space.
    BitArray composite = new BitArray(upperLimit);

    //Only need to cross off numbers up to sqrt.
    int sqrt= (int)Math.Sqrt(upperLimit);
    for (int p = 2; p <= sqrt; ++p) {
        if (composite[p]) continue; //The number is crossed off; skip it

        yield return p; //Not crossed off means it's prime. Return it.

        //Cross off each multiple of this prime
        //Start at the prime squared, because lower numbers will
        //have been crossed off already. No need to check them.
        for (int i = p * p; i < upperLimit; i += p)
            composite[i] = true;
    }
    //The remaining numbers not crossed off are also prime.
    for (int p = sqrt + 1; p < upperLimit; ++p) {
        if (!composite[p]) yield return p;
    }
}


Is my equivalent of Excel's "EOMONTH" function correct? I am trying to create a function similar to Excel's EOMONTH function in C#. I have written the following, however, I am not entirely sure if the it achieves the equivalent functionality. Is my equivalent of Excel's "Eomonth" function correct and are my tests sufficient?

public static DateTime EOMonth(this DateTime dateTime, int months = 0)
{
    DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
    return firstDayOfTheMonth.AddMonths(1 + months).AddDays(-1);
}

Tests

[Test]
public void EOMonth_For5jan2011WithNoAddedMonths_ReturnsLastDayOfJan()
{
    var expectedDate = DateTime.Parse("31-Jan-2011");
    var currentDate = DateTime.Parse("5-Jan-2011");

    var result = currentDate.EOMonth();

    Assert.That(result, Is.EqualTo(expectedDate));
}

[Test]
public void EOMonth_For5jan2011With_1_AddedMonths_ReturnsLastDayOfFeb2011()
{
    var expectedDate = DateTime.Parse("28-Feb-2011");
    var currentDate = DateTime.Parse("5-Jan-2011");

    var result = currentDate.EOMonth(1);

    Assert.That(result, Is.EqualTo(expectedDate));
}

[Test]
public void EOMonth_For5jan2011WithNegative_1_AddedMonths_ReturnsLastDayOfFeb()
{
    var expectedDate = DateTime.Parse("31-Dec-2010");
    var currentDate = DateTime.Parse("5-Jan-2011");

    var result = currentDate.EOMonth(-1);

    Assert.That(result, Is.EqualTo(expectedDate));
}

 [Test]
 public void EOMonth_For28Feb2007_12_AddedMonths_ReturnsLastDayOfFeb2008()
 {
     var expectedDate = DateTime.Parse("29-Feb-2008");
     var currentDate = DateTime.Parse("28-Feb-2007");

     var result = currentDate.EOMonth(12);

     Assert.That(result, Is.EqualTo(expectedDate));
 }

For your implementation, why not use:

return ((new DateTime(dateTime.Year, dateTime.Month, 1)).AddMonths(1 + months).AddDays(-1));

To me, that's a little cleaner, but it might just be me. When I'm just creating an object to be returned, I'm not a fan of storing it in a variable. Instead, just return exactly what you mean to and be done with it.

For your test cases:

I'm not sure that it matters in this instance, since you are relying exclusively on built in methods, but I would create test cases around February and March for the various types of leap years. What if I specify February 29th on a non-leap year? Does it work for the different leap year conditions? I'd also create test cases around new years (December and January).


Does this generic query follow good OOP standards? I am trying to convert over to MySQLi and wanted expert advice.  Is the enclosed code 100% OOP.  Also, how secure is the code against attacks?  I know nothing is 100% secure, but how good/safe is it?  How and what can I make better?  This is just a generic query as I wanted to get a basic model setup.

<?php
define ('DB_HOST', 'localhost');                       //  Host name
define ('DB_USER', 'root');                            //  Mysql username
define ('DB_PASSWORD', 'password');                    //  Mysql password
define ('DB_NAME', 'database');                        //  Database name

// New Connection
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);

require("dbcon.php");  // This is actually the code above in a separate file that I have included here for checking.

$query = "SELECT id, username, firstname FROM users WHERE firstname=?";

if ($stmt = $mysqli->prepare($query))
{
   // Bind the variables
   $firstname = $_POST[first_name];

   // Bind parameters  s - String, b - Boolean, i - Integer etc
   $stmt->bind_param("s", $firstname);
   // Execute it
   $stmt->execute();
   // Store it for num rows
   $stmt->store_result();
   $num_rows = $stmt->num_rows;
   // Assign blank variables
   $id = "";
   $username = "";
   $firstname = "";
   // Bind the result and retrieve the data
   $stmt->bind_result($id, $username, $firstname);
      if(($num_rows) > 0)
      {
         while($stmt->fetch())
         {
            echo $id;
            echo "
";
            echo $username;
            echo "
";
            echo $password;
            echo "
";
            echo "Number of rows: ", $num_rows;
            echo "
";
            echo "
";
         }
      }
      else
      {
         echo "No records";
      }
   // Close the statement
   $stmt->close();
}
// Close connection
$mysqli->close();
?>

Your binding of parameters will help in preventing SQL injections.

You need to sanitize your data first though.
You need to treat everything that comes from a user (passed from the client machine) as 'dirty' and not allow it into your system before it's been 'cleaned'. Your first step would be to clean it - converting all HTML tags and special characters into their HTML entities htmlspecialchars() htmlentities() (well as long as HTML isn't allowed). This will help prevent cross-sight scripting (XSS). Typically then you would move on to validating the data - making sure it's in a format you expect. Then if it's not you return it to the user with an error.
This is also assuming that you've checked the user has permission to run this function, if relevant.


Serialize the properties of an entity framework entity to data fields and back I am trying to write code to convert properties of an Entity Framework entity to strings and back.

Here is the code so far that converts back from strings to the object properties.

I am stuck trying to figure out how to handle datetime.  I am also wondering if there is a better approach.

private static FormatterConverter formatConverter;
public static FormatterConverter FormatConverter
{
    get
    {
        if (formatConverter == null)
        {
            formatConverter = new FormatterConverter();
        }
        return formatConverter;
    }
}

// ChangeValue is an entity framework entity.
static void DoSetValue(ChangeValue cv , PropertyInfo pi, object obj )
{
    try
    {
        switch (pi.PropertyType.ToString())
        {
            case "System.TimeSpan":
            case "System.Nullable`1[System.TimeSpan]":
                var s = cv.Value;
                if (s == "") s = "0";
                var ticks = Convert.ToInt64(s);
                var ts = new TimeSpan(ticks);
                obj = ts;
                break;
            case "":
            case "System.Nullable`1[System.DateTime]":
                // code needed here
                break;
            case "System.Guid":
                obj = new Guid(cv.Value);
                break;
            default:
                pi.SetValue(obj,  FormatConverter.Convert(cv.Value, pi.PropertyType), null);
                break;
        }
    }
    catch (Exception ex)
    {
        ex.Data.Add("", string.Format( "Error converting type for {0} {1} ",pi.Name ,pi.PropertyType.ToString()));
        throw ex;
    }
}

If you are trying to convert the string to DateTime format that might be used in the EF object, you may try:

Convert.ToDateTime("2013-09-10 12:12:12",System.Globalization.CultureInfo.InvariantCulture)


Using 2 threads to compute the nth Fibonacci number (with memoization) If the 5th Fibonacci number has to be computed, I'm trying to split the 2 recursive trees into 2 threads:

                       5

         4                           3

   3           2                2        1

2     1     1     0         1       0

       Thread 1                 Thread 2

My attempt:

public class ParallelFibbonaci
{

static ExecutorService executor = Executors.newFixedThreadPool(2);
// Memoized map.
private static Map<Integer, Long> mem = new ConcurrentHashMap<>();

public static void main(String[] args) throws ExecutionException, InterruptedException{
    final long then = System.nanoTime();

    System.out.println(fib_wrapper(Integer.parseInt(args[0])));

    final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - then);
    System.out.println("Time(ms): " + millis);
    executor.shutdown();
}

public static int fib_wrapper(int n) throws ExecutionException, InterruptedException {
    Future<Integer> future = executor.submit(() -> fib(n-1));
    Future<Integer> future2 = executor.submit(() -> fib(n-2));

    return future2.get() + future.get();
}

public static int fib(int n) throws ExecutionException, InterruptedException {
    if (n == 1)
        return 1;
    if (n == 0)
        return 0;

    if (mem.containsKey(n)) {
        return mem.get(n);
    }

    long x = fib(n-1) + fib(n-2);
    mem.put(n, x);
    return x;
  }
}

I couldn't prove the parallel version to run faster than the simple version, in fact, all my profiling (done with System.nanoTime() which I believe is not the most reliable) revealed it to be 20-30 times slower:

Sid:Programs siddhartha$ java -Xms2G -Xmx4G parallelfibbonaci 1000
817770325994397771
Time(ms): 60

Sid:Programs siddhartha$ java -Xms2G -Xmx4G simplefibbonaci 1000
817770325994397771
Time(ms): 4

Sid:Programs siddhartha$ java -Xms2G -Xmx4G parallelfibbonaci 500
2171430676560690477
Time(ms): 59

Sid:Programs siddhartha$ java -Xms2G -Xmx4G simplefibbonaci 500
2171430676560690477
Time(ms): 2

Any higher n's crashed my program with a stackoverflow error.

In theory, I'd expect using 2 threads on a tree-recursive algorithm to work faster than a single-threaded implementation, however it seems this is clearly not the case. What am I missing here?

Don't parallelize serial problems

  In theory, I'd expect using 2 threads on a tree-recursive algorithm to work faster than a single-threaded implementation, however it seems this is clearly not the case. What am I missing here?

You are duplicating work.  The problem is that generating the Fibonacci sequence is not a tree.  It's a vector.  This is because you don't actually care what the children are.  All you care about is what the current node's two children are.  But you need one of those children to generate the other.  I.e. the n - 2 subtree is actually part of the n - 1 subtree.

So you take an essentially serial operation and you try to split it over two processes.  Unsurprisingly, it takes longer as it tries to synchronize the processes.

Turning it into parallel problems

Is all hope lost?  No.  If you look at solutions to Project Euler #2:  Even Fibonacci Numbers, you will find that

$$F_n = 4 \cdot F_{n-3} + F_{n-6}$$

For example, the 7th Fibonacci number:

$$F_7 = 4 \cdot F_4 + F_1$$
$$F_7 = 4 \cdot 2 + 0 = 8$$

How does that help us?  Think about the 8th, 9th, and 10th Fibonacci numbers:

$$F_8 = 4 \cdot F_5 + F_2$$
$$F_9 = 4 \cdot F_6 + F_3$$
$$F_{10} = 4 \cdot F_7 + F_4$$

Notice anything?  No overlap.  The 7th and 10th overlap, but 7-9 don't and 8-10 don't.  This will continue.  In general, now you have three serial sequences.  So you can parallel process into three threads.

You may also be able to come up with similar equations for two threads or more than three threads.  But I knew about this problem and there's already the mathematical derivation available inside the link.

Another issue is that you are searching from n down.  You might find it easier to generate the sequences from 1, 2, and 3 up with n as an upper bound.  You can do that iteratively rather than recursively, which should avoid the heavy stack usage.

This will only be faster if the system can really parallelize work.  If you were limited to a single core and can now use three, you gain.  If you're just switching between the three threads on the same processor, it will probably still be slower than the serial solution.

Calculate just one element

If all you want to do is generate the nth Fibonacci number, there is a formula to do that directly:

static int fib(int n) {
    double sqrt_5 = Math.sqrt(5);
    double phi = (1 + sqrt_5) / 2;

    double fib_n = Math.pow(phi, n) / sqrt_5;
    return (int) (fib_n + 0.5);
}

That would be the fastest solution for a single value without precalculating the numbers.  Of course, that won't parallel well.


Server side requiring parameters I wrote this middleware for express enabling developers to require certain parameters the easy way. How good is this approach? Can you call this quality code? Is everything OK, or is something missing?

Github

Package: NPM

function getMissingPrams(reqParams, requiredParamsArray) {
  //handling errors
  if (!reqParams)
    return new Error('send reqParams for the first argument')
  if (!(requiredParamsArray instanceof Array))
    return new Error('you must be using array for the second argument')
  if (requiredParamsArray.length < 1)
    return new Error('not found Required parameters')

  //Assigning body keys to array optimizing performance
  const reqParamsArray = Object.keys(reqParams);
  //extracting the missing paramerters
  const missedParams = requiredParamsArray.filter(param => !reqParamsArray.includes(param))
  //here's the array of missedParams
  return missedParams;
}

I'm assuming you're only wanting a review of the approach rather than the implementation. Otherwise, you would have placed the entire implementation in the question (which is required by Code Review if you wanted that reviewed).

Doing parameter checks on runtime is

A performance cost
Noise in the code
Development overhead

If you want to ensure type safety while not sacrificing runtime performance, code readability, or precious developer time (and hair), it is best to move this responsibility off the runtime and to somewhere else. This is either at authoring time, compile time, or both. Your options are either:

To use a type hinting and linter setup, like JSDoc and ESLint. This is the least invasive way to enforce safety while still be able to write in vanilla JS.
Use a type-safe language, like TypeScript or Flow. You'll have to change how your code is written, but type-safety is built-in. You can also write code in TS, compile it to JS, and always be sure that JS is type-safe (and not care about the consuming end).

In either case, there are tools, plugins and editor add-ons that allow you to get immediate feedback on incorrect types (in-editor warnings) and fail the build if the types aren't adhered correctly. An added benefit is that the code is self-documenting, especially if you take the JSDoc route.


Stack without use of STL - version 1.0 This is a basic implementation of a stack. Can anyone please review it and let me know how I can improve this code and overall coding practice?

 #include"iostream"
    #define MAX_SIZE 5
    using namespace std;
    class Mystack
    {
    private:
        int A[MAX_SIZE];
        int top;
    public:
        Mystack();
        void push(int x);
        void pop();
        void topElement();
        void print();
        void isEmpty();
    };
        Mystack::Mystack()
        {
            top = -1;
        }
        void Mystack::push(int x)
        {
            if(top == MAX_SIZE-1)
            {
                cout << "Stack Overflow"<< endl;
                return;
            }
            else
            {
                top++;
                A[top] = x;
            }
        }
        void Mystack::pop()
        {
            if (top != -1)
            {
                top--;
            }
            else
            {
                cout << "Stack Underflow" << endl;
                return;
            }
        }
        void Mystack::isEmpty()
        {
            if (top == -1)
            {
                cout << "Is Empty"<< endl;
            }
            else
            {
                cout << "Not Empty" << endl;
            }
        }
        void Mystack::topElement()
        {
            cout<<"The top element is : "<< A[top];
        }
        void Mystack::print()
        {
            for (int i = 0; i <=top; i++)
            {
                cout << "top:  " << A[i]<< endl;
            }
        }
    void main()
    {
        Mystack s1;
        int num,ch = 1;
        while (ch >0)
        {
            cout << "\n1. PUSH" << endl;
            cout << "2. TOP" << endl;
            cout << "3. IsEmpty" << endl;
            cout << "4. POP" << endl;
            cout << "5. EXIT" << endl;
            cout << "6. Print" << endl;
            cout << "Enter the choice"<<endl;
            cin >> ch;
            switch (ch)
            {
            case 1:
                cout << "Enter the number to be pushed" << endl;
                cin >> num;
                s1.push(num);
                break;
            case 2:
                cout << "Get the TOP Element" << endl;
                s1.topElement();
                break;
            case 3:
                cout << "Check Empty" << endl;
                s1.isEmpty();
                break;
            case 4:
                cout << "POP the element" << endl;
                s1.pop();
                break;
            case 5: exit(0);
            case 6:
                s1.print();
                break;
            }
        }
        system("pause");
    }

This review is in response to the request for help on "overall coding practice." It does not delve into the syntax or semantics of the C++ language. There are three levels: Computer Science, Architecture, Variable Names.
Computer Science
Technically the implementation is not a stack because:
myStack.push(4);
myStack.pop();

does not return 4. To be a proper stack, rather than returning void, pop should be:
int pop();

In other words, pop() must return something that was pushed onto the stack (or an error, but that's an architectural issue not a principle of computer science).
Architecture
Strictly speaking topElement() could return a void and write a message to the console, but it is conventional for it to return something of the same type as the top element of the stack - in the case of reference types, the question of whether it should be a copy [and what type of copy] or a reference to the object itself muddies the waters.
The current implementation of void pop(); points to a larger architectural issue, a low degree of modularity. Currently, user interface is spread across the code and the stack data structure even writes messages to the console. The effect:

The implementation of stack is not broadly reusable.
The user interface does not have a clear design and would be hard to debug at a larger scale. There's a bit of the "spaghetti design pattern."

A more modular approach to implementing stack might be:
public:
    Mystack();
    void push(int x);
    int pop();
    int topElement();
    bool isEmpty();
    bool isFull();  // added to allow bounds checking
    void print();   // could be handled elsewhere but that's pure opinion.

and placing - from the viewpoint of the stack -  all the user interface code in Main. Whether the user interface logic all lives there or in it's own class/module is another question. But reusability and maintenance certainly offer suggestions.
For example, breaking out the user interface and its logic and its content into modules allows handling nasty issues like multiple languages and the quirks of UniCode to be handled more gracefully. String output is the one of the places Your-Not-Gonna'-Need-It [YNGNI] fails and why it is a baked in module for so many development frameworks.
Variable Names
A, num, ch, and s1 though perhaps conventional for C++ example code, don't really scale well because they lack information. Even in the original code:
cout << "top:  " << A[i]<< endl;

is more than 50 lines from:
private:
    int A[MAX_SIZE];

and that distance is only likely to grow as a useful program adds features.
Final Thought
I cannot help but recommend McConnell's Code Complete as a guide to deepening one's understanding of the ways in which software can be organized.