texts:
I am trying to find all the SE answers which contain "on context" in a single sentence, in the meanwhile the "on" is not a part of common collocations in any form, such as "depending on context", "depend on context", "Based on context", "rely on context", "Counting on Context", "Count on Context" ...

Here is the code

SELECT Id, CreationDate, Score, Body
INTO #tb_postcount
  FROM Posts
  WHERE Body LIKE '% on context%'
    AND PostTypeId=2

SELECT Id AS [Post Link] from #tb_postcount
WHERE Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%depend%on context%'
and Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%base%on context%'
and Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%rely%on context%'
and Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%count%on context%'
and Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%lean%on context%'
and Body collate SQL_Latin1_General_CP1_CI_AS NOT LIKE '%take%on context%'

It works well, at least to me:) Could someone please take a look at it?

Is there a more efficient way to do the job?


texts: Usage of Decorator pattern in baking program

texts:
Is this a good usage of Decorator pattern?  I'm trying to use Interfaces instead of Abstract classes.

(Component) Interface

public interface IBake
    {
        string Name { get; }
        double Price { get; }
   }

(Concrete Component)

 public class BakeBase : IBake
    {
        private string m_Name = "Cake Base";
        private double m_Price = 200.00;

        public string Name
        {
            get
            {
               return m_Name;
            }
        }

        public double Price
        {
            get
            {
                return m_Price;
            }
        }

        public string GetCakeCost()
        {
            return "Normal cake is:" + m_Price + "and Tax is: " + (this.m_Price * 0.08f);
        }

    }

Decorator

class CherryDecorator
{
    IBake _iBakeModel;

    public CherryDecorator(IBake iBakeModel)
    {
        _iBakeModel = iBakeModel;
    }

    public string GetName()
    {
        return "Cherry Decorated Cake!";
    }
    public double GetPrice()
    {
        return _iBakeModel.Price + 100;
    }
}

Decorator

class CreamDecorator
    {
        IBake _iBakeModel;

        public CreamDecorator(IBake iBakeModel)
        {
            _iBakeModel = iBakeModel;
        }

        public string GetName()
        {

            return "Cream Decorated Cake!";

        }
        public double GetPrice()
        {

            return _iBakeModel.Price + 50;

        }
    }

Client

 public class Client
{
static void Main(string[] args)
{

    BakeBase bakebase = new BakeBase();
    Console.WriteLine(bakebase.GetCakeCost());
    Console.ReadKey();
    Console.WriteLine(Environment.NewLine);
    CherryDecorator cd = new CherryDecorator(bakebase);
    Console.WriteLine(cd.GetName() + "  " + cd.GetPrice());
    Console.ReadKey();

    Console.WriteLine(Environment.NewLine);
    CreamDecorator crd = new CreamDecorator(bakebase);
    Console.WriteLine(crd.GetName() + "  " + crd.GetPrice());
    Console.ReadKey();

}
}

I'm getting the following, which is not the right total:


texts: Rearranging numbers of an array like a wave

texts:
Given an array of integers, sort the array into a wave like array and
  return it, In other words, arrange the elements into a sequence such
  that a1 >= a2 <= a3 >= a4 <= a5.....

  Example

  Given [1, 2, 3, 4]

  One possible answer: [2, 1, 4, 3]
  Another possible answer : [4, 1, 3, 2]

  NOTE: If there are multiple answers possible, return the one thats
  lexicographically smallest.  So, in example case, you will return [2, 1, 4, 3]

My approach:

public class Solution {
    public ArrayList<Integer> wave(ArrayList<Integer> A) {

        Collections.sort(A);
        int swap1, swap2,temp1,temp2;
        //We will have to swap all the odd numbered elements with the even numbered elements
        //such that all numbers with a gap 0f 1 are sorted
        for( swap1= 0, swap2 = swap1 + 1; swap1 <= A.size()- 2; swap1 = swap1+2,swap2 = swap2+2 )
            {
                //Check if swap1 reaches last element
                if( (swap1 == A.size() - 1) || (swap2 == A.size()) )
                    break;
                else
                    {
                        temp1 = A.get(swap1);
                        temp2 = A.get(swap2);
                        A.set(swap1,temp2);
                        A.set(swap2, temp1);
                    }
            }
        return A;
    }
}

I have the following questions regarding my code:

How can I further optimize my code?  (I am unable to solve these questions within the prescribed time limit. What can I do?)
Is there any better approach to do this question?
Have I violated any convention in coding?
Are there any redundancies in my approach?

Reference


texts: React props children with List and Spinner Loader

texts:
I have a custom component with a List. I need to know if this way is the best for show a Spinner while the fetch is working.

I'm using child props for that, but I don't know if this way is the correct.

import React, { Component, PropTypes } from 'react';
import demoData from './demodata';
// Other import stuff...

export default class HomeScreen extends Component {
  // Constructor component
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2
    });

    this.state = {
      dataSource: ds.cloneWithRows(demoData),
      loading: true
    };

    // Service for fetching data
    this.service = new ServiceApp();
  }

  componentDidMount() {
    this
      .fetchData();

  }

 // Simulate fetchData
 fetchData() {
      const self = this;
      setTimeout(() => {
         self.setState({
            loading: false
         });
      }, 4000);
  }

  render() {
    const component = this.state.loading ? <Spinner /> : (<ListView
      style={styles.container}
      dataSource={this.state.dataSource}
      renderRow={data => <Row {...data} />} />);

    return (
        <Content>
          {component}
        </Content>
    );
  }
}


texts: Making JSON requests to fetch relationships asynchronously

texts:
I would like to refactor the fetchRelationships function to use async await. I am not sure what the best way is to do it as this code contains nested .then at response.json().then((json) =>....

Could sby pls post the refactored version?

export const fetchRelationshipsError = (error) => {
  return {
    type: FETCH_RELATIONSHIPS_FAILURE,
    payload: { error }
  };
};

export const fetchRelationshipsRequest = () => {
  return { type: FETCH_RELATIONSHIPS_REQUEST };
};

export const fetchRelationshipsSuccess = (relationships) => {
  return {
    type: FETCH_RELATIONSHIPS_SUCCESS,
    payload: relationships
  };
};

export const fetchRelationships = (url) => {
  return (dispatch) => {
    dispatch(fetchRelationshipsRequest());

    fetch(url, config)
    .then((response) => {
      const responseObj = {
        response: response,
        payload: response.json().then((json) => {
          return { body: json }
        })
      };

      if (!response.ok) {
        const error = new Error(response.statusText);
        responseObj.payload.then((response) => {
          show_error_alert(response.body);
          dispatch(fetchRelationshipsError(response.body));
        });
        throw error;
      }

      return responseObj.payload;
    })
    .then((response) => {
      dispatch(fetchRelationshipsSuccess(response.body))
    })
    .catch((error) => { console.log('Request failed', error); });
  };
};


texts: Scoring matches of a game - reducing duplicated code

texts:
I'm writing a small application to score matches of a game. (There are two "teams" on each "alliance", and two alliances play each other in a match.) I have  a "logic" class that handles the values of different scoring elements for each team, and calculates that team's score.

Instead of writing getters and setters for each member of the "logic" class, the UI class is a friend of the logic class and can access the private "scoring element" members of that class. Whenever a user enters something into the UI, the UI sets the "scoring element" member of that class--but it will pick a different "alliance" and "team" depending on which control was changed. This leads to a lot of code duplication that I want to avoid.

Here is an example:

void BlockParty::on_comboBox_red_A_currentIndexChanged(int index)
{
    switch (index) {
        case 0 :
            score_red->ramp_position_A = BlockPartyLogic::RAMP_OFF;
            break;
        case 1 :
            score_red->ramp_position_A = BlockPartyLogic::RAMP_PARTIAL;
            break;
        case 2 :
            score_red->ramp_position_A = BlockPartyLogic::RAMP_COMPLETE;
            break;
    }
    score_red->update_internals();
}

(ramp_position_A is an example of a "scoring element".) The above function needs to be repeated three more times, as on_comboBox_red_B_currentIndexChanged, on_comboBox_blue_A, and on_comboBox_blue_B.

Is there a good way to consolidate the logic into a single function that can call each slot with different parameters?

For example, something like the following:

void BlockParty::on_comboBox_currentIndexChanged(int index, Score* score)
{
    switch (index) {
        case 0 :
            score->ramp_position_A = BlockPartyLogic::RAMP_OFF;
            break;
        case 1 :
            score->ramp_position_A = BlockPartyLogic::RAMP_PARTIAL;
            break;
        case 2 :
            score->ramp_position_A = BlockPartyLogic::RAMP_COMPLETE;
            break;
    }
    score->update_internals();
}

I could make a giant switch statement to take care of the logic, but that doesn't actually address the problem.


texts: Correctness and Performance of graph plotting on R

texts:
Current State:

I have two CSV files, their sample attached below:

FileOutputWithoutBuffer-Metrics.csv

File Length , Non-Buffered Time Taken (ns)
1000 , 5499114
2000 , 10971957
3000 , 15736008
4000 , 18970057
5000 , 22173215
6000 , 24612263
7000 , 26118520
8000 , 29934220
9000 , 31919477
10000 , 34940645

FileOutputWithBuffer-Metrics.csv

File Length , Buffered Time Taken (ns)
1000 , 412991
2000 , 224509
3000 , 269990
4000 , 461664
5000 , 485668
6000 , 479069
7000 , 413657
8000 , 438734
9000 , 760068
10000 , 576458

What I want:

I want to plot a compare and contrast graph between these two CSV files corresponding to their File Length column.

What I did:

I wrote the below script for the same:

# This line has to be updated on every place, possible.
scriptPath <- "XXX/XXX/XXX/XXX";

# Read in all csv files.
FileOutputWithoutBufferMetrics <- read.csv(file = file.path(scriptPath, "FileOutputWithoutBuffer-Metrics.csv"), header = TRUE, sep = ",");
FileOutputWithBufferMetrics    <- read.csv(file = file.path(scriptPath, "FileOutputWithBuffer-Metrics.csv"), header = TRUE, sep = ",");

FileOutputMetircs <- merge(FileOutputWithoutBufferMetrics, FileOutputWithBufferMetrics, by=c('File.Length'), all=T);
#colnames(FileOutputMetircs) <- c("File Length", "Non-Buffered OutputStream Time", "Buffered OutputStream Time");
show(FileOutputMetircs);

# Install extra packages :- ggplot2, reshape2.
list.of.packages <- c("ggplot2","reshape2");
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])];
if(length(new.packages)) {
    install.packages(new.packages)
}
require(ggplot2);
require(reshape2);

# Create a graph of FileOutputStream.
df <- melt(FileOutputMetircs, id.vars = 'File.Length', variable.name = 'Time');
ggplot(df, aes(File.Length, value)) + geom_line(aes(colour = Time));

And got this output:

Where help is needed:

First, since I am very new to ggplot. Therefore, need assurity on the correctness of my R script.
Other ways (performace-wise) to optimize the script.

Thanks!.


texts: Returning an existing data frame with four new columns

texts:
I'm trying to implement a function that given a data frame returns the same data frame with four columns added. These new four columns are: for each row, I get the maximum element and its index and put them as two new columns. I do the same with the second maximum element.  I don't care if they are repeated.

add_2max <- function(x)
{
  max1 = max(x, na.rm=TRUE)
  indmax1 = which.max(x)
  y=x[-c(indmax1)]
  max2 = max(y, na.rm=TRUE)
  indmax2 = which(x==max2)
  indmax2 = ifelse(max1==max2, indmax2[2], indmax2[1])
  x=c(x, max1, max2, indmax1, indmax2)
  return (x)
}

add_2max_df <- function(DF)
{
  NewDF=t(apply(DF, 1, add_2max))
  return(NewDF)
}

I'm sure this code can be improved.  What do you recommend in order to do that? Is it fast enough?


texts:
Quite often, I find myself measuring how long some part of my code takes to complete. I normally do that by storing current time using time.time() and then subtracting time after the code is done.

This normally gives me a float that I can then format and print for debugging purposes. This is the function that I have for time formatting:

def time_format(delta: float) -> str:
    output = []
    decimal, integer = math.modf(delta)

    if integer:
        minutes, seconds = divmod(int(integer), 60)

        if minutes:
            output.append("%sm" % minutes)

        if seconds:
            output.append("%ss" % seconds)

    decimal, integer = math.modf(decimal * 1000)
    if integer:
        output.append("%sms" % int(integer))

    decimal, integer = math.modf(decimal * 1000)
    if integer:
        output.append("%sμs" % int(integer))

    decimal, integer = math.modf(decimal * 1000)
    if integer:
        output.append("%sns" % int(integer))

    return ", ".join(output)

I have also been told that the time module has most precision when it comes to time measuring so that's why I'm using it, instead of something like datetime which has nice formatting tools built in.

How could I improve my time formatting function? Are there any built in formatting tools that I'm not aware of? (Searching stack overflow leads me only to questions about datetime.timedelta)


texts:
I have an implementation of flatmap for std::vector. However, I find the repetition of the inferred return type to be ugly. And, in general, I suspect that the implementation could be cleaner or more general.

template<typename T, typename FN>
static auto flatmap(const std::vector<T> &vec, FN fn) -> std::vector<typename std::remove_reference<decltype(fn(T())[0])>::type> {
    std::vector<typename std::remove_reference<decltype(fn(T())[0])>::type> result;
    for(auto x : vec) {
        auto y = fn(x);
        for( auto v : y ) {
            result.push_back(v);
        }
    }
    return result;
};

It can be used like this:

TEST_F(MarkdownUtilTests, testFlatmap) {
    std::vector<int> v = { 1, 2, 3};
    std::vector<int> result = flatmap(v, [](int x) { return std::vector<int> { x, x*2, x*3 }; } );
    assertThat(result, is(std::vector<int> {1,2,3,2,4,6,3,6,9} ));
}


texts:
I created a Queue object when answering this question and I was wondering if it could do with some improvement.

Here is the current code:

var Queue = (function () {

    Queue.prototype.autorun = true;
    Queue.prototype.running = false;
    Queue.prototype.queue = [];

    function Queue(autorun) {
        if (typeof autorun !== "undefined") {
            this.autorun = autorun;
        }
        this.queue = []; //initialize the queue
    };

    Queue.prototype.add = function (callback) {
        var _this = this;
        //add callback to the queue
        this.queue.push(function () {
            var finished = callback();
            if (typeof finished === "undefined" || finished) {
                //  if callback returns `false`, then you have to
                //  call `next` somewhere in the callback
                _this.dequeue();
            }
        });

        if (this.autorun && !this.running) {
            // if nothing is running, then start the engines!
            this.dequeue();
        }

        return this; // for chaining fun!
    };

    Queue.prototype.dequeue = function () {
        this.running = false;
        //get the first element off the queue
        var shift = this.queue.shift();
        if (shift) {
            this.running = true;
            shift();
        }
        return shift;
    };

    Queue.prototype.next = Queue.prototype.dequeue;

    return Queue;

})();

Is there anything that I can expand on or improve in this Object?
Should anything be changed?


texts: Python Combinatory Algorithm - A Binomial Coefficient application with n mutable and k fixed to 2

texts:
This question came from a real use case.
I had a data frame with different columns each one containing data from a data source and I wanted to design a hypothesis test to prove or not if the data had the same mean.
So I had to compute the Kolmogorov-Smirnov test for each couple of columns.
Now the problem can be generalized to any combinatory task.
It follows that I had to implement a Binomial Coefficient like
$$ \binom{n}{k} $$
Where n is the number of columns
and k is = 2
My question is: if exists a more efficient way to apply a function on permutated samples taken from a list? And how to do this permutation  eg. Given a func and a list [a,b,c,d]
func(a,b)
func(a,c)
func(a,d)
func(b,c)
func(b,d)
func(c,d)

I created an algorithm to solve this issue, but I am wondering if there is a better way to do that in Python.
In my algorithm, I simply multiply each n element in an explanatory array with another element i of the same array, with n!=i, instead of computing the statistical test.
to_do=[1,2,3,4,5]
#done will store information on the elements already combined
done=[]
#j will store information on the results of the combination
j=[]

#iterating over the to_do array
for n in to_do:

  #checking if we already computed the n element
  if n not in done:
    print(n)
    #taking another i element from the array
    #where n!=i
    for i in to_do:
      print(i)
      #if the condition is satisfied
      if i!=n:
        #combine the two elements
        m=n*i

        #append the result on the "j" array
        j.append(m)
    #updating the array with the "done" elements
    done.append(n)

print(len(done))
print(len(j))


texts: Improving the flexibility of my library/what can be improved?

texts:
How can I make my library more flexible towards programmers? Here is my library. It's a basic library that provides a simple interface to organise your game (with scenes, and engine/game connection). The only problem that I dislike about it, is the fact that you cannot create a custom 'game loop', you must let the GameLoop class deal with that for you. You can only instead, call to update/draw of the loop if you cannot use a while loop and manually clog the main thread (e.g. Ogre3d and it's call backs to update your game).

I'm also curious on what I can improve upon this library. Does my tutorial make sense? Is my code clean?

https://github.com/miguelishawt/pine


texts:
I have an input text file which contains distance between 2 cities shown below

Luebeck Hamburg 63
Hamburg Bremen 116
Hamburg Hannover 153
Hamburg Berlin 291
Bremen Hannover 132
Bremen Dortmund 234
Hannover Magdeburg 148
Hannover Kassel 165
Magdeburg Berlin 166
Berlin Dresden 204
Dresden Leipzig 119
Leipzig Magdeburg 125
Dortmund Duesseldorf 69
Kassel Frankfurt 185
Frankfurt Dortmund 221
Frankfurt Nuremberg 222
Leipzig Nuremberg 263
Dortmund Saarbruecken 350
Saarbruecken Frankfurt 177
Saarbruecken Karlsruhe 143
Karlsruhe Stuttgart 71
Stuttgart Frankfurt 200
Stuttgart Munich 215
Stuttgart Nuremberg 207
Nuremberg Munich 171
Manchester Birmingham 84
Birmingham Bristol 85
Birmingham London 117
END OF INPUT

My dictionary should be like this:

{
 'luebeck': [('hamburg', '63')], 'dortmund': [('bremen', '234'), ('duesseldorf', '69')]
 'saarbruecken': [('dortmund', '350'), ('frankfurt', '177'), ('karlsruhe', '143')]
  ..
 }

My code is working but it is not efficient and I want to optimize it:

def read_file(filename):
    paths = []
    graph = {}
    f = open(filename, 'r')
    for line in f:
        route = line.lower().split()
        paths.append(route)

    # to remove space and end of input
    del paths[-1]
    del paths[-1]

    for path in paths:
        node = path[0]
        if node not in graph:
            graph[node] = {}
            graph[node][path[1]] = int(path[2])
        elif node in path:
            graph[node][path[1]] = int(path[2])
            node = path[1]
            if node not in graph:
                graph[node] = {}
        node = path[1]
        if node not in graph:
            graph[node] = {}
            graph[node][path[0]] = int(path[2])
        elif node in path:
            graph[node][path[0]] = int(path[2])
    return graph

Please tell me if any additional information is required.


texts: REST API to list books, where null means "everything"

texts:
My company has a REST API, and one design issue that has come up a few times is that we use null to indicate "get everything".

For example /api/books?genre=romance will get all romance books, but /api/books will return all books from all genres.

The current technique used in the code is something like this

public ResponseEntity getBooks(@RequestParam(required = false) String genre) {

    List<BookDto> bookDtos = new ArrayList<>();
    List<Book> allBooks = getAllBooks();

    for (Book book : allBooks) {
       // This if condition is what I take issue with
       if (genre == null || book.genre.equals(genre)) {
           bookDtos.add(book.convertToDto());
       }
    }
    return bookDtos;

}

I think it is bad practice to use null here to convey the meaning of get everything. Is this correct?

My current solution is to distinguish between these two cases at the very top level like so:

public ResponseEntity getBooks(@RequestParam(required = false) String genre) {

    if (genre == null) {
        return getAllBooks();
    } else {
        return getBooks(genre);
    }
}

And then a few supporting functions that funnel all of the logic into the same place by massaging the inputs a little bit.

// This is the core code, that takes a list of genres and returns all books from all those genres.
public Collection<BookDto> getBooks(List<String> genre) {
    // And here is the code that will actually get the books from the database.
    // ...
    // ...
}

// This is a supporting function, that finds all genres and funnels that into the above function.
public Collection<BookDto> getAllBooks() {
    List<String> allGenres = getAllGenres()
    return getBooks(allGenres);
}

// This is a supporting function that builds a list from a single genre, to again funnel into the 1st function.
public Collection<BookDto> getBooks(String genre) {
    List<String> genres = new ArrayList<>();
    genres.add(yearCode);
    return getBooks(genres);
}

The idea here is to have a single place where the work actually takes place and the database is accessed, but to have multiple ways to access it. And more importantly to remove the idea of null == all in the codebase, aside from the very top level where the execution starts after the user requests /api/books.

It's always felt natural to me but I've not seen it used by anyone else (I've only worked at a few places, so this could just be inexperience on my part). Is the proposed design good? Is there a standard way of solving this problem?


texts:
I need a copy_if_max() function, i.e. copy all the elements in an input range that are equal to the max in that range. The most obvious implementation does two passes over the data:

template<class InputIt, class OutputIt>
OutputIt copy_if_max2(InputIt first, InputIt last, OutputIt dst)
{
    using T = typename InputIt::value_type;
    auto m = *std::max_element(first, last);
    return std::copy_if(first, last, dst, [&](T const& elem) {
        return elem >= m; // NOTE: not elem == m, because we use equivalence, not equality
    });
}

This is all nice and dandy (\$O(N)\$ complexity). However, for true input ranges, the two passes over the input data are a no go.

Note also that the maximum of the input range is defined in terms of an operator< that defines an equivalence relation, and not necessarily an equality relation. The suggested single-pass answer by @Yuushi would therefore not work.

I've come up with what I call a clearable back_inserter, that will reset the output range whenever the max is updated. I do that by having an assignment operator that takes a nullptr_t argument (which takes precedence in overload resolution over all other pointers, so even if the actual data would contain a nullptr, this would not match!). Furthermore, there is an implicit conversion to std::size_t so I can detect the underlying output container size.

template<class Container>
class clearable_back_insert_iterator
:
    public std::iterator< std::output_iterator_tag, void, void, void, void >
{
private:
    Container* c_;

public:
    using self_t = clearable_back_insert_iterator;
    using value_type = typename Container::value_type;

    clearable_back_insert_iterator(Container& c): c_(&c) {}

    operator std::size_t() { return c_->size(); }

    self_t& operator=(value_type const& v)
    {
        std::cout << "push_back \n";
        c_->push_back(v);
        return *this;
    }

    self_t& operator=(std::nullptr_t)
    {
        std::cout << "clear \n";
        c_->clear();
        return *this;
    }

    self_t& operator*() { return *this; }
    self_t& operator++() { return *this; }
    self_t& operator++(int) { return *this; }
};

template<class Container>
clearable_back_insert_iterator<Container> clearable_back_inserter(Container& c)
{
    return clearable_back_insert_iterator<Container>(c);
}

This allows me to write a single-pass copy_if_max1() that uses a clearable_back_inserter and a std::transform():

template<class InputIt, class OutputIt>
OutputIt copy_if_max1(InputIt first, InputIt last, OutputIt dst)
{
    using T = typename InputIt::value_type;
    auto m = std::numeric_limits<T>::min();
    std::transform(first, last, dst, [&](T const& elem) {
        if (dst == 0) {             // size()
            m = elem;
            return dst = elem;      // push_back()
        }
        if (m <= elem) {
            if (m != elem) {
                m = elem;
                dst = nullptr;      // clear()
            }
            dst = elem;             // push_back()
        }
        return dst;
    });
    return dst;
}

Live example. I realize that this one-pass version does more copying because it will copy all elements of the input range as long as they match the intermediate maximum, only to be cleared whenever the max is updated.

My questions:

Which points in this design would you critique?
Do you think clearable back_inserters are a good and reusable concept?
Should I use named members size() and clear() instead of conversion to size_t and assignment from nullptr?
Does Boost have some other alternatives (filter_iterator perhaps?)
Is it better to avoid the complications altogether and use the two-pas version copy_if_max2() (perhaps with a full copy of the input to allow multi-passes)?


texts:
As of late I have been learning F#. Today I accumulated what I have learned so far to develop my first program - a script that counts the number of lines of code in a given Visual Studio project.

The code for said program is as follows:

#r "System.Xml.Linq"

open System
open System.IO
open System.Xml.Linq
open System.Text.RegularExpressions

printf "Enter solution path: "
let solutionPath = Console.ReadLine()
let solutionDirPath = Path.GetDirectoryName(solutionPath)

let solutionText = File.ReadAllText(solutionPath)
let projectPaths  =
    Regex.Matches(solutionText, "([^\"]*csproj)")
    |> Seq.cast<Match>
    |> Seq.map (fun m -> Path.Combine(solutionDirPath, m.Groups.[1].Value))

let codeFilePaths =
    projectPaths
    |> Seq.map (fun projPath ->
        let projectDirPath = Path.GetDirectoryName(projPath)
        let document = XDocument.Load(projPath)
        document.Descendants()
            |> Seq.where (fun desc -> desc.Name.LocalName = "Compile")
            |> Seq.map (fun desc -> Path.Combine(projectDirPath, desc.FirstAttribute.Value)))
        |> Seq.concat

let locIsSignificant (loc : string) =
    let sanitizedLoc = loc.Trim()
    match sanitizedLoc with
    | ""  -> false
    | "{" -> false
    | "}" -> false
    | _   -> true

let totalLoc =
    codeFilePaths
    |> Seq.sumBy (fun path ->
        File.ReadLines(path)
        |> Seq.where locIsSignificant
        |> Seq.length)

printfn "Total Loc: %i" totalLoc
Console.ReadKey() |> ignore

I have tried write both clean and idiomatic code but I still have some concerns, namely:

In this script, I introduce sequential intermediate bindings (projectPaths->codeFilePaths->totalLoc) however, the binding locIsSignificant feels like an interruption to this sequence. Have I arranged my code in an conventional way?
Is my code as idomatic as can be? That is, could I make the code more expressive by using constructs or commands that I have not considered?

Of course, any additional feedback is welcome/encouraged.


texts: Regex credit card expiry date auto format

texts:
I'm trying to write a function that will get content from input element and try to format numbers entered in input box in MM/YY. Following is a solution that I have, and I want to reduce the number of lines it has. Can anybody help me write a better function to do this?

If you see this, it auto inserts slash.

Working demo

function formatString(string) {
        return string.replace(
            /^([1-9]\/|[2-9])$/g, '0$1/' // To handle 3/ > 03/
        ).replace(
            /^(0[1-9]{1}|1[0-2]{1})$/g, '$1/' // 11 > 11/
        ).replace(
            /^([0-1]{1})([3-9]{1})$/g, '0$1/$2' // 13 > 01/3
        ).replace(
            /^(\d)\/(\d\d)$/g, '0$1/$2' // To handle 1/11 > 01/11
        ).replace(
            /^(0?[1-9]{1}|1[0-2]{1})([0-9]{2})$/g, '$1/$2' // 141 > 01/41
        ).replace(
            /^([0]{1,})\/|[0]{1,}$/g, '0' // To handle 0/ > 0 and 00 > 0
        ).replace(
            /[^\d\/]|^[\/]{0,}$/g, '' // To allow only numbers and /
        ).replace(
            /\/\//g, '/' // Prevent entering more than 1 /
        );
    }
    event.target.value = formatString(value);

(Stack Overflow post)


texts: How Does This Naive Stack Implementation Look?

texts:
Consider this naive stack implementation in Elixir:

defmodule Stack do
  defstruct name: "", value: 0

  def init() do
    _s = []
  end

  def push(name, value, s) do
    s_new =  [%Stack{name: name, value: value}, s]
    {:ok,s_new}
  end

  def pop(s) do
    [h|tail] = s
    {:ok, h, tail}
  end

  def depth(s) do
    length(s)
  end

end

#Use:
# s = Stack.init()
# {:ok, s} = Stack.push("a",1,s)
# {:ok, item, s} = Stack.pop(s)
# l = Stack.depth(s)

Am I using structs correctly?  Any suggestions for more idiomatic code style?


texts: Censor the middle of words of length N from a text file

texts:
LENGTHS_TO_CENSOR = {4, 5}
CENSOR_CHAR       = '*'
CENSOR_EXT        = "-censored"

def replace_inner(word, char):
    if len(word) < 3:
        return word
    return word[0] + char * len(word[1:-1]) + word[-1]

def create_censor_file(filename):
    output_file = open(filename + CENSOR_EXT, "w+")
    with open(filename) as source:
        for line in source:
            idx = 0

            while idx < len(line):

                # If the character isn't a letter, write it to the output file.
                if not line[idx].isalpha():
                    output_file.write(line[idx])
                    idx += 1

                else:
                    word = ""

                    while idx < len(line) and line[idx].isalpha():
                        word += line[idx]
                        idx += 1

                    if len(word) in LENGTHS_TO_CENSOR:
                        word = replace_inner(word, CENSOR_CHAR)

                    output_file.write(word)

    output_file.close()

def main():
    filename = input("File to be censored: ")
    create_censor_file(filename)

if __name__ == "__main__":
    main()

I was assigned a task to censor words that are length n in a file. This file can potentially contain punctuation and numbers.
I originally tackled the problem by splitting the line into a list of words (using .split(' ')) and checking the length to determine if the program should censor the word or not. This failed for inputs such as:

does not work.for.this.input
or.this

The output file must be exactly like the input but with words of length in LENGTHS_TO_CENSOR censored with CENSOR_CHAR.
I decided to abandon trying to make it Pythonic and ended up with this result. I want to know if there is a way to take this method and make it more Pythonic.


texts: Defining pipelines of functions when passing a main argument across multiple functions

texts:
Discovering sk-learn pipelines (https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html) made me wonder why weren't I using the same idea for any set of functions applied to a single main argument.
Based on this idea I developed the following code (Using kwargs treatment from https://stackoverflow.com/a/58543357):
import inspect
def create_sequential_pipe(func_list):
    """
    Create a pipeline for a series of functions to be applied to a single main argument

    Args:
        func_list: List of functions
    """

    def sequential_pipe(main_arg, **kwargs):

        for func in sequential_pipe._func_list:

            func_args = [k for k, v in inspect.signature(func).parameters.items()]
            func_dict = {k: kwargs.pop(k) for k in dict(kwargs) if k in func_args}
            main_arg = func(main_arg, **func_dict)

        return main_arg

    sequential_pipe._func_list = func_list

    return sequential_pipe

def example_func_1(n, power=1):
    return n ** power

def example_func_2(n, sum=0):
    return n + sum

def example_func_3(n, divide=1):
    return n / divide

if __name__ == "__main__":

    example_pipe= create_sequential_pipe([example_func_1, example_func_2, example_func_3])

    out = example_pipe(2)
    print(out)  # 2.0

    out = example_pipe(2, power=2, sum=1, divide=5)
    print(out)  # 1.0

I feel I could get used to its use, but I couldn't find something similar already implemented in Python, so I feel there must be a downside I am not seeing.
I could just create a wrapper function for the pipeline of functions, but I'm not sure it would be as simple.
Is there something similar commonly used in other languages? Do you think it's obfuscates the code? Are there clear downsides to using this?


texts:
Inspired by the recent surge of questions dealing with changing numbers to their English equivalents (See here, here, and here), I decided to write my own version in Python.

zero_to_nineteen = (
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
    "ten",
    "eleven",
    "twelve",
    "thirteen",
    "fourteen" ,
    "fifteen",
    "sixteen",
    "seventeen",
    "eighteen",
    "nineteen"
)

tens = (
    "zero",
    "ten",
    "twenty",
    "thirty",
    "forty",
    "fifty",
    "sixty",
    "seventy",
    "eighty",
    "ninety"
)

suffixes = {
    3 : "thousand",
    6 : "million",
    9 : "billion",
    12 : "trillion",
    15 : "quadrillion",
    18 : "quintillion",
    21 : "sextillion",
    24 : "septillion",
    27 : "octillion",
    30 : "nonillion",
    33 : "decillion",
    36 : "undecillion"
    39 : "duodecillion",
    42 : "tredicillion",
    45 : "quattuordecillion",
    48 : "quinquadecillion",
    51 : "sedecillion",
    54 : "septendecillion",
    57 : "octodecillion",
    60 : "novendecillion",
    63 : "vigintillion",
    66 : "unvigintillion",
    69 : "duovigintillion",
    72 : "tresvigintillion",
    75 : "quattuorvigintillion",
    78 : "quinquavigintillion",
    81 : "sesvigintillion",
    84 : "septemvigintillion",
    87 : "octovigintillion",
    90 : "novemvigintillion",
    93 : "trigintillion",
    96 : "untrigintillion",
    99 : "duotrigintillion",
    102 : "trestrigintilion",
    105 : "quattuortrigintillion",
    108 : "quinquatrigintillion",
    111 : "sestrigintillion",
    114 : "septentrigintillion",
    117 : "octotrigintillion",
    120 : "noventrigintillion",
    123 : "quadragintillion"
}

def spell_out(number):
    """Returns a string representation of the number, in english"""
    if isinstance(number, float):
        raise ValueError("number must be an integer")

    if number < 0:
        return "negative " + spell_out(-1 * number)

    if number < 20:
        return zero_to_nineteen[number]

    if number < 100:
        tens_digit = number // 10
        ones_digit = number % 10
        if ones_digit == 0:
            return tens[tens_digit]
        else:
            return "{}-{}".format(tens[tens_digit], zero_to_nineteen[ones_digit])

    if number < 1000:
        hundreds_digit = zero_to_nineteen[number // 100]
        rest = number % 100
        if rest == 0:
            return "{} hundred".format(hundreds_digit)
        else:
            return "{} hundred {}".format(hundreds_digit, spell_out(rest))

    suffix_index = log(number)
    suffix_index -= suffix_index % 3

    prefix = spell_out(number // 10 ** suffix_index)
    suffix = suffixes[suffix_index]

    rest_of_number = number % (10 ** suffix_index)

    if suffix_index in suffixes:
        if number % (10 ** suffix_index) == 0:
            return "{} {}".format(prefix, suffix)
        else:
            return "{} {} {}".format(prefix, suffix, spell_out(rest_of_number))

    return "infinity"

def log(number):
    """Returns integer which is log base 10 of number"""
    answer = 0
    while number > 9:
        answer += 1
        number //= 10
    return answer

I would appreciate any comments on my code.


texts:
I recently did problem 1.7 Rotate Matrix in Cracking the Coding Interview. I realized my code is very different than what is in the book and also from what I'm finding online (I'm having trouble following the code in the book). I just want to know if the code I wrote would be appropriate in an interview setting or would I be expected to write code like the solution in the book.
The problem states

Rotate Matrix: Given an image represented by an N×N matrix, where each
pixel in the image is 4 bytes, write a method to rotate the image by
90 degrees. Can you do this in place?

Here is my code:
def transpose(the_array):
    res = []
    for i in range(len(the_array)):
        transposed = []
        for col in the_array:
            transposed.append(col[i])
        transposed.reverse()
        res.append(transposed)
    return res

print(transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))

Also, would the reverse method be ok to use in an interview?
I just realized my solution may not be considered in place.


texts:
I have written a pager in C that is supposed to be used in systems where curses is not installed (or broken). It can also be used as a system-wide pager, it works with man pages (only on BSD, though). I want to spot any portability or output problems, as there may be some due to the dependence on buffered input:

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

/*
 * A very SIMPLE pager that does not require curses. If your curses library
 * is broken, this is practically the only portable one you can easily get.
 * Written by Daniel Roskams, in the public domain
 */

int
main(
    int argc,
    char *argv[])
{
    FILE *fp;
    int ch;

    if (argc < 2) {
        fp = stdin;
    } else if ((fp = fopen(argv[1], "r")) == NULL) {
        perror(argv[1]);
        return EXIT_FAILURE;
    }

    while ((ch = fgetc(fp)) != EOF) {
        if (ch == '\n') {
            getchar();
        } else {
            putchar(ch);
        }
    }

    if (ferror(fp)) {
        perror(argv[1]);
        return EXIT_FAILURE;
    }

    fclose(fp);
    return EXIT_SUCCESS;
}

I don't think there are any code problems themselves, since it compiles with the -Weverything flag with clang.


texts:
I recently got interviewed in a company for Senior level position. They asked me to develop auto-complete component (2 hours time limit) using plain JavaScript similar to this.

I wrote below code, which works as expected, but they responded saying that the solution doesn't match expectations. Please help me figure out what I could improve in this.

Here is the link to working example.

function customAutoComplete(input,sourceList){

if(!input){
    console.error('No input box provided');
}
if(!sourceList ||   sourceList.length<=0){
    console.error('No sourceList provided for customAutoComplete');
}

var suggList;
input.addEventListener('keyup',function(e){
    suggList=populateSourceList(input.value);
    if(suggList){
        input.parentNode.appendChild(suggList);
    }
    if(e.keyCode==40){
        suggList.focus();
    }
});

input.addEventListener('blur',function(e){
    if(e.relatedTarget.id!=input.id + '_autoComplete'){
        setTimeout(clearSuggestionList,200);
    }
});

function populateSourceList(inputText){

    if(!inputText){
        return null;
    }
    var suggList=getSuggestList();
    var size=1;
    sourceList.forEach( function(itm){
        if(itm.indexOf(inputText)>=0) {
            var listItem=document.createElement("option");
            listItem.appendChild(document.createTextNode(itm));
            suggList.appendChild(listItem);
            size++;
        }
    });
    suggList.setAttribute('size',size);
    if(size>1){
        return suggList;
    }
    return null;
}

function getSuggestList(){
    var acListId=input.id + '_autoComplete';
    var acList= document.getElementById(acListId)
    if(!acList){
        acList = document.createElement("select");
        acList.setAttribute('class','suggestion-list');
        acList.setAttribute('id',acListId);
        var stl='left:' + input.offsetLeft + 'px;top:' + (input.offsetTop + input.offsetHeight) + 'px;min-width:' + input.offsetWidth + 'px';
        acList.setAttribute('style',stl);
        acList.addEventListener('keydown',function(e){autoCompleteItemSelected(e,acList)});
        acList.addEventListener('blur', function(){clearSuggestionList(suggList)} );
    }

    else{
        acList.innerHTML='';
    }

    return acList;
}
function clearSuggestionList(suggList){
    if(!suggList){
        suggList=getSuggestList();
    }
    suggList.outerHTML='';
}
function autoCompleteItemSelected(e,list){
    if(e.keyCode==13){
        input.value=list.selectedOptions[0].text;
        clearSuggestionList();
    }
}
}


texts: Setter method for an object using a special logic

texts:
I have a method that received a list of CoordinateBE : setExits(..)
I want to update the existing coordinates list with a new coordinate only if there is no coordinate in the current list that has the same latitude and longitude.
Example:
List: [Coordinate: lat:23, long:24, Coordinate: lat:34, long:24]
I am trying to add a new Coordinate: Coordinate: lat:23, long: 24 ---> this one I cannot add it because already exists in the list.
My implementation is working, but I was wondering if I can improve it, for example through lambda expressions, etc. Do you have any ideas?
// setter
  public void setExits(final List<CoordinateBE> exits) {
            if (getExits().isEmpty()) {
                this.exits = exits;
            } else {
                if (!existenceOfCoordinates(getExits(), exits)) {
                    final List<CoordinateBE> result = new ArrayList<>();
                    result.addAll(getExits());
                    result.addAll(exits);
                    this.exits = result;
                }
            }
        }

//getter
  public List<CoordinateBE> getExits() {
     return exits;
  }

// existenceOfCoordinates
 private boolean existenceOfCoordinates(final List<CoordinateBE> existingCoordinates, final List<CoordinateBE> currentCoordinates) {
    for (final CoordinateBE existingCoordinate : existingCoordinates) {
        for (final CoordinateBE currCoordinateBE : currentCoordinates) {
            if (compareCoordinates(existingCoordinate, currCoordinateBE)) {
                return false;
            }
        }
    }
    return true;
 }

// compareCoordinates
 private boolean compareCoordinates(final CoordinateBE existingCoordinate, final CoordinateBE newCoordinate) {
        return existingCoordinate.getLatitude().equals(newCoordinate.getLatitude())
                && existingCoordinate.getLongitude().equals(newCoordinate.getLongitude());
    }


texts:
I am inserting elements into the map container. For this I am using the same statements multiple times in the below function. Is there any way I can write a generic function for this? So that even at the later point of time, when required, I can insert new elements.

 bool EMRMgr::GetParams()
    {
        EmIOStruct emIOstructObj;
        WCHAR szValue[MAX_PATH] = { 0 };
        DWORD dwDataSize = sizeof(szValue) / sizeof(WCHAR);
        long lRes = 0;
        McStorageType mcStorageTypeObj = McStorageType::eRegistry;
        std::wstring value;

    // First time I am using the below statements to insert elements into the map container

        mcIOstructObj.lpszValueName = (LPWSTR)ER_ID;
        memset(szValue, 0, MAX_PATH);
        mcIOstructObj.lpData = (LPBYTE)&szValue[0];
        lRes = m_cIOManager.ReadValue(mcStorageTypeObj, mcIOstructObj);
        value.clear();
        if ((LPWSTR)mcIOstructObj.lpData == nullptr)
        {
            value.assign(L"");
        }
        else
        {
            value.assign((LPWSTR)mcIOstructObj.lpData);
        }

        m_fileParams.insert({ (std::wstring) ER_ID, value });

    // Second time I am using the below statements to insert elements into the map container

        mcIOstructObj.lpszValueName = (LPWSTR)CPS;
        memset(szValue, 0, MAX_PATH);
        mcIOstructObj.lpData = (LPBYTE)&szValue[0];
        lRes = m_cIOManager.ReadValue(mcStorageTypeObj, mcIOstructObj);
        value.clear();
        if ((LPWSTR)mcIOstructObj.lpData == nullptr)
        {
            value.assign(L"");
        }
        else
        {
            value.assign((LPWSTR)mcIOstructObj.lpData);
        }
        m_fileParams.insert({ (std::wstring) CPS, value });

        return true;
    }


texts: High Performance Calculation of Sums and Returns in Go

texts:
I am writing a finance library with the intention to have the best of Golang's performance.

The function Re calculates the returns of a float list, and function Sum calculates the sum of float list.

//Calculate returns
func Re(data []float64) []float64 {

    re_ := make([]float64, len(data))
    for i := 1; i < len(data); i++ {
        re_[i] = ( (data[i]/data[i-1])-1)
    }

    return re_
}

// sum of float64 list
func Sum(floatList []float64) float64 {

    var totalx float64
    for _, valuex := range floatList {
        totalx += valuex
    }

    return totalx
}

is there any further possible optimisation on these two functions or another more performant way to write them?


texts: Index Match with multiple columns using input boxes

texts:
I find this script handy for preparing ad-hoc reporting. Using two sets of unique identifiers, it allows you to lookup multiple columns of data with the Index Match function. I welcome any feedback or suggestions for improvement.

Sub MatchMaster_PRO()

'Peter Domanico (June 2018)
'this script helps simplify the use of Excel's Index Match function
'place this script in your personal macro workbook and assign it to a button
'use it to pull data between two worksheets that share unique identifiers

'dim ranges
    Dim ValuesToPull As Range
    Dim TargetIDs As Range
    Dim SourceIDs As Range
    Dim MyRange As Range

'dim worksheets
    Dim Source1 As Worksheet
    Dim Target1 As Worksheet
    Dim Source2 As Worksheet
    Dim Target2 As Worksheet

'input box dims
    Dim Prompt1 As String
    Dim Prompt2 As String
    Dim Prompt3 As String
    Dim Prompt4 As String
    Dim Title1 As String
    Dim Title2 As String
    Dim Title3 As String
    Dim Title4 As String

'set prompts
    Prompt1 = "Select values to pull (1 or more columns)"
    Prompt2 = "Select unique IDs on target sheet (1 column only)"
    Prompt3 = "Select unique IDs on source sheet (1 column only)"
    Prompt4 = "Select any range on target sheet"

'set titles
    Title1 = "Source Sheet"
    Title2 = "Target Sheet"
    Title3 = "Source Sheet"
    Title4 = "Target Sheet"

'error handling
    On Error GoTo OuttaHere

'input boxes
    Set SourceIDs = Application.InputBox(Prompt3, Title3, Type:=8)
    Set Source1 = SourceIDs.Worksheet
    SourceIDcolumn = SourceIDs.Column
    LastSourceID = Source1.Cells(Rows.Count, SourceIDcolumn).End(xlUp).Row
    Source1.Activate

    Set ValuesToPull = Application.InputBox(Prompt1, Title1, Type:=8)
    Set Source2 = ValuesToPull.Worksheet
    LastValue = LastSourceID
    Source2.Activate

    Set TargetIDs = Application.InputBox(Prompt2, Title2, Type:=8)
    Set Target1 = TargetIDs.Worksheet
    TargetIDcolumn = TargetIDs.Column
    LastTargetID = Target1.Cells(Rows.Count, TargetIDcolumn).End(xlUp).Row '<~~ also use this for MyRange
    Target1.Activate

    Set MyRange = Application.InputBox(Prompt4, Title4, Type:=8)
    Set Target2 = MyRange.Worksheet
    MyColumn = MyRange.Column
    Target2.Activate

'convert input to Range Cells format
    With Source1
        Set SourceIDs = .Range(.Cells(1, SourceIDcolumn), .Cells(LastSourceID, SourceIDcolumn))
    End With
    With Target1
        Set TargetIDs = .Range(.Cells(1, TargetIDcolumn), .Cells(LastTargetID, TargetIDcolumn))
    End With

    Dim rng As Range
    For Each rng In ValuesToPull.Columns
        ValuesColumn = rng.Column
        NextColumn = Target2.Cells(1, Columns.Count).End(xlToLeft).Column + 1
        With Source2
            Set ValuesToPull = .Range(.Cells(1, ValuesColumn), .Cells(LastValue, ValuesColumn))
        End With
        With Target2
             Set MyRange = .Range(.Cells(1, NextColumn), .Cells(LastTargetID, NextColumn))
        End With
        MyRange = Application.index(ValuesToPull, Application.Match(TargetIDs, SourceIDs, 0))
    Next rng

OuttaHere:
    ActiveWorkbook.ActiveSheet.Columns.AutoFit

End Sub


texts:
A function which replaces an unicode character in a string:

void replaceAllOccurences(std::string& source,
                          const std::string& replaceFrom,
                          const std::string& replaceTo)
{
    std::vector<std::uint8_t> data(source.begin(), source.end());
    std::vector<std::uint8_t> pattern(replaceFrom.begin(), replaceFrom.end());
    std::vector<std::uint8_t> replaceData(replaceTo.begin(), replaceTo.end());

    std::vector<std::uint8_t>::iterator itr;
    while((itr = std::search(data.begin(), data.end(), pattern.begin(), pattern.end())) != data.end())
    {
        data.erase(itr, itr + pattern.size());
        data.insert(itr, replaceData.begin(), replaceData.end());
    }

    source = std::string(data.begin(), data.end());
}

Usage:

std::string source = "123€AAA€BBB";
std::string replaceFrom = "€";
std::string replaceTo = "\x80";

replaceAllOccurences(source, replaceFrom, replaceTo);

replaceTo may be get from some external conversion library, for example: iconvpp. Normally I would convert the whole source using iconvpp library but I have a case where I need to convert only particular character, for example "€".


texts:
In The Nineteenth Byte, we have an excessive amount of carets (carrots, if you will) that direct one's attention to another message. For example:

Amidst the confusion, I made a userscript that highlights in yellow the pointed-at message when the message in question is clicked.

(function(){
    var elements = {}, messages;

    function findCarrotMessage(){
        messages = Array.prototype.slice.call(document.querySelectorAll("[id^='message-']"));
        messages.forEach(function(e){
            if(!elements[e.id] && e.className==="message"){
                elements[e.id] = true;
                e.addEventListener("click", function(s){
                    // count the number of ^'s
                    var num = this.textContent.match(/\^+/g), self = this;
                    if(num){
                        var maxHash = -1;
                        num.forEach(function(k){
                            var destinationMessage = messages[Array.from(messages).indexOf(self)-k.length];
                            destinationMessage.style.background = "yellow";
                            setTimeout(function(e){e.style.background = "";}, 3500, destinationMessage);
                            maxHash = Math.max(destinationMessage.id.slice(destinationMessage.id.indexOf("-")+1), maxHash);
                            elements[self.id] = false;
                        });
                        window.location.hash = "#message-" + maxHash;
                    }
                    this.removeEventListener("click", arguments.callee, false);
                }, false);
            }
        });
    }

    setInterval(findCarrotMessage,50);
})();

How can I improve my code? Thanks!


texts: Implementing the midpoint displacement algorithm in Java

texts:
Thanks for taking the time to read this first off. I want to say that I have always been very interested in generating random terrain and since I'm new to any sort of graphical programming, I decided to start as simple as I could get.

I am trying to implement the midpoint displacement algorithm to make fractal type mountains. I've read the most common resources on it and understand the concept but that hasn't made it any easier. I suppose I have some more general questions about how I would store data effectively, but this is the code I have come up with. The code is pretty awful but it produces numbers and I've tried to make lines with the different points in openGL but I'm getting some pretty crazy results. I'm using the idea discussed on the start of this page. http://www.gameprogrammer.com/fractal.html

import java.util.Random;

public class MidPointGenerator {

private static double[] heightmap;
private static double randrange;
private static int iterations;
private static double roughness;
private static int n;

public MidPointGenerator(double s, int i, double h){
    n = (int)(Math.pow(2, i) + 1); // size of the array
    heightmap = new double[(int)n];
    randrange = s;
    iterations = i;
    roughness = Math.pow(2,-h);
    midPoint(0, n-1, randrange,0,i);
}

public static void midPoint(int left, int right, double range, int i, int goal){

    if(i == goal){
        return;
    }

    int mp = (left + right) / 2;
    double mpheight;

        if(heightmap[left] < heightmap[right]){
        mpheight = ((heightmap[right] - heightmap[left]) / 2.0) + heightmap[left];
        heightmap[mp] = mpheight + random(range);
    }
    if(heightmap[right] < heightmap[left]){
        mpheight = ((heightmap[left] - heightmap[right]) / 2.0) + heightmap[right];
        heightmap[mp] = mpheight + random(range);
    }
    if(heightmap[right] == heightmap[left]){
        heightmap[mp] += random(range);

    midPoint(left, mp, range * roughness, i+1, goal);
    midPoint(mp, right, range * roughness, i+1, goal);

}

public static double random(double range){
    //Returns a random number from -s to s.
    Random random = new Random();
    double randNum =  range - ((2*range) * random.nextDouble());
    return randNum;
}

public static void displayHeights(){
    for(int i = 0; i < heightmap.length; i++){
        System.out.println(heightmap[i]);
    }
}

public double getHeightValue(int index){
    if(index == n ){
        return 0;
    }
    return heightmap[index];
}

public int getIterations(){
    return n;
}

}

So this at least runs, stores the height values in a 1D array thats size depends on the number of iterations I want to do. How can I make my code much more logical and perhaps there is a much better way of implementing this. I was more concerned about just getting something that compiled and ran successfully. I'm convinced the way I'm approaching this is flawed and there is a much better way.

Any criticism is welcomed!
Thanks,
Ryan


texts: Finding a loop in a directed graph in Python

texts:
I wrote this code to find if a directed graph contains a loop or not. I am pretty new to graphs and I saw some examples on the internet but couldn't actually understand their implementations. So I read somewhere that you can colour mark the nodes. So this is my iterative implementation of that method. Is it an okay'ish' approach and how can I improve on it if it's correct?

These are the test cases

def dfs(graph, start):
    color = {i : 'white' for i in graph}
    stack = [start]
    visited = []

    while stack:
        vertex = stack.pop()
        if color[vertex] == 'grey':
            return True
        color[vertex] = 'grey'
        visited.append(vertex)
        stack.extend((graph[vertex]))
        if  len(graph[vertex]) == 0:
            color[vertex] = 'black'
    return False

def cycle_exists(graph):
    for vertex in graph:
         if(dfs(graph, vertex)):
             return True
    return False

# connected graph with cycle
graph1 = { 0 : [1, 2],
           1 : [],
           2 : [3],
           3 : [4],
           4 : [2] }
assert(cycle_exists(graph1) == True)
print("Graph1 has a cycle.")

#----------------------------------------------------

# disconnected graph with cycle
graph2 = { 0 : [],
           1 : [2],
           2 : [],
           3 : [4],
           4 : [5],
           5 : [3] }
assert(cycle_exists(graph2) == True)
print("Graph2 has a cycle.")

#----------------------------------------------------

# disconnected graph without a cycle
graph3 = { 0 : [],
           1 : [],
           2 : [],
           3 : [] }
assert(cycle_exists(graph3) == False)
print("Graph3 has no cycle.")

#----------------------------------------------------

# disconnected graph without a cycle
graph4 = { 0 : [1, 2],
           1 : [3, 4],
           2 : [],
           3 : [],
           4 : [],
           5 : [6, 7],
           6 : [],
           7 : [] }
assert(cycle_exists(graph4) == False)
print("Graph4 has no cycle.")

#----------------------------------------------------

# If assert raises an error, then a test case was not passed.
print("\nAlgorithm passed all test cases")


texts: Algorithm to Iterate All Possible Strings in Clojure

texts:
I'm fairly new to Clojure and I struggled a bit coming up with a nice Clojure-y solution for implementing an algorithm for one of my applications. The real issue I'm trying to solve would require a large writeup in order to understand what it's about, so I've come up with a contrived problem statement that's much easier to understand which is quite similar to my original problem.

  Assume you have mapped numbers to letters like so: 1->a, 2->b, 3->c, ... , 26->z

  If you receive input like "4 1 25", you can easily convert this to the string "day" (because 'd' is the 4th letter in the alphabet, 'a' is the 1st, and 'y' is the 25th).

  Now assume you don't have spaces as delimiters. So the input is "4125". This introduces ambiguity. "4125" can be interpreted as "4 1 25", "4 12 5", and "4 1 2 5".

  Write a function that takes a number, and returns all possible strings from these letter codes.

  So if you receive "4125" (the example above), the function would return: dle, day, dabe

Here is what I came up with:

; Generates map {1->a, 2->b, ... , 26->z}
(def code->letter
  (into {}
        (for [x (range 26)]
          [(str (inc x))
           (str (char (+ x (int \a))))])))

(defn possible-strings
  ([number]
   (possible-strings (str number) 0 ""))
  ([number index acc]
   (if (>= index (count number))
     acc
     (flatten (for [[k v] code->letter
                    :when (.startsWith number k index)]
                (possible-strings number (+ index (count k)) (str acc v)))))))

; Print all the possible strings from the input "4125"
(doseq [s (possible-strings 4125)]
  (println s))

So I believe this is basically a backtracking algorithm. And because it's a backtracking algorithm, it's impossible to make this tail-recursive, correct? Or maybe I'm wrong that this is a backtracking algorithm. If so, what would this kind of solution be classified as?

Anyway, the algorithm seems to work, but I'm not sure this solution is very idiomatic. The part in particular that I really don't like is having to call flatten for each call. I can't imagine that being very efficient either for large inputs. It seems like there must be a better way to do handle that.

Like I said, I'm new to Clojure and functional programming in general, so if there are improvements elsewhere, I'd be happy to hear about them as well. A completely different approach to solving the problem is welcome as well.


texts: Unit tests for os.scandir/scantree a directory

texts:
I wrote my first series of test for this simple function:

def map_directory(self, path='', method='recursive'):
    """
        scan the given path
            method -> recursive (all levels) or single (first level only)
    :param method: string
    :param path: string
    :return: generator
    """
    if not path:
        path = self.path

    if method == 'recursive':
        f = self.scan_tree
    elif method == 'single':
        f = os.scandir
    else:
        raise BullShitError('please enter a valid scanning method : {} is BS'
                            .format(method))
    return f(path)

def scan_tree(self, path=''):
        """
            recursively yield DirEntry objects for given directory.
        :return: generator
        """
        if not path:
            path = self.path

        for entry in (d for d in os.scandir(path) if FileSystemManager.is_readable(d.path) is True):
            try:
                if entry.is_dir(follow_symlinks=False):
                    yield entry
                    yield from self.scan_tree(entry.path)
                else:
                    yield entry
            except PermissionError:
                logger.warning('this entry raised an error : {}'.format(entry.path))
                continue

Tests :

import os
from django.test import TestCase

from packages.system.filesystem import FileSystemManager
from packages.system.local_dirs import user_home

class FileSystemManagerTests(TestCase):

    @classmethod
    def setUpClass(cls):
        cls.test_dir = os.path.join(user_home, 'test/a/b/c')

        os.makedirs(cls.test_dir, 0o755, exist_ok=True)
        cls.fl = FileSystemManager(cls.test_dir)

    @classmethod
    def tearDownClass(cls):
        pass

    def test_map_directory_returns_only_direntry_objects(self):
        """
            map_directory() returns only DirEntry objects in the returned generator
        """
        mapping = self.fl.map_directory()
        for obj in mapping:
            self.assertIsInstance(obj, os.DirEntry)

    def test_map_directory_returns_generator(self):
        """
            map_directory() returns a generator
        """
        from typing import Generator
        self.assertIsInstance(self.fl.map_directory(), Generator)

    def test_map_directory_recursive_method(self):
        """
            map_directory() recursive returns a, b, c
        """
        mapping = self.fl.map_directory(os.path.join(user_home, 'test'))
        self.assertEqual(len(tuple(mapping)), 3)

    def test_map_directory_single_method(self):
        """
            map_directory() single method returns a
        """
        mapping = self.fl.map_directory(os.path.join(user_home, 'test'),
                                        method='single')
        self.assertEqual(len(tuple(mapping)), 1)

I then have 3 main questions:

Is this "over tested"?
Does testing for only the length of the generator suffice for a proper test?
Should I ignore this function which is straightforward enough and center the focus of my tests on the self.scan_tree method?

Any other comments are welcomed, thanks.


texts: Print a double as a decimal with a specified precision

texts:
How could I make this code more effective?

static void     print_decimal(double decimal, int precision)
{
    size_t  integer;

    while (precision--)
    {
        decimal *= 100.;
        integer = (int)decimal;
        if (!precision  && (integer % 10) >= 5 && decimal != (double)integer)
            integer += 10;
        decimal *= .10;
        integer /= 10;
        printf("%i", integer);
        decimal -= integer;
    }
}

Example of calling that show me the decimals of a double with precision

print_decimal(65.226, 4)


texts:
Please review my implementation. I know there is already an implementation in Java, but I just wanted to come up with my implementation. Let me know if I can improve this.

import java.util.NoSuchElementException;

public class LinkedListImplementation<T> {
    private int size;
    private ListNode<T> head;

    static class ListNode<T> {
        private T value;
        private ListNode<T> next;

        public ListNode(T val) {
            this.value = val;
            this.next = null;
        }

        public T getValue() {
            return value;
        }

        public ListNode<T> getNext() {
            return next;
        }

        public void setNext(ListNode<T> nextNode) {
            this.next = nextNode;
            return;
        }

        public String toString() {
            if(this.value == null) {
                return "null";
            }
            return this.value.toString();
        }
    }

    public LinkedListImplementation() {
        head = new ListNode(0);
        head.setNext(null);
        size = 0;
    }

    public void add(T val) {
        ListNode<T> cur = new ListNode<>(val);
        if(size == 0) {
            head.setNext(cur);
            size++;
            return;
        }

        ListNode<T> prev = head;
        while(prev.getNext() != null) {
            prev = prev.getNext();
        }

        prev.setNext(cur);
        size++;
        return;
    }

    public boolean remove(T val) {
        if(size == 0) {
            throw new NoSuchElementException();
        }

        ListNode<T> cur = head;
        ListNode<T> prev = null;
        while(cur.getNext() != null && cur.getNext().getValue() != val) {
            prev = cur;
            cur = cur.getNext();
        }

        if(cur.getNext() != null && cur.getNext().getValue() == val) {
            prev = cur;
            cur = cur.getNext();
            prev.setNext(cur.getNext());
            size--;
        }
        else {
            return false;
        }
        return true;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void clear() {
        head.setNext(null);
        size = 0;
        return;
    }

    public ListNode<T> get(int index) {
        if(index >= size) {
            throw new ArrayIndexOutOfBoundsException();
        }

        int curIndex = index;
        ListNode<T> cur = head;

        while(cur.getNext() != null && curIndex-- > 0) {
            cur = cur.getNext();
        }

        if(curIndex != -1) {
            throw new NoSuchElementException();
        }
        return cur.getNext();
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        ListNode<T> cur = head;
        sb.append(cur.getValue() + "->");

        while(cur.getNext() != null) {
            sb.append(cur.getNext().getValue() + "->");
            cur = cur.getNext();
        }
        sb.append("null");
        return sb.toString();
    }

    public static void main(String[] args) {
        LinkedListImplementation<Integer> list = new LinkedListImplementation<>();
        System.out.println(list.size());
        list.add(1);
        list.add(3);
        list.add(5);
        System.out.println(list.remove(3));
        System.out.println(list.size());
        System.out.println(list.get(1));
        System.out.println(list.remove(6));
        System.out.println(list.get(0));
        System.out.println(list.get(1));
        //System.out.println(list.get(20));// ArraysIndexOutOfBoundsException.
        System.out.println(list.remove(5));
        System.out.println(list.size());
        //System.out.println(list.get(1));// ArraysIndexOutOfBoundsException.
        System.out.println(list.get(0));
        list.clear();
        System.out.println(list.size());
        //System.out.println(list.remove(1));//NoSuchElementException.
    }
}


texts:
I'm writing a very simple CRUD application, and I'm wondering if the way I'm using static methods throughout the code makes sense. I'd very much like to simplify the code if possible.
Any feedback and criticism is very much welcome!

<?php

class Database {

    private const DB_DSN = "127.0.0.1";
    private const DB_USER = "root";
    private const DB_PASSWORD = "root";
    private const DB_NAME = "testDB";
    private const DB_PORT = 8889;

    static function connect() {
        return new PDO(
            "mysql:host=".self::DB_DSN.";port=".self::DB_PORT.
            ";dbname=".self::DB_NAME,
            self::DB_USER,
            self::DB_PASSWORD,
            array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
        );
    }

    static function create() {
        $pdo = new PDO(
            "mysql:host=".self::DB_DSN.";port=".self::DB_PORT,
            self::DB_USER,
            self::DB_PASSWORD,
            array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
        );
        $pdo->exec("CREATE DATABASE IF NOT EXISTS ".self::DB_NAME);
        return self::connect();
    }
}

class User {

    private const TABLE_NAME = "users";

    public $uid;
    public $username;
    public $email;
    public $hash;
    public $created;
    public $verified;
    public $pdo;

    private function __construct() {
    }

    public static function signUp($pdo, $username, $email, $password) {

        if (self::exists($pdo, $username)) {
            return false;
        }

        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO `users` SET `username`=?, `email`=?, `hash`=?");
        $stmt->execute([$username, $email, $hash]);
        return self::fromUId($pdo, $pdo->lastInsertId());
    }

    public static function login($pdo, $username, $password) {

        if (!self::exists($pdo, $username)) {
            return false;
        }

        $stmt = $pdo->prepare("SELECT * FROM `users` WHERE `username` = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetchObject("User");
        $user->pdo = $pdo;
        return password_verify($password, $user->hash) ? $user : false;
    }

    public static function exists($pdo, $username) {

        $stmt = $pdo->prepare("SELECT `uid` FROM `users` WHERE `username` = ?");
        $stmt->execute([$username]);
        return $stmt->fetch(PDO::FETCH_COLUMN);
    }

    public static function fromUId($pdo, $uid) {

        $stmt = $pdo->prepare("SELECT * FROM `users` WHERE `uid` = ?");
        $stmt->execute([$uid]);
        $user = $stmt->fetchObject("User");
        $user->pdo = $pdo;
        return $user;
    }

    public function verify() {

        $stmt = $this->pdo->prepare("UPDATE `users` SET `verified` = 1 WHERE `uid` = ?");
        if ($stmt->execute([$this->uid])) {
            $this->verified = true;
            return true;
        } else {
            return false;
        }
    }
}

$db = Database::create();

$db->exec(
    "CREATE TABLE IF NOT EXISTS `users` (
        `uid` int NOT NULL PRIMARY KEY AUTO_INCREMENT,
        `username` varchar(100) NOT NULL UNIQUE,
        `email` varchar(100) NOT NULL UNIQUE,
        `verified` boolean DEFAULT 0,
        `hash` varchar(255) NOT NULL,
        `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
    )"
);

$db->exec(
    "CREATE TABLE IF NOT EXISTS `images` (
        `id` int NOT NULL PRIMARY KEY AUTO_INCREMENT,
        `uid` int NOT NULL,
        `image` varchar(255) NOT NULL,
        `like_count` int NOT NULL DEFAULT 0
    )"
);

$user = User::signUp($db, 'JohnDoe', 'john.doe@sample.org', '12345');

?>


texts: Understanding import/no-cycle problem in eslint

texts:
I have a some code in which eslint thrown an error of the type: import/no-cycle, but I don't understand where this cyclic dependency comes from.
The exact error thrown is: ESLint: Dependency cycle via ../types:7=>./Jobs:1(import/no-cycle).
File 1. jobs/Jobs
import { AuthJobs } from './Auth';

export interface IJobs {
  auth: AuthJobs;
  // ... more types
}

File 2. jobs/types
import { IJobs } from './Jobs';

// This class doesn't use IJobs
export interface JobRunResponse<D, F = undefined> {
  data?: any;
  dataError?: JobErrorResponse<D>;
}

File 3. jobs/Auth/AuthJobs
// Remember that in File 2, `JobRunResponse` doesn't use `IJobs`
// which at the same time is the one that uses `AuthJobs`
import { JobRunResponse } from '../types';

export class AuthJobs {
  // Class properties and methods
}

File 4. jobs/Auth/index
// Here is where eslint thown the error
export { AuthJobs } from './AuthJobs';

Folder structure
jobs
├── Auth
│   ├── AuthJobs.ts
│   └── index.ts
├── Jobs.ts
└── types.ts

Trying to understand where cyclical dependency comes from, I can think that when JobRunResponse from ../types it's imported in File 3(jobs/Auth/AuthJobs), implicitly import IJobs that use AuthJobs, but this doesn't make sense, I can't find any other explanation.
jobs/Jobs -> jobs/Auth/AuthJobs -> jobs/Auth/index -> jobs/Jobs


texts:
Within my game there are many entities, where each entity has a path (Array<Vector2>) assigned to it. No path to follow (indicating that the entity should move at all) is indicated by an empty path (the path is never null). updateMoveAttributes is called every frame for every entity, so it is important that it is efficient.

Note that my entity's direction is in radians, ranging from - Math.PI to Math.PI, since this is what Math.atan2 returns.

The below snippet contains updateMoveAttributes and its supporting methods.

private final Array<Vector2> path = new Array<>();
private int pathIndex = 0;

private static final float EPSILON = 1e-3f;

private float getXDifference(Vector2 pathComponent) {
    float xDifference = pathComponent.x - getSprite().getX();

    xDifference = Math.abs(xDifference) < EPSILON ? 0 : xDifference;

    return xDifference;
}

private float getYDifference(Vector2 pathComponent) {
    float yDifference = pathComponent.y - getSprite().getY();

    yDifference = Math.abs(yDifference) < EPSILON ? 0 : yDifference;

    return yDifference;
}

public float orient(Vector2 pathComponent) {
    float xDiff = getXDifference(pathComponent);
    float yDiff = getYDifference(pathComponent);

    return (float) Math.atan2(yDiff, xDiff);
}

void updateMoveAttributes() {
    // No path assigned
    if (getPath().size == 0)
        return;

    // No more path to travel
    if (getPathIndex() == getPath().size) {
        setSpeed(0);

        return;
    }

    Vector2 nextPathComponent = getPath().get(getPathIndex());
    float angleToComponent = orient(nextPathComponent);

    setDirection(angleToComponent);

    float xDiff = getXDifference(nextPathComponent);
    float yDiff = getYDifference(nextPathComponent);

    boolean angleInPositiveXQuadrants = (-Math.PI / 2 <= angleToComponent && angleToComponent <= Math.PI / 2);
    boolean pastX = angleInPositiveXQuadrants ? (xDiff <= 0) : (xDiff >= 0);

    boolean angleInPositiveYQuadrants = (0 <= angleToComponent) && (angleToComponent <= Math.PI);
    boolean pastY = angleInPositiveYQuadrants ? (yDiff <= 0) : (yDiff >= 0);

    // Indicates that we have passed the path component we are on route to, adjust course with respect
    // to next available path component.
    if (pastY && pastX)
        setPathIndex(getPathIndex() + 1);

    // In case user upgrades entity during travel of entity -> movement speed changes -> update required for actual speed
    setSpeed(getMovementSpeed());
}

public Array<Vector2> getPath() {
    return path;
}


texts: Getting input from user about 2×2×2 Rubik's Cube state

texts:
I was wondering if there was a way I could shorten this code that gets input from the user about the state of their 2×2×2 Rubik's Cube to solve it. I want it to still be informative so any user knows what to do, the thing is the method is pretty long.

static public int[][] scanCube(){

    int counter0 = 0;
    Scanner in = new Scanner(System.in);

    int[][] input = new int [6][4];

    System.out.println("Welcome to the 2x2x2 cube solver :)\n \n"
            + "Please enter your cube");
    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the TOP side\n");

    while(counter0 < 4){
        input[0][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the LEFT side");

    //reset the counter
    counter0 = 0;
    while(counter0 < 4){
        input[1][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the FRONT side");
    //reset the counter
    counter0 = 0;
    while(counter0 < 4){
        input[2][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the RIGHT side");
    //reset the counter
    counter0 = 0;
    while(counter0 < 4){
        input[3][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the BACK SIDE");
    //reset the counter
    counter0 = 0;
    while(counter0 < 4){
        input[4][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    System.out.println("NOTE: Rotate cube back to starting position before rotating the cube\n"
            + "for the bottom side input\n");

    System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
    System.out.println("Enter the colors for the BOTTOM side");
    //reset the counter
    counter0 = 0;
    while(counter0 < 4){
        input[5][counter0] = Integer.parseInt(in.nextLine());
        counter0++;
    }
    return input;
}


texts: Expanding tilde inside assignments and strings in bash

texts:
Inspired by the work Charles Duffy did in this answer and the work of Jonathan Leffler in this one and because I couldn't leave well-enough alone.

I went and wrote expandTilde.sh:

#!/bin/bash

doExpand() {
  local path
  local -a resultPathElements

  for path in "$@"; do
    : "$path"
    case $path in
      "~+")
        path=$PWD
        ;;
      "~+"/*)
        path=$PWD/${path#"~+/"}
        ;;
      "~-")
        path=$OLDPWD
        ;;
      "~-"/*)
        path=$OLDPWD/${path#"~-/"}
        ;;
      "~")
        path=${HOME-~}
        ;;
      "~"/*)
        path=$HOME/${path#"~/"}
        ;;
      "~"[0-9]|"~"[+-][0-9])
        local num=${path#"~"}
        local op=${num%%[0-9]*}
        num=${num#[+-]}
        local opath=$path
        if [ "$op" = "-" ]; then
          ((num+=1))
        fi
        path=${DIRSTACK[@]: $op$num:1}
        : "${path:=$opath}"
        ;;
      "~"*)
        local username=${path%%/*}
        username=${username#"~"}
        IFS=: read -r _ _ _ _ _ homedir _ < <(getent passwd "$username")
        if [ "$homedir" ]; then
            if [[ $path = */* ]]; then
              path=${homedir}/${path#*/}
            else
              path=$homedir
            fi
        fi
        ;;
    esac
    resultPathElements+=( "$path" )
  done
  local result
  printf -v result '%s:' "${resultPathElements[@]}"
  printf '%s\n' "${result%:}"
}

expandAssign() {
  local -a pathElements
  IFS=: read -r -a pathElements <<<"$1"
  : "${pathElements[@]}"
  doExpand "${pathElements[@]}"
}

expandString() {
    doExpand "$1"
}

So two questions:

Did I miss any cases or get any cases wrong? (Tests in the github repo.)
Can this be improved in any meaningful ways?


texts: How could this be written using continuation passing style?

texts:
Is there a way to use CPS in this code to make the two insert functions tail-call optimized?

defmodule BTree do

  defstruct tree: {node: nil, left: nil, right: nil}
  def new(element), do: %BTree{tree: {node: element, left: nil, right: nil}}

  #insert when there's some data in the tree
  def insert(%BTree{tree: {node: e, left: l, right: r}}, element) when e > element do
    newl = if l == nil, do: new(element), else: insert(l, element)
    %BTree{tree: {node: e, left: newl, right: r }}
  end

  def insert(%BTree{tree: {node: e, left: l, right: r}}, element) when e < element do
    newr = if r == nil, do: new(element), else: insert(r, element)
    %BTree{tree: {node: e, left: l, right: newr }}
  end

  def height(%BTree{tree: {node: _, left: l, right: r}}) do
    lh = if l != nil, do: height(l), else: 0
    rh = if r != nil, do: height(r), else: 0
    1 + max(lh, rh)
  end

end

#BTree.new(10) |> BTree.insert(5) |> BTree.insert(15) |> BTree.height()

As always any comments on idiomatic Elixir code and style are welcome as well.


texts: Best practice to create XML messages with DOMDocument class in PHP

texts:
I want to create XML messages for webservice communication. These messages should be created from a pool of reusable elements. Therefore I have created different classes. A "factory" class, that only returns a message class. An element class, that consists of the reusable parts and the message classes that are the blueprints for the desired XML messages.

My code delivers the expected result, but I'm looking for a best practice. Especially a way to get rid of rewriting the same save() and __construct method in every of the message classes.

Update:

  I have improved my example and moved the root property and the
  save() method from the message classes to the Elements class. I
  also changed the name of the method from save to getMessage as
  there is a DOMDocument method with the same name. Due to these
  changes I have little less redudant code. I still don't know if it is
  good practice, particularly to use the "grandparent" methods in the
  message classes.

// class to create webservice messages
class Messages{

    private function __construct(){}

    public static function get($type) {
        //some error handling if class not exists
        return new $type;
    }
}

// message no.1
class Message_1 extends Elements{

    public function __construct() {
        parent::__construct();
        $this->root = $this->createElement("message1");
    }

    public function add_anotherElement(){
        $this->root->appendChild($this->add_anotherElementBlock("foo", "bar"));
    }

    public function add_element(){
        $this->root->appendChild($this->add_someElementBlock("foo", "bar"));
    }
}

// message no.2
class Message_2 extends Elements {

    public function __construct() {
        parent::__construct();
        $this->root = $this->createElement("message2");
    }

    public function add_elements(){
        $this->root->appendChild($this->add_anotherElementBlock("foo", "bar"));
        $this->root->appendChild($this->add_someElementBlock("foo", "bar"));
    }

}

// message no.3
class Message_3 extends Elements {

    public function __construct() {
        parent::__construct();
        $this->root = $this->createElement("message3");
    }

    public function add_element(){
        // unique Element
        $this->root->appendChild($this->createElement("foo", "bar"));
    }

}

// reusable elements
class Elements extends DOMDocument{

    protected $root;

    protected function add_someElementBlock($foo, $bar) {
        $node = $this->createElement("root");

        $attr = $this->createAttribute("id");
        $attr->value = $foo;
        $node->appendChild($attr);

        $subnode = $this->createElement("sub",$bar);

        $node->appendChild($subnode);

        return $node;
    }

    protected function add_anotherElementBlock($foo, $bar) {
        $node = $this->createElement("anotherRoot");

        $subnode = $this->createElement("anotherSubNode",$bar);
        $attr = $this->createAttribute("anotherAttribute");
        $attr->value = $foo;
        $subnode->appendChild($attr);

        $node->appendChild($subnode);

        return $node;
    }

    public function getMessage(){
        return $this->saveXML($this->root);
    }
}

$message1 = Messages::get('Message_1');
$message1->add_element();
$message1->add_anotherElement();

$message2 = Messages::get('Message_2');
$message2->add_elements();

$message3 = Messages::get('Message_3');
$message3->add_element();

//********************************************
echo "
";
print_r(htmlentities($message1->getMessage()));
echo "
";
echo "
";
echo "
";
print_r(htmlentities($message2->getMessage()));
echo "
";
echo "
";
echo "
";
print_r(htmlentities($message3->getMessage()));
echo "
";


texts:
Follow up question Image processing using Python OOP library
I want to use multiprocessing to analyze several images in parallel:
class SegmentationType(object):
    DISPLAY_NAME = "invalid"

    def __init__(self, filename, path):
        self.filename = filename
        self.path = path
        self.input_data = None
        self.output_data = None

    def read_image(self):
        self.input_data =  cv2.imread(self.path + self.filename)[1]

    def write_image(self):
        cv2.imwrite(self.path + self.filename.split('.')[0] + '_' + self.DISPLAY_NAME + '.png', self.output_data)

    def process(self):
        # override in derived classes to perform an actual segmentation
        pass

    def start_pipeline(self):
        self.read_image()
        self.process()
        self.write_image()

class HSV_Segmenter(SegmentationType):
    DISPLAY_NAME = 'HSV'

    def process(self):
        source = rgb_to_hsv(self.input_data)
        self.output_data = treshold_otsu(source)

class LabSegmenter(SegmentationType):
    DISPLAY_NAME = 'LAB'

    def process(self):
        source = rgb_to_lab(self.input_data)
        self.output_data = global_threshold(source)

segmenter_class = {
'hsv': HSV_Segmentation,
'lab': LAB_Segmenter
}.get(procedure)

if not segmenter_class:
    raise ArgumentError("Invalid segmentation method '{}'".format(procedure))

for img in images:
    os.chdir(img_dir)
    processor =  = segmenter_class(img, img_dir, procedure)
    processor.start_pipeline()

What I tried so far:
image_lst = os.listdir(my_image_path)

# We split the list into sublist with 5 elements because of 512 GB RAM limitation
if len(image_lst) > 4:
    nr_of_sublists = (int(len(image_lst)/2.5))
    image_sub_lst  =(np.array_split(image_lst, nr_of_sublists))
else:
    image_sub_lst = [image_lst]

# We do the analysis for each sublist
for sub_lst in image_sub_lst:
    print (sub_lst)
    pool = multiprocessing.Pool(8)

    # Call the processor
    processor =  = segmenter_class(img, img_dir, procedure)
    processor.start_pipeline()
    # How to call map???
    pool.map(?, sub_lst)
    pool.terminate()


texts: Java creating augmented array of size 400,000,000

texts:
I was solving one competitive coding question having integer bounds 2^100. Fortunately, it was a dp question and I didn't need an array of that size. Practically we cannot create an array of size more than Integer.MAX_VALUE.

But I was thinking of creating a multidimensional array and treat it as a one-dimensional array.

what I need was a very large array with O(1) retrieval time. So Internally it will be a multidimensional array but I will treat it as a one-dimensional array.
So the size of the resultant array will be n*n.

if n is Integer.MAX_VALUE then the resultant augmented array will be of Integer.MAX * Integer.MAX

Here what I did to implement this idea.
BigArray class
public class BigArray
{

    private int[][] arr;
    private int row=0;
    private int col = 0;
    private int size;
    public BigArray(int size)
    {
        arr = new int[size][size];
        this.size = size;
    }
}

add method
public void add(int data)
    {
     if(row > size-1)
        {
            col++;
            row=0;
            this.arr[col][row] = data;
            row++;
        }
        else
        {
            this.arr[col][row] = data;
            row++;
        }
    }

get method
public int get(int pos)
    { //get value in O(1)
        if((int) Math.sqrt(pos) > size)
            return -1;
        int col1 = pos/(size);
        int row1 = pos%(size);
        return arr[col1][row1];
    }

But If I pass Integer.MAX_VALUE in BigArray it throws Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
maximum size I've tried is 20,000 so resultant size will be 20,000 x 20,000 = 400,000,000.
But if add one more dimension to this array I'll get more space.
if BigArray has arr[][][] resultant size will be n x n x n;
if BigArray has arr[][][][] resultant size will be n x n x n x n; and so on.
I know I had to implement necessary methods as I add a new dimension to the base array.
But I would like a review on this type of storage class. I don't know

what's the maximum dimensions java array can have?

Also, do tell me

if can use this approach to create arrays size more than the traditional array size
Future scope such as generic BigArray of character will create string greater size
other opinions/suggestions on this approach


texts:
I've written a small webapp in JavaScript, and am now essentially rewriting it to use RequireJS.  I'm doing this partly to get more familiar with RequireJS (which I have little experience with), as well as for ease of maintaining and upgrading the app.

I'm hoping to get feedback on whether the structure I'm looking at implementing is reasonable/useful/extensible/totally insane.  I've been through the require docs, reading related SO posts and some samples on GitHub, but I'm not sure I'm totally 'getting' Require.

If there are fundamental flaws in the logic it'd be great to get some links to resources (either JS or RequireJS specific), and to get feedback about the overall structure of the app itself.  Suggestions for design patterns also very much appreciated, there's some stuff in there that feels kind of counter intuitive.

main.js

require({

    paths: {
        jquery: '../bower_components/jquery/jquery'
    }

}, function() {
    'use strict';
    require(['jquery', 'app', 'reader', 'env'], function($, App, Reader, Env) {

        $(document).ready(function() {

            var app = new App(
                new Reader(),
                new Env()
            );

        });

    })

});

app.js

define(function() {

    return function(reader, env) {

        this.reader = reader,
        this.env = env

    };

});

reader.js (it's an online e-reader)

define(['jquery'], function($) {

    return function() {

        this.components = [],
        this.firstPage = null,
        this.lastPage = null,
        this.maxFontSize = function() {
            return this.env.isIOS() ? 120 : 160;
        }

    };

});

env.js

define(['jquery'], function($) {

    return function() {

        this.isIOS = function() {
            return navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false; // for example.
        }

    };

});


texts:
The exercise i am working on requires me to read a binary sequence stored in a text file. The objective is to find the occurrences of all subsequences of length between a and b (their values are given in the function parameters) and put them in a list of tuples.
For example: If the following binary sequence is given as input and the length of each subsequence should be between 2 and 4:
a = 2
b = 4

01010010010001000111101100001010011001111000010010011110010000000

I should write a program to generate the following output:
[(1, ["1011", "1101"]),
 (2, ["0101", "0110", "1010"]),
 (3, ["0111", "101", "1110", "1111"]),
 (4, ["0001", "0011", "1100"]),
 (5, ["011", "1000", "110"]),
 (6, ["0000", "111"]),
 (7, ["0010", "1001"]),
 (8, ["0100"]),
 (10, ["010"]),
 (11, ["000", "001", "11"]),
 (12, ["100"]),
 (15, ["01", "10"]),
 (23, ["00"] )]

You will notice that each tuple in the list has two elements. The first element is the number of times a subsequence appears in the given sequence whilst the second element is the list containing the corresponding subsequences.
E.g. the first tuple indicates that the subsequences "1011" and "1101" appear only once in the given sequence.
The solution i have written does solve the problem (it passes all correctness tests), but it is slow and doesn't pass the performance tests (it only passes 5 out of 22 tests) in which the maximum timeout is set to 1 second. How could i make this solution faster?
I am not allowed to import any external libraries.
def ex1(ftesto,a,b,n):
    with open(ftesto,encoding='utf8') as f:
        S = f.read().replace('\n','')
    N = len(S)
    D = {}
    subsequences = {}
    for i in range(N+1):
        for j in range(i+1,N+1):
            if a <= len(S[i:j]) <= b:
                if S[i:j] not in D:
                    D[S[i:j]] = 1
                else:
                    D[S[i:j]] += 1
    for k,v in D.items():
        subsequences.setdefault(v,[]).append(k)
    result = sorted([(k,sorted(v)) for k,v in subsequences.items()])
    return result[:n]

if __name__ == '__main__':

   ftesto = 'ft1.txt'
   a = 2
   b = 4
   n = 20

The amount of elements in the list must be equal or less than "n". That explains why i am using the slicing at the end of the function.


texts:
Here's my implementation of a Stack in Java, all feedback welcome.

import java.util.Iterator;

public class Stack<T> implements Iterable<T> {
    private Node head = null;
    private int size;

    @Override
    public Iterator<T> iterator() {
        return new StackIterator();
    }

    private class Node<T>{

        public Node(T data){
            this.data = data;
            this.next = null;
        }
        T data;
        Node next;
    }

    private class StackIterator implements Iterator<T>{

        private Node current = head;
        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public T next() {
            T item = (T) current.data;
            current = current.next;
            return item;
        }
    }

    public Stack(){
        size = 0;
        head = null;
    }

    public boolean isEmpty(){
        return head == null;

    }

    public void push(T item){
        Node p = new Node(item);
        if(head == null){
            head = p;
            size++;
            return;
        }
        p.next = head;
        head = p;
        size++;

    }

    public T pop(){
        Node current = head;
        if(current.next == null){
            head = null;
        }else{
            try {

                head = head.next;
                size--;
            }catch (Exception e){
                System.out.println("Popping off an empty stack:" + e);
            }
        }

        return (T)current.data;
    }

    public void trace(){
        Node current = head;
        while(current != null){
            System.out.println(current.data);
            current = current.next;
        }
    }
}


texts: Generating a list of menus with AngularJS

texts:
Some days ago, I decided to start learning a JS framework in order to gain skills and become more useful at work. I choose Angular for the purpose, and started learning it by building up my "professional" personal website.

In this site, one of the biggest obstacles I could encounter was the extremely "bogging" way of adding new stuff with plain HTML. Thus, after some readings, I made an Angular app that generates an ordered list from a Javascript array of JSON descriptors.

For transparency, I made a snippet being as short as possible, while keeping it functionally identical.

<!DOCTYPE html>

                 {{ x.content }}

Is it OK this way? That final call after body is slightly annoying for me, but I can't do anything against it.

Are there maybe any additional point to improve this code?


texts:
I am trying to construct a binary message packet. It needs to escape binary value 0 by appending extra 0 in front of it:

//Before escape
data[] = { 1, 2, 3, 4, 5, 0, 6, 7, 8, 9 }

//After escape - value 0 is appended after 0
data[] = { 1, 2, 3, 4, 5, 0, 0, 6, 7, 8, 9 }

My source code:

uint8_t escape_data[32];
uint8_t escape_index = 0;
uint8_t data[] = { 1, 2, 3, 4, 5, 0, 6, 7, 8, 9 };

for (int i = 0; i < sizeof(data); i++)
{
    escape_data[escape_index++] = data[i];
    if (data[i] == 0) {
        escape_data[escape_index++] = 0;
    }
}

Is there any elegant way to solve this problem?

P.S the code above is designed to be simple to read, I ignore those array sizing for simplicity and hard coding them, I want to know a good algorithm or a good way to write to solve this problem with the least variable and memory footprint

Searching for 0
Appending byte in between array


texts:
This morning I've seen this on Twitter:
http://mynewtechworld.tumblr.com/post/135545896048

I case that somebody can't see the image:

  I
  01101100
  01101111
  01110110
  01100101
  you.

Just for fun I wrote this binary to ascii-converter in JavaScript:

var chars = [
  'I ',
  0b01101100,
  0b01101111,
  0b01110110,
  0b01100101,
  ' you.'
];

var result = chars.reduce(function(previous, current) {

  if (!isNaN(current)) {
    current = String.fromCharCode(current.toString());
  }

  return previous + current;
}, '');

My complete implementation on CodePen