Parsing a string with named sections and a key-value pair on each line I have a response String as shown below which I need to parse it and store it my class. Format is shown below:

task name followed by this dotted line -------------  which is also fixed
and then just below key:value pair. It can have many key value pair

Below is the response string.

abc-------------
Load:79008
Peak:4932152

def-------------
Load:79008
Peak:4932216

ghi-------------
Load:79008
Peak:4874588

pqr-------------
Load:79008
Peak:4874748

Below is my class:

public class NameMetrics {

    private String name;
    private Map<String, String> metrics;

    // setters and getters

}

In the above class, name should be abc and metrics map should have Load as the key and 79008 as the value and same with other key:value pairs. Below is the code I have.

String response = restTemplate.getForObject(url, String.class);
BufferedReader reader = new BufferedReader(new StringReader(response));
NameMetrics current = null;
Map<String, String> metricsHolder = null;
List<NameMetrics> result = new ArrayList<>();
while (true) {
  String s = reader.readLine();
  if (s == null) {
    break;  // end reached
  }
  if (s.trim().isEmpty()) {
    continue;  // Skip empty line
  }
  int cut = s.indexOf(':');
  if (cut == -1) {
    cut = s.indexOf('-');
    if (cut == -1) {
      continue;
    }
    metricsHolder = new HashMap<String, String>();
    current = new NameMetrics();
    current.setName(s.substring(0, cut));
    result.add(current);
  } else if (current != null) {
    metricsHolder.put(s.substring(0, cut), s.substring(cut + 1));
    current.setMetrics(metricsHolder);
  }
}

I'd like a code review to see whether this can be improved in any way?

First, I'd like to point out that if are you storing this from your program and reading it back from a file later, you'd be better off Serializing it. But since you're being given this file, let's move on.

Infinite Loops

It's generally discouraged to use while(true) loops. It's not particularly bad (in fact it's sometimes better), but it's always best to look for an alternative for readability sake. Instead, let's use while ((line = reader.readLine()) != null).

Initializing variables as null

I also see you initialized a few variables as null, but that isn't necessary since it's implied for classes. (Also note primitive variables are implied as 0 during initialization).

Using the output format to your advantage

You also have a cut variable that gets the index of the tokens, and then skips the line if it's blank. However, we know that the output is always going to be grouped into three lines, and we always know what those lines are going to be. We also know the data you really want is going to be the first three characters for the name, and everything after the first five characters for the tokens. Let's use that and make everything clear!

Putting it all together

String response = restTemplate.getForObject(url, String.class);
BufferedReader reader = new BufferedReader(new StringReader(response));
NameMetrics current;
Map<String, String> metricsHolder;
List<NameMetrics> result = new ArrayList<>();

String name, load, peak;

String nameline;
while ((nameline = reader.readLine()) != null) {
    name = nameLine.substring(0, 3);
    load = reader.readLine().substring(5);
    peak = reader.readLine().substring(5);
    reader.readline(); //eat empty line

    current = new NameMetrics();
    metricsHolder = new HashMap<>();    //No need to repeat the stuff inside the diamond operator
    metricsHolder.put("Load", load);
    metricsHolder.put("Peak", peak);

    current.setName(name);
    current.setMetrics(metricsHolder);
    result.add(current);
}

Handling varying keys and names

When there are a variable number of keys, we still know that they're all generally in the same format of the name followed dashes, then a list of key:value lines, then a blank line. We can still use this to our advantage as follows:

String name;
String[] mapValues;

final int KEY = 0, VALUE = 1;
String nameline, keyLine;
while ((nameline = reader.readLine().trim()) != null) {    //Loop until the end of the file
    name = nameLine.substring(0, nameLine.indexOf("-") + 1); //Plus because substring excludes last index

    metricsHolder = new HashMap<>();    //No need to repeat the stuff inside the diamond operator
    while (!(keyLine = reader.readLine().trim()).isEmpty()) {   //Loop until block ends with an empty line
        mapValues = reader.readLine().split(":");   //Split key:value format
        metricsHolder.put(mapValues[KEY], mapValues[VALUE]);
    }

    current = new NameMetrics();
    current.setName(name);
    current.setMetrics(metricsHolder);
    result.add(current);
}


Optimise JavaScript DOM update I'm building a virtualised grid in JS/HTML and finding browser performance with large grids fairly slow, particularly in IE10/11.  The following jsfiddle roughly represents my worst case scenario, approx 1000 cells:

http://jsfiddle.net/FGr7g/1/

function test(count) {
var self = window;
var limit = 25;

if (count < limit) {
    //settimeout to give ui chance to render
    setTimeout(function () {
        self.render(count);
        count++;
        test(count);
    }, 0);
}

if (count >= limit) {
    alert((1000 / ((performance.now() - self.startTime) / limit)) + " fps");
}
}

function render(count) {
for (var x = 0; x < this.cellCount; x++) {
    this.cells[x].textContent = count + " _c_" + x;
}
}

window.render = render;

$().ready(function () {
var self = window;

self.cellCount = 1000;
self.cells = [];
self.grid = document.createElement("div");
self.grid.style.position = "relative";
self.grid.style.height = "100%";
self.grid.style.overflow = "hidden";

for (var c = 0; c < cellCount; c++) {
    var cell = document.createElement("div");

    cell.style.width = "49px";
    cell.style.height = "24px";
    cell.style.padding = "10px";
    cell.style.position = "absolute";
    cell.style.overflow = "hidden";
    cell.style.borderTop = "1px solid lightgray";
    cell.style.borderLeft = "1px solid lightgray";
    cell.style.backgroundColor = "whitesmoke";
    cell.style.left = (c % 28) * 50 + "px";
    cell.style.top = (Math.floor(c / 28) * 25) + "px";
    cell.className = cell.className += " test_cell";

    var span = document.createElement("span");
    cell.appendChild(span);

    self.grid.appendChild(cell);

    self.cells.push(span);
}

document.getElementById("grid").appendChild(self.grid);

self.startTime = performance.now();
self.count = 0;
test(self.count);
self.totalTime = 0;
 });

 .test_cell {
 text-align: right;
 font: 8pt Segoe UI, Tahoma, Arial, Verdana;
 width: 49px;
 height: 24px;
 border-left: 1px solid lightgray;
 border-top: 1px solid lightgray;
 position: absolute;
 overflow: hidden;
}

I get around 10fps in IE at full screen, and around 30 in Chrome, assuming my performance measurement code is correct, it is consistent with the fps tools in Chrome so I think it is.

So far I've tried different methods of DOM manipulation - building a HTML string of the whole grid and inserting into the DOM (slower), using DOM fragments (slower), using a table instead of an array of absolute divs (slower), various ways of setting the span's content - innerHTML, textContent etc (made little difference), using different fonts/sizes (no difference).

Based on profiling I suspect that the majority of the time is painting rather than any java script code so I think any large improvements would like come from optimising the HTML/CSS so it is quicker to render, but any suggestions/modifications would be hugely appreciated.

If it makes any difference I am not targeting older browser versions.

First off, your code doesn't seem very optimal. This doesn't effect the speed as far as I can see, but does effect the readability, which may limit the help you get here.

Why do you create a second div inside #grid?
Why do you assign the styles of the cells twice (inline to the style attribute and a second time via the class)?
Why are you using a class at all? A selector such as `#grid > div > div' would be easier.

Here is the simplified code I used: http://jsfiddle.net/jJa8L/2/

Some experimentation show for me that the biggest speed hog seems to be the absolute positioning. When I comment it out, then I get speed improvements of 30 to 50% (40-45 fps) in Chrome. I haven't had a chance to try it out, but I'd try using a table layout (either using a <table> directly in the HTML, or using display: table-* in the CSS).

EDIT: I just discovered one certain optimization: Moving the font property from the class to more global rule (body or #grid), raises the fps in Chrome to 35-38. See http://jsfiddle.net/jJa8L/3/

EDIT 2: Ok, here's a version with table layout: http://jsfiddle.net/jJa8L/4/ It's still at 40-45 fps.

EDIT 3: No idea why I didn't think of this before: Simply let the cells flow with display: inline-block giving #grid an appriopriate width. http://jsfiddle.net/jJa8L/5/ This is  slightly faster (42-47 fps).

EDIT 4:
I just had another idea: There is a considerable speed up in Firefox and IE (but not Chrome for some reason) if you hide the grid while updating the cell texts: http://jsfiddle.net/jJa8L/8/


Freeing a binary tree data structure in C I have this function that I hope to be a good alternative to the recursive (thus performance expensive) approach.

#define _free_all(node, yes_no) \
    do { \
        Tree *__i;
        for (__i = node; __i; __i = __i->yes_no); \
        free(; node != __i; __i = __i->parent) { \
            free(__i->value); \
            free(__i); \
        } \
    } while (0)

void Tree_destroy(tree)
    Tree *tree;
{ /* Destroys a Tree object - Non Recursive */
    if (!tree)
        return;
    _free_all(tree, yes);
    _free_all(tree, no);

    if (tree->parent) {
        if (tree->parent->no == info)
            tree->parent->no = NULL;
        else
            tree->parent->yes = NULL;
    }
    free(tree);
}

The two children of each parent are no and yes.

Are there any issues with this approach ?

1. Bug

JS1 is quite correct to point out that this does not work: it never visits or frees tree->yes->no (among other nodes).

2. Correct algorithm

Consider a finite state machine with three states:

If tree has a left child, set tree to its left child and go to state 1. Otherwise, go to state 2.
If tree has a right child, set tree to its right child and go to state 1. Otherwise, go to state 3.
(In this state tree has no children.) Destroy tree. If tree had no parent, stop. Otherwise, delete whichever of parent's children is equal to tree, set tree to parent and go to state 1.

This state machine walks the tree in post-order, destroying each node after destroying all of its descendant nodes. Here's one way of translating this into C:

void TreeDestroy(Tree *tree)
{
    for (;;) {
        if (tree->left) {
            tree = tree->left;
        } else if (tree->right) {
            tree = tree->right;
        } else {
            Tree *parent = tree->parent;
            free(tree->value);
            free(tree);
            if (!parent)
                break;
            else if (parent->left == tree)
                parent->left = NULL;
            else if (!parent->left && parent->right == tree)
                parent->right = NULL;
            else
                assert(0); /* can't happen if tree is well-formed */
            tree = parent;
        }
    }
}

(I've used "left" and "right" here because these are the more usual names for the two children of a node in a binary tree.)

3. What if there are no parent pointers?

To iteratively destroy a binary tree with no parent pointers, start with the rotate right operation:

void TreeRotateRight(Tree **tree)
{
    Tree *left = (*tree)->left;
    (*tree)->left = left->right;
    left->right = *tree;
    *tree = left;
}

By repeatedly applying the rotate right operation, you can turn a tree into a vine. (A vine is a degenerate tree in which nodes only have right children.)

void TreeToVine(Tree **tree)
{
    while (*tree) {
        while ((*tree)->left)
            TreeRotateRight(tree);
        tree = &((*tree)->right);
    }
}

And then a vine is easy to destroy iteratively:

void TreeDestroy(Tree *tree)
{
    TreeToVine(&tree);
    while (tree) {
        assert(!tree->left);
        Tree *right = tree->right;
        free(tree->value);
        free(tree);
        tree = right;
    }
}


Reading and Writing object from files I have a server which has a permanent state which has to be saved on stable storage. It is composed by three fields:

List<LogEntry> log
int  currentTerm
int votedFor

They have to be set during the server setup (in other words, when the server object is created). Every time that I update their "volatile" value, the relative file must be updated. Until the first time that any of these fields is updated, the value of the relative file must not be changed (in this way if the server goes down before the first udpate, then the state files remain untouched). As last thing, usually the only operation made on the log field is the append operation, but it is possible to replace elements too.

I'd like to have your opinion about the server setup operation (in other words, the constructor). Below you will find my code and solution, but I don't like the fact that when you create a ObjectOutPutStream the original file is overwritten with a new one, but I didn't think anything better than this.

public ServerRMI(...)
{
    ...
    ObjectInputStream reader;
    log = new ArrayList<>();
    try {
        //if Log file exists then should exists Metadata too
        if(Files.exists(Paths.get("Server" + id + "Log"), LinkOption.NOFOLLOW_LINKS))
        {
            reader = new ObjectInputStream(new FileInputStream("Server"+id+"Log"));
            try
            {
                //until there are LogEntry objects in the file, read them and add them to log
                while(true)
                    log.add((LogEntry) reader.readObject());
            }
            catch (EOFException e){}
            catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            reader = new ObjectInputStream(new FileInputStream("Server"+id+"Metadata"));
            currentTerm = reader.readInt();
            votedFor = reader.readInt();
        }
        else//if it is the first time that the server is set up initialize all persistent fields
        {
            currentTerm = 1;
            votedFor = -1;
            log = new ArrayList<LogEntry>();
        }
        logWriter = new ObjectOutputStream(new FileOutputStream("Server"+id+"Log"));
        metadataWriter = new ObjectOutputStream(new FileOutputStream("Server" + id + "Metadata"));
        //since creating a new ObjectOutputStream overwrite the old file with the an empty one, as first thing we rewrite the old content
        for(LogEntry entry : log)
            logWriter.writeObject(entry);
        metadataWriter.writeInt(currentTerm);
        metadataWriter.writeInt(votedFor);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Because you can't update a written value without replacing the value, you have no other possibility to overwrite your metadata (currentTerm and votedFor) if they had changed.

For the log file you can use another approach by using an appendable FileOutputStream, but you will get problems if you just use

logWriter = new ObjectOutputStream(new FileOutputStream("Server"+id+"Log", true));

because the ObjectOutputStream is always writing a header first.

To overcome this problem you need to subclass the ObjectOutputStream like

public class AppendableObjectOutputStream extends ObjectOutputStream {

    public AppendableObjectOutputStream(OutputStream out) throws IOException {
        super(out);
    }
    private boolean append = false;
    public AppendableObjectOutputStream(String fileName, boolean appendIfExists) throws IOException {
        super(new FileOutputStream(fileName, appendIfExists && Files.exists(Paths.get(fileName), LinkOption.NOFOLLOW_LINKS)));
        append = appendIfExists && Files.exists(Paths.get(fileName), LinkOption.NOFOLLOW_LINKS);
    }

    @Override
    protected void writeStreamHeader() throws IOException {
        if (append) {
            reset();
        } else {
            super.writeStreamHeader();
        }
    }
}

See also: https://stackoverflow.com/a/1195078/2655508

Using braces {} for single statements while loops too will make your code less error prone.

A ObjectInputStream should like any other stream be closed after the usage is finished.

//if Log file exists then should exists Metadata too

Assuming that something should be can lead to problems. One could have deleted the metadatafile and you would get problems.

Your method is doing to many things. You should extract parts of it to separate methods. Like

private List<LogEntry> readLogFile(String fileName) throws IOException {
    List<LogEntry> logs = new ArrayList<>();
    if (Files.exists(Paths.get(fileName), LinkOption.NOFOLLOW_LINKS)) {
        ObjectInputStream reader = new ObjectInputStream(new FileInputStream(fileName));
        try {
            //until there are LogEntry objects in the file, read them and add them to log
            while (true) {
                logs.add((LogEntry) reader.readObject());
            }
        } catch (EOFException e) {
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(reader != null){
                reader.close();
            }
        }
    }
    return logs;
}

For reading the metadatafile I would suggest you create a MetaData class which holds the voteFor and Term and is beeing written by using writeObject() and read by readObject() methods. The voteFor and Term should be initialized in the constructor to voteFor = -1 and Term = 1.

This would give you the possibility to use this method

private MetaData readMetaDataFile(String fileName) throws IOException {
    if (Files.exists(Paths.get(fileName), LinkOption.NOFOLLOW_LINKS)) {
        ObjectInputStream reader = new ObjectInputStream(new FileInputStream(fileName));
        try {
            return ((MetaData) reader.readObject());

        } catch (EOFException e) {
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(reader != null){
                reader.close();
            }
        }
    }
    return new MetaData ();
}

Implementing the above mentioned points will lead to

MetaData metaData = null;
String logFileName = "Server" + id + "Log";
String metaDataFileName = "Server"+id+"Metadata";
try {
    log = readLogFile(logFileName );
    metaData = readMetaData(metaDataFileName);

    logWriter = new AppendableObjectOutputStream(logFileName, true);
    metadataWriter = new AppendableObjectOutputStream(metaDataFileName, false);

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

but you should create the metadataWriter only if you really write the data.


Optimizing WordWrap Algorithm I have a word-wrap algorithm that basically generates lines of text that fit the width of the text. Unfortunately, it gets slow when I add too much text.

I was wondering if I oversaw any major optimizations that could be made. Also, if anyone has a design that would still allow strings of lines or string pointers of lines that is better I'd be open to rewriting the algorithm.

Thanks

void AguiTextBox::makeLinesFromWordWrap()
{
    textRows.clear();
    textRows.push_back("");
    std::string curStr;
    std::string curWord;

    int curWordWidth = 0;
    int curLetterWidth = 0;
    int curLineWidth = 0;

    bool isVscroll = isVScrollNeeded();
    int voffset = 0;
    if(isVscroll)
    {
        voffset = pChildVScroll->getWidth();
    }
    int AdjWidthMinusVoffset = getAdjustedWidth() - voffset;
    int len = getTextLength();
    int bytesSkipped = 0;
    int letterLength = 0;
    size_t ind = 0;

    for(int i = 0; i < len; ++i)
    {

        //get the unicode character
        letterLength = _unicodeFunctions.bringToNextUnichar(ind,getText());
        curStr = getText().substr(bytesSkipped,letterLength);

        bytesSkipped += letterLength;

        curLetterWidth = getFont().getTextWidth(curStr);

        //push a new line
        if(curStr[0] == '\n')
        {
            textRows.back() += curWord;
            curWord = "";
            curLetterWidth = 0;
            curWordWidth = 0;
            curLineWidth = 0;
            textRows.push_back("");
            continue;
        }

            //ensure word is not longer than the width
            if(curWordWidth + curLetterWidth >= AdjWidthMinusVoffset &&
                curWord.length() >= 1)
            {
                textRows.back() += curWord;

                textRows.push_back("");
                curWord = "";
                curWordWidth = 0;
                curLineWidth = 0;
            }

            //add letter to word
            curWord += curStr;
            curWordWidth += curLetterWidth;

        //if we need a Vscroll bar start over
        if(!isVscroll && isVScrollNeeded())
        {
            isVscroll = true;
            voffset = pChildVScroll->getWidth();
            AdjWidthMinusVoffset = getAdjustedWidth() - voffset;
            i = -1;
            curWord = "";
            curStr = "";
            textRows.clear();
            textRows.push_back("");
            ind = 0;

            curWordWidth = 0;
            curLetterWidth = 0;
            curLineWidth = 0;

            bytesSkipped = 0;
            continue;
        }

        if(curLineWidth + curWordWidth >=
            AdjWidthMinusVoffset && textRows.back().length() >= 1)
        {
            textRows.push_back("");
            curLineWidth = 0;
        }

        if(curStr[0] == ' ' || curStr[0] == '-')
        {
            textRows.back() += curWord;
            curLineWidth += curWordWidth;
            curWord = "";
            curWordWidth = 0;
        }
    }

    if(curWord != "")
    {
        textRows.back() += curWord;
    }

    updateWidestLine();
}

I have some high-level advice based on a cursory read of your code. It would really help if you could refactor it into multiple methods as this function is too long and does too much. That won't help your speed, but it will make it easier for others to grok your code and provide more advice.

Profile your code

You can't hope to make things faster in an orderly fashion without finding out what parts take the most time. Yes, you can devise a faster algorithm, but you might end up spending days optimizing an O(n^2) algorithm to O(log n) only to find out that part took 1ms anyway.

Split each word first

If you only split at word boundaries, you may as well seek forward for a boundary and extract the substring in one call.

Calculate word widths instead of letter widths

First, when I wrote a similar function in Java many years ago, the cost of calling calculating the width of a string had a fairly high overhead that didn't change with the length of the string. Getting the width a character at a time was significantly more costly than calculating the length of a word. Also, since there may be kerning involved that adjusts the space between letters based on the letter pairs, you can't add up the character widths to arrive at the word width.

If you end up needing to split a word midway, use a binary search to find the cutoff point

This goes with the two above, but you won't really know the best route until you profile.

Make sure you're not using a linked list

You add the string to the list (vector?) and modify it for each character. If this is a linked list instead of an array, it will be very costly. I'm not very familiar with the STL if that's what you're using (those declarations would help), so maybe it maintains a tail pointer. In any case, I would build each line and add it to the list only once it's complete even if you're using an array-based vector. It just seems cleaner.

Show a disabled scroll bar instead of restarting once you determine that scrolling is necessary

Really, a disabled scroll bar isn't that horrendous. ;)

Calculate the widest line as you wrap

I'm betting that the work done in updateWidestLine() is very similar to what you're already doing in makeLinesFromWordWrap(). Take advantage of that and maintain a maxLength local variable as you do the wrapping.


Unit Testing of parser method using pytest This is my first time using pytest. All feedback for this test case is much appreciated.

import pytest
from mock import mock_open, patch

def get_file_contents(file_data):
  with patch.object('builtins.open', mock_open(read_data=file_data)) as mock:
    with open('mocked_file') as f:
      return (line for line in f.readlines())

@pytest.fixture(scope="module")
def text_parser(request):
  from tparse import TextParser
  file_data = getattr(request.module, 'file_contents')
  tparse = TextParser(file_data)
  def fin():
    tparse.close()
  request.addfinalizer(fin)
  return tparse

def test_get_system_entry(self):
  file_data = 'dc nyc server server001 ipaddress 10.10.10.10'
  file_iterable = get_file_contents(file_data)
  assert file_iterable == file_data

I'm not familiar using py.test, but here are some comments I have after reading your code:

There are no comments - this would be helpful to the reader.
In text_parser, you have from tparse import TextParser. I would advise moving this import to the top of the file, for readability.
What is your code trying to do with these tests? What are you testing?


The Rust Book: HashMap Challenge I'm working my way through the Rust Book:

Ch.8 Challenge:
Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in the company. For example, “Add Sally to Engineering” or “Add Amir to Sales”. Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.

use std::collections::HashMap;
#[derive(Debug)]
enum Command {
    Add(String, String),
    List,
    Unknown
}

fn command_filter(input: String) -> Command {
    let mut command_string = input.split_whitespace();
    match command_string.next() {
        Some("Add") => {
            match (command_string.next(), command_string.last()){
                (Some(name), Some(dept)) => Command::Add(name.to_string(), dept.to_string()),
                _ => Command::Unknown
            }
        },
        Some("List") => Command::List,
        _ => Command::Unknown
    }
}

fn process_command(command: Command, employee_map: &mut HashMap<String, String>) {
    match command {
        Command::Add(name, dept) => {
            employee_map.insert(name, dept);
            ()
            },
        Command::List => {
            for (name, dept) in employee_map {
                println!("Name: {} Dept: {}", name, dept);
            };
        },
        Command::Unknown => println!("Unknown command!"),
    };
}

fn main() {
    let mut employee: HashMap<String, String> = HashMap::new();
    let command = command_filter(String::from("Add John to Eng"));
    process_command(command, &mut employee);

    let command = command_filter(String::from("Add Devon to Bio"));
    process_command(command, &mut employee);

    let command = command_filter(String::from("List"));
    process_command(command, &mut employee);
}

As with most devs starting to learn Rust I am finding difficulty with borrowing. I do not come from a C/C++ background and so I'm also finding pointers versus actual object a little tricky too.
Some specific thoughts:

I am suspicious that match statements inside match statements is not good practice.
The Command::Add branch in process_command feels a little hacky with the () return. Edit: After thinking more about this problem, I think if I wrapped the branch responses in Ok() then I could return a Result from that function.

Do you have any feedback?

Hide hashmap implementation
The code can be improved by removing the requirement for the user to operate on a hashmap or to even know that a hashmap is used.
How? This should be hidden from the user by an "interface".
Why?
This is a good coding practice as it would allow the underlying structure/code to change (for example, the hashmap could be swapped for a db) but there would be no API changes to the interface.
I have implemented this change and the changes suggested by @Shepmaster here: github


Javascript calculation function I use this function to to do some calculations based on 4 select inputs and one number input, I don't have experience in Js, I did some research in w3schools then I ended up with the function below.
The Js function is working exactly as I want, but I feel it is not the perfect syntax and it could be shorter and somehow cleaner, any advice would be appreciated.

function calculate() {
  var x = parseFloat(document.getElementById("Lang_from").value);
  var y = parseFloat(document.getElementById("Lang_to").value);
  var q = parseFloat(document.getElementById("quantity").value);
  var s = parseFloat(document.getElementById("subject").value);
  var f = parseFloat(document.getElementById("file_type").value);
  var xx = document.getElementById('Lang_from').selectedOptions[0].text;
  var yy = document.getElementById('Lang_to').selectedOptions[0].text;
  var ff = document.getElementById('file_type').selectedOptions[0].text;
  var ss = document.getElementById('subject').selectedOptions[0].text;

  document.getElementById("total_price").innerHTML = (x + y) * q + (s + f);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

From

        <select id="Lang_from" name="Lang_from" value="" class="form-control pricing_input">
          <option id="en2ar" value="0.025">English</option>
          <option>German</option>
        </select>

To

        <select id="Lang_to" name="Lang_to" value="" class="form-control pricing_input">
          <option value="0.025">German</option>
          <option>English</option>
        </select>

File type

        <select id="file_type" name="file_type" value="" class="form-control pricing_input">
          <option value="0">TXT</option>
          <option value="3">MS word</option>
          <option value="5">PDF (+5$)</option>
          <option value="10">Hand Writing</option>
        </select>

Subject

        <select id="subject" name="subject" value="" class="form-control pricing_input">
          <option value="0">General</option>
          <option value="10">Technical / IT</option>
          <option value="15">Medical</option>
          <option value="5">Press</option>
        </select>

Word count

        <input type="number" id="quantity" name="quantity" min="500" value="1000" class="form-control pricing_input pricing_input_number">

        <button id="calculate" type="button" class="btn btn-primary pricing_btn_calc" onclick="calculate()">Calculate</button>

Access elements via ID

You can get access to elements directly via their ID, if you ensure that each elements id and or name is unique withing the page and JavaScripts global scope.

var x = parseFloat(document.getElementById("Lang_from").value);

becomes

var x = parseFloat(Lang_from.value);

In the example at the bottom I have removed all the names from the HTML. You have not indicated that this is a submit-able form and thus you can do without the extra markup.

Note that forms do provide additional information for clients with special needs. For content that faces the world (public) always consider Accessibility. Dealing with font end interaction (not using forms) you should be familiar with WAI-ARIA and how it makes content meaningful and accessible to everyone .

Use Number rather than parseFloat

Rather than use parseFloat use Number to convert a string number to a Number type

var x = parseFloat(Lang_from.value);

becomes

var x = Number(Lang_from.value);

or you can coerce a string representing a number using an operator. Commonly + is used

var x = + Lang_from.value;

JavaScripts has automatic type coercion and will force the string to a number, Note that + will not work as  var x = "10" + Lang_from.value; as the type is set by "10" and + can operate on strings (concats)

Define appropriate variable types

The variables you use are never modified. JS has several variable types. var, let, and const. Get in a habit of using the most appropriate type, for variables that do not change or should not change use const

const x = +Lang_from.value;

Naming is an important programming skill to master

Always pay special care to the names you use.

Some of your variable names have absolutely no relationship to their content (eg x, y, and maybe f)

Using abbreviations is OK and can reduce clutter, using the first letter of each word in the ID is OK (BUT DEFINING NAME and USING NAME must be no more than a page of apart, as the need to hunt for meaning is a distraction that aids bugs getting in)

const lf = +Lang_from.value;
const lt = +Lang_to.value;
const q =  +quantity.value;
const s =  +subject.value;
const ft = +file_type.value;

Avoid intermediates if possible

Rather than the many names, calculate the total as you access the data.

var total = (+Lang_from.value) + (+Lang_to.value); // The extra + to coerce to number
total *= quantity.value;  // *= same as total = total * quantity.value;
                          // The extra + not ended if the operation on the value is
                          // not +
total += +subject.value;
total += +file_type.value;

NO! don't do this... <button onclick="functionName()">

Avoid putting code within the markup. The event listener for calculate should be added via JavaScript when the page has loaded. Use "load" or "DOMContentLoaded" events

addEventListener("load", function() {  // waits for the page to load
     calculate.addEventListener("click", calculateTotal);
});

// or using arrow function and a slightly earlier event that fires when
// all the HTML content has loaded and been parsed (image and the like may not be ready)
addEventListener("DOMContentLoaded", () => {  // waits for the page to load
     calculate.addEventListener("click", calculateTotal);
});

// NOTE that the element id is calculate which conflicted with the JavaScript function
// name calculate. I renamed the function to calculateTotal ( which I would have done
// even if there was no name conflict)

Loose ends are bad practice

Keep the code clean and do not include code that has no purpose. You have 5 variables that get the selections yet you don't use them. They should not be in the function. If you put them their because you intend to use them at another time, finish the code or add a comment with that code eg /* Todo: Show selection names */  else the code is considered incomplete (easy to forget or worse)

Use appropriate properties

When adding content to an element and it is just text (no HTML content) use the node property Node.textContent to set the text. (Elements inherit properties from Node so can be used on most elements)

Example

Basic Markup only

I have removed all irrelevant information from the Markup, (forms, styling wrappers, name/id duplicates, property duplicates, class name)

I removed the references to the CSS styles. Looking good is important, but start at the core and work up, don't start with looking good, that is why we have CSS, to seperate the two.

"use strict";
addEventListener("DOMContentLoaded", () => {
  calculate.addEventListener("click", calculateTotal);
});

function calculateTotal() {
  var total = (+Lang_from.value) + (+Lang_to.value);
  total *= quantity.value;
  total += (+subject.value) + (+file_type.value);
  total_price.textContent = "$" + total.toFixed(2);
}

From

<select id="Lang_from">
  <option value="0.025">English</option>
  <option>German</option>
</select>

To

<select id="Lang_to">
  <option value="0.025">German</option>
  <option>English</option>
</select>

File type

<select id="file_type">
  <option value="0">TXT</option>
  <option value="3">MS word</option>
  <option value="5">PDF (+5$)</option>
  <option value="10">Hand Writing</option>
</select>

Subject

<select id="subject">
  <option value="0">General</option>
  <option value="10">Technical / IT</option>
  <option value="15">Medical</option>
  <option value="5">Press</option>
</select>

Word count

<input type="number" id="quantity" min="500" value="1000">
<button id="calculate">Calculate</button>

Total price

Beginners note

You will notice the string "use strict"; at the top of the JavaScript, it is a directive that forces JavaScript to run in strict mode.

The name may suggest this is something for experienced coders, quite the contrary as experienced JS coders seldom make the errors this will trap.

Experienced JS coders always use strict mode because its faster and because everyone make mistakes.

Ergo: Always run your javascript in strict mode using the directive "use strict";

This example has no semantic meaning to some

I have not used ARIA to add semantic meaning to the content as I do not think its applicable in this case and would make for a way too long already too long answer.

Slight change to result

I noted that the quantity input is unconstrained in its precision (Allows fractions). When you output values, especially monetary values, be careful to include the correct rounding and precision. A money value ideally always starts with the currency type (I used $ and the value is written with full precision Dollars.Cents eg $10.00.

JavaScripts Number (floating point double) is only an approximation of numbers, in a few calculation a number can easily gain a rounding error and just display the value raw will end you with displayed values like 10.00000000000003 or 3e-17 both not good things to show when it involves money,

References

The site you used as a reference has a bad wrap, being incomplete and out of date, Though it has been years since I have had a good look, so if this remains true I am unsure.

I better reference site is MDN JavaScript and the main landing MDN it has a mostly complete reference of Web technologies, plenty of learning resources (tutorials, examples and the like), and if you need to get to the definitive resource they do provide links to the all the standards documentation (Very dry and hard to read resource of everything) that is applicable.


Calculating freefalling object's height This is the code for my first CS1 project, I hope to be posting my code here to track my progress of learning the language of C++.  I shouldn't be too shabby, since I know C considerably well and have reviewed C++ code here before.

  Write a program that allows the user to enter a time in seconds and
  then outputs how far an object would drop if it is in freefall for
  that length of time.  Assume that the object starts at rest, there is
  no friction or resistance from air, and there is a constant
  acceleration of 32 feet per second due to gravity.  Use the equation:

  $$
\text{distance} = \dfrac{\text{acceleration} \cdot\text{time}^2}{2}
$$

rock.cpp:

/**
 * @file rock.cpp
 * @brief Determines the height that a rock falls (in feet) after a given time
 * @author syb0rg
 * @date 9/8/14
 */

#include <iostream>
#include <cmath>

int main(void)
{
    // initialize variables on declaration
    double time = 0;
    double acceleration = 32.174;

    std::cout << "Enter the time in seconds that a rock will fall: ";
    std::cin >> time;

    double feetFallen = (acceleration * pow(time, 2)) / 2;

    std::cout << "The rock fell " << feetFallen << " feet." << std::endl;
}

Your code is both short and good, so there's not much to say.

Header organization

It's a good idea to keep your headers organized. Keeping them alphabetically ordered allows you to spot accidental duplicates.

main() signature

You don't need to put void in the parentheses. It's very much a C-ism, and is not necessary in C++. Empty parentheses also means the function takes no arguments.

const variables and constants

acceleration is a constant, and should be marked constexpr to indicate it is a compile-time constant. Please note that constexpr is only available in C++11 or later. If you have to use an earlier version, you can replace it with static const for largely the same effect. feetFallen should be marked const, since you only read from it after it is initialized.

Marking variables const and constants constexpr limits the number of moving parts in your application, making it easier to reason about and keep correct.

Unnecessary comment

Your comment about initialization is not necessary. The fact that you initialize variables the same time they are declared is obvious from reading the code.

Invalid user input

time will contain the value 0 if your user inputs non-numeric input. If you want to constrain the user to numeric-only input, you can loop until the user enters only a valid number. Inspired by this StackOverflow answer, your solution could look like this:

while(!(std::cin >> time)){
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Invalid input.  Please enter a number: ";
}


A better approach to parsing this file name in Java? I am creating a file uploader, and one function of the uploader will parse the file name to make sure that it is in the correct format.

This is the proper format of the file name: FILENAME_USERNAME_YYYYMMDD.csv,
where FILENAME and USERNAME are any chars of any length.

Specifically, I must extract the date from the file name and compare it to a date given in the .csv file content. (comparing to a date: MM/DD/YYYY).

Below is the way that I have approached the problem: but if the user happens to input a file with a random, arbitrary file name, it's very possible for the method to throw a null pointer exception.. Hoping for a suggestion for a more elegant solution.

public boolean compareDate(File file, String cellDate)
{
    String date;
    String tempDate;
    String year, month, day;

    int startIndex = file.getName().lastIndexOf("_");
    int lastIndex = file.getName().lastIndexOf(".");

            if (startIndex > 0 && lastIndex > 0)
            {
                tempDate = file.getName().substring(startIndex+1, lastIndex);

                if (tempDate.length() < 8) // 8 == chars in date
                    return false;
            }

            year = tempDate.substring(0,4);
            month = tempDate.substring(4,6);
            day = tempDate.substring(6,8);

            date = month + "/" + day + "/" + year;

            if (date.equals(cellDate) || date.contains(cellDate)) // (ex. 01/25/2013 == 1/25/2013
                return true;
            else
                return false;
}

My version:

public class CodeReview_27975 {
    // match everything between the last "_" and "." [explanation in the notes!]
    private final static Pattern FILENAME_DATE_PATTERN = Pattern.compile(".*_(.*?)\\..*");

    // apply the pattern to extract date from file name
    private String extractDateFromFilename(String filename) {
        Matcher m = FILENAME_DATE_PATTERN.matcher(filename);
        if (!m.matches()) {
            throw new IllegalArgumentException(
                    "Filename doesn't match expected format: " + filename);
        }

        return m.group(1);
    }

    private boolean compareDate(String fileName, String cellDateString) {
        SimpleDateFormat fileDateParser = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat cellDateParser = new SimpleDateFormat("MM/dd/yyyy");

        Date d1, d2;
        try {
            d1 = fileDateParser.parse(extractDateFromFilename(fileName));
            d2 = cellDateParser.parse(cellDateString);
        } catch (ParseException e) {
            throw new IllegalArgumentException(
                    "One of the input dates failed to be parsed:" + fileName
                            + ", " + cellDateString);
        }

        return d1.equals(d2);
    }

    // this is the only public method, but it delegates to private utility functions
    public boolean compareDate(File file, String cellDate) {
        return compareDate(file.getName(), cellDate);
    }

    public static void main(String[] args) {
        CodeReview_27975 app = new CodeReview_27975();
        // easy to test
        System.out.println(app.compareDate("file_user_20130125.csv", "1/25/2013"));
        System.out.println(app.compareDate("file_user_20130125.csv", "01/25/2013"));
        System.out.println(app.compareDate("file_user_20130101.csv", "1/1/2013"));
    }
}

split the single method into smaller, easier to test, chunks.
each function deals with a single concern (most of the code deals with strings, no need to pass the File object further down the stack). This makes it easier to test
regular expressions are useful when dealing with patterns in strings. Extracting date from file is much more robust this way (you'll most likely getting the NullPointerException for non-standard input; the current expression doesn't solve this problem but at least it reports it correctly, making it easier to create a fix)
comparing dates as strings is just wrong; your equals-or-contains trick would fail when comparing 1/1/2013 and 01/01/2013. Creating a Date object is a small price to pay for correctness.
the class could be visually longer but I believe it's easier to understand this way; most of the new code comes from exception handling - if you decided to simply make the caller handle checked exceptions, you could remove most of that.

Also, convention for compare functions is to return an integer: <0 if first argument is smaller, 0 if both are equal and >1 if the first argument if bigger. This would make the method more flexible and potentially useful for the caller. Changing the name to areDatesSame or something like that would be another option.

edit:
".*_(.*?)\\..*" pattern dissected:

.*    any character, zero or more of them at the start
_     an underscore
(.*?) capture a group (after underscore, before the dot)
\.    dot character (has to be escaped into "\\." if inside a String)
.*    any character, any number of them at the end

Regular expressions are a broad subject but knowing the basics (and where/how to look for more detailed information) will always pay off. You can start by having a look at the Java Tutorial on Regex

The expression could be changed to only accept exactly 8 digits in the group (rather than ANY string between "_" and "."), making it a bit more complicated but more specific.

Visualisation from debuggex.com:


From Q to compiler in less than 30 seconds (See the newer version here:  CodeReview question markdown downloader)

As an adjunct to From new Q to compiler in 30 seconds, I've created a Python script to automatically download the markdown from any question on Code Review and save it to a local file using Unix-style line endings.

For instance, to fetch the markdown for this question, one could write:

python fetchQ.py 124479 fetchquestion.md

I'm interested in a general review including style, error handling or any other thing that could be improved.

fetchQ.py

""" Code Review question fetcher.  Given the number of the question, uses
the StackExchange API version 2.2 to fetch the markdown of the question and
write it to a local file with the name given as the second argument. """
import sys
import urllib
import StringIO
import gzip
import json
import HTMLParser

def make_URL(qnumber):
    return 'https://api.stackexchange.com/2.2/questions/'+str(qnumber)+'/?order=desc&sort=activity&site=codereview&filter=!)5IYc5cM9scVj-ftqnOnMD(3TmXe'

def fetch_compressed_data(url):
    compressed = urllib.urlopen(url).read()
    stream = StringIO.StringIO(compressed)
    data = gzip.GzipFile(fileobj=stream).read()
    return data

def fetch_question_markdown(qnumber):
    url = make_URL(qnumber)
    try:
        data = fetch_compressed_data(url)
    except IOError as (err):
        print "Error: {0}: while fetching data from {1}".format(err, url)
        sys.exit()
    try:
        m = json.loads(data)
    except ValueError as (err):
        print "Error: {0}".format(err)
        sys.exit()
    try:
        body = m['items'][0]['body_markdown']
    except KeyError:
        print "Error: item list was empty; bad question number?"
        sys.exit()
    except IndexError:
        print "Error: response does not contain markdown; bad question number?"
        sys.exit()
    h = HTMLParser.HTMLParser()
    md = h.unescape(body)
    return md

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('Usage: fetchQ questionnumber mdfilename')
        sys.exit()
    qnumber, qname = sys.argv[1:3]

    md = fetch_question_markdown(qnumber)
    with open(qname, 'wb') as f:
            f.write(md.encode('utf-8').replace('\r\n','\n'))

Note: This code and its companion C++ project are now available in a github repo.

I have a couple of suggestions which are not specifically about the code, but rather about the user experience.

The first thing I did was copy-paste the script to a file, make it executable and tried to run it.

$ chmod +x fetchQ.py
$ ./fetchQ.py 124307 autoproject
./fetchQ.py: line 5: $' Code Review question fetcher.  Given the number of the question, uses\nthe StackExchange API version 2.2 to fetch the markdown of the question and\nwrite it to a local file with the name given as the second argument. ': command not found
... etc ...

As you understand, I just assumed the script had a shebang line and instead of using python, Bash tried to interpret the script itself. I think other users might have the same expectations and that you should therefore begin your script with the line #!/usr/bin/env python.

Now, you might have noticed, I accidentally left out the .md extension for the file name. Because the primary use-case for this program is to set up a file for AutoProject, which requires files to have that extension, I think it should automatically be added if no other extension is provided.

Finally, the other argument to the program is the question id. Instead of making users extract the id themselves from the url, I think the user should have the option to pass the full link directly because just pressing CtrlL; CtrlC is easier than by hand selecting the id portion.


Which way is better for converting number to string? Sometimes there is need to change an integer to text.
I often use the following way:

"" + myNumber

But there is alternative way:

Integer.toString(myNumber)

Which one is better (performance, readability, safety)?
Or are those equal?

I would recommend

String.valueOf(myNumber)

This allows you to to change myNumber to another primitive type - or a Number - later.

"" + myNumber

should be avoided since :

it produces clutter bytecode (instanciating a new StringBuffer)
it does not convey what you wanted to do with myNumber


Python Constant Class, Different Enum Implementation So I saw a need for and came up with a class implementation to group constants, which I'm calling a Constant Class. I wondered if there existed other similar implementations or if there is a flaw in what I'm doing. My team is currently finding it fairly useful and thought we should see what other people thought. Also to offer out into the world if it indeed is useful to others.

The need was simple. We wanted to group constants as to allow auto-completion and also the ability to reference a list of all the values for validation. This mainly was for the development of an API backend which handle many groups of different types.

import inspect
import re

class ConstantClass(object):
    """ Container class for meant for grouped constants """

    @classmethod
    def all(cls):
        """
        Returns all constant values in class with the attribute requirements:
          - only uppercase letters and underscores
          - must begin and end with a letter

        """
        regex = r'^[A-Z][A-Z_]*[A-Z]$'
        class_items = inspect.getmembers(cls)
        constants = filter(lambda item: re.match(regex, item[0]), class_items)
        values = map(lambda constant: constant[1], constants)

        return values

class TypeNames(ConstantClass):
    TYPE_A = 'Whatever you want it to be'
    TYPE_B = 'Another example'

TypeNames.TYPE_A # returns 'Whatever you want it to be'
TypeNames.all() # returns list of constant values
TypeNames.TYPE_A in TypeNames.all() # Returns True

Enums the closest thing but it requires we type out EnumClass.CONSTANT.value (I honestly find kind of annoying) and there isn't a built-in function to get all the values. I don't know, maybe I'm splitting hairs here but I'm just curious if there is any draw-back to what I'm doing.

The code looks decent, but there are a couple problems with the overall design:

"constants" can be changed (rebound) or removed from the class
the constants don't have a nice repr() (very useful for debugging)

To solve these problems, and more, check out the aenum library1 -- besides advanced Enum and NamedTuple implementations, it also has a Constant2 class.

Your code above would look like:

from aenum import Constant

class TypeNames(Constant):
    TYPE_A = 'Whatever you want it to be'
    TYPE_B = 'Another example'

and in use:

>>> print(repr(TypeNames.TYPE_A))
<TypeNames.TYPE_A: 'Whatever you want it to be'>

>>> print(TypeNames.TYPE_A)
Whatever you want it to be

>>> try:
...     del TypeNames.TYPE_B
... except AttributeError as exc:
...    print(exc)
....
cannot delete constant <TypeNames.TYPE_B>

>>> try:
...     TypeNames.TYPE_B = 'oops!'
... except AttributeError as exc:
...     print(exc)
...
cannot rebind constant <TypeNames.TYPE_B>

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

2 Looking at your all() implementation I can see that should be added to Constant.


Create plain object from URLSearchParams Is there a shorter / cleaner way of creating a plain object from URLSearchParams than this:

const uri = new URL('https://tempuri.org/?token=secret&test=true')
const result = {}
for (let p of uri.searchParams) {
  result[p[0]] = p[1]
}

Expected result:

{ token: 'secret', test: 'true' }

Since ES6 there is a cleaner solution with Object.fromEntries:
const url = 'https://tempuri.org/?token=secret&test=true';
const params = new URL(url).searchParams;
Object.fromEntries(params);

It will output an object like this:
{ token: 'secret', test: 'true' }

See browser compatibility of Object.fromEntries on MDN. Basically all browsers and Node.js 12+ except Samsung Internet, Opera Android, and Internet Explorer. Time to say goodbye to the old browsers :)


Get methods in module, Python Goal: extract methods/functions defined in module. This excludes:

Imports
Lambda methods
Magic methods
Builtin methods
Class methods
Classes
Non-original definitions (i.e. function assignments, alt_name = orig_fn)

My approach + test below. Any room for improvement, or false positives/negatives? (In particular I wonder if we can get away without typechecks, e.g. isinstance(method, types.LambdaType))

Code: live demo

import utils

def get_module_methods(module):
    def is_module_function(obj):
        return ('<function' in str(obj) and
                module.__name__ in getattr(obj, '__module__', ''))

    def not_lambda(obj):
        return not ('<lambda>' in getattr(obj, '__qualname__', ''))

    def not_magic(obj):
        s = getattr(obj, '__name__', '').split('__')
        return (len(s) < 2) or not (s[0] == s[-1] == '')

    def not_duplicate(name, obj):
        return name == getattr(obj, '__name__', '')

    def cond(name, obj):
        return (is_module_function(obj) and not_lambda(obj) and
                not_magic(obj) and not_duplicate(name, obj))

    objects = {name: getattr(module, name) for name in dir(module)}
    m_methods = {}

    for name, obj in objects.items():
        if cond(name, obj):
            m_methods[name] = obj
    return m_methods

mm = get_module_methods(utils)
_ = [print(k, '--', v) for k, v in mm.items()]

Test:

# utils.py
import random
import numpy as np
from inspect import getsource

def fn1(a, b=5):
  print("wrong animal", a, b)

class Dog():
  meow = fn1
  def __init__(self):
    pass

  def bark(self):
    print("WOOF")

d = Dog()
barker = d.bark
mewoer = d.meow
A = 5
arr = np.random.randn(100, 100)

def __getattr__(name):
  return getattr(random, name, None)

magic = __getattr__
duplicate = fn1
_builtin = str
lambd = lambda: 1

# main.py
import utils

# def get_module_methods(): ...

mm = get_module_methods(utils)
_ = [print(k, '--', v) for k, v in mm.items()]

fn1 -- <function fn1 at 0x7f00a7eb2820>

Edit: additional test case for a lambda surrogate:

import functools

def not_lambda():
    return 1
functools.wraps(lambda i: i)(not_lambda).__name__

Code in question and answer catch not_lambda as a lambda - false positive.

pyclbr

The standard library includes the pyclbr module, which provides functions for building a module browser.  pyclbr.readmodule_ex() returns a tree of nested dicts with the functions (defstatements) and classes (class statements) in a module.  So you just need to check the top level dict for items of class pyclbr.Function.

Note that readmodule_ex takes the name of the module (a str), not the actual module.

Just tested this, and it prints out imported functions and dunder functions as well, so those need to be filtered out.

import pyclbr

module = 'tutils'

for k,v in pyclbr.readmodule_ex(module).items():
    if (    isinstance(v, pyclbr.Function)
        and v.module==module
        and not v.name.startswith('__')):
        print(f"{v.name} -- {v.file} at {v.lineno}")


How to reduce number of hierarchical 'if statements' <% @descriptions.each_with_index do |description, i| %>
  <% description.tale2.each do |tax_ref| %>
    <% if condition %>
      <% if condition %>
        <% if condition %>
          <%= $text_first_describe%> <%= $paren_author_yr %>
             <% ref_sp_uniq.each_with_index do |ref, i| %>
               <% if ref == tax_ref.ref_wo_brace%>
                  <% execution %>
               <% elsif i == (ref_sp_uniq.size - 1)%>
                  <%# @ref_desc = "#{@ref_desc_numb}. #{tax_ref.ref_wo_brace}" %>
               <% end %>
             <% end %>
          <% if condition %>
                  <% execution %>
          <% elsif condition %>
            <% execution %>
          <% elsif taxon_name.emend_author_year %>
             <%= print %>
          <% else %>
             <%= print %>
          <% end %>
        <% end %>
      <% else %>
        <% if condition %>
          <%= print %>
          <% ref_sp_uniq.each_with_index do |ref, i| %>
             <% if condition %>
                <% execution %>
             <% elsif condition %>
                  <% execution %>
             <% end %>
          <% end %>
          <% if condition %>
            <% execution %>
          <% elsif condition %>
            <% execution %>
          <% elsif condition %>
            <% execution %>
          <% else %>
            <% execution %>
          <% end %>
        <% end %>
      <% end %>
    <% end %>
  <% end %>
<% end %>

In general, you can try inverting the condition on your outermost if block, and work your way in.  This will often result in less nesting, eg:

if condition1
  if condition2
    #ifblock
  else
    #elseblock2
  end
else
  #elseblock
end

Inside a loop, as you have your code, it would become this strcture, which is less nested:

if !condition
  #elseblock
  next
end
if !condition2
  #elseblock2
  next
end
#ifblock


Find the index of the element with maximum absolute deviation I just completed a Codility test. The question presented was pretty simple but I may have over thought it.

Question:

  Find the element which has the highest absolute deviation from the mean. E.g. Array = [1,1,-1,1].The average is 0.5, so the absolute deviation for each element in the array is [0.5,0.5,1.5,0.5] (note that the -1.5 goes to 1.5 after taking the absolute values of each deviation value) and thus the index with the max absolute deviation is 2 (the index starts from 0).

My code was:

def solution(A):
    if len(A) > 0:
        average = sum(A)*1.0/len(A)
        max_avg = 0
        pos = 0
        for i in range(len(A)):
            if abs(A[i] - average) > max_avg:
                max_avg = abs(A[i] - average)
                pos = i
        return pos
    else:
        return -1

If there's a tie between the max deviation elements i.e. two or more indexes have the same absolute deviation then either of them can be given. The required time-complexity is \$O(N)\$ and space-complexity is \$O(1)\$. In theory, this problem should be really easy but this was my first technical test and I might have overlooked something. Did I possibly miss anything?

Note that in Python 3, you don't need * 1.0 to get floating-point division.  On the other hand, in Python 2, range(len(A)) would use O(N) space.

I recommend three changes:

Put the special case first, to reduce the separation between return -1 and the reason for returning -1.
Rename max_avg → max_deviation.
Use enumerate() to iterate over the array.

The revised solution would be:

def solution(A):
    if not A:
        return -1
    average = sum(A) * 1.0 / len(A)
    max_deviation = 0
    pos = 0
    for i, a in enumerate(A):
        if abs(a - average) > max_deviation:
            max_deviation = abs(a - average)
            pos = i
    return pos


Recursive File Search Using the Dir() Function There are plenty of examples of using the FileSystemObject to recursively search for a file in subfolders.  I thought that it would be interesting to write one using the Dir() function.

I was wondering if there is a way to return the found file without using the extra FoundFile parameter?

Function FindFile(ByVal folderName As String, ByVal FileName As String, Optional ByRef FoundFile As String) As String
    Dim search As String
    Dim dirList As New Collection

    If Not Right(folderName, 1) = "\" Then folderName = folderName & "\"
    search = Dir(folderName & "\*", vbDirectory)
    While Len(search) > 0
        If Not search = "." And Not search = ".." Then
            If GetAttr(folderName & search) = 16 Then
                dirList.Add folderName & search
            Else
                If LCase(search) = LCase(FileName) Then
                    FoundFile = folderName & FileName
                    FindFile = FoundFile
                    Exit Function
                End If
            End If

        End If
        search = Dir()
    Wend

    Dim fld
    For Each fld In dirList
        If Len(FoundFile) > 0 Then
            FindFile = FoundFile
            Exit Function
        Else
            FindFile = FindFile(CStr(fld), FileName, FoundFile)
        End If
    Next

End Function

Just remove it from parameter,
and make it a variable.

Function FindFile(ByVal folderName As String, ByVal FileName As String) As String
    Dim search As String
    Dim dirList As New Collection

    If Not Right(folderName, 1) = "\" Then folderName = folderName & "\"
    search = Dir(folderName & "\*", vbDirectory)
    While Len(search) > 0
        If Not search = "." And Not search = ".." Then
            If GetAttr(folderName & search) = 16 Then
                dirList.Add folderName & search
            Else
                If LCase(search) = LCase(FileName) Then
                    FindFile = folderName & FileName
                    Exit Function
                End If
            End If

        End If
        search = Dir()
    Wend

    Dim fld
    Dim FoundFile As String
    For Each fld In dirList

        FoundFile = FindFile(CStr(fld), FileName)
        If Len(FoundFile) > 0 Then
            FindFile = FoundFile
            Exit Function
        End If
    Next

End Function


Maze solver BFS in Haskell I am really excited that I just wrote my Haskell maze solution in bfs.  This is my very first haskell (and I still haven't tried to build a maze in haskell so that maze is hard coded xD)

ANY suggestions all super welcome!!!

maze = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 2, 2, 2, 2, 2, 2, 2, 0],
        [0, 2, 0, 0, 0, 0, 0, 0, 0],
        [0, 2, 2, 2, 0, 2, 2, 2, 0],
        [0, 0, 0, 2, 0, 2, 0, 2, 0],
        [0, 2, 2, 2, 0, 2, 0, 2, 0],
        [0, 2, 0, 0, 0, 2, 0, 2, 0],
        [0, 2, 2, 2, 2, 2, 0, 2, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0]]
start = (7, 7)
end = (1, 7)

validPosition x y maze = (x >= 0) && (y >= 0) && (length maze) > y && (length (maze !! 0)) > x
getNode x y = if (validPosition x y maze) then Just ((maze !! y) !! x) else Nothing
getNeighborNode x y closed = filter (\(i, j) -> (getNode i j) == (Just 2) && (elem (i,j) closed) == False) [(x+a, y+b) | (a,b) <- [(0,-1),(0,1),(1,0),(-1,0)]]

bfsSolver ((i,j):xs) closed meta
    | ((i,j) /= end) = (bfsSolver (xs++neighbors) (closed++[(i,j)]) (meta++[((a,b), (i,j)) | (a,b)<-neighbors]))
    | otherwise = (constructPath (i,j) meta [])
    where neighbors = (getNeighborNode i j closed)

constructPath (i,j) meta route
    | (length points) > 0 = (constructPath (head points) meta (route++[(i,j)]))
    | otherwise = route++[(i,j)]
    where points = [(x,y) | ((a,b),(x,y)) <- meta, (a,b) == (i,j)]

-- bfsSolver [start] [] []

I've hardly done any Haskell - so it's probably a positive thing that I can easily understand your code - but since you've no answer yet, I'll have a go. Anyway, take everything I say with a pinch of salt, and it'll just be surface stuff since I don't have experience to draw on.

Currently you code uses a linear-time search to determine if an element is in the list of closed elements. Since Ord is implemented for tuples (e.g. (Int, Int)) you can use a Data.Set instead, which will provide logarithmic-time lookup, making your code more efficient on large problems. I'd also consider making meta a Data.Map so that you can efficiently query it as well, and will allow you to dispense with that head points in constructPath.

Though you have attempted to implement a graph-search, your closed system is inadequate, as it still allows the queuing of elements multiple times. Consider the case where the same node is queued by two different other nodes before it is itself expanded (this would occur any time you had a square of 4 cells, starting in one the cell diagonally opposite will be queued twice). The easiest way to solve this is probably to append all the neighbours to closed, and add start to closed from the outset.

I don't know how people do things normally in Haskell, but I hate tuples with a passion (when they leak outside functions), and would replace your coordinate tuples with a dedicated data type, e.g.

data Position = Pos { x :: Int, y :: Int } deriving (Eq, Ord, Show)

This makes the meaning of the 2 elements clear, and ensures that only values intended to be interpreted as a position can be used. It also means you can define meaningful instances over your new type without infecting code which uses tuples.

You are mixing usage for i j and x y; I'd stick with just one of them as best you can, and try to think of something better than a b for your temporaries (dx dy for offsets?) You don't need the coordinates in constructPath; I think something like this would be clearer, though I'll concede that it's no longer entirely clear that this is operating on positions (but it's also a more generic piece of code, meaning it will work for (x, y) or Pos x y):

constructPath position meta route
    | (length points) > 0 = (constructPath (head points) meta (position:route))
    | otherwise = position:route
    where points = [to | (from,to) <- meta, from == position]

(I have also here swapped the concatenation around, which means the route will start at start and end at end, which is what I'd normally expect from a route-finder)

Ideally your code wouldn't contain magic numbers like 0 and 2; much better to create a union or type-class for the types of cells in the grid, e.g.

data Cell = Wall | NotWall deriving (Eq)

NotWall isn't a great name, but it's better than 2, and will make the intention of the filtering code in getNeighborNode (should that be getNeighborNodes?) much clearer.

You can provide a much nicer and more useful API by passing the maze and end in as parameters along with start, and providing a convenience method which calls bfsSolver with the appropriate initial conditions, e.g.

bfs start = bfsSolver [start] [] []

It's so much harder to misuse, and  your consumers would thank you for it.


Handling Java instant Ajax request/respond with Angular I am trying to build a food search app. I am using Angular and Spring. I am currently using the yelp API, but it's done on the Java side.

I think what I have achieved is really bad design. It works, but the data is not always updated correctly.

For Java, I created two methods and one string variable:

private String response;

@RequestMapping(value = "/searchRestaurant", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public void searchRestaurantWithYelp(@RequestBody String jsonData) {

    //here i process the json string and pass the values to yelp function,
    // then yelp sends the respond as a json string, i assigned the value
    // to the response variable.
    response = queryYelp();
}

As you can see, this post request receive a json string from client side, and pass the string to the yelp java API I created. The yelp respond is a json string, and I assign it to the response variable.

I also created a GET method, which simply returns the response, which contains the data yelp returned. I want to immediately return this data to the client/browser, with angular.

@RequestMapping(value = "restaurantResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String returnRestaurantSearchResultWithYelp() {
    return response;
}

Now for my JS/angular side of code:

function HomeCtrl($scope, $http) {
    $scope.term = "";
    $scope.location = "";
    $scope.submitSearch = function () {
        var data = {
            term: $scope.term,
            location: $scope.location
        }; //end data
        var res = $http.post('/searchRestaurant', data);
        $http.get('/restaurantResult').
              success(function (data) {
        $scope.response = data;
        });
    }
 }

I wrapped a $http.get inside the $http.post. This function first sends data, which invoke my Java post method, then retrieves the data right after. I am binding the json data with angular so my app is single page. And with angular two way data binding the {{response}} contains the yelp response and will display instantly to the user.

My simplified HTML:

 <input type="text" ng-model="term"/>
 <input type="text" ng-model="location"/>
 <button ng-click="submitSearch()">Search</button>

 {{response}}

It works, sort of. But I feel there is a better way to do it.

The issue: The {{response}} sometimes cannot be updated instantly. For instance, I search burger king, the response will show me the address, location, etc. Then I type McDonalds, the response still shows the info of Burger King. I have to refresh the browser to get the latest and correct response.

I was wondering what the issue is causing the response not update instantly? Is it because of browser cache?

In terms of the my project build design, what part I did wrong? Is there a better way to handle this type of request?

I type McDonalds, the response still shows the info of Burger King. I have to refresh the browser to get the latest and correct response.

The request is being made before the previous post completes.

In your Angular, you need to chain your $http actions

function HomeCtrl($scope, $http) {
    $scope.term = "";
    $scope.location = "";
    $scope.submitSearch = function () {
        var data = {
            term: $scope.term,
            location: $scope.location
        }; //end data
        var res = $http.post('/searchRestaurant', data);

        //chain from the post
        res.then ( function() {
            return $http.get('/restaurantResult').
        }).then ( function(result) {
            $scope.response = result.data;
            return data;
        }).catch ( function(error) {
            //log error
            throw error;
        });

        //return for further chaining
        return res;
    }
 }

By chaining your actions, you guarantee that the previous action completes before starting the next.

Notice that the .then method returns data differently than the .success method.

Also I avoid the .success and .error methods for two reasons: They ignore return values and they are deprecated. For more information on tbe deprecation of .success and .error, see the AngularJS $http Service API Reference -- deprecation notice.

For more information on chaining see AngularJS $q Service API Reference - chaining promises.

UPDATE

To answer you questions about the differences between .then and .catch methods and the deprecated .success and .error methods.

The $http service .then method returns a response object to its resolve callback.

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function resolveCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function catchCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

The response object has these properties:

data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.

--- AngularJS $http Service API Reference -- general usage

  Deprecated: The $http service .success method spreads out the response object.

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

As I said before, avoid these method for two reasons: they ignore return values and they are deprecated.

The rule of thumb for functional programming is always return something. By ignoring return values, .success and .error break that rule. What makes promises powerful is returning and chaining.


jQuery navigation bar I have a navigation bar without a tags:

    $('div.nav ul li').on('click', function() {
        if($(this).is(':first-child')) {
            $("html, body").animate({
                scrollTop: "0"
            }, 'slow');
        } else if($(this).is(':nth-child(2)')) {
            $("html, body").animate({
                scrollTop: "0"
            }, 'slow');
        } else if($(this).is(':nth-child(3)')) {
            var offset = $('div.features').offset().top;
            $("html, body").animate({
                scrollTop: offset+ 'px'
            }, 'slow');
        } else if($(this).is(':nth-child(4)')) {
            var offset = $(document).height();
            $("html, body").animate({
                scrollTop: offset+ 'px'
            }, 'slow');
        }
    });

I wondered if this way is the best way of doing this.  first-child & nth-child(2) goes to the same place, then each child after that - up to 4 has a different position to go to.

Yes,

you could for starters derive the child position once with

var index =  $('div.nav ul li').index( this )

Then you could adapt to index 0 and 1 in 1 if statement
Finally, you could just derive the index and have the animate statement only once.

Something like this in the end might do:

$('div.nav ul li').on('click', function() {

    var index = $('div.nav ul li').index( this ), top;

    if( index < 2 ){
      top = '0';
    }
    if( index == 2 ){
      top = $('div.features').offset().top + 'px';
    }
    if( index == 3 ){
      top = $(document).height() + 'px';
    }
   if(top){
        $("html, body").animate({
            scrollTop: "0"
        }, 'slow');
   }
});


Flattening a nested map We're migrating our streaming ETL application from Python into Clojure,
the hottest part of the code isn't yet performing as well as our existing
implementation.  This looks to be down to the algorithmic complexity of our flattening function.

Take a nested map, flatten the data structure and rename keys.  We take data
from multiple sources and have to smudge the data to fit a legacy format.
For this all of the keys/values need to be at the root level of the map with the
correct keys.  Any 'new' keys can be left as is and not renamed.

The transformation was originally a threading macro, with a flatten and a
set/rename-keys, this has been improved to rename variables while looping
through each level of the map. The flatten however still accounts for ~80% of the time spent processing a record.

An example input would be as follows:

{:foo {:foo-host "host-1" :user {:foo-user "user-1" :foo-id "id-1"}}
 :bar {:bar-var "potato"}}

With an expected output of:

{:host "host-1" :user "user-1" :id "id-1" :var "potato"}

We've gone through and removed any java reflection, and type hinted the hottest
parts of our code so no more gains can be found there.  The last slow pieces
of code are as follows:

(def match-table {:foo-host :host
                  :foo-user :user
                  :foo-id :id
                  :bar-var :var})

(defn flatten-record
  "Take a nested record and recursively flatten."
  [^clojure.lang.PersistentArrayMap record]
  (into {}
    (for [[k v] record]
      (if (map? v)
        (flatten-record v)
        ;; If the key's not found return itself as the default.
        {(get match-table k k) v}))))

The flatten-record function consumes the stack as it's lacking any tail call
optimisation, trampoline may be a better solution?  The records transformed are
a maximum of 5 deep, so there's no risk of a recursion overflow.

I'm mainly concerned about performance here, so am open to any hints!

Larger examples are available here.

A couple of things to try:

You assemble a map at every level of nesting. It is probably quicker
to pass up sequences of key/value pairs.
Even the single entries return a map. We can cope with a
MapEntry directly using reduce instead of for.

We might end up with ...

(defn flatten-record [record]
  (reduce
   (fn [a [k v]]
     (if (map? v)
       (into a (flatten-record v))
       (conj a (clojure.lang.MapEntry. (match-table k k) v))))
   []
   record))

I'm assuming it's quicker to build a MapEntry than a small vector or list.

The above returns a sequence. We have to convert the product into a map:

(def example-input {:foo {:foo-host "host-1" :user {:foo-user "user-1" :foo-id "id-1"}}
                    :bar {:bar-var "potato"}})

(into {} (flatten-record example-input))
;{:host "host-1", :user "user-1", :id "id-1", :var "potato"}

The recursive call of flatten-recordis not in tail position, so neither recur nor trampolineare available.


Check if Item exists in Grid using Linq I have a grid which allows a user to enter a new Grid item. If the grid item exists or the tb is empty it displays the error. Here's the code I came up with.

Can anybody think of a cleaner or more efficient way of doing so?  Thinking about it now, I guess I could have done it all in one function, and placed InsertTrack() in the else condition of DoesTrackExist and register the script in the if statement.

 private void InsertTrack()
   {
       if (DoesTrackExist(txtEventTracks.Text))
       {
           using (EMSEntities db = new EMSEntities())
           {
               EventTrack newEventTrack = new EventTrack()
               {
                   TrackName = txtEventTracks.Text
               };
                   db.EventTracks.Add(newEventTrack);
                   db.SaveChanges();
           }
       }
       else
       {
          ScriptManager.RegisterStartupScript(Page, typeof(Page), "Error", "alert('Track name cannot be duplicate or empty')", true);
       }
   }
   private bool DoesTrackExist(string txtValue)
   {
       using (EMSEntities db = new EMSEntities())
       {
           var context = from x in db.EventTracks
                         where x.TrackName.Contains(txtEventTracks.Text)
                         select x;

           if (context.Any() || txtEventTracks.Text == "")
           {
               return false;
           }
           else
           {
               return true;
           }
       }
   }

Some people say that adding private functions which are only called in one place in a class clutter the "private interface" of the class. However I actually do prefer it in some cases. In your case I think it makes sense as it makes InsertTrack easier to read so I would not merge the two.

As to DoesTrackExist

Check txtEventTracks.Text == "" first - this avoids performing any query at all.
I assume you meant to use the parameter txtValue instead of accessing the textbox directly.
Might not be more efficient but Any() accepts a predicate as well:

private bool DoesTrackExist(string txtValue)
{
    // maybe even consider IsNullOrWhiteSpace?
    if (string.IsNullOrEmpty(txtValue))
       return false;
    using (EMSEntities db = new EMSEntities())
    {
        return db.EventTracks.Any(x => x.TrackName.Contains(txtValue))
    }
}


Multitasking in NASM Win16 Assembly Requirements (Installed using Scoop)

scoop install nasm dosbox

Build (Using NASM)

nasm -g tasks.asm -o tasks.com

  -g enables debugging capabilities

Execute (Using DOSBox)

mount H: C:\com\parent\path
H:
tasks.com

tasks.asm

Sections are added for clarity.

[org 100h]

section .text

main:
    lea     si, [task_a]
    call    spawn_new_task

    lea     si, [task_b]
    call    spawn_new_task

.loop_forever:
    lea     si, [main_str]
    call    putstring
    call    yield
    jmp     .loop_forever

task_a:
.loop_forever:
    lea     si, [main_a]
    call    putstring
    call    yield
    jmp     .loop_forever

task_b:
.loop_forever:
    lea     si, [main_b]
    call    putstring
    call    yield
    jmp     .loop_forever

spawn_new_task:
    ; find a free task, start pointers off at -1
    xor     cx, cx
    lea     bx, [stack_status]
.loop:
    cmp     cx, 3                 ; change this to add more tasks
    jl      .continue
    ret                           ; no free task, return immediately
.continue:
    cmp     byte [bx], 0
    je      .done                 ; if equal, tasks is free
    inc     cx
    inc     bx
    jmp     .loop
.done:
    mov     byte [bx], 1          ; task was free, reserve it

    lea     bx, [stack_pointers]
    mov     [bx], sp              ; save main's stack pointer
                                  ; switch to free stack
    add     bx, cx
    add     bx, cx                ; free stack is list of words (not bytes) and add is cheaper than mul
    mov     sp, [bx]              ; change to free stack
    push    si                    ; push stuff
    pusha
    pushf
    mov     [bx], sp              ; save new stack's new pointer
    mov     sp, [stack_pointers]  ; change back to main
    ret

yield:
    ; ret already saved by call
    pusha
    pushf
    movzx   cx, byte [current_task]
    ; save current stack pointer
    lea     bx, [stack_pointers]
    add     bx, cx
    add     bx, cx
    mov     [bx], sp
    ; loop through stack status looking for a 1
    lea     bx, [stack_status]
    add     bx, cx                ; make sure we start looking at next task
.loop:
    inc     bx
    inc     cx
    cmp     cx, 3                 ; increment this for more tasks
    jl      .continue
    xor     cx, cx                ; clear cx
    lea     bx, [stack_status]    ; reset bx back to start
.continue:
    cmp     byte [bx], 1          ; is this stack active
    je      .found_one
    jmp     .loop
.found_one:
    mov     [current_task], cl
    ; switch to new stack
    lea     bx, [stack_pointers]
    add     bx, cx
    add     bx, cx
    mov     sp, [bx]
    popf
    popa
    ret

    ; takes an address to write to in si
    ; writes to address until a null term is encountered
    ; returns nothing
putstring:
    mov     ah, 0Eh
.continue:
    lodsb                         ; put char to write in al
    test    al, al                ; simulate and
    je      .done                 ; was al 0?
    int     10h                   ; call interrupt
    jmp     putstring
.done:
    ret

section .rdata

    main_str: db "I am task main", 13, 10, 0
    main_a: db "I am task a", 13, 10, 0
    main_b: db "I am task b", 13, 10, 0

section .data

    current_task: db 0

    stack_status:
    status_1: db 1                ; this is for Main
    status_2: db 0
    status_3: db 0

    stacks: times 256 * 2 db 0

    stack_pointers:
    dw 0                          ; this is for Main
    dw stacks + 256
    dw stacks + 512

This is a nice example of Cooperative Multitasking. Each task has to decide if and when it yields. However based on the fact that the individual tasks are placed in a single program, this could sooner be called Cooperative Multithreading.

In the putstring procedure you erroneously wrote jmp putstring where you clearly wanted to write jmp .continue. That's an honest mistake.
What you do keep neglecting though is the DisplayPage parameter that BIOS expects in the BH register.

If you've programmed in MASM before, it can be hard to adopt the shorter way to load an address via the mov instruction. mov si, task_a does the same as your lea si, [task_a] but it is 1 byte shorter. You used this many times (11x).

    cmp     cx, 3                 ; change this to add more tasks
    jl      .continue
    ret                           ; no free task, return immediately
.continue:

This ressembles a beginner's code, yet I'm sure you are not a beginner!
The spawn_new_task procedure has a nice ret near its end, so why not jump there based on the opposite condition?

    cmp     cx, 3                 ; change this to add more tasks
    jnl     .ret                  ; no free task, return immediately

    ...

.ret:
    ret

Same thing happens here:

    cmp     byte [bx], 1          ; is this stack active
    je      .found_one
    jmp     .loop
.found_one:

Why not write (no need for the label this time):

      cmp     byte [bx], 1          ; is this stack active
      jne     .loop

Because your main task will always be active, there's no reason to consider it in the search for a free task slot. This saves one iteration forever.
Also there's no need to test the CX counter up front. Better have the test near the bottom and avoid the extraneous unconditional jump back. So changing from a Do While loop into a Loop While loop.
Starting from a byte that is known to be 0, inc byte [bx] will produce shorter code than mov byte [bx], 1.

spawn_new_task:                   ; find a free task, start pointers off at -1
    xor     cx, cx
    mov     bx, stack_status
.loop:
    inc     bx
    inc     cx
    cmp     [bx], ch              ; CH=0
    je      .done                 ; if equal, tasks is free
    cmp     cx, 2                 ; change this to add more 'spawnable' tasks
    jb      .loop
    ret                           ; no free task, return immediately
.done:
    inc     byte [bx]             ; task was free, reserve it

What's the comment "start pointers off at -1" about? Your code nowhere has any -1.

The bulk of this program contains empty space. You can easily move the free space for the additional stacks outside of the program file.

The following rewrite (FASM) reveals a code size reduction of 9% (171 → 156) and a file size reduction of 72% (735 → 208).

org 100h

main:
    mov     si, task_a
    call    spawn_new_task
    mov     si, task_b
    call    spawn_new_task

.loop_forever:
    mov     si, main_str
    call    putstring
    call    yield
    jmp     .loop_forever

task_a:
    mov     si, main_a
    call    putstring
    call    yield
    jmp     task_a

task_b:
    mov     si, main_b
    call    putstring
    call    yield
    jmp     task_b

spawn_new_task:                   ; find a free task slot
    xor     cx, cx
    mov     bx, stack_status
.loop:
    inc     bx
    inc     cx
    cmp     [bx], ch              ; CH=0
    je      .done                 ; if equal, task slot is free
    cmp     cx, 2                 ; change this to add more 'spawnable' tasks
    jb      .loop
    ret                           ; no free task, return immediately
.done:
    inc     byte [bx]             ; task was free, reserve it
    mov     bx, stack_pointers
    mov     [bx], sp              ; save main's stack pointer
    add     bx, cx                ; switch to free stack
    add     bx, cx                ; free stack is list of words (not bytes) and add is cheaper than mul
    mov     sp, [bx]              ; change to free stack
    push    si                    ; push stuff
    pusha
    pushf
    mov     [bx], sp              ; save new stack's new pointer
    mov     sp, [stack_pointers]  ; change back to main
    ret

yield:
    ; ret already saved by call
    pusha
    pushf
    movzx   cx, byte [current_task]
    ; save current stack pointer
    mov     bx, stack_pointers
    add     bx, cx
    add     bx, cx
    mov     [bx], sp
    ; loop through stack status looking for a 1
    mov     bx, stack_status
    add     bx, cx                ; make sure we start looking at next task
.loop:
    inc     bx
    inc     cx
    cmp     cx, 3                 ; increment this for more tasks
    jb      .continue
    xor     cx, cx                ; clear cx
    mov     bx, stack_status      ; reset bx back to start
.continue:
    cmp     byte [bx], 1          ; is this stack active
    jne     .loop
    mov     [current_task], cl
    ; switch to new stack
    mov     bx, stack_pointers
    add     bx, cx
    add     bx, cx
    mov     sp, [bx]
    popf
    popa
    ret

    ; takes an address to write to in si
    ; writes to address until a null term is encountered
    ; returns nothing
putstring:
    mov     bh, 0
    mov     ah, 0Eh
    jmp     .first
.next:
    int     10h                   ; call interrupt
.first:
    lodsb                         ; put char to write in al
    test    al, al                ; simulate and
    jnz     .next                 ; was al 0?
    ret

    main_str: db "I am task main", 13, 10, 0
    main_a: db "I am task a", 13, 10, 0
    main_b: db "I am task b", 13, 10, 0

    current_task: db 0

    stack_status:
    status_1: db 1                ; this is for Main
    status_2: db 0
    status_3: db 0

    stack_pointers:
    dw 0                          ; this is for Main
    dw stacks + 256
    dw stacks + 512

    stacks:


Given a room number, find the floor on which the room lies I came across a question where I had to find the floor by using given room no. And given no data structure to hold the data. What we know is distribution of the rooms across the floors.

I have given below solution for it but, I think it may break as number of floors increases.

int queryRoom = 37;
int totalFloor = 6;

int currentRm = 0;
int floorInQuestion = 1; // staring floor

while (floorInQuestion != totalFloor) {
    if (floorInQuestion % 2 != 0) {
        currentRm = currentRm + 5;
    } else {
        currentRm = currentRm + 10;
    }
    if (queryRoom <= currentRm)
        break;
    floorInQuestion++;
}

System.out.println(floorInQuestion);

When presented with problems that require and input value set, and an output value set, it's always best to express the problem as a function. In your case, the problem is: "Given an input room number, what floor is it on?"

This type of question can then be expressed as a single function:

public static int whichFloor(int room) {
    ....
}

That function is the result of a process called "function extraction", taking a piece of logic, and extracting just that piece in to its own function.

This makes the code logic more visible, and it also helps you to organize your thoughts. It also makes some logic expression more simple (early return values).

So, taking your code in to a function, you get:

System.out.println(whichFloor(37));

And, now we implement whichFloor as:

public static int whichFloor(int queryRoom) {
    int totalFloor = 6;

    int currentRm = 0;
    int floorInQuestion = 1; // staring floor

    while (floorInQuestion != totalFloor) {
        if (floorInQuestion % 2 != 0) {
            currentRm = currentRm + 5;
        } else {
            currentRm = currentRm + 10;
        }
        if (queryRoom <= currentRm) {
            return floorInQuestion;
        }
        floorInQuestion++;
    }
    return -1;
}

There are some changes in that logic. Specifically, I have:

Added {...} braces on the last condition...
... which is now a return statement, and not a break
returns -1 if there's no matching floor.

Now, that while-statement should be a for loop:

public static int whichFloor(int queryRoom) {
    int totalFloor = 6;
    int currentRm = 0;

    for (int floorInQuestion = 1; floorInQuestion != totalFloor, floorInQuestion++) {
        if (floorInQuestion % 2 != 0) {
            currentRm = currentRm + 5;
        } else {
            currentRm = currentRm + 10;
        }
        if (queryRoom <= currentRm) {
            return floorInQuestion;
        }
    }
    return -1;
}

Now, as a looping system, that's how you should have presented your solution.

Note that your logic is clear enough, your variables are well named, and the logic looks sound enough. On the whole, your answer is good, and just needed some tweaks.

... but... is there a better solution that does not use looping?

Consider the pattern in the rooms/floors...

Odd floors have 5 rooms, even floors have 10 rooms. Can we exploit this better? Well, yes, we can treat the floors in pairs and have 15 rooms per pair... and then figure out whether it's in the first of the pair, or the second. Note that using division and remainder operations works best as a 0-based system, not a 1-based system like the input values are in, so we "map" each room to be 1 less, and each floor too, so we treat room 1 as if it was room 0, and floor 1 as if it was floor 0, and then shift the results back afterwards too. I have named zero-based variables with the prefix zero...

public static int whichFloor(int queryRoom) {
    int zeroRoom = queryRoom - 1;    // convert to zero-based room
    int zeroPair = zeroRoom / 15;    // get which 15-room floor-pair the room is in
    int zeroOffset = zeroRoom % 15;  // get which room in the pair
    int zeroFloor = zeroPair * 2;    // convert the pairs back to floors.
    if (zeroOffset >= 5) {
        // the room in the pair is in the upper floor of the pair.
        zeroFloor += 1;
    }

    int resultFloor = zeroFloor + 1; // convert back to one-based system.
    return resultFloor;
}


Temperature Conversion Program I'm having trouble accessing variables throughout multiple functions. For example, I need to use userinput throughout many other functions, but do not have access to it with my current code. I am pretty sure that I need to change the parameters of my functions, so that I can pass the value of those functions by reference, but I'm having trouble doing that.

Here's what my code looks like right now:

#include <cstdlib>
#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

double fahrtocels();
double celstofahr();
double celstokelv();
double kelvtocels();

int main()
{
    do { int userinput=0;

    cout << " 1) Fahr to Cels" << endl;
    cout << " 2) Cels to Fahr" << endl;
    cout << " 3) Cels to Kelv" << endl;
    cout << " 4) Kelv to Cels" << endl;
cin >> userinput;
if(userinput=1)
fahrtocels();
if(userinput=2)
celstofahr();
if(userinput=3)
celstokelv();
if(userinput=4)
kelvtocels(); } while(userinput=0);

}

double fahrtocels()
{
    int input;
    int tempinput;
    double finaloutput;
    cout <<" Please Enter the Temp in Fahrenheit"<<endl;
    cin >> input;
userinput= 1;
    tempinput = input - 32;

finaloutput = tempinput/1.8;

    cout<<input<< " degrees fahrenheit is equivalent to  " << finaloutput<< "  celsius"<< endl;
    userinput = 0;
}

double celstofahr()
{
    int inputcels;
    int tempinputcels;
    double finaloutputcels;
    cout <<" Please Enter the Temp in Celsius"<<endl;
    cin >> inputcels;

    tempinputcels = inputcels * 1.8;

finaloutputcels = tempinputcels + 32;

    cout<<inputcels<< " degrees celsius is equivalent to  " << finaloutputcels<< "  fahrenheit"<< endl;
}

double celstokelv()
{
    int inputcelskelv;
    double finaloutputcelskelv;
    cout <<" Please Enter the Temp in Celsius for Kelvin Conversion"<<endl;
    cin >> inputcelskelv;

finaloutputcelskelv = inputcelskelv + 273.15;

    cout<<inputcelskelv<< " degrees celsius is equivalent to  " << finaloutputcelskelv<< " kelvin"<< endl;
}

double kelvtocels()
{
    int inputkelvcels;
    double finaloutputkelvcels;

    cout <<" Please Enter the Temp in Kelvin for Celsius conversion"<<endl;
    cin >> inputkelvcels;

finaloutputkelvcels = inputkelvcels - 273.15;

    cout<<inputkelvcels<< " degrees kelvin is equivalent to  " << finaloutputkelvcels<< " celsius"<< endl;
}

First, the code is technically off-topic, since it has a pretty clear bug (in main):

} while(userinput=0);

This is almost certainly intended to be userinput==0. As-is, it's an assignment, which yields 0, which is treated as false, so the loop only ever executes once, regardless of input from the user.

While I agree with the basic approach @Konrad has advocated, putting together a table of the data needed for the conversions, I think I'd implement it just a bit differently. I would not use std::pair. I'd explicitly define a struct so the values would have meaningful names:

struct conversion {
    double offset;
    double coefficient;
};

Then your conversion would look like:

double convert(conversion_type conversion, double input) {
   conversion c = conversions[conversion];
   return (input+c.offset)*c.coefficient;
}

...which seems more readable, at least to me. If you do want to maintain separate functions for each conversion, I'd still break things up into one function doing input. another doing the conversion itself, and a third to display the result. I'd still make it largely table drive, using a vector (or array) of pointers to functions, using the number entered by the user to to index into that (after assuring that it's within range, of course).