Implementation of the linked list data structure in C++ How is this designed so far?

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

#include <memory>
#include <iostream>

template <typename T> using ptr = std::shared_ptr<T>;

template <typename V>
class LinkedList
{
private:
    class Node
    {
    private:
        V data;
        ptr<Node> next;
    public:
        Node() : next{} {}
        Node(V _data) : next{}, data{_data} {}
        ptr<Node>& getNext(){
            return this->next;
        }
        V getData(){
            return this->data;
        }
    };

    ptr<Node> head;
    ptr<Node> tail;
    size_t _size;

public:

    LinkedList() : head{}, tail {}, _size{} {}

    void add(V _data){
        auto _tmp = std::make_shared<Node>(_data);
        if(isEmpty()){
            head = _tmp;
            tail = _tmp;
        } else {
            tail->getNext() = _tmp;
            tail = _tmp;
        }
        _size++;
    }

    bool isEmpty(){
        if(head == nullptr) return true;
        else return false;
    }

    V operator[](int index){
        int _c {};
        ptr<Node> tmp = head;
        while(tmp!=nullptr){
            if(_c == index){
                break;
            }
            tmp = tmp->getNext();
            _c++;
        }
        return tmp->getData();
    }

    void addFirst(V _data){
        auto _tmp = std::make_shared<Node>(_data);
        if(isEmpty()){
            _tmp->getNext() = head;
            head = _tmp;
            tail = _tmp;
        } else {
            _tmp->getNext() = head;
            head = _tmp;
        }
        _size++;
    }

    template <typename V>
    void insertAfter(int index, V _data){

        auto _tmp = std::make_shared<Node>(_data);
        std::shared_ptr<Node> _curr;
        std::shared_ptr<Node> _afterIndex;

        if(index<0 || index > size()-1){std::cerr << "__INDEX_OUT_OF_RANGE__" << std::endl;}
        else {
            int _c {};
            ptr<Node> tmp = head;
            while(tmp!=nullptr){
                if(_c == index){
                     _curr = tmp;
                     _afterIndex = _curr->getNext();
                     break;
                }
                tmp = tmp->getNext();
                _c++;
            }

            _curr->getNext() = _tmp;
            _tmp->getNext() = _afterIndex;
            _size++;
        }
    }

    void traverseList(){
        {
            ptr<Node> tmp = head;
            while(tmp!=nullptr){
                std::cout << tmp->getData() << std::endl;
                tmp = tmp->getNext();
            }
        }

    }

    size_t size(){ return _size; }
};

#endif // LINKEDLIST_H

#include "linkedlist.h"
#include <string>
int main(){

    auto list = std::make_shared<LinkedList<std::string>>();

    list->addFirst("Bob");
    list->add("Carl");
    list->add("Mario");
    list->add("Elliot");
    list->addFirst("Neo");
    list->insertAfter(0,"I'm inserted after " + (*list)[0]);

    for (int i {} ; i < list->size(); ++i) {
        std::cout << (*list)[i] << std::endl;
    }

    return 0;
}

Namespace

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

The term "linked list" is a common term. So I would expect somebody out there is already using the macro LINKEDLIST_H. When somebody uses that library and your library then you will get some funny interactions.

As a result I would make the include guards a little more unique. When I define header guards they include the full namespace and the the file name in the include guard.

Which brings me to namespace. All your work is in the global namespace. Which can lead to collision in names (Again LinkedList is a common type name). So creating a unique namespace for your code could be useful (I like the Java method of using your domain name).

#ifndef THORSANVIL_UTIL_LINKED_LIST_H
#define THORSANVIL_UTIL_LINKED_LIST_H

namespace ThorsAnvil
{
     namespace Util
     {

class LinkedList
{
};

     }
}
#endif

Containers Vs Smart Pointers

There are two common techniques for managing dynamic memory: Containers and Smart Pointers. Since the job of the container is to perform memory management so delegating this to Smart pointers is counter productive.

Secondly shared_ptr should not be your first choice of smart pointer. The shared pointer has significant overheads.

template <typename T> using ptr = std::shared_ptr<T>;

Given the choice I would prefer std::unique_ptr when you are expressing ownership, but simply use a normal RAW pointer inside function where no owner knowledge is needed.

Private Membership

template <typename V>
class LinkedList
{
private:
    class Node
    {

The class LinkedList::Node is exposed as public. Exposing this class exposes implementation details. Exposing implementation details makes your class much more brittle and harder to change.

Constructor

default constructor

    public:
        Node() : next{} {}

A default constructor. Do you need it. This can only be used when the object type V os default constructible. Conversely if the type V is not default constructible this constructor can not be used. Which would mean that certain portions of your class are unusable.

Construction

        Node(V _data) : next{}, data{_data} {}

This constructor passes _data by value. This means _data is copied into the function then it also copied again into the member. So you have multiple copies. Normally I would pass by const reference to avoid at least one copy.

Additionally in C++11 we introduced move semantics. This can thought of as an optimized copy. You should try and define your class to use move semantics so that you can remove the additional copy.

Also introduced in C++11 were variadic templates and perfect forwarding. This can be used to build objects in place using their own constructors very easily. This allows us to build the objects into the container with creating an external copy.

So if we put all three of these together I would write the Node class like this.

        struct Node
        {
            Node*   next;   // not owned.
            V       data;

            Node(V const& data)
                : next(nullptr)
                , data(data)
            {}
            Node(V&& data)
                : next(nullptr)
                , data(data)
            {}
            template<typename... Args>
            Node(Args&& args...)
                : next(nullptr)
                , data(std::forward<Args>(args)...)
            {}
        };

Head Tail Vs Sentinel

    ptr<Node> head;
    ptr<Node> tail;

Sure you can use a singly linked list and head and tail. Personally I prefer to use a doubly linked list and a sentinel (there are several other questions on code review where I explain this technique in detail).

Using a sentinel object allows you to write code without having to worry about nullptr this can considerably simplify the code.

The additional benefit (of the sentinel technique) is that you have a node in your chain that can be used by the end iterator (one past the end of the list).

Const member functions

    size_t size(){ return _size; }

    bool isEmpty(){
        if(head == nullptr) return true;
        else return false;
    }

Functions that do not mutate the state of the object should be marked const. Note: When passing around large objects to functions it is quite common to pass them by const reference. This means you can only call const methods on the object.

    size_t size() const { return _size; }

if test anti pattern

    bool isEmpty(){
        if(head == nullptr) return true;
        else return false;
    }

This is an anti pattern. There is no need to perform a test and return true/false. Simply return the value of the test.

    bool isEmpty() const
    {
        return (head == nullptr);
    }

Error

What happens when index is greater than size?

    V operator[](int index){
        int _c {};
        ptr<Node> tmp = head;
        while(tmp!=nullptr){
            if(_c == index){
                break;
            }
            tmp = tmp->getNext();
            _c++;
        }

        // I bet this de-reference a null ptr
        // Does it.
        return tmp->getData();
    }

Name your function appropriately

This may traverse the list. But that is not what it is actually doing. The traverse is just a side effect of the action you are taking.

    void traverseList(){
        {
            ptr<Node> tmp = head;
            while(tmp!=nullptr){
                std::cout << tmp->getData() << std::endl;
                tmp = tmp->getNext();
            }
        }

To me this looks like a print function name it as such. Also it always prints to std::cout. Why not pass the stream you want to print to (it can default to std::cout.

     void printList(std::ostream& str = std::cout)
     {
         // Code as before
     }
     // Then just for giggles we add a friend function to make
     // printing more C++ like.

     friend std::ostream& operator<<(std::ostream& s, LinkedList const& ll)
     {
         ll.printList(s);
         return s;
     }


Spawning two threads and if any of the threads returns true, let the main thread ignore the other and move on Exact problem statement:

A main thread spawns 2 new threads, the main thread waits on this
threads with these conditions:

if any of the threads returns True, then main thread moves on and prints the thread_id and timestamp of the thread.
if both threads return false, finish execution and don't print anything

My attempt:
public static void main(String[] args) throws InterruptedException, ExecutionException{
        FutureTask<Boolean> futureTask = new FutureTask<>(() -> {
          System.out.println("Hello, World 1!");
          return true;
        });
        FutureTask<Boolean> futureTask2 = new FutureTask<>(() -> {
          System.out.println("Hello, World 2!");
          return true;
        });

        Thread t1 = new Thread(futureTask);
        Thread t2 = new Thread(futureTask2);
        t1.start();
        t2.start();

        // Wait for either to be done.
        while (!futureTask.isDone() && !futureTask2.isDone());

        if (futureTask.isDone()) {
          if (futureTask.get()) {
            System.out.println("1 - " + t1.getId() + " " + System.currentTimeMillis());
            return;
          }
        }

        if (futureTask2.isDone()) {
          if (futureTask2.get()) {
            System.out.println("2 - " + t2.getId() + " " + System.currentTimeMillis());
            return;
          }
        }
    }
}

When I run this a few times, sometimes thread 1 wins, sometimes 2, which seems to make sense to me. Appreciate any room for improvement or advice.

Bug
I'd post this as a comment and a close vote, but you already have two answers.
Your program does not actually fulfill the problem statement.  If one thread quickly returns false and the other has not finished yet (but will return true eventually), your program halts and prints nothing.  But instead, it should wait for the second thread to finish.
Testing
You could have found this yourself with a more robust testing framework.  You should test all of the following situations:

Both return true.  Task 1 returns first.
Both return true.  Task 2 returns first.
Task 1 returns true first and later task 2 would return false.
Task 1 returns true but task 2 returns false later.
Task 2 returns true first and later task 1 would return false.
Task 2 returns true but task 1 returns false later.
Both return false.  Task 1 returns first.
Both return false.  Task 2 returns first.

You might also want to check what happens when a task never returns.  There may be other edge cases as well.
Numbered variables
Variables named 1 and 2 are a potential code smell.  In general when you have this, you should consider if you could actually either name the variables better or switch to a collection (e.g. an array or something that implements the Collection interface).
A side benefit of switching to a collection is that it frees you up in case the requirements change from two to another number.
This is not to say that there are no circumstances under which numbered variables are OK.  Only that when you consider using them, you should consider if they really make sense.
Modularization
To make testing easier, I would move the main code outside of the main method.  So instead of editing the main method for each test, your tests would create the appropriate tasks and pass them to the task runner.  The task runner could then enshrine the logic of

Create threads.
Launch them.
Check if they are finished.
If one is finished, check if its task returned true and produce the correct output.
If both returned false, return.

Note that this will be easier to test if the task runner method returns a string rather than printing output.  You can leave the printing logic in your main method.
Test frameworks
Even better than putting your tests in your main method, put them into some kind of test framework.  E.g. JUnit.  With a testing framework, it is easy to run every test every time.


Area Calculator in Java This is a simple Area Calculator coded in Java. What this does is that it prompts the user to select a shape, and asks for the details needed to calculate the area of that specific shape.

Main.java:

package com.AreaCalculator;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Welcome to the Area Calculator! Enter 1 to find the area of a Rectangle, Enter 2 to find the area of a Square, Enter 3 to find the area of a Triangle or Enter 4 to find the area of a Circle");

        int userInput = Integer.parseInt(scanner.next());

        if(userInput == 1) {
            System.out.println("Please enter the length of the rectangle: ");
            int length = Integer.parseInt(scanner.next());
            System.out.println("Please enter the width of the rectangle: ");
            int width = Integer.parseInt(scanner.next());

            System.out.println(length * width);
        } else if(userInput == 2) {
            System.out.println("Please enter the length of a side: ");
            int lengthOfASide = Integer.parseInt(scanner.next());

            System.out.println(lengthOfASide * lengthOfASide);
        } else if(userInput == 3) {
            System.out.println("Please enter the base of the triangle: ");
            int triangleBase = Integer.parseInt(scanner.next());
            System.out.println("Please enter the height of the triangle: ");
            int triangleHeight = Integer.parseInt(scanner.next());

            System.out.println((0.5 * triangleBase) * triangleHeight);
        } else if(userInput == 4) {
            System.out.println("Please enter the radius of the circle: ");
            int radius = Integer.parseInt(scanner.next());

            System.out.println(Math.PI * (radius * radius));
        }
    }
}

Making a package for a one-class program seems like overkill.  You would be better off naming the class AreaCalculator, which would be more meaningful than Main.

Instead of writing the menu as a very long string, it would be more manageable to split it:

System.out.println("Welcome to the Area Calculator! " +
    "Enter 1 to find the area of a Rectangle, " +
    "Enter 2 to find the area of a Square, " +
    "Enter 3 to find the area of a Triangle or " +
    "Enter 4 to find the area of a Circle");

(This has no effect on performance.  The compiler will embed just one long string constant in the bytecode.)

A chain of if-elses would be better written using a switch block.  Not only is it easier to see the patten at a glance, it is also more efficient, in that it compiles to a single tableswitch opcode.

Since there are so many places where you write System.out.println() followed by scanner.nextInt(), it makes sense to write a function for that.  Should you later decide to add validation and error handling, you can implement it in one central place.  I suggest changing System.out.println() to System.out.print().

I don't see any reason why the inputs should be restricted to ints.  You could just as easily accept doubles.

I recommend splitting each calculation into a separate function, to ensure that they do not interfere with each other.  For example, if you were to add support for parallelograms and trapezoids, you might have a conflict for a variable named height, if you lumped everything into main().  The resulting main() would be just a menu.

import java.util.Scanner;

public class AreaCalculator {
    private static double ask(Scanner scanner, String prompt) {
        System.out.print(prompt);
        return scanner.nextDouble();
    }

    private static void rectangle(Scanner scanner) {
        double length = ask(scanner, "Please enter the length of the rectangle: ");
        double width = ask(scanner, "Please enter the width of the rectangle: ");
        System.out.println(length * width);
    }

    private static void square(Scanner scanner) {
        double lengthOfASide = ask(scanner, "Please enter the length of a side: ");
        System.out.println(lengthOfASide * lengthOfASide);
    }

    private static void triangle(Scanner scanner) {
        double triangleBase = ask(scanner, "Please enter the base of the triangle: ");
        double triangleHeight = ask(scanner, "Please enter the height of the triangle: ");
        System.out.println(0.5 * triangleBase * triangleHeight);
    }

    private static void circle(Scanner scanner) {
        double radius = ask(scanner, "Please enter the radius of the circle: ");
        System.out.println(Math.PI * (radius * radius));
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Welcome to the Area Calculator! " +
            "Enter 1 to find the area of a Rectangle, " +
            "Enter 2 to find the area of a Square, " +
            "Enter 3 to find the area of a Triangle or " +
            "Enter 4 to find the area of a Circle");

        switch (scanner.nextInt()) {
          case 1:
            rectangle(scanner);
            break;
          case 2:
            square(scanner);
            break;
          case 3:
            triangle(scanner);
            break;
          case 4:
            circle(scanner);
            break;
        }
    }
}


poh-tay-toh poh-tah-toh, does writing the same code a different way affect readability? I have a particular if statement that could be written in different ways, and I'm curious as to whether there's any significant difference in readability that I should prefer one over the other:

The flow can be boiled down to

if string does not begin with '_'
    do stuff
else
    throw error

Some different ways of writing the if condition:

str[0] !== '_'
str.indexOf('_')
!/^_/.test(str)
/^[^_]/.test(str)

I think the first is the simplest and the most readable one from the list but I'd prefer the charAt function:

x.charAt(0) !== '_'

Furthermore, I'd reverse the condition:

if string begins with '_' {
    throw error
}
do stuff

Reference:

How to get first character of string?
Flattening Arrow Code


Generate subsets of k elements from a set of strings This is the task:

Write a recursive program, which prints all subsets of a given set of N words.
Example input:
words = {'test', 'rock', 'fun'}

Example output:
(), (test), (rock), (fun), (test rock), (test fun),

(rock fun), (test rock fun)

In fact I need to generate all subsets from 0 to words.Length. In Pascal (if anybody knows) there is a function (not sure that it's "function") that looks like that:
var a:set of example

I need the same in C#. This is what I tried (the program works, but it's a lot of code):
class Program
{
    static int abc;
    static string[] extractedwords;
    static int k;
    static int margin;
    static string[] words = { "coffee", "ice-cream", "chocolate", "red" };
    static void Main(string[] args)
    {
        abc = 0;
        k = 1;
        Console.WriteLine("The margin of words: ");
        margin = int.Parse(Console.ReadLine());
        extractedwords = new string[margin];
        GenerateWords(0);
    }
    static void GenerateWords(int n)
    {
        if (n == k)
        {
            if (n != 0)
            {
                for (int s = n - 1; s >= 0; s--)
                {
                    for (int a = 0; a < s; a++)
                    {
                        if (extractedwords[s] == extractedwords[a])
                        {
                            return;
                        }
                    }
                }
            }
            PrintWords(extractedwords);
            return;
        }
        for (int a = 0; a < words.Length; a++)
        {
            extractedwords[n] = words[a];
            GenerateWords(n + 1);
        }
        if (k >= margin)
        {
            return;
        }
        if (n == 0)
        {
            k++;
            GenerateWords(n);
        }
    }
    static void PrintWords(string[] words)
    {
        for (int n = 0; n < words.Length; n++)
        {
            Console.Write("{0} ", words[n]);
        }
        Console.WriteLine();
    }
}

Unused variables

At least one of your variables (abc) is never used.  This might be because you've changed the way the code works.  If you refactor your code, try to remember to cleanup at the same time / straight after.  It's a lot easier to do while the code is fresh in your mind and it prevents large amounts of technical debt building up over time.

margin of words

I found this prompt confusing (maybe it's just me).  I think a better prompt would be something like "Please enter the maximum number of words per group: ".  Try to be expressive and imagine that you're not going to be the one using your application.

Variable Names

Similarly, think about your variable names.  They should express what it is the variables actually represent.  Names like k, s, n and a tell me nothing about what the variable represents.  This makes the code harder to read because you have to keep referring back to determine the previous context.  Single letter variable names can be ok for short iteration variables where the context is obvious, but can you honestly say that this is meaningful in its current state:

for (int s = n - 1; s >= 0; s--)

Magic Numbers

You've got some magic numbers in your code.  I'm not totally against using numbers when the context makes it obvious what the numbers mean.  However, this isn't always the case with yours.  For example:

GenerateWords(0);

When I look at this line, it looks like the method is going to generate 0 words which doesn't make sense.  Looking at the function definition, the parameter is labelled as n, which again adds no context.

Console Output

At the moment your outputting straight to the console as you generate the combinations.  Generally, you want to try to separate user interaction from your algorithms.  This allows you to reuse the algorithms in different contexts, put different front ends on your code etc.

Static State

At the moment, your storing your state in static variables that are accessed from your recursive method.  This is OK in your example code, however if you were to put the method into a library, it would mean that you couldn't call it from two different threads to process different word lists.  If the state is passed in, instead, the methods become more flexible.

Minimise what your client needs to know

When you write recursive functions, you'll often need to pass extra parameters into the method in order to support the recursion and the termination conditions.  Clients shouldn't need to know this information (this give you more flexibility if you want to change the way the method works in the future).

Putting it together

Putting some of the above together, you might end up with code something like this:

static void Main()
{
    var combinations = GenerateWordCombinations(new string[] { "coffee", "ice-cream", "chocolate", "red" }, 2);

    combinations.ForEach(x => Console.WriteLine($"({x})"));
}

static public List<string> GenerateWordCombinations(string[] inputWords, int? maxWordsPerCombination = null)
{
    var combinations = new List<string> { "" };
    GenerateWordCombinations(inputWords, "", maxWordsPerCombination??inputWords.Length, combinations);
    return combinations;
}

static private void GenerateWordCombinations(IEnumerable<string> words, string prefix, int maxWordsPerCombination, IList<string> combinations)
{
    if(words.Count() == 0 || maxWordsPerCombination == 0)
    {
        return;
    }

    foreach(var word in words)
    {
        GenerateWordCombinations(words.Where(x => x != word), prefix + word + " ", maxWordsPerCombination - 1, combinations);
        combinations.Add(prefix + word);
    }
}

Things to note about the alternative code above:

I've ignored user input
There's two versions of GenerateWordCombinations, the private one which is recursive and a public one which can be called from clients.  The public one accepts a list of words to search for combinations and the maximum number of words to find in each combination.  The number of words is optional and defaults to null, so that if it's not supplied the number of words in the supplied list can be used instead.
Rather than printing directly to the console, the GenerateWordCombinations methods add the combinations to a list and then returns the list to the caller.
The code uses some of the collection extension methods to do some of the heavy lifting.
Combinations are output in a different order from your original application.


Pasting from another workbook I have a macro comprised of this and similar Subs. They work, but I feel like it's slowing it down. Two workbooks are open, and various ranges are copied from one that is hidden (wbSource) and pasted into the other (mainWB), which is not hidden. There is formatting in all the cells that need to be copied, not just the values. Is there a way to do this better?

Sub CopyData()
Dim mainWB  As Workbook
Dim mainWS  As Worksheet
Set mainWB = ActiveWorkbook
Set mainWS = mainWB.Sheets(1)

Dim wbSource As Workbook
Set wbSource = Workbooks.Open(Filename:="H:\Formatting.xlsx")
ActiveWindow.Visible = False

wbSource.Sheets(1).Range("A10:CX15").Copy
mainWS.Paste
Range("A1").Select
wbSource.Sheets(1).Range("A25:M26").Copy
mainWS.Paste
mainWS.Range("AF8").Select
wbSource.Sheets(1).Range("D49").Copy
mainWS.Paste
mainWS.Range("AF10").Select
wbSource.Sheets(1).Range("D51").Copy
mainWS.Paste

wbSource.Close
End Sub

Yes, there is a way to do this better.

Always Option Explicit.

No need (almost always) for .Select, this is a human activity and explicitly referencing the ranges in VBA is more efficient. This also creates extra work for the VBA engine.

You hide your active window, but you do not unhide it.

Don't be afraid to use you favourite search engine to look up even the simplest commands, especially if you are fixing up code generated by the macro recorder. Sometimes these commands have methods and properties that make life easier (e.g. see what I have done with the copy method - look up the "Excel Range.Copy" method to see what gems are there).

However, with the amount of code you have here, I am really surprised that you would notice any slowing down!

Sub CopyData()
    Dim mainWB  As Workbook
    Dim mainWS  As Worksheet
    Set mainWB = ActiveWorkbook
    Set mainWS = mainWB.Sheets(1)

    Dim wbSource As Workbook
    Set wbSource = Workbooks.Open(Filename:="H:\Formatting.xlsx")
    'ActiveWindow.Visible = False ' Why?

    wbSource.Sheets(1).Range("A10:CX15").Copy mainWS.Range("A10:CX15")
    wbSource.Sheets(1).Range("A25:M26").Copy mainWS.Range("A1") 'Haven't tested this line to see what effect the different range size has.
    wbSource.Sheets(1).Range("D49").Copy mainWS.Range("AF8")
    wbSource.Sheets(1).Range("D51").Copy mainWS.Range("AF10")
    wbSource.Close
End Sub

And the usual staples of setting Application.ScreenUpdating, Application.EnableEvents, Application.Calculation will assist in managing what happens or is shown when the routine is run. ActiveWindow.Visible could be handy, but remember to turn it back on after doing the work. Your ActiveWindow may not be what you think it is.


Basic Nim game vs computer in JavaScript This is my first time writing a basic program/game in any programming language.
It is supposed to a be a Nim game vs a computer with these basic parameters:

Use prompt() to prompt moves and input.
Use console.log() draw the board.

The board should look like this:

  Pile A: ooooo

  Pile B: ooo

  Pile C: ooooo

It has been very difficult for me to approach this problem, and I know the logic that I have used is very basic and buggy. Any pointers would be appreciated, whether in the code or my approach to solving the problem in general.

 var pileA = {
   circles: "ooooo",
   print: function() {
     console.log("Pile A: " + this.circles);
   }
 };

 var pileB = {
   circles: "ooooo",
   print: function() {
     console.log("Pile B: " + this.circles);
   }
 };

 var pileC = {
   circles: "ooooo",
   print: function() {
     console.log("Pile C: " + this.circles);
   }
 };

 function printBoard(){
     console.log("**** Nim ****");
     pileA.print();
     pileB.print();
     pileC.print();
 }

 function yourMove(){

     printBoard();

     var moveData = prompt("Type letter of pile and # of o's you are removing.\n" +
                             "Ex. A1 or C4");

     if (moveData[0] == 'A') {
         var x = pileA.circles.length - moveData[1];
         pileA.circles = pileA.circles.slice(0,x);
         return pileA.circles;
     } else if (moveData[0] == 'B') {
         var x = pileB.circles.length - moveData[1];
         pileB.circles = pileB.circles.slice(0,x);
         return pileB.circles;
     } else if (moveData[0] == 'C') {
         var x = pileC.circles.length - (moveData[1]+1);
         pileC.circles = pileC.circles.slice(0,x);
         return pileC.circles;
         }

 }

 function computersMove() {

     printBoard();

     alert("Now it is the computer's turn!");

     if (pileA.circles != "") {
         pileA.circles = pileA.circles.slice(0,0);
         return pileA.circles;
     } else if (pileB.circles != "") {
         pileB.circles = pileB.circles.slice(0,0);
         return pileB.circles;
     } else if (pileC.circles != "") {
         pileC.circles = pileC.circles.slice(0,0);
         return pileC.circles;
     }

     if (pileA.circles == "" &&
     pileB.circles == "" &&
     pileC.circles == "") {
         console.log("Computer Wins!!!");
         }
 }

 while (pileA.circles != "" ||
     pileB.circles != "" ||
     pileC.circles != "") {

         yourMove();
         if (pileA.circles == "" &&
             pileB.circles == "" &&
             pileC.circles == "") {
                 console.log("You win!!!");
                 }

        if (pileA.circles != "" ||
            pileB.circles != "" ||
            pileC.circles != "") {
                 computersMove();
                 }
     }

 alert('Game Over!');

I stumbled across this because a friend told me he got hit with this question recently for a coding bootcamp entrance exam. I had to look and see what it is, of course : )

Josh has a great answer with excellent use of higher order functions and keeping things DRY. At a glance, one change that I'd make with his code is the usage of the reduce function. It's a bit verbose and possibly difficult for a beginner to parse through. A clearer declaration would be using something like Array.every (once all the circles return an empty string "", the GameOver function returns true). It's a tiny gripe, but it's more intuitive. The usage would be substituted like this:

function isGameOver() {
  return piles.every(function(pile) {
    return pile.circles === "";
  });
}


Integer to String recursive method I was experimenting with lists, sets, and finally maps when I spotted a pattern in my code to make it recursive. Now I haven't used recursion much in the past or at work and I was very excited to have something that does recursion.

I have this recursive method that takes in an Integer and returns a string representation of the Integer by reading two HashMaps.

For example representation(11) will be Eleven OR representation(89) will be Eighty-Nine, ect.

I have arranged to handle up to 999,999. Are there any improvements I could make to this current implementation to handle things more efficiently/speedily?

public String representation(Integer num) {
    StringBuffer numRep = new StringBuffer();
    StringBuffer hundred = new StringBuffer("Hundred");
    StringBuffer thousand = new StringBuffer("Thousand");
    //The case for anything less than 20; 0-19
    if (num < 20) {
        numRep.append(genNumMap.get(num));

    //The case for any integer less than 100; 20-99
    } else if (num < 100) {
        int temp = num % 10;
        if (temp == 0) {
            numRep.append(greaterNumMap.get(num));
        } else {
            numRep.append(greaterNumMap.get(num - temp) + "-"
                    + representation(temp));
        }
    //The case for any integer less than 1000, covers the hundreds; 100-999
    } else if (num < 1000) {
        int temp = num % 100;
        if (temp == 0) {
            numRep.append(representation(num / 100) + "-" + hundred);
        } else {
            numRep.append(representation((num - temp) / 100) + "-" + hundred
                    + "-" + representation(temp));
        }
    //The case for any integer less that one million, covers the thousands; 1,000 - 999,999
    } else if (num < 1000000) {
        int temp = num % 1000;
        if (temp == 0) {
            numRep.append(representation(num / 1000) + "-" + thousand);
        } else {
            numRep.append(representation((num - temp) / 1000) + "-" + thousand
                    + "-" + representation(temp));
        }
    } else if (num > 1000000){
        numRep.append("Sorry, this number is too large");
        JOptionPane.showMessageDialog(null, "Sorry, this number is too large\n"+"Integers 0 through 999,999 are exceptable.");
    }
    return numRep.toString();
}

Such an algorithm is very rarely used, so it is extremely unlikely that its performance matters. So, most chances are you do not need to optimize it at all. But if you insist:
Do not pre-initialize the 'hundred' and 'thousand' StringBuffers. Only initialize them if they are needed. As a matter of fact, it is good practice (though it does not have anything to do with performance) to not even declare them outside of the narrowest possible scope in which they will be used.  By the way, I do not understand why 'hundred' and 'thousand' are StringBuffers instead of Strings.
You do not need HashMaps for this job; just use arrays of String. They will be faster.
It seems like the kind of recursion you are using is tail recursion, so you can trivially convert your function to work iteratively, which will probably yield better performance. I am not saying it will necessarily perform better, so write both versions and benchmark one against the other if you really care about performance. But if you do not, then keep the recursive version, it is way cooler, and even easier to read.
When you append to a StringBuffer, never append multiple strings concatenated with +. Always use a separate call to append() for each string.  Otherwise, the compiler will very likely be creating more temporary StringBuffers behind your back in order to optimize your string append operations.
Considering that any number minus zero is still the same number, you can optimize this:

int temp = num % 1000;
if (temp == 0) {
    numRep.append(representation(num / 1000) + "-" + thousand);
} else {
    numRep.append(representation((num - temp) / 1000) + "-" + thousand
            + "-" + representation(temp));
}

into this:

int temp = num % 1000;
numRep.append( representation( (num - temp) / 1000) );
numRep.append( "-" );
numRep.append( thousand );
if( temp != 0 )
{
    numRep.append( "-" );
    numRep.append( representation( temp ) );
}


Loading a combo box with branch names I'm using this way to load a combo box with branch names, but it's taking more time if there is more number of data.

Is there a better way to do this, like binding in PHP?

<select name="CmbBr" id="CmbBr">
  <?php
     include ("dbcon_.php");
     $sql = mysql_query("SELECT BranchName FROM TblBranch ORDER BY BranchName ASC");
     if(!mysql_num_rows($sql) == 0)
     {
        while($row = mysql_fetch_array($sql))
       {
           ?>
              <option value="<?php echo $row["BranchName"];?>"><?php echo $row["BranchName"]; ?></option>
           <?php
       }
     }
  ?>
</select>

I'd just like to note that use of the mysql_* functions are going to be deprecated in the next version or the one after than(link at the end). You should start using mysqli or PDO.

http://news.php.net/php.internals/53799


Vigenère Cipher problem in competitive programming I've just started doing programming problems.
https://icpcarchive.ecs.baylor.edu/external/58/p5880.pdf
The code below works fine, but my run time is 2.715 seconds and the time limit is 3 seconds.
How can I improve speed of this code?
I've already started to use sys.stdin instead of input().
import string
import sys

while True:
    key = sys.stdin.readline().strip()
    key = int(key) if key.isdigit() else key
    if key == 0: break

    decrypted_msg = sys.stdin.readline().strip()
    decrypted_msg = int(decrypted_msg) if decrypted_msg.isdigit() else decrypted_msg
    if decrypted_msg == 0: break

    key = (len(decrypted_msg)//len(key) + 1) * key
    key = key[0:len(decrypted_msg)]

    encrypted_msg = ""

    for i in range(len(decrypted_msg)):
        key_idx = string.ascii_uppercase.index(key[i])
        deciphered_idx = string.ascii_uppercase.index(decrypted_msg[i])

        enciphered_idx = (deciphered_idx + key_idx + 1) % len(string.ascii_uppercase)
        encrypted_msg += string.ascii_uppercase[enciphered_idx]

    print(encrypted_msg)

Comments

decrypted_msg is misleading. It's not decrypted but rather "not encrypted". But really just call it "plaintext", as the problem statement does.
Similarly, "enciphered" and "encrypted" are not just inconsistent (make up your mind), but go against the problem statement's term "ciphertext".
The end-signal string '0' can simply be checked as a string.
No need to check the plaintext against '0'.
Mapping str.strip over sys.stdin makes the code a bit nicer. We can even use a nice for statement then.
Better just zip the plaintext and key instead of iterating over indices.
Searching the letters in the alphabet string isn't super terrible, but it's apparently faster to look up letter pairs in a dictionary.
itertools.cycle is a nicer (and I think faster) way to cycle the key.
Repeatedly extending a string with += might degrade to quadratic time overall. Better use ''.join on an iterable.
A little time can be saved by storing string.ascii_uppercase.index in a variable instead of looking up the attributes ascii_uppercase and index over and over again.

Solution 1: My fastest[*], using a lookup-table mapping letter pairs to single letters
This gets accepted in 0.382 seconds here, where I believe you submitted yours (tried four times, impressively always got the exact same time).
[*] In my other answer benchmarking a worst case, actually my solution 3 is fastest.
import sys
from itertools import cycle
from string import ascii_uppercase as abc

table = {(abc[i], abc[j]): abc[(i + j + 1) % 26]
         for i in range(26)
         for j in range(26)}.get

lines = map(str.strip, sys.stdin)
for key in lines:
    if key == '0':
        break
    plaintext = next(lines)

    print(''.join(map(table, zip(plaintext, cycle(key)))))

I did get it down to 0.372 seconds by using sys.stdout.write, but meh, not worth it.
Solution 2: My fastest with str.index:
Here's the fastest I got with str.index, got accepted in 0.699 seconds. Note that my bcd is twice the alphabet and starts with "B", so I can use bcd[p + k] instead of the slower abc[(p + k + 1) % 26].
from string import ascii_uppercase as abc
import sys
from itertools import cycle

index = abc.index
bcd = abc[1:] + abc

lines = map(str.strip, sys.stdin)
for key in lines:
    if key == '0':
        break
    plaintext = next(lines)

    key = cycle(map(index, key))
    plaintext = map(index, plaintext)

    print(''.join([bcd[p + k] for p, k in zip(plaintext, key)]))

Solution 3: O(|key|) Python operations
Since the plaintext has up to 100,000 letters but the key has only up to 1,000 letters, and since Python operations are slow, I also tried doing just O(|key|) Python operations instead of O(|plaintext|) Python operations. By using str.translate. For example if the key is 'KEY', then the entire string slice plaintext[0::3] is translated with the key letter 'K'. And [1::3] and [2::3] get translated with 'E' and 'Y', respectively. Sadly, it was slower, got accepted in 0.985 seconds:
import sys
from string import ascii_uppercase as abc

tables = {c: str.maketrans(abc, abc[i:] + abc[:i])
          for i, c in enumerate(abc, 1)}

lines = map(str.strip, sys.stdin)
for key in lines:
    if key == '0':
        break
    plaintext = next(lines)

    ciphertext = [None] * len(plaintext)
    n = len(key)
    for i, k in enumerate(key):
        ciphertext[i::n] = plaintext[i::n].translate(tables[k])

    print(''.join(ciphertext))

Solution 3b: Using bytearray
Solution 3 but with bytes/bytearray instead of str. Accepted in 0.619 seconds. Not sure whether it's the input/output or the bytearray.translate that's responsible for the speed-up:
import sys
from string import ascii_uppercase as abc

abc = abc.encode()
tables = {c: bytearray.maketrans(abc, abc[i:] + abc[:i])
          for i, c in enumerate(abc, 1)}

lines = map(bytes.strip, sys.stdin.buffer)
write = sys.stdout.buffer.write
for key in lines:
    if key == b'0':
        break
    plaintext = next(lines)

    ciphertext = bytearray(plaintext)
    n = len(key)
    for i, k in enumerate(key):
        ciphertext[i::n] = ciphertext[i::n].translate(tables[k])

    write(ciphertext)
    write(b'\n')


Palindromes with stacks I'm creating a simple function to verify whether or not a string is a palindrome, and must use stacks in solving it.

bool isPalindrome(string word) {
    // #1 determine length
    int n = word.size();

    // #3 make sure we have an even string
    if (n % 2 != 0)
        word.erase(0, 1);

    // #2 load the stack
    stack<char> s;
    for (int i = 0; i < n / 2; i++) {
        s.push(word[i]);
        word.erase(i, 1);
    }

    // #4 if our stack is empty, then return true
    if (s.empty())
        return true;

    // #5 compare the first & last letters for a valid palindrome
    /*if (s.top() == word[0]) {
        s.pop();
        word.erase(0, 1);
    } else
        return false;*/

    while (n != 0) {
        if (s.top() == word[0]) {
            s.pop();
            word.erase(0, 1);

            // return true only when our stack is empty
            if (s.empty())
                return true;
        } else
            return false;
    }
}

Is there a better way to do this? Are there any evident issues with the current state of the program?

First, a palindrome can have an odd number of characters:

  Even-character palindrome: 1221
  Odd-character palindrome: 13531

You only support even-character palindromes, which is bad, but even worse, you do not return an error about invalid input for an odd-digit palindrome, you remove the first digit.

Second, to help prevent errors, you should always use braces around one-liner if and loop statements:

if (n % 2 != 0) {
    word.erase(0, 1);
}

Third, don't leave dead code in there.  You have a chunk of code commented out, so that should be removed.

Fourth, your comments are in the order of #1, #3, #2, ...  Either the comments should be fixed or the code should be re-ordered.

Fifth, there is a mistake right here:

for (int i = 0; i < n / 2; i++) {
    s.push(word[i]);
    word.erase(i, 1);
}

Sixth, it appears that you are using namespace std; somewhere in your code as you did not prefix stack or string.  This is not a good idea because namespaces can contain functions with the same name, so you can have problems with your code when you start using multiple namespaces, or even if you have a function in the same file that has the same name as a function in the namespace.  You can read more about it here.

So, with the word "qweewq", you first remove "q" so the word is "weewq".  Next, i == 1, so you remove "e", so the word is "wewq", and so on.  You should change this to:

for (int i = 0; i < n / 2; i++) {
    s.push(word[0]);
    word.erase(0, 1);
}

This is a working solution:

bool isPalindrome(std::string word) {

    int wordSize = word.size();

    // #1 load the stack
    std::stack<char> s;
    for (int i = 0; i < wordSize / 2; i++) {
        s.push(word[0]);
        word.erase(0, 1);
    }

    // #2 make sure word size is same as stack size (handle odd-character palindromes)
    if (word.size() > s.size()) {
        word.erase(0, 1);
    }

    // #3 if our stack is empty, then return true
    if (s.size() == 0) {
        return true;
    }

    // #4 validate palindrome
    while (s.size() > 0) {

        if (s.top() == word[0]) {
            s.pop();
            word.erase(0, 1);

            // return true only when our stack is empty
            if (s.size() == 0 || word.size() == 0) {
                return true;
            }
        }
        else {
            return false;
        }
    }
}

Improvements on this solution are given here.


Make an arraylist of unique values I have, in Java, an arraylist with these values (many lines, this is just an extract):

  20/03/2013 23:31:46   6870    6810    6800    6720    6860    6670    6700    6650    6750    6830    34864   34272
  20/03/2013 23:31:46 6910    6780    6800    6720    6860    6680    6620    6690    6760    6790    35072   34496

where the first two values are strings that contain data and are stored in a single element.

What I want to do is to compare the string data elements and delete, for example, the second one and all the elements referred to that line.

For now, I've used a for cycle that every 13 elements compares the string (in order to compare only data strings).

Can I implement this with other better solutions?

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Downsampler {
    public static void main(String[] args) throws Exception{
        //The input file
        Scanner s = new Scanner(new File("prova.txt"));

        //Saving each element of the input file in an arraylist
        ArrayList<String> list = new ArrayList<String>();
        while (s.hasNext()){
            list.add(s.next());
        }
        s.close();

        //Arraylist to save modified values
        ArrayList<String> ds = new ArrayList<String>();

        int i;
        for(i=0; i<=list.size()-13; i=i+14){
            //combining the first to values to obtain data
            String str = list.get(i)+" "+list.get(i+1);
            ds.add(str);
            //add all the other values to arraylist ds
            int j;
            for(j=2; j<14; j++){
                ds.add(list.get(i+j));
            }

            //comparing data values
            int k;
            for(k=0; k<=ds.size()-12; k=k+13){
                ds.get(k); //first data string element

                //Comparing with other strings and delete
                //TODO
            }
        }
    }
}

To answer your question.. it depends on how you want to handle the data. Take a step back and put your self in the users shoes. Lets say the user has those numbers saved as bank account transactions.. He would want those numbers saved somewhere, but not necessarily visible. If that was the case you wouldn't want "delete" that data. You could, however, parse the data into say a table. You could give each cell in that table a class that has a boolean value called visible, and a int value. Then you could set a row or column to not visible as you wish. That would give you the ability to then just loop through the rows and columns and output the data as needed.


Designing a better logger class Could you please critisize the logger class below? Can it be used in a multi threaded web environment? If not how can I improve it? Is there anything wrong with locking in WriteToLog method or multithreading in FlushLog method?

public class Logger
{
    private static Logger instance;
    private static Queue<LogData> logQueue;
    private static string logDir = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["LogDirectory"]);
    private static string logFile = "log.txt";
    private static int maxLogAge = Int32.Parse(ConfigurationManager.AppSettings["LogMaxAge"]);
    private static int queueSize = Int32.Parse(ConfigurationManager.AppSettings["LogQueueSize"]);
    private static DateTime LastFlushed = DateTime.Now;

    private Logger() { }

    public static Logger Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Logger();
                logQueue = new Queue<LogData>();
            }
            return instance;
        }
    }

    public void WriteToLog(string message)
    {
        lock (logQueue)
        {
            LogData logEntry = new LogData(message);
            logQueue.Enqueue(logEntry);

            if (logQueue.Count >= queueSize || DoPeriodicFlush())
            {
                FlushLog();
            }
        }
    }

    private bool DoPeriodicFlush()
    {
        TimeSpan logAge = DateTime.Now - LastFlushed;
        if (logAge.TotalSeconds >= maxLogAge)
        {
            LastFlushed = DateTime.Now;
            return true;
        }
        else
        {
            return false;
        }
    }

    private void FlushLog()
    {
        System.Threading.ThreadPool.QueueUserWorkItem(q => {
            while (logQueue.Count > 0)
            {
                LogData entry = logQueue.Dequeue();
                string logPath = logDir + entry.LogDate + "_" + logFile;

                using (System.IO.StreamWriter file = new System.IO.StreamWriter(logPath, true, System.Text.Encoding.UTF8))
                {
                    file.WriteLine(string.Format("{0}\t{1}", entry.LogTime, entry.Message));
                }
            }
        });
    }

    ~Logger()
    {
        FlushLog();
    }
}

public class LogData
{
    public string Message { get; set; }
    public string LogTime { get; set; }
    public string LogDate { get; set; }

    public LogData(string message)
    {
        Message = message;
        LogDate = DateTime.Now.ToString("yyyy-MM-dd");
        LogTime = DateTime.Now.ToString("HH:mm:ss.fff tt");
    }
}

Thanks in advance,

This code is not thread safe.  You synchronize (lock) while adding to the queue, but your code which removes from the code does not lock the queue, and will always run on a background thread, which is going to cause potential race conditions.

If you really must write your own logging, I would, at the least, look into using ConcurrentQueue<T> to avoid the need for locking on adding.  BlockingCollection<T> would make this far simpler, as you could just have a thread call GetConsumingEnumerable() to process items as they're added.

That being said, logging is something that's been handled many times, and handled well.  You'd be far better off using something like the new Semantic Logging Application Block (from P&P) or even log4net.


Sum the Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below N.

  #include <stdio.h>
  int main(){
    int i=0,j,k,l,sum=0;
    scanf("%d",&i);
    if(i<=100000&&i>0){
    for(j=0;j<i;j++){
        scanf("%d",&k);
        if(k<=1000000000&&k>0){
        for(l=3;l<k;l++){
            if(l%3==0||l%5==0)
                {sum+=l;}
        }}
    printf("%d\n",sum);
    sum=0;
    }}

The above code does satisfy all the test cases but it has been rejected citing that it is very slow. Please suggest improvements to the code.

Generally, try to think about the problem before brute-forcing it.

Is there an easy way to sum all the multiples of 3 below \$N\$? Of course there is.
First we note that the largest multiple of 3 is \$3 * \lfloor\frac{N}{3}\rfloor\$ and the sum of all the multiples is then \$3 * 1 + 3 * 2 + ... 3 * \lfloor\frac{N}{3}\rfloor\$. Factor out the 3 and you get \$3 * (1 + 2 + 3 + ... \lfloor\frac{N}{3}\rfloor)\$. Now we use Gauss's trick for summing the natural numbers to get a nice easy formula for the sum: \$3*x*\frac{x+1}{2}\$, where \$x\$ is \$\lfloor\frac{N}{3}\rfloor\$.

Similarly, we can get the sum for the multiples of 5, and add the results together. However, we then have a bunch of duplicates (namely multiples of 15)
which we can also calculate in a similar manner and then subtract to get the final result.

This approach completely eliminates any and all looping, and so will be super quick.

Now, let's discuss your code. Here's a list of suggestions:

If you are prompting the user, provide some helpful hints as to what you are expecting as input.
Having hardcoded bounds such as yours is unintuitive. Have your sum be a long or even long long (depending on the desired platform) and you will not run into issues with integer inputs, which are guaranteed by scanf(%d). This will also cut down on the indentation, increasing readability.
Variable names are important. While it is pretty easy to see that i, k are the bounds, and j, l are counter variables after reading the code, it would be even easier to understand with lower_bound, upper_bound and i, j for the counters (per standard practices).
Consider generalizing the problem to create a function that will be reusable elsewhere.


Return all words which have their reverse present in a string Problem Statement:

  Given a string of words return all words which have their reverse present in the string as ( (word1 , reverseword1 ) , (word2 ,reverseword2) )

Example Case:

Input:

  Sachin tendulkar is the best tseb eht nihcaS

Output:

  { ( best ,   tseb )  , ( the  ,  eht) , (Sachin  ,  nihcaS) }

My approach is to use a map and return the words if a match to the reverse of the current word is found in the map.

#include<iostream>
#include<unordered_map>
#include<string>

using namespace std;

int main()
{
unordered_map <string, int> binMap;
string test="Sachin tendulkar is the best tseb eht nihcaS si";
int i=0,j=0;
string temp,rev;
string::iterator it;
cout<<"{";

for(i = 0, it = test.begin() ; it <= test.end(); ++it)
    {

        if(*it==' ' || it==test.end())
        {
            temp=test.substr(j,i-j);
            rev=string(temp.rbegin(), temp.rend());
            if(binMap[rev]==1)
            cout<<"( "<<rev<<","<<temp<<" ), ";
            else
            binMap[temp]=1;
            j=i+1;
        }
        i++;
    }
cout<<"}";
return 0;
}

Is this the most optimal way to solve the problem or am I doing something wrong?

I have observed a few things that may help you improve your code.

Use library functions

One of the things the code does is to separate words in the input.  However, this could be done more easily by using a std::stringstream:

stringstream in(test);
string word;
while (in >> word) {
    // test each word
}

Use more whitespace to enhance readability of the code

Instead of crowding things together like this:

cout<<"( "<<rev<<","<<temp<<" ), ";

most people find it more easily readable if you use more space:

cout << "( " << rev << ", " << word << " ) ";

Only print words once

Right now, with this input string:

string test="Sachin tendulkar is si is the best tseb eht nihcaS si";

The word "is" gets reported twice.

  {( is,si ), ( best,tseb ), ( the,eht ), ( Sachin,nihcaS ), ( is,si ), }

One way to handle that is to note when each word is actually reported and to only do it once.  Here's one way to do that:

stringstream in(test);
enum state { DETECTED=1, REPORTED };
unordered_map <string, state> binMap;

string word;
cout << "{";
while (in >> word) {
    string rev{word.rbegin(), word.rend()};
    if (binMap[rev] == DETECTED && binMap[word] != REPORTED) {
        cout << "( " << rev << ", " << word << " ) ";
        binMap[word] = REPORTED;
    } else {
        binMap[word] = DETECTED;
    }
}
cout << "}\n";


C-style generic stack implementation in C# I saw a nice generic stack implemented in C, in Stanford's CS107 Programming Paradigms course, so I tried to rewrite it in C#:

public unsafe static class NativeMemory
{
    [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
    public static extern  void* memcpy(void* dest, void* src, UIntPtr count);

    [DllImport("msvcrt.dll", EntryPoint = "malloc", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
    public static extern  void* malloc(UIntPtr count);

    [DllImport("msvcrt.dll", EntryPoint = "realloc", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
    public static extern  void* realloc(void* src, UIntPtr count);

    [DllImport("msvcrt.dll", EntryPoint = "free", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
    public static extern void free(void* src);
}

public unsafe delegate void FreeFunction(void* elemAddr);

public unsafe struct Stack : IDisposable
{
    private readonly int elemSize;
    private readonly FreeFunction freeFunction;
    private int alloclength;
    private void* elems;

    public Stack(int elemSize, FreeFunction freeFunction)
        : this()
    {
        this.elemSize = elemSize;
        this.freeFunction = freeFunction;
        alloclength = 4;
        elems = NativeMemory.malloc((UIntPtr) (elemSize * alloclength));
    }

    public int Count { get; set; }

    public void Push(void* elemAddr)
    {
        if (alloclength == Count)
        {
            Grow();
        }
        NativeMemory.memcpy(((byte*)elems + Count* elemSize), elemAddr, (UIntPtr) elemSize);
        Count++;
    }

    public void Pop(void* elemAddr)
    {
        void* source = ((byte*) elems + (--Count* elemSize));
        NativeMemory.memcpy(elemAddr, source, (UIntPtr)elemSize);
    }

    private void Grow()
    {
        alloclength *= 2;
        elems = NativeMemory.realloc(elems, (UIntPtr) (alloclength* elemSize));
    }

    public void Dispose()
    {
        if (freeFunction != null)
        {
            for (int i = 0; i < Count; i++)
            {
                void* elemAddr = ((byte*) elems + (elemSize * i));
                freeFunction(elemAddr);
            }
        }
        NativeMemory.free(elems);
    }
}

public class Program
{
    private unsafe static void Main(string[] args)
    {
        using (Stack s = new Stack(sizeof (char*), null))
        {
            string[] names = {"rezo", "jack", "andrew"};
            foreach (string n in names)
            {
                fixed (char* ptr = n)
                {
                    char* name = ptr;
                    s.Push(&name);
                }
            }

            while (s.Count > 0)
            {
                char* name;
                s.Pop(&name);
                Console.WriteLine(new string(name));
            }
        }
    }
}

Example of how to store managed objects:

private unsafe static void Main(string[] args)
{
    var names = new[] {"Brad", "Andrew", "Jon","Melissa"};

    using (Stack stack = new Stack(sizeof(GCHandle), (ptr) =>
    {
        GCHandle handle = GCHandle.FromIntPtr(new IntPtr(ptr));
        handle.Free();
    }))
    {
        foreach (var name in names)
        {
            GCHandle handle = GCHandle.Alloc(name);
            stack.Push(&handle);
        }

        while (stack.Count > 0)
        {
            GCHandle objHandle;
            stack.Pop(&objHandle);
            Console.WriteLine((string)objHandle.Target);
        }
    }
}

What do you think about this? Is there a better way to implement a C-style generic stack in C#?

UIntPtr is the wrong type to represent a count (it's basically a void *). You want UInt32 or UInt64 depending on your architecture.
Count should be private set; callers should not be able to change it directly
Why are elemsize and alloclength both signed ints? Shouldn't they be unsigned? Or at least check the incoming elemsize in the constructor?
I hope that the documentation explains that the FreeFunction is for freeing individual elements that the Stack owns if it gets destroyed nonempty.
What's supposed to happen when they Pop an empty stack? Right now you get undefined behavior.
What's supposed to happen if the malloc() or realloc() fails?


Query WordPress database, returning an array of rows This is one of my first attempts at querying the WordPress database for data, and some my first PHP code ever, so please bear that in mind when commenting.
It is supposed find data between two dates, and show it as HTML in a for each loop. How can this be made better? What is the correct way to query a WordPress database?
<?php
require_once('wp-load.php');
$sd = date('Y-m-d', strtotime(($startdate = filter_input(INPUT_GET, 'startdate'))));
$ed = date('Y-m-d', strtotime(($enddate = filter_input(INPUT_GET, 'enddate'))));
$query = $wpdb->prepare("SELECT FirstName, LastName, FROM WHEN HireDate BETWEEN '%s' and '%s'" $sd, $ed);
echo $query;
$results = $wpdb->get_results( $query );
?>

If you're working with a custom table you have within your database, which you use for WP, then using $wpdb is the way to go. Just remember to use prepare, if there's any user submitted stuff included in the query.
If on the other the data is stored as posts (with custom post type) with associated post meta, then WP_Query with meta_query argument is more appropriate way to find the data. (It uses $wpdb in the end, but is the more typical way to query posts).


Parsing in between of brackets I do parsing of the string in order to find wrapped sub-string inside brackets of the first level. a+(b+(d-g))+g+d, in this case I will need to separate (b+(d-g)). Below is the function which i use for such situations. This function is invoked when i find any opening bracket (. I did profiling of the program and unfortunately it is one of the slowest parts.

Could you please advise how I can optimise the code?

Input

"(b+(d-g))+g+d"
 ^            ^
 |            +--------iterator `end_` points to the end of the expression
 +-------------iterator `tail_` points to beginning of the expression with brackets

Output

string with (b+(d-g))

side-effect

tail_ iterator

"(b+(d-g))+g+d"
         ^
         |
         +------iterator `tail_` points to the last correctly closed bracket.

Function

string get_between_brackets(string::iterator& tail_, const string::iterator& end_)
{
    string brackets_content;
    brackets_content.reserve(248); //cannot be longer than that
    if(distance(tail_, end_) >= 2)
    {
        uint br_cnt = 0;
        while(tail_ != end_)
        {
            const auto& chr = *tail_;
            switch(chr)
            {
                case '(': ++br_cnt; break;
                case ')': --br_cnt; break;
            }
            if(br_cnt >= 0)
                brackets_content.push_back(chr);

            if (br_cnt == 0)
                break;

            advance(tail_, 1);
        }
    } else throw std::invalid_argument("brackets tail is not long enough");
    return(brackets_content);
}

Design

Your main issue is design. Without looking at the rest of your code to understand how it works this is a bit of a guess. But it feels like you have a design issue with your larger algorithm. There are much better ways to solve this without scanning way ahead in the input stream.

As pointed out by @JerryCoffin above in the comments shunting yard or recursive descent are things you should look into. Personally I think the shunting yard algorithm would give you the most benefit at this point.

Review of Code

Iterators are supposed to be very simple object that carry little state. So passing them by value should not be an issue. Also is there a need to limit this to string::iterator?

string get_between_brackets(string::iterator& tail_, const string::iterator& end_)

I would have done:
    string get_between_brackets(string::iterator& tail_, const string::iterator& end_)

template<typename I>
std::string get_between_brackets(I tail_, I end_)

That's a great comment.

    brackets_content.reserve(248); //cannot be longer than that

But i don't see that being enforced anywhere.

This switch is broken:

            switch(chr)
            {
                case '(': ++br_cnt; break;
                case ')': --br_cnt; break;
            }

Any character that does not match ')' or '(' leads to undefined behavior. You should must have a default option.

You throw if there is not enough charaters to hold two braces.

else throw std::invalid_argument("brackets tail is not long enough");

But your code works perfectly well if there are no braces in the code. Also I would expect it to throw if the braces were not balanced.

Also rather than building the result slowly character by character as you parse it. It would be simpler (and more effecient) to just remember the beignning and end and return a sub string.

    return std::string(firstBrace, lastBracePlusOne);


Converting a binary string to hexadecimal using Rust Once again, I am reinventing the wheel here to understand the fundamentals of rust. In a previous question I requested feedback on my function that performed a hexadecimal to binary conversion. In this snippet, I am seeking some constructive feedback on converting from binary to hexadecimal.

fn main() {

    let hexadecimal_value = convert_to_hex_from_binary("10111");
    println!("Converted: {}", hexadecimal_value);
}

fn convert_to_hex_from_binary(binary: &str) -> String {
    let padding_count = 4 - binary.len() % 4;

    let padded_binary = if padding_count > 0 {
        ["0".repeat(padding_count), binary.to_string()].concat()
    } else {
        binary.to_string()
    };

    let mut counter = 0;
    let mut hex_string = String::new();
    while counter < padded_binary.len() {
        let converted = to_hex(&padded_binary[counter..counter + 4]);
        hex_string.push_str(converted);
        counter += 4;
    }

    hex_string
}

fn to_hex(b: &str) -> &str {
    match b {
        "0000" => "0",
        "0001" => "1",
        "0010" => "2",
        "0011" => "3",
        "0100" => "4",
        "0101" => "5",
        "0110" => "6",
        "0111" => "7",
        "1000" => "8",
        "1001" => "9",
        "1010" => "A",
        "1011" => "B",
        "1100" => "C",
        "1101" => "D",
        "1110" => "E",
        "1111" => "F",
        _ => "",
    }
}

A couple of things:

Any time you have a function which could fail, it should return an Option<T>.  Ask yourself, if someone calls convert_to_hex_from_binary("foobar") and gets back "", is that reasonable?  They will need to manually check that their input makes sense, or that the output makes sense every time.  Static checking of these errors is part of the joy of Rust.

With that it mind, change to_hex like so:

fn to_hex(b: &str) -> Option<&str> {
    match b {
        "0000" => Some("0"),
        "0001" => Some("1"),
        "0010" => Some("2"),
        "0011" => Some("3"),
        "0100" => Some("4"),
        "0101" => Some("5"),
        "0110" => Some("6"),
        "0111" => Some("7"),
        "1000" => Some("8"),
        "1001" => Some("9"),
        "1010" => Some("A"),
        "1011" => Some("B"),
        "1100" => Some("C"),
        "1101" => Some("D"),
        "1110" => Some("E"),
        "1111" => Some("F"),
        _ => None,
    }
}

You are iterating over a known range of values to get counter.  Instead of using a while loop, you can use a range.  Since you're now returning None from to_hex you can now shortcut returning if something is wrong with None.

Your inner loop now looks like this:

let mut hex_string = String::new();
for counter in (0..padded_binary.len()).step_by(4) {
    match to_hex(&padded_binary[counter..counter + 4])
    {
        Some(converted) => hex_string.push_str(converted),
        None => return None
    };
}

Your function signature and return type also need to match Option<String>:

fn convert_to_hex_from_binary(binary: &str) -> Option<String> {
    ...
    Some(hex_string)
}

Your padded_binary definition can be simplified, since repeating "0" zero times is exactly the same as not repeating it.

The definition is simply:

let padded_binary = ["0".repeat(padding_count), binary.to_string()].concat();

A couple of non Rust specific things:

Consider writing some tests.
String representation of binary numbers often begin with '0b'.  For example 0b1101 == 13.  You might want to consider checking for this prefix on the input string and trimming it.
You may have already thought about this, but consider if you want to trim whitespace or leave it to the function caller.


A c++ program to solve a Rubik's Cube I wanted to write a c++ program to solve a 3x3 rubik's cube, but failed at it. So I picked up a 2x2 rubik's cube and wrote a program using Blindfold cubing algorithm. Can anyone help me write a more efficient program ?
This is the program I wrote

#include<iostream>
#include<string>
using namespace std;
class Solver
{
    string b = "RD' RU' R'U' RU R'F' RU R'U' R'FR DR'      ";
    string c = "F RU' R'U' RU R'F' RU R'U' R'FR F'         ";
    string d = "FU' R'U' RU R'F' RU R'U' R'FR2F'           ";
    string e = "F'D RU' R'U' RU R'F' RU R'U' R'FR D'F      ";
    string f = "F2D RU' R'U' RU R'F' RU R'U' R'FR D'F2     ";
    string g = "RF RU' R'U' RU R'F' RU R'U' R'FR F'R'      ";
    string h = "D RU' R'U' RU R'F' RU R'U' R'FR D'         ";
    string i = "U' R'U' RU R'F' RU R'U' R'FR R             ";
    string j = "R'U' R'U' RU R'F' RU R'U' R'FR R2          ";
    string k = "R2U' R'U' RU R'F' RU R'U' R'F              ";
    string l = "RU' R'U' RU R'F' RU R'U' R'FR              ";
    string n = "D2 RF RU' R'U' RU R'F' RU R'U' R'FR F'R' D2";
    string o = "D'RU' R'U' RU R'F' RU R'U' R'FR D          ";
    string p = "R'F RU' R'U' RU R'F' RU R'U' R'FR F'R      ";
    string r = "F2 RU' R'U' RU R'F' RU R'U' R'FR F2        ";
    string s = "DR F RU' R'U' RU R'F' RU R'U' R'FR F' R'D' ";
    string t = "D2 RU' R'U' RU R'F' RU R'U' R'FR D2        ";
    string u = "F RU' R'U' RU R'F' RU R'U' R'FR F'         ";
    string v = "D'F RU' R'U' RU R'F' RU R'U' R'FR F'D      ";
    string w = "D2F RU' R'U' RU R'F' RU R'U' R'FR F'D2     ";
    string x = "DF RU' R'U' RU R'F' RU R'U' R'FR F'D'      ";
    public:
    string getSol(char letter)
    {
        switch(letter)
        {
            case 'b': return b;
            case 'c': return c;
            case 'd': return d;
            case 'e': return e;
            case 'f': return f;
            case 'g': return g;
            case 'h': return h;
            case 'i': return i;
            case 'j': return j;
            case 'k': return k;
            case 'l': return l;
            case 'n': return n;
            case 'o': return o;
            case 'p': return p;
            case 'r': return r;
            case 's': return s;
            case 't': return t;
            case 'u': return u;
            case 'v': return v;
            case 'w': return w;
            case 'x': return x;
            default: return "Please Enter Correct sequence";
        }
    }
};
int main()
{
    int i = 0;
    char seq[50];
    string solution;
    Solver sol;
    cout<<"-----------------------------------------------"<<endl;
    cout<<"|            Cube Solver 2x2 v1.0             |"<<endl;
    cout<<"|            Developed by Pavan P             |"<<endl;
    cout<<"-----------------------------------------------"<<endl<<endl;
    cout<<"Enter the Sequence in small letters: ";
    cin.clear();
    cin>>seq;
    while(seq[i]!='\0')
    {
        i++;
    }
    cout<<endl;
    cout<<"-----------------------------------------------"<<endl;
    cout<<"|    This may be a solution, try buddy        |"<<endl<<endl;
    for(int j=0;j<i;j++)
    {
        solution = sol.getSol(seq[j]);
        cout<<"| "<<solution<<" |"<<endl;
    }
    cout<<"-----------------------------------------------"<<endl;
    cout<<"Thank You"<<endl;
    cin.get();
        cin.get();
    return 0;
}

Here are some things that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Rethink your object design

Right now, the Solver object simply holds two dozen static strings.  It has no intelligence and does not, in any sense, know anything about the cube it purports to solve.  A better solver might keep a model of the scrambled cube to track its state.

Don't optimize blindly

First, we should keep in mind what Donald Knuth has said about optimization:

  "The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming."

Your particular program probably spends 99% of its time doing I/O, so the performance differences among possible alternatives is probably best approximated as zero.  If what you're really after is a better algorithm, then that's a different problem.

Don't use std::endl if '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can potentially improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.

Use string concatenation

The code currently includes these lines:

cout<<"-----------------------------------------------"<<endl;
cout<<"|            Cube Solver 2x2 v1.0             |"<<endl;
cout<<"|            Developed by Pavan P             |"<<endl;
cout<<"-----------------------------------------------"<<endl<<endl;
cout<<"Enter the Sequence in small letters: ";

Each of those is a separate call to operator<< but they don't need to be.  Another way to write that would be like this:

std::cout <<
    "-----------------------------------------------\n"
    "|            Cube Solver 2x2 v1.0             |\n"
    "|            Developed by Pavan P             |\n"
    "-----------------------------------------------\n"
    "Enter the Sequence in small letters: ";

This reduces the entire sequence to a single call to operator<< because consecutive strings in C++ (and in C, for that matter) are automatically concatenated into a single string by the compiler.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Quicksort using first element pivot I'm trying to get my Quicksort implementation doing fewer comparisons. The first element is used as a pivot. Could you give me some directions if there are any places that should be optimized in a sense of making fewer comparisons? As I understand, it's due to a redundant recursion pass, since the partition subroutine and comparisons counting in it are implemented correctly.

#include <vector>

using namespace std;
using uint = unsigned int;

uint PartitionSub(vector<uint>& inp, uint l, uint r, uint& numOfCmp);

void QuickSort(vector<uint>& inp, uint l, uint r, uint& numOfCmp)
{
    if (r - l < 2)
        return;

    uint newPivotIdx = PartitionSub(inp, l, r, numOfCmp);

    QuickSort(inp, l, newPivotIdx, numOfCmp);
    QuickSort(inp, newPivotIdx + 1, r, numOfCmp);
}

uint PartitionSub(vector<uint>& inp, uint l, uint r, uint& numOfCmp)
{
    auto swap = [&inp](uint a, uint b)
    {
        uint buf = inp[a];
        inp[a] = inp[b];
        inp[b] = buf;
    };

    //numOfCmp += r - l; // we can use this, but ++numOfCmp just before
                         // comparison is more clear
    uint i = l + 1;
    uint j = l + 1;

    uint p = inp[l];

    for (; j <= r; j++)
    {
        ++numOfCmp;
        if (inp[j] <= p)
        {
            if (i != j)
                swap(i, j);
            i++;
        }
    }

    uint newPivotIdx = i - 1;
    swap(l, newPivotIdx);
    return newPivotIdx;
}

Prefer standard integer types

Instead of:

using uint = unsigned int;

Prefer

#include <cstdint>
//use the std::uint32_t in code (or whichever width)

Don't use namespace std

Common advice which will help guard against namespace collisions. In your case I think you could get away with just:

using std::vector;

Quicksort Algorithm

A common optimization to remove average case comparisons is to more intelligently select your pivot. One approach which strengthens the asymptotic runtime of the algorithm is the 'median of fives' approach. In this approach you select your pivot to be the median of 'the median of each of the n/5 sublists of length 5'. In practise, however, this could increase the number of comparisons. It's hard to recommend a strategy without knowing the size and characteristics of your input.


Printing doubles using string manipulation Having mostly used Qt and its classes like QString, I wrote a little exercise with plain C++11. I'm looking for two kinds of input: generally improving the code and/or doing it better in an entirely different way (still standard C++11 or C++14, no Boost or anything).

The code is for printing doubles with given number of significant digits, by first producing a string using scientific notation, and then manipulating that string to move the dot and pad it with zeros.

#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <stdexcept>

template <typename T>
std::string number_to_sci_string(T number, int precision) {
    std::stringstream ss;
    ss << std::scientific << std::setprecision(precision-1) << number;
    return ss.str();
}

std::string sci_string_to_normal(const std::string &s) {
    auto dot_pos = s.find('.');
    auto e_pos = s.find('e');
    if (dot_pos == std::string::npos || // dot required
        dot_pos < 1 ||  // part1 below must not be empty
        e_pos == std::string::npos || // e required
        e_pos >= s.length()-1 || // must not be last
        e_pos - dot_pos < 2) { // part2 below must not be empty
        throw std::invalid_argument(s);
    }

    auto exponent = std::stoi(s.substr(e_pos + 1), nullptr, 10);
    if (exponent == 0) {
        return s.substr(0, e_pos);
    }
    else {
        auto part1 = s.substr(0, dot_pos);
        auto part2 = s.substr(dot_pos + 1, e_pos - dot_pos - 1);
        auto part2length = static_cast<ssize_t>(part2.length());
        if (exponent >= part2length) {
            auto fill = std::string(exponent - part2length, '0');
            return part1 + part2 + fill;
        }
        else if (exponent < 0) {
            auto fill = "0." + std::string(-1 - exponent, '0');
            // this is the only case where sign matters
            auto sign = (s[0] == '-' || s[0] == '+')
                        ? std::string(1, s[0])
                        : std::string();
            return sign + fill + part1.substr(sign.length()) + part2;
        }
        else { // 0 < exponent < part2.length()
            return part1 + part2.substr(0,  exponent) + "." + part2.substr(exponent);
        }
    }
}

using namespace std;

int main(void)
{
    vector<double> nums{ -2000.0005, -1.2345234, -0.000011345, 0, 0.0000001, 0.1342134, 1.1234, 10000 };
    for_each(nums.begin(), nums.end(), [](double &n) {
        string sci = number_to_sci_string(n, 5);
        string nor = sci_string_to_normal(sci);
        cout << n << ": " << sci << " == " << nor << endl;
    });
}

number_to_sci_string looks ok, though you could considerably improve performance by chucking the template, restricting to float, double and long double and using snprintf:

std::string number_to_sci_string(long double number, int precision) {
    std::string s(std::snprintf(0, 0, "%.*Le", precision-1, number), '\0');
    std::snprintf(&s[0], s.size()+1, "%.*Le", precision-1, number);
    return s;
}

Also, I really wonder why you are using a different notion of precision than the standard library...
I suggest you be a bit more flexible in what you accept:

The exponent e00 should be optional.
The fractional part (and decimal point) .00 should be optional.
If there's a fractional part, the integer part should be optional.

Don't use using namespace std;, even in the implementation-file: You don't control what symbols it contains, and there are no guarantees none are added.
The opening brace of main()'s body is, in contrast to all other functions, on a separate line. Why?
Prefer the for-range-loop to std::for_each+lambda. The compiler should compile both to the same result, but the former is simpler and looks better.


Converting Array of Floats to UINT8 (`char`) or UINT16 (`unsigned short`) Using SSE4 The problem is given image in 32 Bit Floating Point Format (float) how to convert it to UINT8 (char) or UNIT16 (unsigned short) in the most efficient way.

Assumptions:

Image is very long, namely don't be troubled with edge cases.
One can not assume the image is in any given range.
Output data must be clipped into the proper range ([0, 255], [0, 2 ^ 16 - 1]). I think the term is to be saturated.
Data should be rounded to nearest integer.
One could use SSE4 operations (Namely, everything but AVX).

I'd rather have a code in C style.
But C++ is also OK (I will translate it on my own).

I tried this simple code for the UINT8 case:

void ConvertToUint8(char* mO, float* mF, float* mB, int numRows, int numCols, int numColsPad, float scalingFctr)
{
    // mB - Background, mF - Foreground

    int ii, jj;

    __m128  floatPx;
    __m128  scalingFactor;
    __m128i uint8Px;

    scalingFactor = _mm_set1_ps(scalingFctr);

#pragma omp parallel for private(jj, floatPx, scalingFactor, uint8Px)
    for (ii = 0; ii < numRows; ii++) {
        for (jj = 0; jj < numCols; jj += SSE_STRIDE) {

            floatPx = _mm_loadu_ps(&mB[(ii * numColsPad) + jj]);
            uint8Px = _mm_cvtps_epi32(_mm_mul_ps(floatPx, scalingFactor));

            uint8Px = _mm_packus_epi32(uint8Px, uint8Px);
            uint8Px = _mm_packus_epi16(uint8Px, uint8Px);

            *(int *) (mO[(ii * numColsPad) + jj]) = _mm_cvtsi128_si32(uint8Px);

        }
    }

}

The code above is based on StackOverflow Q29856006 - SSE intrinsics: Convert 32-bit floats to UNSIGNED 8-bit integers.

But I'm sure there are better ways (For instance, why not load 4 packed __m128 and then store 32 Pixels at once)?

why not load 4 packed __m128 and then store 32 Pixels at once

I think that's 16 pixels, but it's a good plan. The pack instructions were used inefficiently (in the linked question that was not really an issue) and that would be improved by processing more elements simultaneously. For example, something like this:

#define SSE_STRIDE 16

void ConvertToUint8(char* mO, float* mF, float* mB, unsigned numRows, unsigned numCols, unsigned numColsPad, float scalingFctr)
{
    unsigned ii, jj;
    __m128 a, b, c, d;
    __m128i ai, bi, ci, di, p0, p1;
    __m128 scalingFactor = _mm_set1_ps(scalingFctr);
    float *inptr;
    __m128i *outptr;

#pragma omp parallel for private(jj, a, b, c, d, ai, bi, ci, di, p0, p1, inptr, outptr)
    for (ii = 0; ii < numRows; ii++) {
        inptr = &mB[ii * numColsPad];
        outptr = (__m128i*)&mO[ii * numColsPad];
        for (jj = 0; jj < numCols; jj += SSE_STRIDE) {
            a = _mm_loadu_ps(inptr);
            b = _mm_loadu_ps(inptr + 4);
            c = _mm_loadu_ps(inptr + 8);
            d = _mm_loadu_ps(inptr + 12);
            inptr += SSE_STRIDE;
            ai = _mm_cvtps_epi32(_mm_mul_ps(a, scalingFactor));
            bi = _mm_cvtps_epi32(_mm_mul_ps(b, scalingFactor));
            ci = _mm_cvtps_epi32(_mm_mul_ps(c, scalingFactor));
            di = _mm_cvtps_epi32(_mm_mul_ps(d, scalingFactor));
            p0 = _mm_packs_epi32(ai, bi),
            p1 = _mm_packs_epi32(ci, di);
            p0 = _mm_packus_epi16(p0, p1);
            _mm_storeu_si128(outptr++, p0);
        }
    }
}

I've also changed some thing to unsigned, because some useless sign-extension was going on sometimes (depending on how it was compiled). inptr and outptr are now calculated outside the inner loop, normally we can expect the compiler to be pretty clever about that too but compiling with OpenMP support seemed to make Clang less clever, it put the actual multiplication between ii and numColsPad inside the inner loop. That's not good, because on Intel that imul would go to p1, and p1 is already completely packed with the float-to-int conversions and fp-multiplications (eg on Skylake both of those go to p01). That loop should be able to run at 1 iteration every 4 cycles in the best case on most architectures, but with that extra imul in there that wouldn't be possible.

To convert to uint16 something similar can be used, but with _mm_packus_epi32 and no packing to bytes.


extract all textcontent in htmlcollection to array with javascript Here is the raw data
anycasestr = "

refinement

decent

elegant

";

to extract all the textcontent to an array like ["refinement", "decent", "elegant"]
I wrote this code (jquery has been included)
htmlObject = $(anycasestr);
arr = Array.prototype.slice.call(htmlObject[0].getElementsByTagName("div"));
arr_page = [];
for (i = 0; i < 3; i++) {
    arr_page.push(arr[i].textContent);
}

It produces what I want.
I'm just concerned if it is implemented in an elegant way. Could someone take a look at it?
For example, should I have used xpath or something, in terms of computational concerns?

Declare your variables - whenever you assign to or reference a variable without defining it first, you will either (1) implicitly create a property on the global object (which can result in weird bugs), or (2) throw an error, if you're running in strict mode. You currently aren't defining any of your variables. Fix it by putting const (or, when needed, let) in front of them when assigning to them for the first time, eg const htmlObject = $(anycasestr);.
jQuery or DOM methods? You're using jQuery to turn the string into a jQuery collection of elements, but then you're using getElementsByTagName to select children. If you're using jQuery, you can be concise and consistent to use it to select the
 children.. To find children of an element which match a particular tag name, call .find on the jQuery collection - then, you can use .map to turn the found jQuery elements into a collection of just the text of the elements:
const $parent = $(anycasestr);
const arr = $parent.find('div')
  .map((_, child) => child.textContent)
  .get(); // turn the jQuery collection of strings into an array of strings

const anycasestr = `

refinement

decent

elegant

`;
const $parent = $(anycasestr);
const arr = $parent.find('div')
  .map((_, child) => child.textContent)
  .get(); // turn the jQuery collection of strings into an array of strings
console.log(arr);

Or, you can use DOMParser instead. Using DOMParser rather than jQuery to turn the text into a collection of elements can avoid accidental execution of malicious scripts. Example exploit using jQuery:

const anycasestr = `<img src="" onerror="alert('evil')">`;
const $parent = $(anycasestr);

With DOMParser:

const anycasestr = `

refinement

decent

elegant

`;
const doc = new DOMParser().parseFromString(anycasestr, 'text/html');
const arr = [...doc.querySelectorAll('div > div')]
  .map(div => div.textContent);
console.log(arr);

The query string div > div selects
 elements which are direct children of another
. It works exactly the same way as CSS selectors. querySelectorAll is a great tool for concise selection of elements - it can be easier to write and understand at a glance than other methods (like your original htmlObject[0].getElementsByTagName("div")).
Array.prototype.slice.call is a bit verbose - on non-ancient environments, you can use spread syntax instead, like I did above. Creating an array all at once by mapping is also somewhat more elegant than declaring an array then .pushing onto it.
If you had more
 children and wanted to take only the text from the first 3 of them, it'd be more functional to .slice the array of elements instead of putting an iteration count in a for loop:

const anycasestr = `

refinement

decent

elegant

don't include me

don't include me

don't include me

`;
const doc = new DOMParser().parseFromString(anycasestr, 'text/html');
const arr = [...doc.querySelectorAll('div > div')]
  .slice(0, 3)
  .map(div => div.textContent);
console.log(arr);

in terms of computational concerns?

Unless the stuff that needs to be parsed is unreasonably large, performance for this sort of thing is not a concern; better to write clean, readable, maintainable code. If you later find that something is taking longer to run than is ideal, you can identify the bottleneck and then figure out how to fix it. (But this almost certainly won't be the bottleneck.)


Generate dummy customer data Just out of curiosity, I have this code lying around a personal project in which I will generate lots of dummy customer data.
Here's the code:
faker = Faker()
# Faker.seed(random.randint(0, sys.maxsize))

async def get_random_customer_login(count: int, user: CustomerLogin_PydanticIn) -> list:
    data = []

    for i in range(count):
        plain_email = user.plain_email
        user_ip = user.user_ip
        user_id = user.user_id
        client_id = user.client_id
        result = user.result
        fail_cause = user.fail_cause
        process = user.process
        user_agent = user.user_agent
        device_token = user.device_token
        event_timedate = user.event_timedate

        if plain_email is None:
            plain_email = await get_random_email()

        if user_ip is None:
            user_ip = await get_random_ip_address()

        if user_id is None:
            user_id = uuid.uuid4()

        if client_id is None:
            client_id = await get_random_client_id()

        if result is None:
            result = await get_random_result()

            if 'AUTHENTICATION_SUCCESS' not in result:
                fail_cause = await get_random_fail_cause()
                if fail_cause is None:
                    fail_cause = await get_random_fail_cause()

        if process is None:
            process = await get_random_ub_process()

        if user_agent is None:
            user_agent = await get_random_user_agent()

        if device_token is None:
            device_token = uuid.uuid4()

        if event_timedate is None:
            event_timedate = await get_random_utc_timestamp()

        customer_login = CustomerLogin_PydanticIn(
            event_timedate=event_timedate,
            user_id=user_id,
            device_token=device_token,
            user_ip=user_ip,
            user_agent=user_agent,
            client_id=client_id,
            process=process,
            result=result,
            fail_cause=fail_cause,
            plain_email=plain_email)
        data.append(customer_login)
    return data

async def get_random_email() -> str:
    return faker.ascii_company_email()

async def get_random_ip_address() -> str:
    return faker.ipv4_public()

async def get_random_ub_process() -> str:
    return faker.random_element(elements=PROCESS_LIST)

async def get_random_client_id() -> str:
    return faker.random_element(elements=CLIENT_ID_LIST)

async def get_random_result() -> str:
    return faker.random_element(elements=RESULT_LIST)

async def get_random_fail_cause() -> str:
    return faker.random_element(elements=FAILURE_CAUSE_LIST)

async def get_random_user_agent() -> str:
    return faker.user_agent()

async def get_random_utc_timestamp() -> datetime.datetime:
    return pytz.utc.localize(faker.date_time_this_century())

Basically, this function takes in a count of dummy data to be created, and the CustomerLogin pydantic object. The catch is the function will assign some randomly generated value of fields in CustomerLogin that are not provided.
Anyway, this code works. However, I think there's a lot of room to optimize and should I set faker seed?

I can't come up with many performance improvements, but I have a couple of suggestions for you.
Dummy variable in the for loop
You have a for loop that goes
for i in range(count):
    # ...

but you do nothing with i because you just want to execute the function i times.
A very idiomatic way to say you don't need the variable is by writing
for _ in range(count):

It saves people the time of looking for the usage of i inside the loop.
One item per line, end line with comma on long lists
You have a long list of kwargs that you pass in to CustomerLogin_PydanticIn, and in those cases it is better to have a kwarg per line and ending every line with a comma. You almost do this, you are just missing the last line:
customer_login = CustomerLogin_PydanticIn(
    event_timedate=event_timedate,
    # ...
    plain_email=plain_email,
)

This apparently tiny change will be more git friendly if/when you need to add/remove kwargs.
Short circuiting
Finally, for the sake of completeness (as this was already mentioned in other answers) you can use short-circuiting for the None checks:
plain_email = user.plain_email
if plain_email is None:
    plain_email = await get_random_email()

becomes
plain_email = user.plain_email or await get_random_email()

Double fail cause..?
Your code reads:
        if result is None:
            result = await get_random_result()

            if 'AUTHENTICATION_SUCCESS' not in result:
                fail_cause = await get_random_fail_cause()
                if fail_cause is None:
                    fail_cause = await get_random_fail_cause()

In particular, you do fail_cause = await get_random_fail_cause() and if fail_cause is None, you do the exact same line again, but only once more.
What if fail_cause is still None? Maybe you know that get_random_fail_cause doesn't return two Nones in a row?
Assuming you don't know that for sure, you would probably write a while loop:
fail_cause = None
while fail_cause is None:
    fail_cause = await get_random_fail_cause()


The Trip Programming challenge UVA10137 I have the following solution for the Trip problem from Skiena's and Revilla's Programming Challenges (full problem description here).

//#include "stdafx.h"
#include <iostream>
#include <string> //Always import <string> if piping std input to a string in .net
#include<algorithm>
#include<math.h>
#include<fstream>
using namespace std;
int main()
{
    //ofstream myfile;
    //myfile.open("example.txt");

    int n; //number of students sharing trip costs.
    while (cin >> n) {
        if (n == 0) {
            return 0;
        }

        double *ammounts_spent = new double[n];
        double total_spent = 0;
        for (int i = 0; i < n; i++) {
            cin >> ammounts_spent[i];
            total_spent += ammounts_spent[i];
        }
        double ammount_exchanged = 0;
        double ammount_exchanged_below = 0;
        double ammount_exchanged_above = 0;

        double average_spent = total_spent / n;
        double rounded_down_average_spent =(double)((int)(average_spent * 100)/(double)100);
        double rounded_up_average_spent = rounded_down_average_spent + 0.01;
        if (rounded_down_average_spent - average_spent < 0) {
            for (int i = 0; i < n; i++) {
                if (average_spent > ammounts_spent[i]) {
                    ammount_exchanged_below += rounded_down_average_spent - ammounts_spent[i];
                }
                else {
                    ammount_exchanged_above += ammounts_spent[i] - rounded_up_average_spent;
                }
            }

        }
        else {
            for (int i = 0; i < n; i++) {
                if (average_spent > ammounts_spent[i]) {
                    ammount_exchanged_below += average_spent - ammounts_spent[i];
                }
                else {
                    ammount_exchanged_above += ammounts_spent[i] -average_spent;
                }
            }

        }

        ammount_exchanged = max(ammount_exchanged_above, ammount_exchanged_below);
        if (ammount_exchanged == floor(ammount_exchanged)) {
            cout << "$" << ammount_exchanged << ".00\n";

        }
        else {
            cout << "$" << ammount_exchanged << "\n";
        }
    }
}

It works for all debug input given on udebug and even for tricky instances such as

> 4
> 1.01
> 1.01
> 1.00
> 1.00

Where the amount exchanged is $0.00. Yet the UVA online judge is giving me a verdict of wrong answer.

Printing loses precision

Using this input file:

6
0 0 0 0 10000 10000

Your program gives this answer:

$13333.3

The actual answer should be $13333.32.  The program seemed correct, but the printing only printed out 6 digits of precision.  I made this change to your program which made it print out the correct answer:

cout.precision(15);

Better to use integers

It would be safer to use integers throughout your program.  There could be any number of floating point roundoff problems that might show up unexpectedly, especially since 0.01 is not perfectly representable by a double.