texts:
Interested in a review of this code, in particular the (hopefully monadic) bind. I actually put this to good use. It was a nice complement to Guava's Optional, and shorter than:

  Optional.fromNullable(x).or(y);

And I threw in a bind method, which I think lifts it up into monad space.

One question I wasn't sure of the the semantics of multiple calls. Should I carry along the original default value, or does each new value become the default? So in psuedo code, should

  Either.with("A").or("B").or(null)

result in "A" (the original default) or "B"? I thought "B" made more sense.

I'm interested in if I got the monad signature & semantics right.

public class Either<A> {

    private final A value;

    /**
     * constructor sets the default & value the same
     * @param defaultValue
     */
    Either(A value) {
        if (value == null) {
            throw new IllegalArgumentException("Either cannot be null");
        }
        this.value = value;
    }

    /**
     * constructor sets the default & value the same
     * @param defaultValue
     */
    Either(A defaultValue, A value) {
        this.value = (value == null) ? defaultValue : value;
    }

    /**
     * the unit method lifts the value into the monadic space
     *
     * @param value
     * @return an either with the value as default
     */
    public static <A> Either<A> with(A value) {
        return new Either<A>(value);
    }

    /**
     * create a new either using the previous default
     *
     * @param value
     * @return
     */
    public Either<A> or(A value) {
        return new Either<A>(this.value, value);
    }

    /**
     * @return the value, or the default
     */
    public A get() {
        return value;
    }

    /**
     * completes this class as a monad
     *
     * @param f
     * @return an either of the new type
     */
    public <B> Either<B> bind(Function<A, Either<B>> f) {
        return f.apply(value);
    }
}

And here are the unit tests for bind (and sample usage):

static class ToInt implements Function<String, Either<Integer>> {

    private final int defaultInt;

    /**
     * lol closures in java
     *
     * @param defaultInt
     */
    public ToInt(int defaultInt) {
        this.defaultInt = defaultInt;
    }

    @Override
    public Either<Integer> apply(String s) {
        try {
            return Either.with(Integer.parseInt(s));
        }
        catch (NumberFormatException nfe) {
            return Either.with(defaultInt);
        }
    }
};

private static final Function<Integer, Either<Double>> SQRT = new Function<Integer, Either<Double>>() {
    @Override
    public Either<Double> apply(Integer i) {
        return Either.with(Math.sqrt(i));
    }
};

private static final int TEN_THOUSAND = 10000;
private final ToInt TO_INT = new ToInt(TEN_THOUSAND);

// ~=~=~=~=~=~=~=~=~=~=
// Tests

public void bindToIntEmptyEXPECTDefault() {
    // Arrange
    Either<String> a = Either.with("");

    // Act
    Either<Double> b = a.bind(TO_INT).bind(SQRT);

    // Assert
    assertEquals(b.get(), 100.0);
}

public void bindToIntFormatEXPECTDefault() {
    // Arrange
    Either<String> a = Either.with("zoom");

    // Act
    Either<Double> b = a.bind(TO_INT).bind(SQRT);

    // Assert
    assertEquals(b.get(), 100.0);
}

public void bindToIntEXPECTInt() {
    // Arrange
    Either<String> a = Either.with("144");

    // Act
    Either<Double> b = a.bind(TO_INT).bind(SQRT);

    // Assert
    assertEquals(b.get(), 12.0);
}


texts: Test whether a type T is among the types of a tuple

texts:
On SO, I asked for a way to do it without variadics. I also provided a typical "normal" implementation with variadics:

template <typename V, typename T>
struct Is_in_tuple;

template <typename V, typename T0, typename... T>
struct Is_in_tuple <V, tuple<T0, T...> >
{
  static const bool value = Is_in_tuple<V, tuple<T...> >::value;
};

template <typename V, typename... T>
struct Is_in_tuple <V, tuple<V, T...> >
{
  static const bool value = true;
};

template <typename V>
struct Is_in_tuple <V, tuple<> >
{
  static const bool value = false;
};

I'd like a review on the above code. Is it safe / OK / missing something, before I make it my standard way of querying type lists?


texts:
I had some difficulties implementing a redis-like plugin basil.js, particularly the LREM method. The complexity was to loop only once (and not the whole array every time if we have 0 !== count) ascending or descending. My code below works and passes tests, but I was wondering if another smarter implementation (fewer intermediary vars) was possible.

Here is the whole source.

lrem: function (key, count, value) {
    if ('undefined' === typeof count || 'undefined' === typeof value)
        throw new Error('ERR wrong number of arguments for \'lrem\' command');

    var list = this.get(key) || [];

    if (0 === list.length)
        return 0;

    // added here for Basil, even if objects are supported
    // we to not support (yet?) object comparison, too heavy
    if ('number' !== typeof value && 'string' !== typeof value)
        throw new Error('ERR syntax error');

    var index = count >= 0 ? 0 : list.length - 1,
        length = list.length,
        iteration = 0,
        removed = 0;

    // iterate on whole list or stop if we found exactly the right count occurences
    while (iteration < length && (0 === count || (0 !== count && removed !== Math.abs(count)))) {

        if (value === list[index]) {
            list.splice(index, 1);
            removed++;

            // we removed an element, we need to decrease index if we are
            // looping from 0 to length otherwise we'll skip some values..
            if (count >= 0)
                index--;
        }

        iteration++;
        count >= 0 ? index++ : index--;
    }

    if (0 === list.length)
        this.remove(key);
    else
        this.set(key, list);

    return removed;
}


texts:
I have a script that changes the colour, it selects the colour by the id, then it listens what colour was clicked, and if the colour choose was black or whatever other colours, it will do the job.

However, there is a lot of repetition with the if statement. Is there a way to refactor this?

How about if color choosen ${colorClicked} then style bg with = the ${colorAssosiated} or something like that?

Can we re-factor this? But with ES5 best.

var black = document.getElementById("black");
var blue = document.getElementById("blue");
var red = document.getElementById("red");

//01. Listen for button click
var buttonClick = this.addEventListener ("click", function(e) {
    console.log(e.target.id + " button was clicked");
    var colorChosen = e.target.id;

    //02. Change background colour
      if (colorChosen == "black"){
        document.body.style.background = "black";
        console.log('You chose Black!');
      } else if (colorChosen == "blue") {
        document.body.style.background = "blue";
        console.log('You chose Blue!');
      } else if (colorChosen == "red") {
        document.body.style.background = "red";
        console.log('You chose Red!');

      }

});


texts:
I am just trying to improve my coding and designing skills in C++ and for that
I am trying to solve same age old problem of mapping a http request to method.

Could you guys please look at my program and point me to mistakes I am doing with design and coding style?

resource.hpp

#include <functional>
#include <string>

typedef std::function<void(void)> Handler;

enum class RequestMethod {
  GET,
  PUT,
  POST,
  DELETE
};

class Resource {

  public:
    Resource() {}
    void SetMethodHandler(const RequestMethod method, const Handler& callback);
    Handler GetMethodHandler();

    void SetPath(const std::string& path);
    std::string& GetPath();

  private:
    Resource(const Resource& other) = delete;
    Resource& operator=(Resource& rhs) = delete;

    std::string m_path;
    RequestMethod m_method;
    Handler m_callback;
};

resource.cpp

#include "resource.hpp"

void Resource::SetPath(const std::string& path) {
  m_path = path;
}

std::string& Resource :: GetPath() {
  return m_path;
}

void Resource :: SetMethodHandler(RequestMethod method, const Handler& callback) {
  m_method = method;
  m_callback = callback;
}

Handler Resource :: GetMethodHandler() {
  return m_callback;
}

main.cpp

#include "resource.hpp"
#include <memory>
#include <iostream>
#include <map>

void LoginMethodHandler() {
  std::cout << "Code here to handle a login request." << std::endl;
}

int main() {

  using ResourceSharedPtr = std::shared_ptr<Resource>;

  ResourceSharedPtr resource_ptr = std::make_shared<Resource>();
  resource_ptr->SetPath("/login");
  resource_ptr->SetMethodHandler(RequestMethod::GET, LoginMethodHandler);

  /* call to method handler */
  /* ideally in full blown application, logic will be search for path and
     method and call approriate handler */
  resource_ptr->GetMethodHandler()();

  auto path_map = std::make_pair(resource_ptr->GetPath(),resource_ptr);
  return 0;
}


texts: Performane issue for Matlab-like reshape in OpenCV

texts:
I am translating Matlab code to OpenCV. The code involves lots of reshaping of large matrices. As the Matlab reshape differs from OpenCV you can't just use OpenCV reshape.

Here is why: Let's suppose we have a 2x4x3 matrix such as this:

a(:,:,1) =

     1     3     5     7
     2     4     6     8

a(:,:,2) =

     9    11    13    15
    10    12    14    16

a(:,:,3) =

    17    19    21    23
    18    20    22    24

When we perform reshape(a,4,3,2) the result is:

ans(:,:,1) =

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

ans(:,:,2) =

    13    17    21
    14    18    22
    15    19    23
    16    20    24

But if we perform a similar reshape in OpenCV we get:

ans(:,:,1) =

     1     17   11
     5     21   15
     2     18   12
     6     22   16

ans(:,:,2) =

    9     3     19
    13    7     23
    10    4     20
    14    8     24

This is due to the different ways of traversing the matrix in OpenCV and Matlab. Matlab first traverses columns then rows and last depth. OpenCV first traverses depth then rows and last columns.

I have written a function to do a Matlab-like reshape for 3D matrices. First I reshape the input matrix to a row matrix. For the matrix mentioned above, the result matrix will be [1 2 3 ... 24], then I reshape the row matrix to the desired channels. But as can you see, this code involves lots of creating auxiliary matrices and copying and transposing that will not be good for the performance.

Mat matlab_reshape(const Mat &m, int new_row, int new_col, int new_ch)
{
    int old_row, old_col, old_ch;
    old_row = m.size().height;
    old_col = m.size().width;
    old_ch = m.channels();

    Mat m1 ( 1, new_row*new_col*new_ch, m.depth() );

    vector <Mat> p(old_ch);
    split(m,p);
    for ( int i=0; i<p.size(); ++i ){
        Mat t ( p[i].size().height, p[i].size().width, m1.type() );
        t = p[i].t();
        Mat aux = m1.colRange(i*old_row*old_col,(i+1)*old_row*old_col).rowRange(0,1);
        t.reshape(0,1).copyTo(aux);
    }

    vector <Mat> r(new_ch);
    for ( int i=0; i<r.size(); ++i ){
        Mat aux = m1.colRange(i*new_row*new_col,(i+1)*new_row*new_col).rowRange(0,1);
        r[i] = aux.reshape(0, new_col);
        r[i] = r[i].t();
    }

    Mat result;
    merge(r, result);
    return result;
}

Here is an example:

Mat_ <Vec3b> m(2,4);
m(0,0) = Vec3b(1,9,17);
m(0,1) = Vec3b(3,11,19);
m(0,2) = Vec3b(5.1,13,21);
m(0,3) = Vec3b(7,15,23);
m(1,0) = Vec3b(2,10,18);
m(1,1) = Vec3b(4,12,20);
m(1,2) = Vec3b(6,14,22);
m(1,3) = Vec3b(8,16,24);
cout << m << endl;
cout << m.reshape(2,4) << endl;
cout << matlab_reshape(m,4,3,2) << endl;

Performance comparison of reshaping matrices of [24700 X 10 X 1] size to matrices of [130 X 190 X 10] size:

My code:

0.006222
0.006528
0.006716
0.006733
0.006508

Matlab:

0.000039
0.000036
0.000042
0.000035
0.000031


texts: Get a specific value from a big JSON response

texts:
I have this code to access travel time from the Google directions api JSON result:

let jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

                DispatchQueue.main.sync
                    {
                        if (jsonResult.value(forKey: "status") as! String == "OK")
                        {

                            if let routes = jsonResult.value(forKey: "routes") as? NSArray
                            {

                                if let legs = routes.value(forKey: "legs") as? NSArray
                                {

                                    if let duration = legs.value(forKey: "duration_in_traffic") as? NSArray
                                    {

                                        for i in 0..<duration.count
                                        {
                                            let timeDuration = duration[i] as! NSArray

                                            if let time = timeDuration.value(forKey: "value") as? NSArray
                                            {

                                                print("Current Time: \(Int(time[0] as! NSNumber)/60) Min")

                                            }
                                        }

                                    }

                                }

                            }

                        }
                }

It works perfectly fine but it looks like really bad code. But every example i found solves it similar. Has anyone a cleaner solution? Thank you in advance!


texts: Filter option for PFQueryTableViewController in Swift

texts:
I have a PFQueryTableViewController, and have create a separate TableViewController that allows me to select a filter option. When the user selects an option to filter by, I pass the index value back, and then append that Int value to an array. The variable is declared at the top like:

var indexArray = [0]

In my QueryForTable() function, I've written:

    if indexArray == [0] {

        query.orderByDescending("createdAt")

    } else if indexArray == [1] {

        query.orderByAscending("FilmName")

    } else if indexArray == [2] {

        query.orderByDescending("OurRating")

    } else if indexArray == [3] {

        query.orderByAscending("DirectedBy")

    } else if indexArray == [4] {

        query.orderByDescending("UpVoteCount")

    } else if indexArray == [5] {

        query.orderByDescending("DownVoteCount")

    }

This code works fine, and is filtering the option fine.

I'm wondering if there is a better way to write the above code in my QueryForTable() function? Maybe to reduce the amount of code needed?

Any advice appreciated.


texts:
I put together a Haskell function for Knuth's word wrap algorithm. A simplified version of the algorithm is described here.

I've already been told that there are certain aspects of my style that are not very agreeable (e.g. lack of comments and type declarations). However, I'd like to get some opinions on where I might be able to improve the performance of the code itself without resorting to agressive, structure breaking optimization techniques.

import Data.Array
import Data.List
import Data.Ord

knuth m xs = map (concat . intersperse " ") $ split ixs 1 ws
  where
    (_:ixs)           = reverse $ snd (c ! lls)
    ws                = words xs
    ls                = map length ws
    lls               = length ls

    split [] _ ws     = [ws]
    split (x:xs) n ws = let (a, b) = splitAt (x-n) ws in a : split xs x b

    c                 = listArray (0, lls) $ map go [0..lls]
      where
        go 0          = (0, [])
        go j          = minimumBy (comparing fst) $ map (path j) [1..j]
        path j i      = let (x, p) = c ! (i-1) in (lc ! (i, j) + x, i:p)

    lc                = listArray ((1, 1), (lls, lls)) $ concat $ go ls
      where
        go            = map (costs . extras) . take lls . tails
        extras        = lpad lls 0 . map (m -) . zipWith (+) [0..] . scanl1 (+)
        lpad m x      = reverse . take m . (++ repeat x) . reverse
        costs []      = []
        costs (e:es)
          | e < 0     = (1/0) : costs es
          | null es   = [0]
          | otherwise = exp (fromIntegral e) : costs es

The code can be exercised like the following examples:

t1 = knuth 6 "aaa bb cc ddddd"
t2 = knuth 37 "You cant trust code that you did not create yourself. (Especially code from companies that employ people like me.) No amount of source-level verification or scrutiny will protect you from untrusted code."


texts:
I believe that clean and elegant retry code is notoriously difficult, so I'm wondering how the following code could be improved. The retryGet function should have the same interface and contract as http.Get, except for the number of attempts argument, of course.

func retryGet(url string, maxAttempts int) (*http.Response, error) {
    attempts := 0

    if maxAttempts < 1 {
        return nil, errors.New("maxAttempts must be at least 1")
    }

    for {
        attempts++
        response, err := http.Get(url)
        if err == nil && response.StatusCode == http.StatusOK {
            return response, nil
        }

        delay, retry := shouldRetry(maxAttempts, attempts, response)
        if !retry {
            return response, err
        }

        if err == nil {
            defer response.Body.Close()
        }

        time.Sleep(delay)
    }
}

func shouldRetry(maxAttempts, attempts int, response *http.Response) (time.Duration, bool) {
    if attempts >= maxAttempts {
        return time.Duration(0), false
    }

    delay := time.Duration(attempts) * time.Second

    if response != nil && response.Header.Get("Retry-After") != "" {
        after, err := strconv.ParseInt(response.Header.Get("Retry-After"), 10, 64)
        if err != nil && after > 0 {
            delay = time.Duration(after) * time.Second
        }
    }

    return delay, true
}


texts: Initializing the edge values of 2D array in Java

texts:
I have been asked to write Java method code to do the below:

+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+
| 0 |   |   |   | 0 |
+---+---+---+---+---+
| 0 |   |   |   | 0 |
+---+---+---+---+---+
| 0 |   |   |   | 0 |
+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+

I am assuming that they are NOT asking me to create a char[5][5];
i.e :

char[][] grid = {
    {'0','0','0','0','0'},
    {'0',' ',' ',' ','0'},
    {'0',' ',' ',' ','0'},
    {'0',' ',' ',' ','0'},
    {'0','0','0','0','0'}
};

I am assuming that the method will take a 2D array of int i.e int[][] and just reset the fence values to zero, and not changing the inner values. And that the array sizes is not fixed.

Having assumed that, I came up with below answer:

// Original answer
public int[][] initGrid1(int[][] grid) {
    int initVal = 0;
    int maxRows = grid.length;
    int maxCols = grid[0].length;

    for (int rows = 0; rows < grid.length; rows++) {
        for (int cols = 0; cols < grid[0].length; cols++) {
            if (rows == 0 || rows == maxRows - 1) {
                grid[rows][cols] = initVal;
            }
            if (cols == 0 || cols == maxCols - 1) {
                grid[rows][cols] = initVal;
            }
        }
    }
    return grid;
}

The response I got was: Isn't there a simpler way to do this?

Below are some of options I later came up with. I would like to know if you know of simpler way to do. Hoping to do this with Java8 features but found it difficult as individual occurrence needed to be identified for location.

// Option 2
public int[][] initGrid2(int[][] grid) {
    int initVal = 0;
    int maxRow = grid.length - 1;
    int maxCol = grid[0].length - 1;

    for (int rows = 0; rows < grid.length; rows++) {
        grid[rows][0] = initVal;
        grid[rows][maxCol] = initVal;
        for (int cols = 0; cols < grid[0].length; cols++) {
            grid[0][cols] = initVal;
            grid[maxRow][cols] = initVal;
        }
    }
    return grid;
}

If the grid is assumed to be a square.

// Option 3
public int[][] initGrid3(int[][] grid) {
    int initVal = 0;
    int maxlen = grid.length - 1;
    for (int j = 0; j < grid.length; j++) {
        grid[j][0] = initVal;
        grid[j][maxlen] = initVal;
        grid[0][j] = initVal;
        grid[maxlen][j] = initVal;
    }
    return grid;
}

If I traverse through the array with a cursor (c):

// Option 4
public int[][] initGrid4(int[][] grid) {
    int initVal = 0;
    int xL = grid.length;
    int yL = grid[0].length;
    int max = xL * yL;
    for (int c = 0; c < max; i++) {
        int x = c / xL;
        int y = (c == 0) ? 0 : c % yL;
        if (x == 0 || x == (xL - 1)) {
            grid[x][y] = initVal;
        }
        if (y == 0 || y == (yL - 1)) {
            grid[x][y] = initVal;
        }
    }
    return grid;
}

Using Java 8 feature, I was stuck with below, I don't if there is an option here:

grid[0] = IntStream.range(0, grid.length).map(i -> 0).toArray();
...don't know what to do in between.
grid[maxlen-1] = IntStream.range(0, grid.length).map(i -> 0).toArray();

1) So the big question; what is simpler?: (readability and maintainability) or smaller code or using latest features? Of course your assistance should not be just words but also code snippet.

2) And do you agree with my first answer?


texts: Marking a new dataTable row as consumed or cancelled

texts:
This is working code from a dataTable, which shows the function executed after the row is created:

    "createdRow" : function (nRow, data, iDataIndex) {

            var $row = $(datatable.row(nRow).draw().node());
            var $quantityInput=  $row.find("input.quantity");
            var rowClass;

            if (data.wasConsumed || data.wasCancelled){
                $quantityInput.parent().append("<span>"+ $quantityInput.val() +"</span>");
                $row.find("input, select").remove();

                if(data.wasConsumed){
                   rowClass = ".consumed";
                } else if (data.wasCancelled){
                   rowClass = ".cancelled";
                }

                $row.addClass(rowClass);
            }
      }

I added the if(data.wasConsumed || data.wasCancelled) because repeating the shared code in the other two if-statements seems worse to me.
Here the expected results (Action1 is the shared action):

wasCancelled: Action1, Action2
wasConsumed: Action1; Action3
Both false: noAction

My questions:

Are these if-statements poorly designed? (in general and also in this particular example)
How could these be refactored/improved?
Any other suggestions?


texts: Sorting large 1GB file with 100 millions numbers using merge sort

texts:
My task is to sort 1GB file with 100 million numbers using merge sort without recursion. My idea is to split file into 4 pieces, then to 2 and at the end to one file.

#include<iostream>
#include<fstream>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
std::vector <long> vec;

int i=0,numberOfpieces=0;
string line,filename;

//sorting and merge 2 files
void sort_merge(string result, string file1, string file2){

fstream wynik((result+".txt"), std::ios::out);

    string line, line2;
    long s1,s2;
    fstream sorted_1,sorted_2;
    sorted_1.open(file1+".txt");
    sorted_2.open(file2+".txt");

    getline(sorted_1,line);
    s1=atol(line.c_str());
    getline(sorted_2,line2);
    s2=atol(line2.c_str());

    do
    {
        if(s1==s2)
        {
            wynik<<s1<<endl;
            getline(sorted_1,line);
            s1=atol(line.c_str());
            getline(sorted_2,line2);
            s2=atol(line2.c_str());
        }
        if(s1<s2)
        {
            wynik<<s1<<endl;
            getline(sorted_1,line);
            s1=atol(line.c_str());
        }
        if(s1>s2)
        {
            wynik<<s2<<endl;
            getline(sorted_2,line2);
            s2=atol(line2.c_str());
        }
        if(sorted_1.eof())
        {
            do
            {
                wynik<<s2<<endl;
                getline(sorted_2,line2);
                s2=atol(line2.c_str());

            }
            while(!sorted_2.eof());
            break;
        }

        if(sorted_2.eof())
        {
            do
            {
                wynik<<s1<<endl;
                getline(sorted_1,line);
                s1=atol(line.c_str());
            }
            while(!sorted_1.eof());
        }

    }
    while (!sorted_1.eof() ||!sorted_2.eof());}

int main()
{
    fstream file;
    file.open("file.txt");
    if (file.good() == true )
    {
        do
        {
            for(i=1;i<=25000000;i++){ //splittining file into 4 pieces
            getline(file,line);
            vec.push_back(atol(line.c_str()));
            if(file.eof()){ //in case of last piece when quantity of numbers is less than 50
                break;
            }
            }
            sort(vec.begin(), vec.end() );//sorting vector
            std::string nm = std::to_string(numberOfpieces); //creating indyvidual name for piece
            filename="sorted_piece_"+nm+".txt";
            fstream sorted_piece(filename, std::ios::out);

            for ( auto &i : vec ) { //saving into file
                sorted_piece<< i <<endl;
            }

            numberOfpieces++;
            vec.clear();
        }
        while ( !file.eof() );
    }
string outFile;
string sorted1;
string sorted2;
int j=0,counti=0;

for(j=0;j<numberOfpieces;j+=2){//merging into 2 pieces
    std::string j1 = std::to_string(j);
    std::string j2 = std::to_string(j+1);
    std::string c = std::to_string(counti);
    outFile=c+"_sorted_piece";
    sorted1="sorted_piece_"+j1;
    sorted2="sorted_piece_"+j2;
    sort_merge(outFile,sorted1,sorted2);
    counti++;
}
outFile=numbersSorted;
sorted1=1_sorted_piece;
sorted2=2_sorted_piece;
sort_merge(outFile,sorted1,sorted2);//merging into 1 piece

return 0;
}

Unfortunately it is slow and I don't know exactly what is the best way to improve it, because vector sorting has \$O(nlog(n))\$ complexity. Also, my algorithm with merging 2 files have \$O(n)\$ complexity. Maybe splitting into files takes too much time, but I can't hold vectors that are too long in RAM.


texts:
https://leetcode.com/problems/daily-temperatures/

  Given a list of daily temperatures T, return a list such that, for
  each day in the input, tells you how many days you would have to wait
  until a warmer temperature. If there is no future day for which this
  is possible, put 0 instead.

  For example, given the list of temperatures T = [73, 74, 75, 71, 69,
  72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

  Note: The length of temperatures will be in the range [1, 30000]. Each
  temperature will be an integer in the range [30, 100].

Please review for performance.

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

namespace ArrayQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/daily-temperatures/
    /// </summary>
    [TestClass]
    public class DailyTemperaturesTest
    {
        [TestMethod]
        public void ExmapleTest()
        {
            int[] temperatures = {73, 74, 75, 71, 69, 72, 76, 73};
            int[] days = {1, 1, 4, 2, 1, 1, 0, 0};
            CollectionAssert.AreEqual(days, DailyTemperaturesClass.DailyTemperatures(temperatures));
        }

        [TestMethod]
        public void SmallExampleTest()
        {
            int[] temperatures = {73, 72, 73, 74};
            int[] days = {3, 1, 1, 0};
            CollectionAssert.AreEqual(days, DailyTemperaturesClass.DailyTemperatures(temperatures));
        }
    }

    public class DailyTemperaturesClass
    {
        public static int[] DailyTemperatures(int[] T)
        {
            int[] days = new int[T.Length];
            // we are using a stack to remeber all the temps we saw until now,
            // the next time we see one which is higher we pop all the temps which are lower
            Stack<int> stack = new Stack<int>();
            for (int i = T.Length - 1; i >= 0; i--)
            {
                //if the current temp is greater or equals to the top of the stack
                // pop all until found one which is higher temp then T[i]
                while (stack.Count > 0 && T[i] >= T[stack.Peek()])
                {
                    stack.Pop();
                }

                if (stack.Count == 0)
                {
                    days[i] = 0;
                }
                else
                {
                    days[i] = stack.Peek() - i; // number of days between higher temp to i
                }
                stack.Push(i);// we push current temp to the Top of the stack.
            }

            return days;
        }
    }
}


texts: BoundLess Grid, grid with unknown and infinite dimension

texts:
The reason this was made was because of a combination of things. Firstly, it was made for me to get more acquainted with some ECMA2016 syntax. Secondly, this is a useful utility class when working with grids of undefined width and height, including negative points (I couldn't easily find some already made). Besides that, I also tried abstracting the class in a way, returning a function, I think would result in a convenient shorthand way of using the class.

Any pointers would be appreciated. If there's something I could use / use better with the new ECMA2016 features, that'd be awesome to see!

I'm betting using get and set as function names in the class isn't such a great convention to follow, either.

For some reason, only parts of the code are pasted and reformatted weird online. Otherwise, it looks correct in Atom.

GitHub
JsFiddle demonstration

/*
    A grid which can have any bounds and be checked against.
  create: let grid = new BoundlessGrid();
  set: grid( 0,0, "start point" )
  get: let myVal = grid(0,0);
  delete y:  delete grid()[0][0];
  delete x: delete grid()[0];
  iterate: grid().forEach( (x,y,grid)=> {... } );
*/
function forEach(callback) {
    for (let x in this) {
        for (let y in this[x]) {
            callback(x, y, this);
        }
    }
};

class BoundlessGrid {
  constructor() {
    this.grid = { forEach: forEach };
    Object.defineProperty(this.grid, "forEach", { enumerable: "false" });
    // return a function that abstracts the object into
    // something that has friendlier shorthand syntax
    return (x, y, val) => {return this.handler(x, y, val)};
  }

  set(x, y, val) {
    if (!this.grid.hasOwnProperty(x)) {
      let self = this;
      // automatically removes the x grid axis when
      // the last y point is deleted from that x
      this.grid[x] = new Proxy({}, {
        deleteProperty(yAxis, y) {
          delete yAxis[y];
          if (Object.keys(yAxis).length == 0) { delete self.grid[x];}
        }
      });
    }
    this.grid[x][y] = val;
  }

  get(x, y) { if (this.grid.hasOwnProperty(x)) { return this.grid[x][y]; } }

  // Single function that delegates to others
  // by determining inputs
  handler(x, y, val) {
    if (x === undefined) { return this.grid; }
    if (val !== undefined ) {this.set(x, y, val); }
        else { return this.get(x, y); }
  }
}

module.exports = BoundlessGrid;


texts: Finding, substituting and executing values in dictionaries

texts:
I wrote this code for finding, substituting and executing values in dictionary, much like $() bash operator works.

I used nested functions for this, forming hierarchy and encapsulating their names.
But now I'm concern, that this may be an overhead in reading ease and unit testing now
sucks, because I can't write test for concrete nested function in other file.

Should I make this functions global, or this approach is acceptable?

def execute_steps(config):
    def search_for_expand(var_name, stage_name):
        if var_name in config.typedef.evaluators:
            return config.typedef.evaluators[var_name]
        if var_name in config.typedef.stages[stage_name]:
            return config.typedef.stages[stage_name][var_name]
        for stage in config.typedef.stages:
            if var_name in config.typedef.stages[stage]:
                return config.typedef.stages[stage][var_name]
        return var_name

    def execute_abstract(stage_name):
        def substitute_macroses(var_name):
            def is_expandable(value):
                return DEF.EXECUTOR in value

            def expand(var_value):
                for match in DEF.EXECUTOR_RE.finditer(var_value):
                    value_to_expand = match.group(1)
                    var_value = var_value.replace(match.group(0),
                                                  search_for_expand(value_to_expand,
                                                  stage_name))
                return var_value

            var_value = stage[var_name]
            if is_expandable(var_value):
                stage[var_name] = expand(var_value)

        stage = config.typedef.stages[stage_name]
        for k in stage:
            substitute_macroses(k)

    def execute_build(stage):
        execute_abstract(DEF.BUILD)
        out = subprocess.run(stage[config.build_process.result],
                            shell=True,
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return out

    def execute_static(stage, build_out):
        execute_abstract(DEF.STATIC)
        out = subprocess.run(stage[config.static_process.result],
                            shell=True,
                            input=build_out.stdout,
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return out

    def execute_dynamic(stage, static_out):
        execute_abstract(DEF.DYNAMIC)
        out = subprocess.run(stage[config.dynamic_process.result],
                            shell=True,
                            input=static_out.stdout,
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return out

    build_out = execute_build(config.typedef.stages[DEF.BUILD])
    static_out = execute_static(config.typedef.stages[DEF.STATIC], build_out)
    dynamic_out = execute_dynamic(config.typedef.stages[DEF.DYNAMIC], static_out)

    return (build_out, static_out, dynamic_out)


texts:
Description

The ActivityLifecycleHelper uses wrap(Context)to create the class and save a global Application field. It then uses with(ActivityCallbacks) to register android.app.Application.ActivityLifecycleCallbacks on the Application field. Whenever onActivityResumed(Activity) is triggered the class calls a null  OnSaved(Bundle). Whenever onActivitySaveInstanceState(Activity, Bundle) is triggered the class calls a saved/null OnSaved(Bundle). It then unregisters the android.app.Application.ActivityLifecycleCallbacks when onActivityDestroyed(Activity) is triggered. Finally, it returns the base context of the Application field.

ActivityLifecycleHelper.class

public class ActivityLifecycleHelper {

    public interface ActivityCallbacks {
        void OnSaved(Bundle savedInstance);
    }

    private final Application application;

    private ActivityLifecycleHelper(Application application) {
        this.application = application;
    }

    public static ActivityLifecycleHelper wrap(Context context) {
        return new ActivityLifecycleHelper(assertApplication(context));
    }

    public Context with(final ActivityCallbacks callbacks) {
        application.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity a, Bundle b) {}

            @Override
            public void onActivityStarted(Activity a) {}

            @Override
            public void onActivityResumed(Activity a) {
                callbacks.OnSaved(null);
            }

            @Override
            public void onActivityPaused(Activity a) {}

            @Override
            public void onActivityStopped(Activity a) {}

            @Override
            public void onActivitySaveInstanceState(Activity a, Bundle b) {
                callbacks.OnSaved(b);
            }

            @Override
            public void onActivityDestroyed(Activity a) {
                application.unregisterActivityLifecycleCallbacks(this);
            }
        });
        return application.getBaseContext();
    }

    private static Application assertApplication(Context context) {
        final Context application = context.getApplicationContext();
        if (application instanceof Application) return (Application) application;
        throw new NullPointerException("Context must be instance of Application");
    }
}

Usage

public class Usage implements ActivityLifecycleHelper.ActivityCallbacks {

    private final Context context;

    Usage(Context context) {
        this.context = ActivityLifecycleHelper.wrap(context).with(this);
    }

    @Override
    public void OnSaved(Bundle savedInstance) {
        // doingit
    }
}

Reasoning

This is used within a library that when initialized receives a context that will extend from an Application and hooks into any Activity LifeCycle events.

OnResume() will allow the library to reset some things and onSaveInstanceState() is so the library can rebuild.

Needed

Will this approach register/unregister appropriately? Is anything bad design?
 Will this cause any context leaks?


texts: An approach to the network messaging service

texts:
I'm working on the communication module of an ecommerce application. This module takes care of handling messages that come from other apps over the wire.
The awful switch case is never an option so I decided to look for some pattern. While reading about this topic found that Message Factory and Double Dispatch patterns are the very useful in this scenario. I created my own version following those, but there is one issue I cannot figure out (maybe is ok the way I'm doing it). The things is: as I have one class responsible for handling each message, where should I put the code that register each message handler? In the code I've seen that logic is putted together in some method like in the code, but that will imply one line for each message handler, and maybe there is a shortcut for this. I thought about using reflection to discover Message Handlers at runtime but that would be a performance penalty just to avoid a couple lines of code that I can write I forget about them.
Any other idea?

Interface

/// <summary>
/// Represents the entity in charge of handling messages from other applications
/// </summary>
interface ICommunicationService
{
    void RegisterHandler(IMessageHandler handler);

    void ProcessMessage(Message message);
}

Concrete implementation

class CommunicationService : ICommunicationService
{
    private readonly Dictionary<int, IMessageHandler> handlers = new Dictionary<int, IMessageHandler>();

    public void CommunicationService()
    {
        // this is what I want to avoid or improve.
        RegisterHandler(new LoginResponseMessageHandler());
        // ... a line for each handler should go next
    }

    public void RegisterHandler(IMessageHandler handler)
    {
        if (!handlers.ContainsKey(handler.Command))
            handlers.Add(handler.Command, handler);
        else
            handlers[handler.Command] = handler;
    }

    public void ProcessMessage(Message message)
    {
        // Incoming messages that does not have a handler registered will be ignored. This could be or not
        // the desired behavior.
        if (handlers.ContainsKey(message.Command))
            handlers[message.Command].ProcessMessage(message);
    }
}

Message Handlers

interface IMessageHandler
{
    /// <summary>
    /// Gets the identifier of the Command this handler will process.
    /// </summary>
    int Command { get; }

    /// <summary>
    /// When implemented, should contain the logic for handling the requested command.
    /// </summary>
    void ProcessMessage(Message message);
}

Example message handler

class LoginResponseMessageHandler : IMessageHandler
{
    public int MessageId
    {
        get { return 1; } // set the id of the message. this will identify the message across all apps.
    }

    public void ProcessMessage(Message message)
    {
        // here we receive the incomming message and we take care of it...
    }
}

PD: Looking at the code another question came to mind. As you can see I'm using an integer value to identify each message between all apps. Is that a good choice?


texts: Kth to last element of a singly linked list

texts:
Find the kth to last element of a singly linked list

Any comments?

import org.junit.Test;

public class Solution {
  // Find kth to last element of a singly linked list
  // Solution proposed: Use a runner that is k steps ahead
  // when runner hits end of linked list, slow on kth to end element

  public Node n3 = new Node(3);
  public Node n2 = new Node(2,n3);
  public Node n1 = new Node(1,n2);
  public Node head = new Node(0,n1);

  public Node findKthToLast(Node head, int k){
    // place the runner k steps ahead
    if (head == null){
      return null;
    }

    Node runner = new Node(head);
    Node slow = new Node(head);

    for (int i = 0; i < k; i++){
      if (runner.getNext() == null){
        return null;
      }
      else{
        runner = runner.getNext();
      }
    }

    while (runner != null){
      runner = runner.getNext();
      slow = slow.getNext();
    }

    return slow;
  }

  @Test
  void test1th(){
    System.out.println(findKthToLast(head, 1).getValue());
  }

  @Test
  void testLargerThanList(){
    System.out.println(findKthToLast(head, 15));
  }

  @Test
  void testNonDegenerate(){
    System.out.println(findKthToLast(head, 2).getValue());
  }

  public static void main(String[] args) {
    Solution e = new Solution();
    e.test1th();
    e.testLargerThanList();
    e.testNonDegenerate();
  }

}

class Node {
  private int value;

  private Node next;

  public Node(int v) {
    value = v;
  }

  public Node(int v, Node n) {
    value = v;
    next = n;
  }

  public Node(Node n){
    this.value = n.value;
    this.next = n.next;
  }

  public Node getNext(){
    return next;
  }
  public int getValue(){
    return value;
  }
  public void setNext(Node n){
    this.next = n;
  }
}


texts:
Is there a better, more elegant solution to the following method?

Boolean[] spades = new Boolean[10]; // 40 cards deck

foreach (Card card in m_Cards.Where(card => (card.Suit == Suit.Spades)))
    spades[(Int32)card.Rank] = true; // Rank goes from Ace (0) to King (10)

if (spades[0] && spades[1] && spades[2])
{
    points += 3;

    for (Int32 i = 3; i < spades.Length; ++i)
    {
        if (spades[i])
            ++points;
        else
            break;
    }
}

In fact, the function awards 3 points to the player only if he owns Ace, Two and Three... and, always if this condition is satisfied, it awards him a point for every card that extends the sequence. Examples:

Ace + Three + Five = 0 Points
Ace + Two + Three = 3 Points
Ace + Two + Three + Five = 3 Points
Ace + Two + Three + Four + Five + Six = 6 Points

Every kind of better solution is accepted, such as Linq and enumerable extensions.


texts: Count words with given prefix using Trie

texts:
I have been trying to solve this HackerRank problem:

We're going to make our own Contacts application! The application must perform two types of operations:

add name, where  is a string denoting a contact name. This must store  as a new contact in the application.

find partial, where  is a string denoting a partial name to search the application for. It must count the number of contacts starting with  and print the count on a new line.

Given  sequential add and find operations, perform each operation in order.

What I came up is this
class TrieNode():
    def __init__(self):
        self.children = {}
        self.word_count = 0

class Trie():
    def __init__(self):
        self.root = self.get_node()

    def get_node(self):
        return TrieNode()

    def add(self, key):
        crawl = self.root
        for char in key:
            if char not in crawl.children:
                crawl.children[char] = self.get_node()
            crawl = crawl.children[char]
            crawl.word_count += 1

    def get_prefix(self, key):
        crawl = self.root
        for char in key:
            if char not in crawl.children:
                return None
            crawl = crawl.children[char]
        return crawl

    def find(self, key):
        node = self.get_prefix(key)
        return node.word_count if node else 0

The code above is a modification of this from GeeksForGeeks. The modifications that I have done are keeping a word_count for every trie node. This denotes how many words start with the prefix ending in that node's letter. The other modification is using a hashmap to keep children rather than lists.
On HackerRank, 9/11 test cases pass, and the other 2 timeout. I can't figure out where I can optimize this further.
I know of a radix tree that is an optimized version of a normal trie, but that saves on space, rather than time, so I haven't explored that option.
Can anyone help me figure out where I can optimize for time in my code?
Thanks!


texts: Chrome extension -- replace words on a page from a large dictionary

texts:
This works, but is very very slow. Any recommendations on better, less trivial ways of accomplishing this would be appreciated. With a smaller dictionary it's fine, but the dictionary is about 80 different mappings. I also hardly ever work with JS so any  input would be great. Obviously I have not included the dictionary.

var TEXTNODE = 3;

var elements = document.getElementsByTagName('*');

var wordMap = [
    [['word'], 'different word'],
    [['phrase'], 'something else'],
    [['one'], 'two'],

    /* etc for 80 lines */

];

function createRegularExpression(words)
{
    return new RegExp( '\\b(' + words.join('|') + ')s?\\b', 'gi');
}

function replaceText(text)
{
    for (var ii = 0; ii < wordMap.length; ii++)
    {
        var newText = text.replace(createRegularExpression(wordMap[ii][0]), wordMap[ii][1]);
        if (text != newText)
        {
            return newText;
        }
    }

return null;

}

for (var ii = 0; ii < elements.length; ii++)
{
    var element = elements[ii];

    for (var jj = 0; jj < element.childNodes.length; jj++)
    {
        var node = element.childNodes[jj];

        if (node.nodeType === TEXTNODE)
        {
            var text = node.nodeValue;
            var lastText = text;
            var newText = text;;

            /* Have to keep looping because it will only replace the first occurence */

            while (newText != null)
            {
                lastText = newText;
                newText = replaceText(lastText);
            }
            if (lastText != text)
            {
                element.replaceChild(document.createTextNode(lastText), node);
            }
        }
    }
}

UPDATE: Thanks to the awesome response I was able to rework this and it works lighting fast. I'll eventually look into that optimization. Thank you!!!!!!!! Updated code:

var wordMap = {
'word': 'new word',
'this is a phrase': 'new phrase',
'map this': 'to this'

//...
};

var regex = new RegExp('\\b(' + Object.keys(wordMap).join('|') + ')\\b', 'ig');

/* tree walker */
var treeWalker = document.createTreeWalker (
    document.body,
    NodeFilter.SHOW_TEXT,
    null,
    false
);

/* text nodes */
var textNodes = [];

while (treeWalker.nextNode())
{
    textNodes.push(treeWalker.currentNode);
}

/* iterate text nodes and modify in place */
for (var i = 0, len = textNodes.length; i < len; i++)
{
    textNodes[i].nodeValue = textNodes[i].nodeValue.replace(regex,
        function(match)
        {
            var replacementWord = wordMap[match.toLowerCase()];

            /* match capitalization -- wordMap is all lowercase */

            if (match != match.toLowerCase())
            {
                if (match == match.toLowerCase().charAt(0).toUpperCase())
                {
                    replacementWord = replacementWord.charAt(0).toUpperCase() + replacementWord.slice(1);
                }
                else if (match == match.toUpperCase())
                {
                    replacementWord = replacementWord.toUpperCase();
                }
            }

            console.log('replacing ' + match + ' with ' + replacementWord);
            return replacementWord;
        }
    );
}


texts: Generating stock prices using geometric brownian motion

texts:
I am writing a c++ class of "A simple least squares approach" by Longstaff and Schwartz. I have only finished writing a function for creating the stock price paths using geometric brownian motion. I am still a bit of a novice when it comes to writing classes in c++ and I just want to see if there is anything I can improve on with what I have written so far.

That being said, should I include pointers or any other type of data structure to make the code better?

Here is my main.cpp:

#include <iostream>
#include <vector>
#include <random>
#include <time.h>
#include <math.h>
#include "LSM.h"

using namespace std;

int main(){
    const double r = 0.04;          // Riskless interest rate
    const double q = 0.0;           // Divident yield
    const double sigma = 0.20;      // Volatility of stock
    const double T = 1;             // Time (expiry)
    const int N = 2;                // Number of time steps
    const double K = 100.0;         // Strike price
    const double S0 = 102.0;        // Initial stock price
    const int M = 4;                // Number of paths
    const int R = 2;                // Choice of basis for Laguerre polynomial

    LSM Option_value(r,q,sigma,T,N,K,S0,M,R);

    return 0;
}

Here is the header file:

#include <iostream>
#include <vector>
#include <random>
#include <time.h>
#include <math.h>

using namespace std;

#ifndef LSM_H
#define LSM_H

class LSM {
public:
    // Overload Constructor
    LSM(const double, const double, const double, const int, const int, const double, const double, const int, const int);

    // Destructor
    ~LSM();

    // Generate M paths of stock prices (Geometric Brownian Motion)
    vector<double> GBM(const int, const int, const double, const double, const double, const double, const double);

private:
    // Member variables
    double new_r;
    double new_q;
    double new_sigma;
    int new_T;
    int new_N;
    double new_K;
    double new_S0;
    int new_M;
    int new_R;

};

#endif

and here is the .cpp file correlated to the header file above:

#include "LSM.h"

LSM::LSM( const double r, const double q, const double sigma, const int T, const int N, const double K, const double S0, const int M, const int R){
    new_r = r;
    new_q = q;
    new_sigma = sigma;
    new_T = T;
    new_N = N;
    new_K = K;
    new_S0 = S0;
    new_M = M;
    new_R = R;

    vector<double> v;
    v = GBM(new_M, new_N, new_T, new_r, new_q, new_sigma, new_S0);
    for(int i = 0; i < v.size(); i++){
        cout << v[i] << endl;
    }

}

LSM::~LSM(){

}

vector<double> LSM::GBM(const int M, const int N, const double T, const double r, const double q, const double sigma, const double S0){
    double dt =  T/N;
    vector<double> Z;
    vector<double> S;
    S.push_back(S0);
    mt19937 e2(time(0));
    normal_distribution<double> dist(0.0, 1.0);
    for(int i = 0; i < M; i++){
        Z.push_back(dist(e2));
    }
    double drift  = exp(dt*(r-0.5*sigma*sigma));
    double vol = sqrt(sigma*sigma*dt);
    for(int i = 1; i < M; i++){
        S.push_back(S[i-1] * drift * exp(vol*Z[i]));
    }
    return S;
}


texts:
I'm a beginner in JavaScript and I am sure that there is a better way to do it (basic one minute timer from 01:00 to 00:00 running from pageload):

JSFiddle

window.onload=function(){
(function(){
     setInterval(function(){
     cro();
     document.getElementById('unminut').innerHTML="0"+jocminut+":"+jocsecunda1+jocsecunda2;
    },1000);
    }());
}
var jocminut = 1;
var jocsecunda1 = 6;
var jocsecunda2 = 10;
function cro(){
    if(jocsecunda1!=0||jocsecunda2!=0){
        jocsecunda2 -=1;
        while(jocminut==1){
            jocminut-=1;
            jocsecunda1 -=1;
        }
            while(jocsecunda2==-1){
                jocsecunda1-=1;
                jocsecunda2=9;

            }

    }
}


texts:
I am currently trying to teach myself some programming. I have started to work with Python by doing this challenge.

For each test case, I need to find the sum of the self-similarities of a string with each of its suffixes.  For example, given the string ababaa, the self-similarity scores are

6 (because ababaa = ababaa)
0 (because ababaa ≠ babaa)
3 (because ababaa and abaa share three initial characters)
0 (because ababaa ≠ baa)
1 (because ababaa and aa share one initial character)
1 (because ababaa and a share one initial character)

… for a total score of 11.

When I test run it works out fine, however when I run this code with longer strings it takes too long time to run, so the site shuts down the program.  Each input string consists of up to 100000 lowercase characters.

Is this because this code make unnecessary loops? Or what else might the problem be here?

# Solution.py for https://www.hackerrank.com/challenges/string-similarity
import sys
for line in sys.stdin:
  if line.islower():
    line = line[:-1] # line will be compared to suffix
    line_length = len(line)
    points = 0
    for s in xrange(0,line_length):
      suffix = line[s:]
      suffix_length = len(suffix)
      count = 1
      while count < suffix_length+1:
        if line.startswith(suffix[:1]): # if line and first character of suffix mach
          if line.startswith(suffix[:suffix_length]):
            points += len(suffix[:suffix_length])
            break
          else:
            if line.startswith(suffix[:count+1]):
              count += 1
            elif line.startswith(suffix[:count]):
              points += len(suffix[:count])
              break
        else:
          break
    print points


texts:
This is a C++ implementation of the decorator pattern. I am also learning about interfaces and (pure) virtual functions.

#include <iostream>
#include <string>

// interface

class AbstractObject {
protected:
    std::string name;
    virtual void displayTo(std::ostream&) const = 0;
public:
    friend class Decorator;
    friend std::ostream& operator<<(std::ostream&, const AbstractObject&);

    AbstractObject(std::string name) : name(name) {}
};

std::ostream& operator<<(std::ostream& os, const AbstractObject& object) {
    object.displayTo(os);
    return os;
}

// implementation

class Object : public AbstractObject {
protected:
    void displayTo(std::ostream& os) const {
        os << name;
    }
public:
    Object(std::string name): AbstractObject(name) {}
};

class Decorator : public AbstractObject {
protected:
    const AbstractObject& ref_decoratedObject;
    void displayTo(std::ostream& os) const {
        os << name << " decorates ";
        ref_decoratedObject.displayTo(os);
    }
public:
    Decorator(std::string name, const AbstractObject& ref_decoratedObject)
    : AbstractObject(name), ref_decoratedObject(ref_decoratedObject) {}
};

int main() {
    AbstractObject& human = Object("Alice");
    AbstractObject& shirt = Decorator("blue shirt", human);
    AbstractObject& jacket = Decorator("red jacket", shirt);

    std::cout << human << std::endl;
    std::cout << jacket << std::endl;

    getchar();

    return 0;
}


texts:
Make() takes projects with a list of tuples representing project references in the form of (Dependency, Dependent) and returns projects in the order to be build:

static void Main(string[] args)
{
    var projects = new[] { "a", "b", "c", "d", "e", "f" };
    var dependencies = new[] { ("a", "b"), ("a", "c"), ("e", "f"), ("c", "f"), ("f", "d") };
    Console.WriteLine(
        string.Join(", ", Make(projects, dependencies))); // a, e, b, c, f, d
}

Where:

static IEnumerable<string> Make(
    IEnumerable<string> projects,
    IEnumerable<(string Dependency, string Dependent)> references)
{
    var dependents = new HashSet<string>(references.Select(d => d.Dependent));
    var build = new HashSet<string>(projects.Except(dependents));
    return
        !projects.Any() ? Enumerable.Empty<string>() :
        !build.Any() ? throw new Exception("Circled references detected.") :
        build.Concat(Make(
            projects.Except(build).ToArray(),
            references.Where(r => !build.Contains(r.Dependency)).ToArray()));
}

What about run-time complexity of this one? Could it be optimized?


texts: Code to get the IP address and format it to run in nmap

texts:
For scanning my subnet using my IP address, I need to run the following command

nmap -sn 192.168.100.*

I want to extend this functionality such that I don't have to manually specify the first three parts of the IP range myself. I came up with this rough solution.

ip=$( hostname -I | awk '{print $1}' | awk -F. '{print $1; print $2; print $3}' ORS="."; echo -n "*");
nmap -sn $ip

Is there a more cleaner way of achieving the same?


texts:
This is an iterative review. The next iteration is located here: Utilities for Various Builtins #2
This code puts several builtins (And a few non-builtins) into the base classes.

  const XtraUtils = {};
  class Utility {
    constructor(ofWhat){
      this.utils = {};
      this.aidsIn = ofWhat;
    }
    activate() {
      for (var x in this.utils) {
        window[this.aidsIn].prototype[x] = this.utils[x];
      }
    }
    addUtil(util, name) {
      this.utils[name] = util;
    }
  };
  XtraUtils.Number = new Utility("Number");
  XtraUtils.String = new Utility("String");
  XtraUtils.Array = new Utility("Array");
  XtraUtils.Number.addUtil(function(in_min, in_max, out_min, out_max) {
    return (this - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
  }, "map");
  XtraUtils.Number.addUtil(function(inputBase = 10, outputBase = 10){parseInt(this, inputBase).toString(outputBase)}, "toBaseN");
  XtraUtils.Number.addUtil(function(n){
    return Math.pow(this, n);
  }, "toTheNthPower");
  XtraUtils.Number.addUtil(function(){
    return Math.ceil(this);
  }, "ceil");
  XtraUtils.Number.addUtil(function(){
    return Math.floor(this);
  }, "floor");
  XtraUtils.Number.addUtil(function() {
    return Math.sqrt(this);
  }, "sqrt");
  XtraUtils.Array.addUtil(function() {
    const i = this.map(function(item) {
      return typeof item == "number";
    });
    const isAllNums = i.indexOf(false) == -1;
    if (!isAllNums) {
      throw "The array must be all numbers.";
      return;
    };
    let max = 0;
    let isFirst = true;
    this.forEach(function(item) {
      if (isFirst || item > max) {
        max = item;
        isFirst = false;
      };
    });
    return max;
  }, "max");
  XtraUtils.Array.addUtil(function() {
    const i = this.map(function(item) {
      return typeof item == "number";
    });
    const isAllNums = i.indexOf(false) == -1;
    if (!isAllNums) {
      throw "The array must be all numbers.";
      return;
    };
    let min = 0;
    let isFirst = true;
    this.forEach(function(item) {
      if (isFirst || item < min) {
        min = item;
        isFirst = false;
      };
    });
    return min;
  }, "min");
  XtraUtils.Array.addUtil(function() {
    let i = this.map(function(item) {
      return typeof item == "number";
    });
    const isAllNums = i.indexOf(false) == -1;
    if (!isAllNums) {
      throw "The array must be all numbers.";
      return;
    };
    let total = 0;
    var isFirst = true;
    this.forEach(function(item) {
      total += item;
    });
    const mean = total / this.length;
    return mean;
  }, "mean");

Feel free to use the utils if you like.


texts:
I wrote a factorial/permutations/combinations program in Java, and I want to do the same in C#.  I noticed (from various research) that when you use the ulong variable type, the max value is higher than Java's long.  My limitation in the Java version was that the long type was too small to do numbers like 30, or 100.  I wrote a little thing that would test if my hypothesis that C# could stretch the range of my program, but I was proven wrong.  My Java version can reach approximately 24, but the C# goes to roughly 20.  Is there anything I can do to reach my goal?

using System;

namespace codeAdmiral{
  public class Factorial{
     public static void Main(){
        ulong num;
        Console.WriteLine("Enter value");
        num = ulong.Parse(Console.ReadLine());
        ulong factorial = 1;
        for (ulong forBlockvar = num; forBlockvar > 1; forBlockvar--){
                 factorial *= forBlockvar;
        }
        Console.WriteLine("The Factorial for the Given input is:");
        Console.WriteLine(factorial);
    }
  }
}


texts:
I want to check some timing of my (pre-C11) C++ and wrote a class:

class ScopedTimer {
    timespec start_,end_;
    std::string name_;      /// name of this timer (used in output)
    bool active_;           /// if not active, no output is printed
    clockid_t clock_id_;    /// clock type used for this timer

public:
    ScopedTimer(std::string name, clockid_t clock_id = CLOCK_REALTIME, bool active = true):
        name_(name),
        active_(active),
        clock_id_(clock_id)
    {
        clock_gettime(clock_id_, &start_);
    }

    ~ScopedTimer(){
        if (active_){
            clock_gettime(clock_id_, &end_);

            double dt_ms = (end_.tv_sec - start_.tv_sec) * 1000.0 + (end_.tv_nsec - start_.tv_nsec) / 1000000.0;

             cout << "runtime " << name_ << "  " << dt_ms  << "  ms" << endl;
        }
    }

};

It is rather easy to check the running time of a full function:

void foo()
{
 ScopedTimer t("foo");
  do_stuff();
}

or also to check a part of a function:

void findCorners(cv::Mat& img, bool with_timing_output)
{
  cv::Mat gx_dil;
  cv::Mat dil_element_x = createDilElement(1);
    {
     ScopedTimer t("dilation during findCorners",with_timing_output);
     cv::dilate(gx_img, gx_dil, dil_element_x, Point(-1, -1), 5, BORDER_DEFAULT);
    }
}

What do you think about it?


texts: Haskell marking procedure for non-unique lists

texts:
I'm writing a function for generating solutions for a backtracking search problem. To that end, I need to mark an item from a list by removing it from that list, and placing it in a second list.

So I have a pair of lists:

non-marked items
marked items

and my method generates all distinct list pairs of possible markings. Because the list may contain duplicates, I'm selecting the marked item via the index.

Example:

mark 0 ([1,2,2],[]) == ([2,2],[1])
selections ([1,2,2],[]) == [([2,2],[1]),([1,2],[2])]

Code so far:

mark :: Int -> ([a], [a]) -> ([a], [a])
mark i (src,tgt) = (src',tgt')
    where
        src' = let (ys,zs) = splitAt i src in ys ++ (tail zs)
        tgt' = tgt ++ [e]
        e = src !! i

selections :: Eq a => ([a],[a]) -> [([a],[a])]
selections pair@(left,_) = nub [ mark i pair | i <- [0..((length left)-1)] ]

I'm not happy with the implementation: it seems crude, looks ugly, and I think it's obvious that someone with a background in imperative languages wrote this function.

Can this be solved more elegantly, with Array or other list mechanisms, e.g. a fold?


texts: Node JS delete multiple MySQL linked records and delete physical file

texts:
I have the following tables in MySQL:
create table PostSchema
(id int not null primary key auto_increment,
categories int not null,
title varchar(50),
status varchar(20),
comments bool,
body varchar(255),
filename varchar(255),
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP);

create table commentSchema (
id int not null primary key auto_increment,
userID int,
message varchar(255),
image varchar(255),
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
postID int);

Currently..
When a post is created it saves an image in the '/uploads' directory. Path name is referenced in table PostSchema column name filename.
Next, when a comment is created with an image attached it is also saved in '/uploads' directory and the actual path name is referenced in commentSchema in column image.
My Idea
I have a router set up to delete the records from PostSchema and any comments are relevant to PostSchema. On top of that, I'll implement a unlink function to remove any images referenced in the both tables that are held in the /uploads directory.
I have a working code, just want to hear some reviews if there is anywhere I can improve :)
Current working code:
router.delete('/:id', (req, response)=>{
  // Execute query for deleting the post

    // Get filename from database
    db.query("SELECT filename FROM PostSchema WHERE id = ?", req.params.id,(err,fileResult)=>{
      // If error
      if(err){
        return res.status(500).end(err.message);
      }
      // If not an error continue...
      else{

        try {

          // Unlink comments images
          db.query("select image from commentschema where postID = ?", req.params.id, (cErr, cRes)=>{
            if(cErr){
              return res.status(500).end(err.message);
            }
            else{
              if(fs.existsSync(uploadDir + cRes[0].image)){
                fs.unlink(uploadDir + cRes[0].image, (commentFile) => {
                  if (commentFile) throw err;
                });
              }
            }
          });

          // Unlink PostSchema images
          fs.unlink(uploadDir + fileResult[0].filename, (errs)=>{
            // Delete PostSchema + Delete comments
            db.query("delete t1, t2 from postschema t1 join commentschema t2 on t1.id = t2.postid where t1.id = ?;", req.params.id,(errors, results)=>{
              if(errors){
                console.log(errors);
              }
              else{
                db.query("delete from postschema where id = ?", req.params.id, (er, res)=>{
                  if(errors){
                    console.log(errors);
                  }
                  else{
                    // Redirect to all posts page
                    req.flash('success_message', 'Post was succesfully deleted');
                    response.redirect(303, '/admin/posts');
                  }
                });
              }
            });
        });
      }
      catch (e) {
        return res.status(500).end(e.message);
      }
    }
  });
});


texts: Arithmetic expression parsing, and converting infix to postfix notation

texts:
I'm doing a infix to postfix conversion. The code works, but here are some points I want to improve

1) In the line of

while ((!operators.empty())&&(order(operators.top()) >= order(token[0])))

If the condition order changes ( check the stack empty later), there'll be a segmentation fault (because I'm calling operators.top() which is NULL)

2) Convert from char to string using:

 string s(1, operators.top());

which I think constantly create a new variable s and delete it.

How to improve this code?

#include "Parser.h"
#include <sstream>
#include <algorithm>
#include <iterator>

using namespace std;

Parser::Parser()
{
    Postfix="";
    _source="";
    operators=std::stack<char>();
}

string Parser::postfix()
{
    return Postfix;
}

string Parser::source()
{
    return _source;
}

Parser& Parser::parse(string s)
{
    Postfix="";
    _source="";
    operators=std::stack<char>();

    _source=s;
    string token;

    istringstream iss (_source);
    while (iss >> token)
    {
        if (isdigit(token))
            Postfix.append(token).append(" ");

        if (isoperator(token))
        {
            if (operators.empty())
            {
                operators.push(token[0]);
            }
            else
            {
                // Pop until get the same order operator
                while ((!operators.empty())&&(order(operators.top()) >= order(token[0])))
                {
                    string s(1, operators.top());
                    Postfix.append(s).append(" ");
                    operators.pop();
                }
                operators.push(token[0]);
            }
        }
        cout <<Postfix<<"\n";
    }
    while(!operators.empty())
    {
        string s(1, operators.top());
        Postfix.append(s).append(" ");
        operators.pop();
    }
    return *this;
}

bool Parser::isdigit(const string &str)
{
    return str.find_first_not_of("-0123456789") == std::string::npos;
}

bool Parser::isoperator(const string &str)
{
    return (str=="+")||(str=="-")||(str=="*")||(str=="/");
}
int Parser::order(const char& c)
{
    if (c=='+')
        return 1;
    else if (c=='-')
        return 1;
    else if (c=='*')
        return 2;
    else if (c=='/')
        return 2;
    else
        return 0;
}


texts:
Is this implementation of binary search correct? Any special or edge cases that I missed out? Maybe it should be optimized for elements that are less than the first element of the array or greater than the last element?

bool binarySearch (int* array, int arraySize, int element)
{
    if ( arraySize == 0 )
    {
        return false;
    }

    int startPos = 0;
    int endPos = arraySize;
    while ( true )
    {
        int spanSize = endPos - startPos;
        if ( spanSize == 1 )
        {
            break;
        }
        int pivotPos = startPos + (spanSize >> 1);
        if ( element < array[pivotPos] )
        {
            // go left
            endPos = pivotPos;
        }
        else
        {
            // go right
            startPos = pivotPos;
        }
    }
    return element == array[startPos];
}

http://ideone.com/bcGsWG


texts: Simple input class change with vanilla JS

texts:
I am just testing how I solved simple stuff.

Goal: The aim is to expand the width of an input and collapse it.

When mouseover expand,.

When mouseout collapse.

When you have text inside the input keep it expanded.

To me it seems too much, repeating some stuff in JS.
Also thought about adding a debouncer or throttle but was not successful.

There's probably another way to solve it with pure CSS.

HTML:

    2 inputs, 1 is collapsed
    the other is expanded

collapsed

    <input type="text" class="collapsed">

    expanded

    <input type="text" class="expanded">

CSS:

input {
    width: 20px;
    transition: width 1s;
}

.expanded{
    width: 256px;
}

JS:

let collapsedInput = document.querySelector('.collapsed');

const handleMouseOut = () => {
    collapsedInput.classList.remove('expanded');
}

const handleMouseOVer = () => {
    collapsedInput.classList.add('expanded');
}

collapsedInput.addEventListener('mouseover', handleMouseOVer);

collapsedInput.addEventListener('mouseout', handleMouseOut);

collapsedInput.addEventListener('input', () => {
    if(collapsedInput.value !== ""){
        collapsedInput.classList.add('expanded');
        collapsedInput.removeEventListener('mouseout', handleMouseOut);
    } else {
        collapsedInput.classList.remove('expanded');
        collapsedInput.addEventListener('mouseout', handleMouseOut);
    }
})


texts: Displaying the multiples of a given number

texts:
Here's a method I made that's supposed to print out multiples of any numbers up to any quantity:

def DisplayMultiples(multiplesOf, count)
  i = multiplesOf
  while i <= count
    if i % multiplesOf == 0
      puts i
    end
    i += 1
  end
end

Any suggestions on how to improve the code to something more fitting to the Ruby style? I'm coming from a C# background so I'd like to switch things up a bit.


texts:
I'm building a functional React component that allows a list of products to be sorted by various properties. The properties could be top-level or nested properties. And I'd also like a sort order to be defined. As a secondary sort, I'd like a name property to be used.
I have left out the React parts to boil it down to the plain JS.
Here's my first take on it:
sort = [one-of-the-cases]
ascending = [true||false]

const sortFunc = (a, b) => {
  let aParam = null
  let bParam = null
  switch (sort) {
    case 'brand':
      aParam = a.brand.title
      bParam = b.brand.title
      break
    case 'weight':
      aParam = a.metadata.weight
      bParam = b.metadata.weight
      break
    case 'price':
      aParam = a.price.unit_amount
      bParam = b.price.unit_amount
      break
    case 'style':
      aParam = a.metadata.style
      bParam = b.metadata.style
      break
    case 'arrival':
      aParam = b.created
      bParam = a.created
      break
    default:
      aParam = a.brand.title
      bParam = b.brand.title
      break
  }

  // Sort by property, ascending or descending
  if (aParam < bParam) {
    return ascending ? -1 : 1
  }
  if (aParam > bParam) {
    return ascending ? 1 : -1
  }

  // Sort by name
  if (a.name < b.name) {
    return -1
  }
  if (a.name > b.name) {
    return 1
  }

  return 0
}

products.sort(sortFunc)

This seems overly complicated. One idea I have is to flatten the object to eliminate the nested properties, which would make it possible to store the sort param as a variable, and use bracket notation to reference the object property. This would eliminate the switch statement.
Any other ideas for simplifying this complicated sort?


texts: Converting A Map[String, Seq[String]] To A Seq[(String, String)] in Scala

texts:
My current code:

val headers : Map[String, Seq[String]] = ...
//NOTE:  ("key" -> Seq()) is  valid entry
headers.toList flatMap {x => x._2 map { y => (x._1 -> y) }}

This feels clumsy...is there a better way to do this?

Goal

I have a Map[String, Seq[String]] representing all the headers in an HTTP request.   That needs to be translated to a Seq[(String, String)] in order to be passed to a method that expects that headers to be stored in that format.

The code is supposed to convert to this format.   The pair "something" -> Seq("val1", "val2", "val3") would be translated to 3 (String,String)'s.   "something" -> Seq() would be translated to 0.

Concern

I'm still getting the hang of some aspects of the functional approach.  In a lot of cases, this one included, it feels like I'm building hard-to read, overly complex code.  I get that it's just a tolist + two maps, but this seems way less clear than some of the imperative alternatives, for example:

val ret = mutable.Seq[(String,String]()
for (kv <- headers; value <- kv._2) ret :+ (kv._1, value)

or even:

Set[Tuple2[String,String]] ret = new HashSet[Tuple2[String,String]]()
for (key : headers.keySet) {
  for (value : headers.get(key) {
     ret.add(new Tuple2(key, value))
  }
}


texts: Comparing two arrays by index in python in a cleaner way

texts:
I have a simple task I want to do, I want to compare two arrays like this:
array 1 of data:  [0.0, 92.6, 87.8, 668.8, 0.0, 86.3, 0.0, 147.1]
array 2 of data:  [16.7, 0.0, 0.0, 135.3, 0.0, 205.5, 0.0, 93.8]

I want to find the difference between each value by index, and if the difference is lower than 50%, keep the value of the second array in a third array.
array 3 of data : [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 93.8]

Now I believe using a for loop would be the best option, iterating through each array since both have the same length, the code below is part of my code, array1 and array2 are arrays like above.
for scan in sensor:
        #here is some code where we build the Array1 and Array 2 from serial data which is inside the loop.
    if specialcount ==1: #build the first array
      #get data from dict and build first array
      datadict={ 0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], }
    if specialcount ==2: #build the second array.
        #get data from dict and build second array
      datadict={ 0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], }
    if specialcount ==3: #after we build 2 arrays, specialcount goes to 3, and we now compare the arrays
            indexsizeofArray1 = len(array1)
            indexsizeofArray2 = len(array2)
            if indexsizeofArray1 != indexsizeofArray2:
                print ("array mismatch, try again")
                break
            elif indexsizeofArray1 == indexsizeofArray2:
                print("array match, proccessing")
                array3 = [0,0,0,0,0,0,0,0]
                for X in range (indexsizeofArray2):
                    difference = array2[X]-array1[X]
                    fiftypercent = array1[X]-(array1[X]/2)
                    lowerrange = int(array1[X]-fiftypercent)
                    upperrange = int(array1[X]+fiftypercent)
                    if array2[X] in range (lowerrange,upperrange):
                        array3[X]=array2[X]
                    if X == indexsizeofArray2:
                        print("final array: ",array3)
    specialcount +=1

Above is my code ,I do get the result I want of course, but I believe I could make it cleaner mostly because I am in the code transforming float to int as they work with the range function. I am sure there is a cleaner way of doing this , that specialcount==3 is my condition since I build the 2 arrays inside the forloop before as soon as the second array is built, then we, this is inside a loop where I am polling constantly a sensor, the sensor is special in the sense that if I stop polling it and go out of the loop, it will not work again unless I restart it , as such I must be inside this loop all the time.
I am sure I can improve the speed of it if slightly, mostly on the reinitialization of the datadict, since I initialized it before , however inside the loop I populate it with the data up until a certain point, in which I then create the first array of data, and clear it so I can rebuild it.  The goal is to build two arrays of 2 different variables that must be related, once those 2 lists  are built, I need to compare them, ensure that they are not that different and if they are not , pass it to another function , if its too different, the value for that index in the list is 0 .


texts: Daily Coding Challenge solution - day 21

texts:
The Challenge
Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required.

For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.

I believe this code has no errors but if you find any, please do let me know. Otherwise, feel free to use this solution if you get stuck

My Solution

def item_2(element):
    return (element[1]) #Returns second element of tuple for sorting

classes = [(15,50),(51,53),(54,58),(60,70),(61,63),(65,69),(71,83)]
#classes = [(30, 75), (0, 50), (60, 150), (0, 500), (40, 70)]
classes.sort(key=item_2)

print("The following classes will be needed")
while classes:
    item = classes[0]
    index = 0

    end_time = item[1]
    remaining = classes[1:]
    room_bookings = []
    room_bookings.append(item)
    for next_item in remaining:
        if next_item[0] > end_time:
            room_bookings.append(next_item)
            classes.remove(next_item)
            end_time = next_item[1]
    print(room_bookings)
    classes.remove(item)


texts:
I wrote a program to automatically optimize my Brainfuck source files. It works well, but the optimizations are only trivial ones and probably there are still some other points to improve.

def main():

    print "Enter the path of a brainfuck source file you want to optimize"
    path = raw_input()
    if path in ('exit', 'quit', 'close'):
        exit()
    f = open(path, 'r')
    text = f.read()
    f.close()
    cmd = '' # removing comments and whitespaces
    for c in text:
        if c in ('+', '-', '<', '>', '.', ',', '[', ']'):
            cmd += c
    found = True
    while found:
        length = len(cmd)
        found = False
        for i in range(length-1):
            if cmd[i:i+2] in ('+-', '-+', '<>', '><'):
                cmd = cmd[0:i] + cmd[i+2:length] # removing useless instruction pairs
                found = True
    ending = ''
    for i in range(len(path)):
        if path[i] == '.':
            ending = path[i:len(path)]
            path = path[0:i]
            break
    path = path + '_opt' + ending
    f = open(path, 'w')
    f.write(cmd)
    f.close()

if __name__ == '__main__':
    while True:
        main()

EDIT:
I'm considering about removing whole brackets, if it is obvious that they are never called. This is the case, if an opening bracket is directly after a closing bracket (][), because the first loop only breaks if the current cell value is zero and that means, that either the pointer or the cell value has to change to make the second loop work. However, unlike the other optimizations, I can't just remove ][, it should remove everything between [and the matching ] (including [ and ]). Are there any other cases I could remove unnecessary brainfuck code?


texts: Return an object but with one property different

texts:
In the following code I want to return all the same keys and values except the property color. If the name is default, return the color: '#1F2532', if it's different than default, it will call a function that gives me random colors color: pickColor([]). But I think there is a better way to write this instead of repeating code and just changing the property color. How can I do this?

class Project {

  static createProject(data) {
    if (data.name !== 'default') {
      return {
        owner: {
          name: data.owner,
          avatar: data.ownerAvatar
        },
        users: [
          {
            name: data.owner,
            avatar: data.ownerAvatar,
            active: true,
          }],
        name: data.name,
        retrospectives: [],
        color: pickColor([])
      }
    } else {
      return {
        owner: {
          name: data.owner,
          avatar: data.ownerAvatar
        },
        users: [
          {
            name: data.owner,
            avatar: data.ownerAvatar,
            active: true,
          }],
        name: data.name,
        retrospectives: [],
        color: '#1F2532'
      }
    }
  }
}


texts:
I wrote a responsive mixin for Less when I couldn't find a full featured one. Curious what other developers have done to solve this problem and hoping to improve/reduce my code since I'm very new to Less:

It would be invoked like:

element {
    overflow: visible;

    .responsive(768px, 0, min, {
        overflow: hidden;
    });
}

Args are: width, height, min|max, rules
This would set overflow: hidden for > 768px. You could also set max in the declaration to set overflow: hidden for < 768px.

.responsive(@width: 0, @height: 0, @type: min, @rules) {
.responsive-max() when(@type = max) {
    .responsive-max-full() when(@width > 0) and (@height > 0) {
        @media only screen and (max-width: @width) and (max-height: @height) {
            @rules();
        }
    }
    .responsive-max-width() when(@width > 0) and (@height < 1) {
        @media only screen and (max-width: @width) {
            @rules();
        }
    }
    .responsive-max-height() when(@width < 1) and (@height > 0) {
        @media only screen and (max-height: @height) {
            @rules();
        }
    }
    .responsive-max-full();
    .responsive-max-width();
    .responsive-max-height();
}
.responsive-min() when(@type = min) {
    .responsive-min-full() when(@width > 0) and (@height > 0) {
        @media only screen and (min-width: @width) and (min-height: @height) {
            @rules();
        }
    }
    .responsive-min-width() when(@width > 0) and (@height < 1) {
        @media only screen and (min-width: @width) {
            @rules();
        }
    }
    .responsive-min-height() when(@width < 1) and (@height > 0) {
        @media only screen and (min-height: @height) {
            @rules();
        }
    }
    .responsive-min-full();
    .responsive-min-width();
    .responsive-min-height();
}
.responsive-max();
.responsive-min();
}


texts: Automate the Boring Stuff - Collatz Exercise

texts:
I wrote the following code for the Collatz exercise: The Collatz Sequence

Any feedback is appreciated.

  Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.

def collatz(n):
    while n > 1:
        if n % 2 == 0:
            n = int(n // 2)
            print (n)
        elif n % 2 == 1:
            n = int(3 * n + 1)
            print (n)

n = int(input("Enter a number: "))
collatz (n)


texts: Find sum of number of times that each character of source occurs in the target

texts:
I wrote the following code in response to this question "find sum of number of times that each character of source occurs in the target", is there any better solution for it?

Analysis

Target is alex alexander
Source is ardx
Characters of source that exist in target are like a--x-a--xa-d-r
Total is 7.

Code

    String target = "alex alexander";
    String source = "ardx";
    char[] a = source.toCharArray();
    int occurrences = 0;

    for (int i = 0; i < a.length; i++) {
        String t = target;
        int index = t.indexOf(a[i]);

        while (index != -1) {
            occurrences++;
            t = t.substring(index + 1);
            index = t.indexOf(a[i]);
        }

    }
    System.out.println(occurrences);
}

Output

7


texts: Building a nested tree structure from an ordered list

texts:
I have an ordered list in this format. The data is ordered by path so that the list will never contain a child before the parent in the list.

id, path
1, null
2, null
3, 1
4, 1-3
5, 2
6, 2-5

Each entry contains the path it needs to place itself in the tree structure.

The catch is that the list doesn't always start with nulls sometimes the list starts in the middle of a path.

id, path
10, 2-5-6
11, 2-5-6-10
12, 2-5-6-10
13, 2-5-6-10-11
14, 2-5-6-10-11-13
15, 2-5-6-10-12

In this case I need to treat the first record in this list as the root and build out everything else as normal without permanently editing the paths of any items in the list.

    function nestComments(comments) {
    var nested = {
        "Comments": []
    };
    if (!comments) return nested;

    var normalize,
        path,
        level;

    for (var i = 0; i < comments.length; i++) {

        var comment = comments[i],
            tree = nested,
            isValid = true;

        if (comment.path) {
            path = comment.path.split('-');

            //permalinked comments don't have null paths
            //keep track of the permalink the path
            //adjust children paths to treat permalink path like the root

            //if the first comment has a path then we need to normalize the path
            if (i === 0) {
                normalize = path.length;
            }

            if (normalize) {
                //normalize the path based on the peramlink's path
                path.splice(0, normalize);
            }

            for (var j = 0; j < path.length; j++) {
                var step = path[j];

                var index = tree.Comments.findIndex(x => x.comment_id.toString() === step);
                if (index < 0) {
                    isValid = false;
                    break;
                }
                tree = tree.Comments[index];

                tree.Comments = tree.Comments || [];
            }

        }

        if (!path || path.length === 0) {
            level = 0;
        } else {
            level = path.findIndex(x => x === path[path.length - 1]);
        }

        if (!trimComments(level, tree) || !isValid) {
            continue;
        }

        tree.Comments.push(comment);

    }
    return nested;
}

function trimComments(level, tree) {
    var result;
    switch (level) {
        case 0:
            result = true; // limit based on the sql query
            break;
        case 1:
            result = tree.Comments.length < 5;
            break;
        case 2:
            result = tree.Comments.length < 5;
            break;
        case 3:
            result = tree.Comments.length < 3;
            break;
        case 4:
            result = tree.Comments.length < 2;
            break;
        case 5:
            result = tree.Comments.length < 1;
            break;
        case 6:
            result = tree.Comments.length < 1;
            break;
        default:
            result = false;
            break;
    }
    return result;
}

var comments = nestComments([{comment_id: 4, path:"1-2-3"},{comment_id: 5, path:"1-2-3-4"},{comment_id: 6,path:"1-2-3-4"}, {comment_id: 7, path:"1-2-3-4-6"},{comment_id: 8, path:"1-2-3-4-6"}, {comment_id: 9, path:"1-2-3-4-6-7"}, {comment_id: 10, path:"1-2-3-4-6-7-9"}, {comment_id: 11, path:"1-2-3-4-6-8"}]);

console.log(comments);

Please help me improve this code.


texts:
Function Enumerate-Properties($fileName)
{
    $path = (Get-Item $fileName).FullName
    $shell = New-Object -COMObject Shell.Application
    $folder = Split-Path $path
    $file = Split-Path $path -Leaf
    $shellfolder = $shell.Namespace($folder)
    0..287 | Foreach-Object {'{0} = {1}' -f $_, $shellfolder.GetDetailsOf($null, $_)}
}
Function Find-Property($fileName, $PropertyName)
{
    $shell = New-Object -COMObject Shell.Application
    $path = (Get-Item $fileName).FullName
    $folder = Split-Path $path
    $file = Split-Path $path -Leaf
    $shellfolder = $shell.Namespace($folder)
    $shellfile = $shellfolder.ParseName($file)
    $found = $false
    0..287 | Foreach-Object {
        $test1 = $shellfolder.GetDetailsOf($null, $_)
        if($PropertyName -eq $shellfolder.GetDetailsOf($null, $_))
        {
            $found = $true
            return $_
            break
        }
    }
    if(!$found)
    {
        Write-Host "Property "$PropertyName " was not found"
    }
}
Function Get-PropertyValue($fileName, $property)
{
    $shell = New-Object -COMObject Shell.Application
    $path = (Get-Item $fileName).FullName
    $folder = Split-Path $path
    $file = Split-Path $path -Leaf
    $shellfolder = $shell.Namespace($folder)
    $shellfile = $shellfolder.ParseName($file)
    return $shellfolder.GetDetailsOf($shellfile,$property)
}
Function Create-List3($files, $property)
{
    $array = @()
    $propertyNum = Find-Property $files[0] $property
    foreach($file in $files)
    {
        $file | Add-Member -MemberType noteproperty -Name $property -Value (Get-PropertyValue $file $propertyNum).toString() -force
        $array = $array + $file
    }
    return $array
}

This code is designed to be used in something like the following fashion:

$files = dir *.mp4
$propery = "Bit rate"
$array = Create-List3 $files $property
$array | Format-Table Name, Length, $property -auto

As far as I can tell, this code works when you give it a nice amount of .mp4 files. It fares less well when handed other things (folders and the like), the break statement in the Find-Property does nothing (and there has to be a better way to do that anyway).

I am mostly concerned that while this is valid Powershell code, it is very poor Powershell code, in that it is written in a psudo-C# style (that is where I am coming from) and not a Powershell style.

Additionally, I am positive that there easier ways to set up the COM Objects that I am using, and parsing filenames (and reusing them, but that is more complex probably).

How can I make this code better idiomatic Powershell?


texts:
I've written this Card component which is composed of thumbnail image, name, symbol, total_volume, current_price, and price_change_percentage_24h.

I want to refactor my renderPriceChange function since it's using the same pattern.
const renderPriceChange = (price) => {
  if (price > 0) {
    return (
      <Text style={styles.rise}>
        <AntDesign name='caretup' color='#03AE9D' size={10} />{' '}
        {percentageFormat(item.price_change_percentage_24h)}%
      </Text>
    );
  } else {
    return (
      <Text style={styles.drop}>
        <AntDesign name='caretdown' color='#fb2c33' size={10} />{' '}
        {percentageFormat(item.price_change_percentage_24h)}%
      </Text>
    );
  }
};

How to make it look cleaner with smart and less code?


texts: RxSwift iOS Observable FIFO Queue Implementation in Swift 2

texts:
I am trying to develop an Observable queue that executes given Observable chains one at a time. The code will be used to encode videos on an iPhone and only one queue will be needed per launch, therefore it is declared as static. It seems to work but I am not sure I covered all the edge cases.

Below is the implementation as well as the test. I use Swift 2 with the latest supported RxSwift pod.

class SomeObject {}

// Implementation
extension SomeObject {
    // Will be created once per runtime
    static let queueSubject: PublishSubject<Observable<Int>> = PublishSubject()

    // Will be called once per runtime
    static func consumeQueue() {

        let queueName = "someQueue"
        let queue = dispatch_queue_create(queueName, DISPATCH_QUEUE_SERIAL)
        let scheduler = SerialDispatchQueueScheduler(queue: queue, internalSerialQueueName: queueName)
        let lock = NSLock()

        lock.unlock()

        _ = queueSubject
            .observeOn(scheduler)
            .doOnNext({ _ in
                print("queue locking")
                lock.lock()
                print("queue locked")
            })
            .flatMap({
                return $0.observeOn(scheduler).subscribeOn(scheduler)
            })
            .doOnNext({
                print("queue unlocking")
                lock.unlock()
                print("queue unlocked")
            })
            .subscribeOn(scheduler)
            .subscribe(
                onNext: { _ in
                    print("queue onNext")
                },
                onError: { _ in
                    print("queue error")
                },
                onCompleted: {
                    print("queue completed")
                },
                onDisposed: {}
        )
    }
}

// Test
extension SomeObject {
    static func testQueue() {
        SomeObject.consumeQueue()

        let test1 = Observable<Int>.timer(1.0, scheduler: MainScheduler.instance)
                .doOnCompleted({
                    print("test 1")
                })

        let test2 = Observable<Int>.timer(1.0, scheduler: MainScheduler.instance)
                .doOnCompleted({
                    print("test 2")
                })

        SomeObject.queueSubject.onNext(test1)
        SomeObject.queueSubject.onNext(test2)
    }
}


texts:
I am working on a website, and due to some reasons, they want my code to be as short as possible. I have, from my side, tried everything to shorten this code.

So if possible, can you all also help me in making this code shorter?  I know that there are vulnerabilities, and I will solve them later.

For now, just help me make it shorter. There are two files that need to be shortened.

first.php

<?php
$LocationId = (isset($_GET['l'])) ? $_GET['l'] : null;
if( $LocationId )
{ //Make connection to DB
    $DBConn = mysqli_connect("localhost","root","","url") or die("Connection Error");
//Selects the URL which mathces the ID or say shortcode
    $Resut  = mysqli_query($DBConn, sprintf("SELECT url FROM url WHERE id LIKE '%s' LIMIT 0,1", mysqli_real_escape_string($DBConn, $LocationId))) or die( mysqli_error() );
    if( $Resut )
    {   $Row = mysqli_fetch_array($Resut);
        if( isset($Row['url']) && !empty($Row['url']) ) //checks whether URL exist or not
        {        header('HTTP/1.1 301 Moved Permanently');
            header(sprintf('Location: %s', $Row['url'])); //Redirects the user to the long URL
            exit;   }
        else
        {   echo "Invalid URL"; }}} //If wrong ID given by user then returns this error
?>

second.php

<?php
$con=mysqli_connect("localhost","root","","url") or die("Connection Error");

$url = $_POST['url'];
$sql=mysqli_query($con,"INSERT INTO url (url)VALUES('$url')");

$result = mysqli_query($con,"SELECT * FROM url WHERE url='$url'");
while($id = mysqli_fetch_array($result))
  {
  echo " URL Shortened Successfully! ".'<br>'."Your shortened URL is ";
  echo 'http://localhost/redirect/' . $id['id'];
  }

mysqli_close($con);
?>

And one more thing: there are 6-7 lines of whose meaning I can't understand, so please explain this to me this as well. Those 6-7 lines are as follows:

 $Resut  = mysqli_query($DBConn, sprintf("SELECT url FROM url WHERE id LIKE '%s' LIMIT 0,1", mysqli_real_escape_string($DBConn, $LocationId))) or die( mysqli_error() );
    if( $Resut )
    {   $Row = mysqli_fetch_array($Resut);
        if( isset($Row['url']) && !empty($Row['url']) ) //checks whether URL exist or not
        {        header('HTTP/1.1 301 Moved Permanently');
            header(sprintf('Location: %s', $Row['url'])); //Redirects the user to the long URL
            exit;   }


texts:
Question

We are given an array (indexed from 1) of N elements on which we make M queries:

add(Left, Right, X) - all the elements between the position Left and Right (1<=Left<=Right<=N) are raising their values with X.

After all the operations are completed, print the array.

example

Array: 1 1 1 4 5 6

operations: (1, 5, 2), (2, 3, 10)

Final array: 3 13 13 6 7 6

Discussion

I managed to produce the expected output but I was wondering if this code can be simplified using a queue data structure somehow?

The complexity of this code is M*N (please correct me if I am wrong) - This naive approach is looping all the operations for every element of the input array.

Naive approach

#include <iostream>

using namespace std;

int Queue[1000], backInd;

void push(int i)
{
    ++backInd;
    Queue[backInd] = i;
}

void applyOperations(int input[], int operations[], int N, int M)
{
    for (int x = 0; x < N; ++x){
        int item = input[x];
        int offset = 0;
        for (int op = 0; op < M; ++op)
        {
            if (x + 1 >= operations[op + offset] && x + 1 <= operations[op + offset + 1])
            {
                item += operations[op + offset + 2];
            }
            offset += 2;
        }
        push(item);
    }
}

int main()
{
    backInd = -1;
    frontInd = 0;
    int input[] = {1, 1, 1, 4, 5, 6};
    int operations[] = {1, 5, 2, 2, 3, 10};
    int N = 6;
    int M = 2;

    applyOperations(input, operations, N, M);

    for (int x = 0; x < N; ++x) {
        cout << Queue[x] << " ";
    }

    return 0;
}