texts:
I'm using a Promise chain to write some data to a file, execute a command on it, inspect its results, and send the results, using Express.js. The thing about my function is that I need to be able to exit early from multiple conditions.

The following code comes from an Express.js handler. my-command is a command that takes one input file, and outputs either resultWithBadName.txt, when the output is only one "page," and result-{id}.txt, when the output has multiple pages.

var cp = require('child_process'),
    Promise = require('bluebird');

var results,
    id = req.param.id; // from user

promisifiedWriteFile('src.txt', 'foobar' /* real content from user */).catch(function (err) {
    return Promise.reject({ text: 'Cannot write file', err: err });
}).then(function() {
    return exec(
        'my-command src.txt'
    ).catch(function (err) {
        // Considered a user error.
        res.send({
            error: err.stderr,
            id: id,
            pages: 0
        });
        return Promise.reject('DONE');     // UGLY
    });
}).then(function (ret) {
    results = ret;
    // Check if output only has one page
    return promisifiedStat(
        'resultWithBadName.txt'
    ).catch(function () {
        // Nope, has multiple pages. Coutn how many pages there are.
        return countPagesInOutput(id).then(function (pages) {
            res.send({
                output: results.stderr,
                id: id,
                pages: pages
            });
            return Promise.reject('DONE'); // UGLY
        });
    });
}).then(function () {
    // Yep, only has one page. Let's make the result have standard naming scheme.
    return promisifiedRename(
        'resultWithBadName.txt',
        'result' + id + '.txt'
    ).catch(function (err) {
        return Promise.reject({ text: 'file rename failed', err: err });
    });
}).then(function () {
    res.send({
        output: results.stderr,
        id: id,
        pages: 1
    });
}).catch(function (err) {
    if (err === 'DONE') return;         // UGLY
    res.status(500).send('Internal server error: ' +
        (err.text || err.message || '')
    );
    console.error(err.err || err);
}).catch(console.error);

function exec() {
    var args = [].slice.apply(arguments);
    return new Promise(function (fulfill, reject) {
        args.push(function (err, stdout, stderr) {
            if (err) {
                err.stderr = stderr;
                return reject(err);
            }
            fulfill({
                stdout: stdout,
                stderr: stderr
            });
        });
        cp.exec.apply(cp, args);
    });
};

I have read somewhere that one can chain the thens inside a onFulfilled handler, but that adds even more pyramids to my code, which Promises are supposed to prevent…

Now my question is, is there a way to remove the ugly 'DONE' hack?


texts: Traverse materialized path hierarchy for children nodes

texts:
I have a sorted list of materialized hierarchy paths:

paths = ['10001', '1000100001', '100010000100001', '100010000100002', '1000100002', '100010000200001', '100010000200002']

I am getting the immediate children paths (nodes) for each non leaf node.

steplen = 5 # size of each hierarchy step
max_depth = len(max(paths, key=len)) // steplen
def _traverse_hierarchy(parent='', idx=0) -> Tuple[int, List[str]]:
    children_paths_for_parent = []
    while idx < len(paths) and paths[idx].startswith(parent):
        path = paths[idx]
        if len(path) == len(parent) + steplen: # direct report
            children_paths_for_parent.append(path)

        idx += 1
        if len(path) // steplen != max_depth: # not leaf node
            new_idx, children_paths = _traverse_hierarchy(parent=path, idx=idx)
            print(f'Direct Reports for {path}', children_paths)
            idx = new_idx

    return idx, children_paths_for_parent

I'm not concerned about getting a stack overflow error (the hierarchy won't be too deep).

How can I improve/optimize this code?


texts:
I want to make post editing on my blog. I get data from a form and want to put it into a database. I'm not sure if using setters is the best way, so maybe you can show me better solution?

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
  $formData = $form->getData();

  $post->setTitle($formData->getTitle());
  $post->setText($formData->getText());
  $post->setAuthor($formData->getAuthor());
  $em->flush();

  $this->addFlash(
    'notice',
    'Post updated!'
  );

  return $this->redirectToRoute('admin');
}


texts: Efficiently Generate Subset of all Permutations or Combinations with and without Repetition (C++)

texts:
Suppose I want to write some functions which return the vector containing a vector representing all permutations or combinations with or without repetition (dependent on the function) of a subset of a given size of a given input vector.  Right now, my code is looking like this:

#include <vector>
#include <algorithm>
#include <iostream>

template <typename T>
struct permcomb
{
  std::vector<std::vector<T>> end_set;
  std::vector<T>* data;
  permcomb(std::vector<T>& param) : data(&param) {}

  void permutation_help(std::vector<T> seen, int recurse_num, bool repetition, bool comb)
  {
    if(recurse_num == 0)
    {
      if(end_set.size() > 0 && comb)
      {
        bool f = false;
        for(int i = 0; i < end_set.size(); i++)
        {
          if(std::is_permutation(end_set[i].begin(), end_set[i].end(), seen.begin()))
          {
            f = true;
          }
        }
        if(!f)
        {
          end_set.push_back(seen);
        }
      }
      else // permutations always choose this one
      {
        end_set.push_back(seen);
      }
    }
    else
    {
      for(int i = 0; i < (*data).size(); i++)
      {
        if(repetition || find(seen.begin(), seen.end(), (*data)[i]) == seen.end()) // if not found
        {
          seen.push_back((*data)[i]);
          permutation_help(seen, recurse_num - 1, repetition, comb);
          seen.pop_back();
        }
      }
    }
  }
};

// return all permutations no repetition
template <typename T>
std::vector<std::vector<T>> rapnr(std::vector<T>& data, int subset_size)
{
  permcomb<T> helpstruct(data);
  std::vector<T> empty {};
  helpstruct.permutation_help(empty, subset_size, false, false);
  return helpstruct.end_set;
}

// return all permutations with repetition
template <typename T>
std::vector<std::vector<T>> rapwr(std::vector<T>& data, int subset_size)
{
  permcomb<T> helpstruct(data);
  std::vector<T> empty {};
  helpstruct.permutation_help(empty, subset_size, true, false);
  return helpstruct.end_set;
}

// return all combinations no repitition
template <typename T>
std::vector<std::vector<T>> racnr(std::vector<T>& data, int subset_size)
{
  permcomb<T> helpstruct(data);
  std::vector<T> empty {};
  helpstruct.permutation_help(empty, subset_size, false, true);
  return helpstruct.end_set;
}

// return all combinations with repetition
template <typename T>
std::vector<std::vector<T>> racwr(std::vector<T>& data, int subset_size)
{
  permcomb<T> helpstruct(data);
  std::vector<T> empty {};
  helpstruct.permutation_help(empty, subset_size, true, true);
  return helpstruct.end_set;
}

This seems to be giving me the right answers so far... but I'm not really happy with the way I went about generating the combinations.  Literally the only thing I could think of doing was generating all of the permutations and then eliminating all but one of those which were permutations of each other.  This clearly doesn't seem very efficient, but I was at a loss for else I could do.  Similarly, I don't feel as I generated the permutations that well either since I always have to go back and search for items that I've already inserted to make sure that I don't insert them again (in the case that repetition isn't allowed).  So what steps can I take to optimize what I have so far?


texts:
I am fairly new to Python and I'm trying to make a script that does three basic things: prints the contents of a file, overwrites it with your new lines, and prints the new file. I rewrote the script with functions and was looking for critiques. Is this a good use of functions? What would you do different?

print("Type the name of the file for overwriting.")
file = input(">")
x = open(file)
print("The contents are currently: \n", x.read())
print("Enter in the new lines")
l1 = input(">")
l2 = input(">")
l3 = input(">")
x.close()

y = open(file, 'w')

print("Entering new lines.")

y.write(l1 + '\n' + l2 + '\n' + l3)
y.close()

z = open(file).read()
print("The new contents are:")
print(z)

Script with functions:

def open_and_read(x):
    print(open(x).read())

def nl(x):
    z.write(x + '\n')

temp = ">"
print("Type the name of the file for overwriting.")
file = input(temp)
print(f"The current content of {file} is:")
open_and_read(file)

z = open(file, 'w')

print("Enter in three new lines of text:")
l1 = input(temp)
l2 = input(temp)
l3 = input(temp)

nl(l1)
nl(l2)
nl(l3)

z.close()

print("The new contents are:")
open_and_read(file)


texts: Codility AbsDistinct: Why is this solution not O(n)?

texts:
This is part of a series of algorithmic lessons and tests by Codility.

For copyright reasons, I cannot reproduce the question, which asks to compute the number of distinct absolute values in a given sorted array.

The question requires a response in \$O(n)\$ time complexity. My response (below) was detected as \$O(n*log(n))\$ by Codility, but I have no idea why. It looks to me like we're only going to go over each item of the array once. Am I wrong or is this \$O(n)\$?

public int solution(int[] A) {
    // write your code in Java SE 8
    int result = 0;
    int start = 0;
    int end = A.length - 1;

    while (start <= end) {
        result++;
        int startValue = Math.abs(A[start]);
        int endValue = Math.abs(A[end]);
        int currentValueFound = Math.max(startValue, endValue);
        while (start <= end && Math.abs(A[start]) == currentValueFound) {
            start++;
        }
        while (start <= end && Math.abs(A[end]) == currentValueFound) {
            end--;
        }
    }
    return result;
}

In addition, if anyone has an idea what could have triggered the error in the arth_overflow test, I am interested.


texts: Getting the order of values so none are hidden

texts:
if (parseInt(obj[0].actual) > parseInt(obj[0].projected) && parseInt(obj[0].projected) > parseInt(obj[0].le)) {
    biggesteClass = 'bar';
    biggestVal = obj[0].actual;
    secondClass ='bar2';
    secondVal = obj[0].projected;
    thirdClass ='bar3';
    thirdVal = obj[0].le;
} else if (parseInt(obj[0].actual) > parseInt(obj[0].le) && parseInt(obj[0].le) > parseInt(obj[0].projected)) {
    biggesteClass = 'bar';
    biggestVal = obj[0].actual;
    secondClass = 'bar3';
    secondVal = obj[0].le;
    thirdClass ='bar2';
    thirdVal = obj[0].projected;
} else if (parseInt(obj[0].projected) > parseInt(obj[0].actual) && parseInt(obj[0].actual) > parseInt(obj[0].le)) {
    biggesteClass = 'bar2';
    biggestVal = obj[0].projected;
    secondClass ='bar';
    secondVal = obj[0].actual;
    thirdClass ='bar3';
    thirdVal = obj[0].le;
}  else if (parseInt(obj[0].projected) > parseInt(obj[0].le) && parseInt(obj[0].le) > parseInt(obj[0].actual)) {
    biggesteClass = 'bar2';
    biggestVal = obj[0].projected;
    secondClass ='bar3';
    secondVal = obj[0].le;
    thirdClass ='bar';
    thirdVal = parseInt(obj[0].actual);
} else if (parseInt(obj[0].le) > parseInt(obj[0].actual) && parseInt(obj[0].actual) > parseInt(obj[0].projected)) {
    biggesteClass = 'bar3';
    biggestVal = obj[0].le;
    secondClass ='bar';
    secondVal = obj[0].actual;
    thirdClass ='bar2';
    thirdVal = obj[0].projected;
} else {
    biggesteClass = 'bar3';
    biggestVal = obj[0].le;
    secondClass ='bar2';
    secondVal = obj[0].projected;
    thirdClass ='bar';
    thirdVal = obj[0].actual;
}

What I am trying to do here is, I am setting the biggest, second, and third value to create an overlapped bar-chart for d3.js.

// Select, append to SVG, and add attributes to rectangles for bar chart
svg.selectAll("." + biggesteClass)
    .data(obj)
    .enter().append("rect")
        .attr("class", biggesteClass)
        .attr("height", function(d, i) {return (biggestVal * 10)})
        .attr("width","150")
        .attr("x", function(d, i) {return (i * 80) + 25})
        .attr("y", function(d, i) {return 280 - (biggestVal * 10)});
svg.selectAll("." + secondClass)
    .data(obj)
    .enter().append("rect")
        .attr("class", secondClass)
        .attr("height", function(d, i) {return (secondVal * 10)})
        .attr("width","150")
        .attr("x", function(d, i) {return (i * 80) + 25})
        .attr("y", function(d, i) {return 280 - (secondVal * 10)});
svg.selectAll("." + thirdClass)
    .data(obj)
    .enter().append("rect")
        .attr("class", thirdClass)
        .attr("height", function(d, i) {return (thirdVal * 10)})
        .attr("width","150")
        .attr("x", function(d, i) {return (i * 80) + 25})
        .attr("y", function(d, i) {return 280 - (thirdVal * 10)});

I needed to find the order of the values, since the smallest value has to go last not to get covered (hidden) by the bigger values.

The thing is, I think my first code snippet is messy and can be better, but not sure how to.

How can I refactor it not to look code-smelly?


texts:
I have done this small piece of code used to search for a given word across several fields of a Django model.

Goal was to have first entries equals to the word, then entries starting by the world and finally just entries containing it.

I would like to have feedback on it :

# -*- coding: utf-8 -*-
"""Module created to search a specific term in several fields of a model"""
from itertools import chain
import operator

from django.db.models import Q

__author__ = 'trnsnt'

def search_for_term(model, term, fields, number=10):
    """
    Generic method used to search term on list of fields.
    Return first fields equals to term, then fields starting by the term, and at the end fields containing term
    :param model: Django model class
    :param term: Searched term
    :param fields: Fields to look for
    :param number: Number of wanted response
    :return: List of objects
    """
    searcher = ['iexact', 'istartswith', 'icontains']
    objects = []
    for search in searcher:
        curr_filter = reduce(operator.or_, [Q(('%s__%s' % (field, search), term)) for field in fields])
        # Need to search for number to handle duplicate objects
        objects = uniquify(objects, model.objects.filter(curr_filter)[:number])[:number]
        if len(objects) == number:
            return objects
    return objects

def uniquify(*queryests):
    """Take several queryset and return list of unique object
    :param queryests: QuerySets we want to uniquify
    """
    seen = set()
    return [x for x in chain(*queryests) if not (x in seen or seen.add(x))]


texts: Function for splitting an integer into smaller values

texts:
This is the function I've implemented in an answer to this question.  I've tried to make this as simple and idiomatic as possible, using C++11.  Could this still be improved in any way?

#include <algorithm>
#include <cstdint>
#include <iostream>
#include <iterator>
#include <vector>

typedef std::vector<int> SplitValues;

SplitValues splitter(std::int32_t number)
{
    SplitValues values(8);

    for (auto& iter : values)
    {
        iter = static_cast<int>(number & 0xF);
        number >>= 4;
    }

    return values;
}

int main()
{
    std::int32_t number = 432214123;

    SplitValues values = splitter(number);

    std::reverse_copy(values.begin(), values.end(),
        std::ostream_iterator<int>(std::cout, " "));
}

Test run

Questions:

Is SplitValues an appropriate name for a typedef, or does it sound more like a variable?
If I pass the hard-coded number instead of the number variable, will it still be treated as the same type as the parameter?


texts: Generating CSV strings for various 3rd party utilities

texts:
I'm generating CSV strings for various 3rd party utilities and this section of code gets repeated in many classes. Is there a better way to generate this string?

public override string CsvString()
{
    return (
        string.Format("\u0022{0}\u0022,\u0022{1}\u0022,\u0022{2}\u0022,\u0022{3}\u0022,\u0022{4}\u0022,\u0022{5}\u0022,\u0022{6}\u0022,\u0022{7}\u0022,\u0022{8}\u0022,\u0022{9}\u0022,\u0022{10}\u0022,\u0022{11}\u0022,\u0022{12}\u0022,\u0022{13}\u0022",

        this.BlockType,         //  1, A_NAME
        this.Tag,               //  2, A_TAG
        this.Description,       //  3, A_DESC
        this.InitialScan,       //  4, A_ISCAN
        this.AutoManual,        //  5, A_SCAN
        this.ScanTime,          //  6, A_SCANT
        this.IoDevice,          //  7, A_IODV
        this.IoAddress,         //  8, A_IOAD
        this.InitialAmStatus,   //  9, A_IAM
        this.AlarmPriority,     // 10, A_PRI
        this.AlarmEnable,       // 11, A_ENAB
        this.EnableOutput,      // 12, A_EOUT
        this.HistDescription,   // 13, A_HIST_DESC
        this.SecurityArea1      // 14, A_SECURITYAREA1
    ));
}


texts: Move array element to the first position

texts:
I wrote an update() function to make an entry the first element in an array.

var arr = [
    {v: 1},
    {v: 2},
    {v: 3},
    {v: 4},
];

function update(e) {
    var i = arr.findIndex(o => o.v === e.v);
    if (i === 0) return;
    if (i > 0) arr = [e].concat(arr.slice(0, i), arr.slice(i+1));
    if (i < 0) arr = [e].concat(arr.slice(0, arr.length - 1)); // keep the array has 4 elements
}

update({v: 1});
update({v: 2});
update({v: 6});

Is there any better way to do this? I think slice and concat will make the performance not good.


texts: Best way convert byte array to hex string

texts:
Is it possible to write this method in a prettier way?

public static string ByteArrayToString(byte[] byteArray)
{
  var hex = new StringBuilder(byteArray.Length * 2);
  foreach (var b in byteArray)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}


texts: Meeting Point problem from interviewstreet.com

texts:
I am trying to solve the "Meeting Point" problem from interviewstreet.com:

  There is an infinite integer grid at which N people have their houses on. They decide to unite at a common meeting place, which is someone's house.
  From any given cell, all 8 adjacent cells are reachable in 1 unit of time.
  eg: (x,y) can be reached from (x-1,y+1) in a single unit of time.
  Find a common meeting place which minimises the sum of the travel times of all the persons.

For example, if the input is:

4
0 1
2 5
3 1
4 0

the output must be 8. Here's my solution:

def pos(a):
    if a<0:
        return -a
    else:
        return a
n = long(raw_input())
min =0
inputs = []
for i in range(n):
    temp = raw_input().split()
    inputs.append([long(temp[0]),long(temp[1])])
x = inputs[0][0]
y = inputs[0][1]
for i in range(n):
    min += max(pos(x-inputs[i][0]),pos(y-inputs[i][1]))
for i in range(1,n):
    x = inputs[i][0]
    y = inputs[i][1]
    temp =0
    for j in range(n):
        temp += max(pos(x-inputs[j][0]),pos(y-inputs[j][1]))
    if min>temp:
        min =temp
print min

I know I am brute forcing the answer but I couldn't find an algorithm that fits the problem. I have been thinking about the problem statement for a while yet I don't have any clue how to optimize it. If any of you could help me with the code in Python or C.


texts:
I finally got my upload form and code that uploads to db. I used tutorial from this site.

As I am php newbie, I want to know how secure this code is and if it is not secure at all (which I am almost sure of...) could someone tell me how to make it secure. This upload should be only for pdf, jpeg, jpg, doc files. Also this upload will be available to public.

<form method="post" enctype="multipart/form-data">

please select a file

<input type="hidden" name="MAX_FILE_SIZE"
value="16000000">
<input name="userfile" type="file" id="userfile">

<input name="upload"
type="submit" class="box" id="upload" value=" Upload ">

</form>

<?php
if(isset($_POST['upload'])&&$_FILES['userfile']['size']>0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fileType=(get_magic_quotes_gpc()==0 ? mysql_real_escape_string(
$_FILES['userfile']['type']) : mysql_real_escape_string(
stripslashes ($_FILES['userfile'])));
$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
    $fileName = addslashes($fileName);
}
$con = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
$db = mysql_select_db('olearyinternational', $con);
if($db){
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
mysql_close();
echo "
File $fileName uploaded
";
}else { echo "file upload failed"; }
}
?>


texts:
I'm getting an array and I needed to find a duplicate ID inside:

var aDuplicateId = [];
            //get the duplicated configuration indexs
            for (var i = 0; i < aConfigurations.length; i++) {
                //in case the index is the duplicate array skip
                if (aDuplicateId.indexOf(i) >= 0) {
                    continue;
                }
                var iId = aConfigurations[i]._metadata.id;
                //find duplicate ids
                var iIndex = _.findLastIndex(aConfigurations, function(o) {
                    return o._metadata.id === iId;
                });
                //add the duplicate id index to array
                if (iIndex >= 0 && iIndex !== i) {
                    aDuplicateId.push(iIndex);
                }
            }


texts:
I have the following data frame:

real_test <- as.data.frame(matrix(rep(NA, 12), nrow = 4, ncol = 3))
real_test$V1 <- c("1 NA NA NA", "1 2 NA NA", "1 NA 3 NA", "1 2 3 NA")
real_test$V2 <- c(1, 2, 2, 3)
real_test$V3 <- c(1, 1, 1, 1)
names(real_test) <- c("BUCKET", "POS_BREADTH", "freq")

For each element of real_test$BUCKET I want to return the next real_test$BUCKET using the following approach:

This function returns all non-NA elements of any given x

pat <- function(x){
      x <- as.vector(read.table(text = x, sep = " ", colClasses = "numeric"))
      ready <- x[!is.na(x)]
      return(paste(ready, sep = ","))
    }

This function looks for an item with +1 POS_BREADTH

segment <- function(x, y){
  inter <- real_test[colSums(outer(paste("\\b", pat(x), "\\b", sep = ""), real_test$BUCKET, Vectorize(grepl))) == length(pat(x)),]
  inter <- inter[inter$POS_BREADTH == y + 1, c(1,3)]
  return(inter$BUCKET[which.max(inter$freq)])
}

And I use mapply to pass the column names as x and y in a function:

real_test$TARTGET <- mapply(segment, real_test$BUCKET, real_test$POS_BREADTH)

Is there a faster way? The \\bpat(x)\\b is intentional since I want to have a full match in grepl.


texts: Test whether a string representing an object n-levels deep is available

texts:
I was writing some JavaScript that depended on several global variables being present.

I read about the "guard pattern" from a StackOverflow answer but since I need to check for multiple objects it quickly becomes quite tedious to have lines like this everywhere:

if (foo && foo.bar && foo.bar.baz) {
    // access foo.bar.baz
}

I wanted to replace the above with:

if (isAvailable("foo.bar.baz")) {
    // access foo.bar.baz
}

Here is the implementation for isAvailable:

// test whether a string that represents an object in a certain
// context (using dot notation) of n-levels deep is available
function isAvailable(s,context) {
    var aSplit, ob;

    if (s === undefined || s === null) {
        return false;
    }

    aSplit = s.split('.');
    ob = context[aSplit.shift()];
    while (ob !== undefined && aSplit.length > 0) {
        ob = ob[aSplit.shift()];
    }
    return typeof ob === "object";
}

Here is a JSBin: http://jsbin.com/jokowomepo/edit?js,console

Also, I should mention that I am only interested in solving this problem with vanilla JavaScript...no libs.

My implementation seems to work, but I'd be interested if there are improvements that could be made.

Any feedback?


texts:
In an array of strings 'a' having 'n' strings i have to select the Palin Pairs from the given strings .for ex for input 3 bba abb abb Output=2

I am getting correct output but want to reduce time complexity....what other logic or enhancement I can use to optimize the code

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;

public class TestClass {

public static void main(String[] args) throws Exception {
    Date d=new Date();

     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     ArrayList<StringBuffer> al=new ArrayList<StringBuffer>();
     int count=0;
     int no=Integer.parseInt(br.readLine());
     for (int i = 0; i < no; i++) {

     String line=br.readLine();

       al.add(new StringBuffer(line));
     }
     long ts1=System.nanoTime();
     int i=0;
     int j=0;
    for( i=0;i<al.size();i++){
        StringBuffer str=al.get(i);
        String comp=str.toString();
            for(j=i+1;j<al.size();j++){
                StringBuffer rev=al.get(j);

                String st=(rev.reverse()).toString();

                if(st.equals(comp)){
                    count++;
                }

            }
    }
    System.out.println(count);

}

}


texts: Enum conversion to Enumeration class with small Business Logic inside

texts:
I had old enum, I converted it to Enumeration class and added one method inside (isValid). I am not sure if it is good approach to add such small business logic into Enumeration class. I would like to understand if this is a good approach or not.

Here is old enum:

internal enum Rule
{
    None = 0,

    CompensationIsZero = 1,

    CompensationLessThanDemand = 2,

    CompensationBetweenZeroAndDemand = 3,

    CompensationEqualsDemand = 4,

    CompensationLessOrEqualsDemand = 5
}

Here it is rewritten to Enumeration class and IsValid method is added.

 public class Rule : Enumeration
{
        public static readonly Rule None = new Rule (0, "None");
        public static readonly Rule CompensationIsZero  = new Rule (1, "CompensationIsZero ");
        public static readonly Rule CompensationLessThanDemand = new Rule(2, "CompensationLessThanDemand ");
       ....
       // there are about 5 rules

       public Rule(int id, string name)
        : base(id, name)
       { }

        public bool IsValid(decimal compensation, decimal demand, int rule) {
                if (rule == Rule.None.Id) return true;
                if (rule == Rule.CompensationIsZero.Id) then return compensation == 0;
                if (rule == Rule.CompensationLessThanDemand .Id) then return compensation < demand;

                ...
         }
}

Enumeration class implementation version is very similar like in this article (https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types)

Thus I have values compensation and demand (these come from UI).
And I have some type based on which I get Rule value from database.
And so I call method IsValid (compensation, demand, ruleIdFromDb). If it is not validated then I show error on UI.


texts:
In a Python (3.6) application I receive messages from Kafka in JSON format. (The code base makes heavy use of static type annotations, and every file is automatically checked using mypy --strict to catch type errors as early as possible.)

So I try to deserialize the received messages into objects immediately in order to avoid working with Dict[str, Any] instances in the downstream code. I'd like the deserialization to be type-safe, i.e., to not only fail if not all class members are defined in the JSON string, but also if one or more of them have an incorrect type.

My current approach looks as follows:

(The class Foo in the unit tests is an example of a typical target_class.)

#!/usr/bin/env python3

"""
Type-safe JSON deserialization
"""

import inspect
from typing import Any, List
import json
import unittest

def get_all_member_variable_names(target_class: Any) -> List[str]:
    """Return list of all public member variables."""
    all_members = [name for name, _ in inspect.getmembers(target_class,\
                       lambda a: not inspect.isroutine(a))]
    return list(filter(lambda name: not name.startswith("__"), all_members))

def deserialize_json(target_class: Any, object_repr: str) -> Any:
    """Constructs an object in a type-safe way from a JSON strings"""
    data = json.loads(object_repr)
    members = get_all_member_variable_names(target_class)
    for needed_key in members:
        if needed_key not in data:
            raise ValueError(f'Key {needed_key} is missing.')
    dummy = target_class()
    for needed_key in members:
        json_type = type(data[needed_key])
        target_type = type(getattr(dummy, needed_key))
        if json_type != target_type:
            raise TypeError(f'Key {needed_key} has incorrect type. '
                            '({json_type} instead of {target_type}')
    return target_class(**data)

class Foo():
    """Some dummy class"""
    val: int = 0
    msg: str = ''
    frac: float = 0.0

    def __init__(self, val: int = 0, msg: str = '', frac: float = 0.0) -> None:
        self.val: int = val
        self.msg: str = msg
        self.frac: float = frac

class TestDeserialization(unittest.TestCase):
    """Test with valid and invalid JSON strings"""

    def test_ok(self) -> None:
        """Valid JSON string"""
        object_repr = '{"val": 42, "msg": "hello", "frac": 3.14}'
        a_foo: Foo = deserialize_json(Foo, object_repr)
        self.assertEqual(a_foo.val, 42)
        self.assertEqual(a_foo.msg, 'hello')
        self.assertEqual(a_foo.frac, 3.14)

    def test_missing(self) -> None:
        """Invalid JSON string: missing a field"""
        object_repr = '{"val": 42, "msg": "hello"}'
        with self.assertRaises(ValueError):
            deserialize_json(Foo, object_repr)

    def test_incorrect_type(self) -> None:
        """Invalid JSON string: incorrect type of a field"""
        object_repr = '{"val": 42, "msg": "hello", "frac": "incorrect"}'
        with self.assertRaises(TypeError):
            deserialize_json(Foo, object_repr)

It works and the unit tests succeed, but I'm not sure if I am missing some potential problem or other opportunities to improve this. It would be cool if you could give me some hints or general criticism.


texts: Extension methods to make ConcurrentDictionary GetOrAdd and AddOrUpdate thread safe when using valueFactory delegates

texts:
The ConcurrentDictionary<T,V> in .NET 4.0 is thread safe but not all methods are atomic.

This points out that:

  ... not all methods are atomic, specifically GetOrAdd and AddOrUpdate. The user delegate that is passed to these methods is invoked outside of the dictionary's internal lock.

Example Problem:

It is possible for the delegate method to be executed more than once for a given key.

public static readonly ConcurrentDictionary<int, string> store =
    new ConcurrentDictionary<int, string>();

[TestMethod]
public void UnsafeConcurrentDictionaryTest()
{

    Thread t1 = new Thread(() =>
    {
        store.GetOrAdd(0, i =>
        {
            string msg = "Hello from t1";
            Trace.WriteLine(msg);
            Thread.SpinWait(10000);
            return msg;
        });
    });

    Thread t2 = new Thread(() =>
    {
        store.GetOrAdd(0, i =>
        {
            string msg = "Hello from t2";
            Trace.WriteLine(msg);
            Thread.SpinWait(10000);
            return msg;
        });
    });

    t1.Start();
    t2.Start();
    t1.Join();
    t2.Join();
}

The result shown in the Trace window shows "Hello from t1" and "Hello from t2". This is NOT the desired behavior for most implementations that we are using and confirms the problem noted in the MSDN link above. What we want is for only one of those delegates to be executed.

Proposed Solution:

I have to use the delegate overloads of these methods which led me to investigate this matter further. I stumbled onto this post which suggests using the Lazy<T> class to ensure the delegate is only invoked once. With that in mind I wrote the following extension methods to mask the adding of a Lazy<T> wrapper to the value.

public static V GetOrAdd<T, U, V>(this ConcurrentDictionary<T, U> dictionary, T key, Func<T, V> valueFactory)
where U : Lazy<V>
{
    U lazy = dictionary.GetOrAdd(key, (U)new Lazy<V>(() => valueFactory(key)));
    return lazy.Value;
}

public static V AddOrUpdate<T, U, V>(this ConcurrentDictionary<T, U> dictionary, T key, Func<T, V> addValueFactory, Func<T, V, V> updateValueFactory)
where U : Lazy<V>
{
    U lazy = dictionary.AddOrUpdate(key,
                (U)new Lazy<V>(() => addValueFactory(key)),
                (k, oldValue) => (U)new Lazy<V>(() => updateValueFactory(k, oldValue.Value)));
    return lazy.Value;
}

Testing Solution:

Executing the same test above using a ConcurrentDictionary that has a Lazy value results in the value delegate ONLY being executed once (you either see "Hello from t1" or "Hello from t2")!

public static readonly ConcurrentDictionary<int, Lazy<string>> safeStore =
            new ConcurrentDictionary<int, Lazy<string>>();

So it seems that this approach accomplished the goal.

What do you think of this approach?


texts:
I've wrote a C++ program to calculate the determinant of a matrix:

#include <iostream>
#include <string>

double getDeterminant(double arr[], int dimension);

int main() {

    //First, the user has to enter the dimension of the matrix
    int dimension;
    std::cout << "Please enter dimension of Matrix: ";
    std::cin >> dimension;
    std::cout << std::endl;
    double matrix[dimension][dimension];

    //Now, the user has to enter the matrix line by line, seperated by commas
    std::string str;
    for(int i = 1; i <= dimension; i++) {
        std::cout << "Enter line " << i << " only seperated by commas: ";
        std::cin >> str;
        std::cout << std::endl;
        str = str + ',';
        std::string number;
        int count = 0;
        for(int k = 0; k < str.length(); k++) {
            if(str[k] != ',') {
                number = number + str[k];
            }
            else {
                matrix[i - 1][count] = std::stod(number);
                number = "";
                count++;
            }
        }
    }

    //Conversion to a onedimensional matrix to be able to give it over as a parameter
    double array[dimension * dimension];
    int k = 0;
    for(int i = 0; i < dimension; i++) {
        for(int j = 0; j < dimension; j++) {
            array[k] = matrix[i][j];
            k++;
        }
    }

    //Output
    for(int i = 0; i < dimension; i++) {
        for(int j = 0; j < dimension; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }

    std::cout << "Determinant of the matrix is : " << getDeterminant(array, dimension) << std::endl;
    return 0;
}

double getDeterminant(double array[], int dimension) {

    //Formula for 2x2-matrix
    if(dimension == 2) {
        return array[0] * array[3] - array[1] * array[2];
    }

    //Conversion back to 2D-array
    double matrix[dimension][dimension];
    int k = 0;
    for(int i = 0; i < dimension; i++) {
        for(int j = 0; j < dimension; j++) {
            matrix[i][j] = array[k];
            k++;
        }
    }

    double result = 0;
    int sign = 1;
    for(int i = 0; i < dimension; i++) {

        //Submatrix
        double subMatrix[dimension - 1][dimension -1];
        for(int m = 1; m < dimension; m++) {
            int z = 0;
            for(int n = 0; n < dimension; n++) {
                if(n != i) {
                    subMatrix[m-1][z] = matrix[m][n];
                    z++;
                }
            }
        }

        //Conversion of the submatrix to 1D-array
        double array2[(dimension - 1) * (dimension - 1)];
        int k = 0;
        for(int x = 0; x < dimension - 1; x++) {
            for(int y = 0; y < dimension - 1; y++) {
                array2[k] = subMatrix[x][y];
                k++;
            }
        }

        //recursive call
        result = result + sign * matrix[0][i] * getDeterminant(array2, dimension -1);
        sign = -sign;
    }

    return result;
}

I would appreciate any suggestions on improving the code!

You can find the follow-up question here.


texts:
I made a simple calculator.

I would also like to write some simple unit tests for my CalculatorEngine class. I had to make some of my private methods as package-private over this. How is it usually better to do it - to enhance access modifier or to make inner test class?

And what another more complicated cases it's better to test?

My CalculatorEngineTest class is:

import org.junit.Before;
import org.junit.Test;

import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;

public class CalculatorEngineTest {

    CalculatorEngine calcEngine = new CalculatorEngine();

    @Before
    public void runBeforeEveryTest() {
        calcEngine.currentTotal = 0;
    }

    @Test
    public void testGetTotalStringInt() throws Exception {
        calcEngine.currentTotal = 50;
        assertTrue(calcEngine.currentTotal % 1.0 == 0);
    }

    @Test
    public void testGetTotalStringDouble() throws Exception {
        calcEngine.equal("50.5");
        assertTrue(calcEngine.currentTotal % 1.0 != 0);
    }

    @Test
    public void testEqual() throws Exception {
        calcEngine.equal("20");
        assertEquals(calcEngine.currentTotal, 20.0);
    }

    @Test
    public void testAdd() throws Exception {
        calcEngine.add(20);
        assertEquals(calcEngine.currentTotal, 20.0);

    }

    @Test
    public void testSubtract() throws Exception {
        calcEngine.subtract(20);
        assertEquals(calcEngine.currentTotal, -20.0);
    }

    @Test
    public void testMultiplyByZero() throws Exception {
        calcEngine.multiply(10);
        assertEquals(calcEngine.currentTotal, 0.0);
    }

    @Test
    public void testDivideByZero() throws Exception {
        calcEngine.divide(10);
        assertEquals(calcEngine.currentTotal, 0.0);
    }

    @Test
    public void testMultiply() throws Exception {
        calcEngine.add(10);
        calcEngine.multiply(10);
        assertEquals(calcEngine.currentTotal, 100.0);
    }

    @Test
    public void testDivide() throws Exception {
        calcEngine.add(10);
        calcEngine.divide(10);
        assertEquals(calcEngine.currentTotal, 1.0);
    }
}


texts:
I'm using BFS to see if a given path exists in a graph:

static class Node{
    int data;
    Node next;

    public Node(int data){
        this.data = data;
    }
}

//Adjency List to store the reference to head of each Node/Vertice
static class AdjList implements Iterable<Integer>{
    Node head;
    public void add(int to){
        if(head==null){
            head = new Node(to);
        }else{
            Node temp = head;
            while(temp.next!=null)
                temp = temp.next;
            temp.next = new Node(to);
        }
    }

    //Used to iterate over the adjacency list while BFS
    @Override
    public Iterator<Integer> iterator(){
        Iterator<Integer> it = new Iterator<Integer>(){
            Node temp = head;
            @Override
            public boolean hasNext(){
                return temp!=null;
            }

            @Override
            public Integer next(){
                Node toRet = temp;
                temp = temp.next;
                return toRet.data;
            }

            @Override
            public void remove(){
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }

}

static class Graph{
    AdjList[] lists;
    int numberOfNodes;

    public Graph(int numberOfNodes){
        lists = new AdjList[numberOfNodes];
        this.numberOfNodes = numberOfNodes;
        for(int i=0; i<numberOfNodes; i++){
            lists[i] = new AdjList();
        }
    }

    //Adds edge from/to vertice
    public void addEdge(int from, int to){
        lists[from].add(to);
    }

    public boolean BFS(int from, int to){
        LinkedList<Integer> queue = new LinkedList<>();
        queue.add(from);
        boolean[] visited = new boolean[numberOfNodes];
        visited[from]= true;

        while(!queue.isEmpty()){
            if(visited[to]==true)
                return true;
            int curr = queue.poll();
            System.out.print(curr + " ");
            Iterator<Integer> iter = lists[curr].iterator();
            while(iter.hasNext()){
                int currVal = iter.next();
                if(visited[currVal]==false){
                    queue.add(currVal);
                    visited[currVal]=true;
                }
            }
        }
        return false;
    }

}

public static void main(String[] args) {
    Graph myGraph = new Graph(3);
    myGraph.addEdge(0, 1);
    myGraph.addEdge(1,2);
    myGraph.addEdge(2,1);
    System.out.println("Path from 2 to 0 exists : " + Boolean.valueOf(myGraph.BFS(2,0)));
}

I could've used DFS for the same purpose which requires lesser memory than BFS, but since my Graph was pretty small, it wouldn't have made much of a difference. Apart from that, under what circumstances should I prefer either of them?


texts: Small app to show variables declared in a bash script

texts:
This code and updates are available on Github.

I've written a small utility to dump the variables that are assigned in a bash script.

Please note:

This script depends on the shfmt and jq apps.
I am not looking to make this script posix compliant, only bash specific.

Some possible areas for improvement:

Can the jq query be improved?
Are there other entries in the json output of shfmt that I can look for variable assignments.
Any gotchas I'm missing?

As I type out this question, it occurs to me that showing variables used in a script would be a good thing to allow as an option. I'll look into it, but if anyone has any ideas in this respect, I'm interested in hearing your input.

#!/bin/bash

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

warn() { printf '%s\n' "$*" >&2; }

die() {
  (($#)) && warn "$*"
  exit 1
}

command_exists() { command -v "$1" &> /dev/null; }

#------------------------------------------------------------------------------
_showvars() {
  local filename=$1
  [[ -f $filename ]] || die "$filename is not a file or does not exist."
  [[ -r $filename ]] || die "$filename is not readable."

  jq_query='[ .. | select(.Assigns?) | .. | select(.Name?) | .Name.Value ] | unique[]'

  # shellcheck disable=SC2046
  printf '  %s\n' $(shfmt -tojson < "$filename" | jq "$jq_query" | tr -d '"')
}

#------------------------------------------------------------------------------
(($#)) || {
  cat << EOH

showvars is a simple script that shows
what variables are assigned in a bash
script

usage: showvars filename [filename ...]

EOH

  exit 1
}

for r in shfmt jq; do
  command_exists $r || die This script depends on $r and it is not found.
done

for f in "$@"; do
  printf '\n%s:\n' "$f"
  _showvars "$f"
  shift
done

echo

Edit: Fixed copy-paste error with (($#))... line
Edit: Removed code that removes lower case variables (an artifact from another code solution)


texts:
I needed to make a point class for a term project that involved arbitrary dimensional points.  I came up with this, and I know that it works fine, but I'm looking to improve it so I can reuse it in the future.  Any criticisms or suggestions are very much appreciated.

#ifndef POINT_HPP
#define POINT_HPP

#include <array>
#include <cmath>
#include <initializer_list>
#include <iostream>

template <size_t D>
struct Point;

template <size_t D>
struct Point {
  Point(const std::initializer_list<double>& v) {
    size_t i = 0;
    for (auto e : v) {
      coordinates_[i++] = e;
    }
  }

  explicit Point(const std::array<double, D>& arr) : coordinates_{arr} {}

  double operator[](size_t dimension) const { return coordinates_[dimension]; }
  Point<D>& operator=(const Point& other) {
    this->coordinates_ = other.coordinates_;
    return *this;
  }
  std::array<double, D> coordinates_;
};

/*
 * Finds euclidian distance between two Point classes of same dimension
 */
template <size_t D>
double distance(const Point<D>& lhs, const Point<D>& rhs) {
  double dist = 0;
  for (size_t i = 0; i < D; i++) dist += std::pow(lhs[i] - rhs[i], 2);
  return std::sqrt(dist);
}

/*
 * Finds euclidian distance between Point and axis
 */
template <size_t D>
double distance(const Point<D>& point, double value, int axis) {
  return std::abs(point[axis] - value);
}

/*
 * Print the point components of a Point in ascending order.
 * Prints in the form {x, y, z} with no newline.
 */
template <size_t D>
std::ostream& operator<<(std::ostream& os, const Point<D>& point) {
  os << "{";
  for (size_t i = 0; i < D - 1; i++) {
    os << point[i] << ", ";
  }
  os << point[D - 1] << "}";
  return os;
}

template <size_t D>
bool operator==(const Point<D>& lhs, const Point<D>& rhs) {
  return lhs.coordinates_ == rhs.coordinates_;
}

namespace std {
/*
 * Make our Point class hashable
 */
template <size_t D>
struct hash<Point<D>> {
  size_t operator()(const Point<D>& x) const {
    return hash<array<double, D>>()(x.coordinates_);
  }
};

/*
 * Also make it swappable for sorting
 */
template <size_t D>
void swap(Point<D>& lhs, Point<D>& rhs) {
  swap(lhs.coordinates_, rhs.coordinates_);
}
}  // namespace std

#endif  // POINT_HPP


texts: Binary Search Tree insert method (map interface)

texts:
This is my implementation based on Map<K,V> interface. The BST is a linked binary tree with root reference, both internal and external nodes (MyBSNode) contains (key, value) entries

What do you think? There's something to improve?

public BSPosition<E> insert(int k, E e) {
    if(isEmpty()){
        /* Sets root */
        BSPosition<E> r = new MyBSNode<E>(null);
        r.setElement(k, e);
        setRoot(r);
        size++;
        return r;
    }

    BSPosition<E> n = treeInsert(k, root);          //k-key node or last node visited
    if(k == n.getKey()){                            //tree has already a k-key node
        n.setElement(k, e);                         //only modifies e
        return n;
    }
    /* n is a external (last visited) node with different key */
    size++;
    if(k < n.getKey())
        return n.setLeftChild(k, e);
    else
        return n.setRightChild(k, e);

}

private BSPosition<E> treeInsert(int k, BSPosition<E> v){
    if(isLeaf(v))                       return v;

    if(k < v.getKey()){
        if(v.getLeftChild() == null)    return v;
        return treeInsert(k, v.getLeftChild());
    }
    else if(k == v.getKey())            return v;

    else{
        if(v.getRightChild() == null)   return v;
        return treeInsert(k, v.getRightChild());
    }
}


texts: Counting the number of bits of a positive integer #2

texts:
I think the running time of this should be \$O(log_{2}(n))\$:

def count_bits(num):
    assert num >= 0
    count = 0
    while (num != 0):
        num >>= 1
        count += 1
    return count

print count_bits(0) #0
print count_bits(2) #2
print count_bits(pow(10, 2)) #7
print count_bits(pow(10, 9)) #30


texts: SQL Query with results from 2 Tables, 1 table multiple times

texts:
I have the following data in SQL tables.
Table 1

id
name

1
John

2
Smith

3
Jenny

4
Bill

Table 2

_id
value
value_id

1
New York
1

2
London
1

3
Chicago
1

1
Vegas
2

3
Atlanta
2

4
Tampa Bay
2

4
Paris
1

The result that i'm trying to show is this.

id
name
city_1
city_2

1
John
New York
Vegas

2
Smith
London
NULL

3
Jenny
Chicago
Atlanta

4
Bill
Tampa Bay
Paris

But the result i'm getting is this.

id
name
city_1
city_2

1
John
New York
Vegas

3
Jenny
Chicago
Atlanta

4
Bill
Tampa Bay
Paris

The code i'm using is this.
select a.id,a.name, b.value as city_1, c.value as city_2 from table1 as a
join table2 as b on a.id=b._id
join table2 as c on a.id=c._id
where b.value_id=1 and c.value_id=2

can someone let me know where i'm making a mistake.


texts:
I am working on an angular stack that has n amount of services that hold data in stores of this type:

fooStore$ = BehaviorSubject<FooStoreType>({})

accessing properties in these have generally been done like this:

export wantedPropSelector$ = fooStore$.pipe(
  map(store => store.wantedProp)
);

Now I'm working on improving this by adding memoization and selector singletons for each service. I've ended up with a pattern that allows this syntax in the service-side:

export wantedPropSelector$ = select(fooStore$, store => store.wantedProp);

and the select function looks like this:

type MappingFunction<T, R> = (mappable: T) => R;
type MemoizationFunction<R> = (previousResult: R, currentResult: R) => boolean;

export function select<T, R>(
  inStream: Observable<T>,
  mappingFunction: MappingFunction<T, R>,
  memoizationFunction?: MemoizationFunction<R>
): Observable<R> {
  return inStream.pipe(
    map(mappingFunction),
    distinctUntilChanged(memoizationFunction),
    shareReplay(1)
  );
}

My assumption is that distinctUntilChanged will give me memoization, and it's possible to send in custom memoization logic for Objects, and shareReplay(1) will allow me to turn the selectors into singletons that also return the last value.

I'd greatly appreciate CR on this from anyone sufficiently experienced with RxJs to point out any possible flaws in this code.


texts: Extending numpy array by replacing each element with a matrix

texts:
Suppose I have a H*W numpy array like this (H=3 and W=2):

[[0 1]
 [2 3]
 [4 5]]

I would like to replace each element with a matrix of M*N repeated element (M=2 and N=3):

[[[[0 0 0]
   [0 0 0]]

  [[1 1 1]
   [1 1 1]]]

 [[[2 2 2]
   [2 2 2]]

  [[3 3 3]
   [3 3 3]]]

 [[[4 4 4]
   [4 4 4]]

  [[5 5 5]
   [5 5 5]]]]

My current code first turn each element into a 2D matrix by calling expand_dims() twice, and then expand these matrices using repeat() twice too:

import numpy as np

H, W, M, N = 3, 2, 2, 3

array = np.arange(H * W).reshape(H, W)

array = np.expand_dims(array, axis=2)
array = np.expand_dims(array, axis=3)
array = np.repeat(array, M, axis=2)
array = np.repeat(array, N, axis=3)

Is there a more straightforward and elegant way to obtain the same result?


texts: Convert number from one radix to another

texts:
I am relatively new to coding and could use some help figuring out how I could improve my coding technique and habits. Here's an example of a working Java program I wrote that converts a number of some radix (from 2 to 36) to another radix (from 2 to 36).

Any tips or criticisms?

class RadixConverter {
    // command line arguments: (number) (radix of number) (radix to be converted to)
    public static void main(String[] args) {
        String n = args[0];                                   // n kept as String to support alphabetic representations of numerals for larger radixes
        int startRadix = Integer.parseInt(args[1]);
        int endRadix = Integer.parseInt(args[2]);
        int decimal = convertToDecimal(n, startRadix);
        String result = convertToBase(decimal, endRadix);
        System.out.printf("%s (%d) = %s (%d)%n", n, startRadix, result, endRadix);
    }

    public static int convertToDecimal(String n, int startRadix) {
        int sum = 0;
        for (int i = 0; i < n.length(); i++) {                                                 // begins at first digit and ends at last digit
            char digit = n.charAt(i);
            int placeValue = (int) Math.pow(startRadix, n.length() - i - 1);                   // place value of digit's column
            if ((digit >= 48) && (digit <= 57) && (digit - 48 < startRadix)) {                 // if digit is numerical and is within specified radix
                sum += (digit - 48) * placeValue;
            } else if ((digit >= 65) && (digit <= 90) && (digit - 65 + 10 < startRadix)) {     // if digit is alphabetic and within specified radix
                sum += (digit - 55) * placeValue;
            } else {
                throw new IllegalArgumentException("\n\nThe input number is invalid or contains digits outside of its specified radix.\n");
            }
        }
        return sum;
    }

    public static String convertToBase(int decimal, int endRadix) {
        StringBuilder sb = new StringBuilder("");
        do {
            int rem = decimal % endRadix;
            if ((rem <= 9) && (endRadix <= 36) && (endRadix >= 2)) {
                sb.append(Integer.toString(rem));
            } else if ((rem <= 35) && (endRadix <= 36) && (endRadix >= 2)) {
                sb.append((char) (rem + 55));
            } else {
                throw new IllegalArgumentException("\n\nThe output radix must be from 2 to 36.\n");
            }
            decimal /= endRadix;
        } while (decimal != 0);
        return reverseOrder(sb.toString());
    }

    public static String reverseOrder(String s) {
        StringBuilder sb = new StringBuilder("");
        for (int i = s.length() - 1; i >= 0; i--) {    // executes each character in reverse order
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }
}


texts: A Countdown Timer with reset functionality in pure Javascript

texts:
This works for me, but is this the right way to create this timer?
I might be naive about this but I think this is close to perfect in pure JS.
What would be the drawbacks of using this Timer compared to creating it in a different way?

Click start and the timer starts to countdown.
Click reset and the timer resets back to the starting time.

HTML:
<button onclick='startStopTimer()'>Start</button>
<button onclick='startStopTimer()'>Reset</button>

00:10

JavaScript:
console.clear()
let timer = document.querySelector('h1')
let startingTime = 9
let startTimer;
let startStopTimer = () => {
  if(startTimer){
    clearInterval(startTimer);
    timer.innerHTML = '00:10'
    startingTime = 9
    return startTimer = undefined
  }else{
    return startTimer = setInterval(()=>{
      timer.innerHTML = `00:0${startingTime--}`
    }, 1000)
  }
}


texts: Using Regexp to select the date from a string

texts:
I have a string with date details with time, but I would like to show the day information alone.  For that, I use the regexp to select the date.  Can anyone tell me the regexp, and if what is used is the correct one?

Here is my string:

2014-09-12T00:00:00

Here is the regexp, what is used:

\d.+\-\d{1,2}

I am getting the result as:

2014-09-12

I am getting correct result, but I am wondering if there may be a better approach.


texts: Excluding a long list of words with grep

texts:
This Bash program extracts the 20 first lines of each man page present on a system and uses grep to remove lines matching a list of selected terms.

How can I improve the grep part? (something less repetitive, with less pipe but that do the same job)

#!/bin/bash

# generate the list
compgen -c > man

# extract each man of the list
while read -r LINE; do
MANWIDHT=80 man "$LINE" | head -20 | grep -v NAME | grep -v 1 | grep -v SYNOPSIS | grep -v SYNOPSYS | grep -v OVERVIEW | grep -v VERSION | grep -v VERSION | grep -v INTRODUCTION | grep -v 5 | grep -v ABSTRACT | grep -v 4 | grep -v DESCRIPTION | grep -v COPYRIGHT | grep -v ABRT | grep -v SEE | grep -v 8 | grep -v case | grep -v 2 | grep -v STATUS | grep -v CHECK | grep -v UNIX | grep -v FORTUNE | grep -v PROLOG | grep -v Usage | grep -v Help | grep -v Introduction | grep -v Local | grep -v ARGUMENTS | grep -v SYNTAX | grep -v NOTE | grep -v QUERYING | grep -v 3 | grep -v Description | grep -v Note | grep -v Name | grep -v COPYING | grep -v COMMAND | grep -v USAGE | grep -v EXAMPLE | grep -v 3 | grep -v OPTIONS | grep -v AUTHOR | grep -v DOCUMENTS | grep -v SUMMARY | grep -v -e '^$' && echo -en '\n'
done < man > man1

# add the % to each empty line
sed -i -e 's/^$/%/' man1

# merge to fortune-rtfm db
cat man1 > fortune-rtfm


texts: Mergesort, instrumented for counting reads and writes

texts:
I have just finished an implementation of mergesort, and I was wondering if I can further reduce the amount of reads and writes. I have looked at it for a while, and to my eyes, I cannot see anything that could really influence the amount of r/w.

public void doMergeSort(int[] array)
{
    doMergeSort(array, 0, array.length - 1);
}

public void doMergeSort(int[] array, int low, int high)
{
    // If Low Bound Is Geater/Equal Than High Bound, Child Arrays Have Been Split As Far As They Can
    if(low < high)
    {
        int middle = low + (high - low) / 2;

        doMergeSort(array, low, middle);
        doMergeSort(array, middle + 1, high);

        merge(array, low, middle, high);
    }
}

private void merge(int[] parentArray, int low, int middle, int high)
{
    int pIndex = low;
    int lIndex = 0;
    int rIndex = 0;

    // Declare Arrays For The First And Second Half Of The Parent Array
    int[] leftArray = new int[(middle + 1) - low];
    int[] rightArray = new int[high - middle];

    // Populate The Left/Right Arrays
    populateArray(parentArray, leftArray, low, middle);
    populateArray(parentArray, rightArray, middle + 1, high);

    // Loop While The Left/Right Array 'Search' Indices Are Less Than The Arrays Lengths
    while(lIndex < leftArray.length && rIndex < rightArray.length)
    {
        // Check If The Left Array Value If Smaller Than The Right Array Value (Value At Respective Index)
        reads += 2;
        if(leftArray[lIndex] < rightArray[rIndex])
        {
            reads++;
            writes++;
            parentArray[pIndex] = leftArray[lIndex];

            lIndex++;
        }
        else
        {
            reads++;
            writes++;
            parentArray[pIndex] = rightArray[rIndex];

            rIndex++;
        }

        pIndex++;
    }

    // If Looped Over All Right Array Values, Populate The Rest Of The Parent Array With Left Array Values
    while(lIndex < leftArray.length)
    {
        reads++;
        writes++;
        parentArray[pIndex] = leftArray[lIndex];

        lIndex++;
        pIndex++;
    }

    // If Looped Over All Left Array Values, Populate The Rest Of The Parent Array With Right Array Values
    while(rIndex < rightArray.length)
    {
        reads++;
        writes++;
        parentArray[pIndex] = rightArray[rIndex];

        rIndex++;
        pIndex++;
    }
}

private void populateArray(int[] originalArray, int[] newArray, int start, int end)
{
    int i = 0;

    for(int j = start; j <= end; j++)
    {
        reads ++;
        writes++;
        newArray[i] = originalArray[j];

        i++;
    }
}


texts: Live-streaming tweets and plot its sentimental value in colors on a world map

texts:
I want to have someone reviewing and helping me get some good ideas in how to improve my current project.

All information about the project is in the following github link.

I would also appreciate ideas on how to plot in a more efficient way.

Code:

import tweepy, json
from tweepy.api import API
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from textblob import TextBlob
import re

""" Variables
================"""
searches  = ['trump']    # max 250 input searches in a list of strings
maxTweets = 100000         # max number of tweets to analyse.

# Get the Authentication keys from another file. (Easier to push to git)
with open("/Users/se/Documents/Lek med Python/pyCharmProjects/dataScienceFromScratch/src/twitterKeys.txt","r") as file:
    CONSUMER_KEY        = file.readline().rstrip()
    CONSUMER_SECRET     = file.readline().rstrip()
    ACCESS_TOKEN        = file.readline().rstrip()
    ACCESS_TOKEN_SECRET = file.readline().rstrip()

# Twitter API needs to be validated
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

# The class takes in a stream of tweets and filter out some specific properties.
# It is a live streaming so it will be kind of slow and in this purpose i filter
# the Coordinates which only around 3-4% of all tweets have.
class Stream2Screen(tweepy.StreamListener):
    def __init__(self, api=None):
        self.api = api or API()
        self.counter = 0            # Counts amount of tweets already got

    # This is the method that recieves the tweet in the name of data.
    def on_data(self, data):
        datadict = json.loads(data)     # easier to handle in a json file

        # Checks so that the coordinate is in the tweet
        if (datadict.get('place') != None):
            coordinate = calcCenterOfPolygone(datadict['place']['bounding_box']['coordinates'][0])
            tweet = cleanTweets(datadict['text'])
            sentiment = sentimentAnalysis(tweet)
            plotOnMap(coordinate, sentiment.polarity)
            print(tweet)
            print(sentiment, "\n")
            self.counter += 1
            if(self.counter % 100 == 0):
                print(self.counter)

        # if we sent a False as return value we close the "pipeline" of streams
        if self.counter < maxTweets:
            return True
        else:
            return False

    def on_error(self, status_code):
        print(status_code)
        return True

    # Trial to get sentimental value of a tweet using TextBlob
def sentimentAnalysis(tweet):
    tweet = TextBlob(cleanTweets(tweet))
    return tweet.sentiment

def cleanTweets(tweet):
    return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())

# Inputs 4 Coordinates in a list and calc the mid point.
def calcCenterOfPolygone(coordinates):
    return [sum([x[0] for x in coordinates]) / 4,
            sum([x[1] for x in coordinates]) / 4]

# Plots the coordinate on the map
def plotOnMap(centerPoint, polarity):
    plt.ion()
    color = 'black'
    if (polarity < 0): color='r'
    elif (polarity > 0): color='g'
    m.plot(centerPoint[0], centerPoint[1], marker='o', markersize=5, color=color)
    draw_map(m)
    plt.pause(0.000001)

# draws the map the first time
def draw_map(m, scale=0.2):
    m.shadedrelief(scale=scale)

fig = plt.figure(figsize=(12, 6))
m = Basemap(projection='cyl', resolution=None,
            llcrnrlat=-90, urcrnrlat=90,
            llcrnrlon=-180, urcrnrlon=180,)

# Starts the twitter feed and searches for the keyword
stream = tweepy.streaming.Stream(auth, Stream2Screen())

while True:
    try:
        stream.filter(track=searches)
    except:
        print("error"*10)
        continue

draw_map(m)
plt.show()
plt.draw()


texts: Recording a customer's shopping cart as an order

texts:
I have come up with the following method to post a transaction to a database, in the context of an e-commerce Java web application. The transaction consists in submitting a new order alongside its details:

public long insertOrder(Customer customer, Hashtable<String, CartItem> shoppingCart)
{
    long returnValue = 0L;
    Connection connection = null;
    Statement statement = null;
    try {
        connection = MySqlConnection.getConnection();
        connection.setAutoCommit(false);
        statement = connection.createStatement();
        long orderId = System.currentTimeMillis();
        OrderPeer.insertOrder(statement, orderId, customer);
        OrderDetailsPeer.insertOrderDetails(statement, orderId, shoppingCart);
        connection.commit();
        returnValue = orderId;
    } catch (SQLException e) {
        try { connection.rollback(); } catch (Exception ex) { }
        System.out.println("Could not insert order: " + e.getMessage());
    } finally {
        try { statement.close(); } catch (Exception e) { }
        try { connection.close(); } catch (Exception e) { }
    }
    return returnValue;
}

I would like to know if I am handling the exception, rolling back, and closing the statement/connection in the best possible manner.


texts: Determining position of point W.R.T to given line equation

texts:
Problem from HackerRank::

  Problem Statement:

  There are \$N\$ lines. Each line has an index between \$1\$ and \$N\$. The slope of each line is negative, i.e. it goes from upper-left to lower-right.

  There are \$Q\$ queries. Each of them is in the format \$L\$ \$R\$ \$x\$ \$y\$, and you should output whether there is any line with index between \$L\$ and \$R\$ and the point \$(x,y)\$ is under it. If there is, then the answer isYES, otherwiseNO`.

  As you know, any line splits an infinite plane into two regions. The point \$(x,y)\$ is under the line if that point is at the same region with point \$(-\infty , -\infty)\$ . If the point lies on the line it does not count.

  Input Format:

  The first line contains \$N\$, the number of lines. The following \$N\$ lines each contains two integers \$m\$ and \$n\$ that describes the line \$mx + n = y\$.

  Output Format:

  For each query, output one line containing either YES or NO.

  Sample Input:

2
-1 3
-2 -4
3
1 2 0 0
1 1 0 0
2 2 0 0

  Sample Output:

YES YES NO

  Explanation:

For this, I've submitted this code in Python, but in half of the test case, the time limit was exceeded.

n = int(input())
x = []
y = []
for i in range(n):
    l = list(map(int, input().split()))
    x.append(l[0])
    y.append(l[1])
q = int(input())

for i in range(q):
    p = list(map(int, input().split()))
    L = p[0]-1
    R = p[1]-1
    X = p[2]
    Y = p[3]
    flag = 0
    for i in range(L,R+1,1):
        if(Y - x[i]*X - y[i] < 0):
            print("YES")
            flag = 1
            break;
    if(flag == 0):
        print("NO")

I can't understand how can I improve my code further. Because for loop to check from L to R is necessary. also the loop to execute every query is necessary. So in total 2 loops are needed. How can I reduce time here?


texts:
I have a real-world problem involving finding the best known term from a string containing sets of terms. We have Term objects that are comparable in that they have a method a_term.is_better_than(other_term). This method is Boolean -- if it returns False, then a_term may be as good as other_term, but isn't better.

Using this method, I need to pare down a set of terms to the best ones. The best way I've been able to think about this is to compare pairs of terms and eliminate any terms when one isn't as good as the other, something like this:

def get_best_terms(terms: Set[Term]): Set[Term]
    best_terms = set()
    m_terms = list(terms)
    while m_terms:
        term = m_terms.pop()
        for i in reversed(range(len(m_terms))):
            if term.is_better_than(m_terms[i]):
                del m_terms[i]
            if m_terms[i].is_better_than(term):
                break
        else: # We never encountered the `break` statement
            best_terms.add(term)
            break
    best_terms |= {a_term for a_term in m_terms
                   if not (term.is_better_than(a_term) or
                           a_term.is_better_than(term))}
    return best_terms

This approach is functional, but pretty gross in my opinion. For one thing, there's a lot of mutation going on here. For another, once I've identified a single best term, finding all the terms that are equally good is messy. The whole thing is hard to read.

What do you suggest?

Examples

A Term is a string with some metadata attached. For example,

a = AutoTerm(term='honda', term_span=1, term_range=(1, 2),
            original_term='CAR HONDA ACC...')
b = AutoTerm(term='2015 honda accord', term_span=2, term_range=(1, 3),
             original_term='2015 HONDA ACC...')
c = AutoTerm(term='2015 accord', ...)

Sometimes a term is a better choice because it's more specific, but there are other nuances, such as a match in a database. Let's say, arbitrarily, that b and c are equally good, but a is not as good. Then

assert get_best_terms({a, b, c}) == {b, c}

should pass.


texts:
I just started learning to code during quarantine and whilst learning python, I created this program for a binary search. This is really basic so I assume that there is a way easier method. If anyone knows how I can make this way simpler, your help would be appreciated.

list = [1,15,37,53,29,22,31,90,14,6,37,40]
finished = False
target = 37
list.sort()
print(list)
while finished == False:
    n = len(list)
    print(n)
    if target < list[int(n/2)]:
        for items in range(int(n / 2), n):
            list.pop()
        print('Item is too large.')
    elif target == list[int(n/2)]:
        finished = True
        print('The item has been found.')
    else:
        list.reverse()
        for items in range(int(n / 2), n):
            list.pop()
        list.reverse()
        print('Item is too small.')
    print(list)


texts:
This is a follow-up question of this one: Tic Tac Toe game in Haskell

I have revised my code. How does it look now?

import System.Random (randomRIO)
import System.IO (hFlush, stdout, getLine)
import Data.List (intercalate)
import Data.Array

data Tile   = EmptyTile | X | O deriving (Eq)
data Player = Player1 | Player2

showTile :: Tile -> String
showTile EmptyTile = " "
showTile X         = "X"
showTile O         = "O"

showBoard :: Board -> String
showBoard b = let bstr = fmap showTile b
                  blist = boardAsList bstr
              in  unlines [intercalate "|" row | row <- blist]
              where
                boardAsList b = [[b!(x,y) | y <- [1,2,3]] | x <- [1,2,3]]

type Board = Array (Int,Int) Tile

emptyBoard :: Board
emptyBoard = array ((1,1),(3,3)) [((x,y), EmptyTile) | x <- [1,2,3], y <- [1,2,3]]

put :: Board -> Tile -> Int -> Int -> Maybe Board
put b t x y = case b!(x,y) of
                EmptyTile -> Just (b // [((x,y), t)])
                _         -> Nothing

p1wins, p2wins :: Board -> Bool
p1wins b = tileWins b X
p2wins b = tileWins b O

tileWins :: Board -> Tile -> Bool
tileWins b t =
   any (\row -> all (\col -> b!(row,col) == t) [1..3]) [1..3] ||
   any (\col -> all (\row -> b!(row,col) == t) [1..3]) [1..3] ||
   all (\rc -> b!(rc,rc) == t) [1..3] ||
   all (\rc -> b!(rc,4-rc) == t) [1..3]

checkFull :: Board -> Bool
checkFull b = all (\row -> all (\col -> b!(row, col) /= EmptyTile) [1..3]) [1..3]

compMove :: Board -> IO (Board)
compMove b = do
    (row, col) <- getRandomEmpty b
    let (Just b') = put b O row col
    return b'

getRandomEmpty :: Board -> IO (Int, Int)
getRandomEmpty b = do
    col <- randomRIO (1,3)
    row <- randomRIO (1,3)
    case b!(row, col) of
        EmptyTile -> return (row, col)
        _         -> getRandomEmpty b

prompt :: String -> IO String
prompt s = do
    putStr s
    hFlush stdout
    getLine

showTileNumbers :: String
showTileNumbers  = (unlines
                   [intercalate "|" ["(" ++ show x ++ "," ++ show y ++ ")" |
                   y <- [1,2,3]] | x <- [1,2,3]])

main :: IO ()
main = do
    putStrLn "This is classic tic tac toe game."
    putStrLn "In order to play, you need to put a number between 0 and 8"
    putStrLn "This table shows tile numbers"
    putStrLn showTileNumbers
    putStrLn $ showBoard emptyBoard
    playTurn emptyBoard Player1
    where
        playTurn b Player1 = do
            row <- prompt "Row: "
            col <- prompt "Col: "
            let newboard = put b X (read row) (read col)
            case newboard of
                Nothing -> do
                            putStrLn "Invalid move."
                            playTurn b Player1
                Just b' -> if p1wins b' then
                                putStrLn "You win"
                            else
                                playTurnIfNotTie b' Player2
        playTurn b Player2 = do
            b' <- compMove b
            putStrLn $ showBoard b'
            if p2wins b' then
                putStrLn "You Lose!"
            else
                playTurnIfNotTie b' Player1

        playTurnIfNotTie b p = if checkFull b then
                                  putStrLn "Tie."
                               else
                                  playTurn b p


texts: NodeJS module to calculate linear motion

texts:
I am on the process of changing jobs, so I would like to get an idea of what I do wrong in order to improve.

For this, I have created a small node module. It's very simple; it calculates linear motion (distance, velocity, time). I am interested in knowing what I do wrong, whether it's some crucial mistake or something secondary as the way I format my comments.

/**
*   Checks whether two values are valid to be operated with
*   @param {Float} operandA
*   @param {Float} operandB
*   @return {Boolean}
*/
const areValuesValid = (operandA, operandB) => {
    if(isNaN(operandA) || isNaN(operandB)) return false;

    if(operandA === null || operandB === null) return false;

    return true;
}

/**
*   Rounds a value to a max of two decimals
*   @param {Float} val
*   @return {Float}
*/
const round = (val) => {
    return Math.round(val * 100) / 100;
}

/**
*   Calculates the time in relation to the velocity and the distance
*   @param {Float} velocity
*   @param {Float} distance
*   @return {Float}
*/
const calculateTime = (velocity, distance) => {
    if(areValuesValid(velocity, distance) === false)
        return 0;

    if(parseFloat(velocity) === 0)
        return 0;

    return round(distance / velocity);
}

/**
*   Calculates the velocity in relation to the time and the distance
*   @param {Float} time
*   @param {Float} distance
*   @return {Float}
*/
const calculateVelocity = (time, distance) => {
    if(areValuesValid(time, distance) === false)
        return 0;

    if(parseFloat(time) === 0)
        return 0;

    return round(distance / time);
}

/**
*   Calculates the distance in relation to the velocity and the time
*   @param {Float} velocity
*   @param {Float} time
*   @return {Float}
*/
const calculateDistance = (velocity, time) => {
    if(areValuesValid(velocity, time) === false)
        return 0;

    return round(velocity * time);
}

module.exports = { areValuesValid, calculateTime, calculateVelocity, calculateDistance }

If anybody is willing to go the extra mile, I have created a repository with this code, which also includes some tests. Github. I would like to know if I go about the tests the right way, if the module structure makes sense and whatever else is criticizable.


texts: PS1 for Bash prompt showing last exit status, written mostly in Python

texts:
I had most of this functionality accomplished in BASH, but I was having trouble getting the last process's return value (even though I had a minimal working example). Plus, the escape codes made everything unreadable and I wasn't sure how to factor them out appropriately.

Since I know Python pretty well, I decided to rewrite it in Python, since I have now figured out enough shell that I felt confident embedding some Python into it.

The __future__ import should allow this to work in Python 2 or 3.

I do not know if this is cross-compatible with other shells, or if this is only likely to work in BASH, but another driver that pushed me in this direction was that desire. I am aware of the PROMPT_COMMAND for BASH.

Perhaps I could use a  similar technique along with a BASH function to keep it all in shell and avoid the Python process altogether. However, I find this to be incredibly easy to read, work on, and modify without fear of breaking it - especially relative to shell scripting.

Another perhaps: maybe these escape codes are already available in the Python standard library. I looked at ncurses - I don't think that's the one I want to focus on.

I'm not sure if I factored the escape codes properly - perhaps I should have the constants point to the formatted escapes instead. But theoretically I could embed multiple codes into a single escape, instead of doing it multiple times for every tweak. Maybe there's a drawback to doing that my way, too.

PS1="\$(export LAST_RETURN_VALUE="\$?" WHOAMI="\$\(whoami\)" HOSTNAME ; python -c \"
from __future__ import print_function
import os
import datetime

ESC = '\033[{0}m'
esc = ESC.format

OFF, BOLD, UNDERSCORE, BLINK = 0, 1, 4, 5
BLACK, BLACKBG = 30, 40
RED, REDBG = 31, 41
GREEN, GREENBG = 32, 42
YELLOW, YELLOWBG = 33, 43
BLUE, BLUEBG = 34, 44
MAGENTA, MAGENTABG = 35, 45
CYAN, CYANBG = 36, 46
WHITE, WHITEBG = 37, 47

LAST_RET = os.environ['LAST_RETURN_VALUE']

print(esc(YELLOW) + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
      esc(GREEN) + os.environ['WHOAMI'] + esc(RED) + '@' +
      esc(CYAN) + os.environ['HOSTNAME'],
      esc(BLUE) + esc(BOLD) + os.getcwd() +
      esc(OFF))
if LAST_RET != '0':
    print(esc(MAGENTABG) + LAST_RET + esc(OFF), end='')
print('$ ', end='')
\" "

I'm getting impatient and want to go ahead and post this. I usually do more due diligence on code I write, but I'm up way past my bedtime already, and I think this is too clever not to share.

Here's the result:


texts:
I am writing a code in Golang to execute a periodic function (every 2 second). According to documentation and an example I have written two programs. Can anybody tell which one is better? Also, is there another better solution?

Code 1:

package main

import (
    "fmt"
    "time"
)

func periodicFunc(tick time.Time){
    fmt.Println("Tick at: ", tick)
}

func main(){
    fmt.Println("Starting a new ticker....")

    ticker := time.NewTicker(2 * time.Second)
    go func(){
        for t := range ticker.C {
            //Call the periodic function here.
            periodicFunc(t)
        }
    }()

    quit := make(chan bool, 1)
    // main will continue to wait untill there is an entry in quit
    <-quit
}

Code 2:

package main

import (
    "fmt"
    "time"
)

func periodicFunc(tick time.Time){
    fmt.Println("Tick at: ", tick)
}
func main(){
    ticker := time.NewTicker(1 * time.Second)

    go func() {
        for {
           select {
            case <- ticker.C:
                //Call the periodic function here.
                periodicFunc(<- ticker.C)
            }
        }
     }()

    quit := make(chan bool, 1)
    // main will continue to wait untill there is an entry in quit
    <-quit
}


texts:
I called my template OrderedList, but I don't like the name. Is there a better one?

It stores a vector of values of type T, and a map from each value to its index in the vector.

Just for information, the code should be pure C++03, so please don't suggest how it could be improved with C++11/14/17 extensions, or with Boost.

template<class T> class OrderedList {
    public:
        typedef typename std::map<T, int> MapInd;
    public:
        int Insert(const T& val); // insert new value, return its index
        int Find(const T& val) const; // find index for the value, or -1 if not found
        const T& operator[](int i) const {return vValues[i];}
        int Size() const {return vValues.size();}
    private:
        MapInd mapIndices; // index for each element
        std::vector<T> vValues; // element for each index
};

template<class T> int OrderedList<T>::Insert(const T& val) {
    if (Size() < 0)
        return -1;
    int ind = Find(val);
    if (ind >= 0)
        return ind;
    ind = Size();
    mapIndices[val] = ind;
    vValues.push_back(val);
    return ind;
}

template<class T> int OrderedList<T>::Find(const T& val) const {
    typename MapInd::const_iterator it = mapIndices.find(val);
    if (it != mapIndices.end())
        return it->second;
    return -1;
}


texts: Making thousands of DOM elements draggable with JavaScript

texts:
This is a very simple implementation of dragging elements in html/js. I'm working on a web application that could have thousands of draggable elements on screen at any given time.

Currently, this code works perfectly as shown below (with only one draggable element), however if I copy and paste that element (This is draggable) a few thousand times (I've been using around 4000 for testing) page load is significantly slower, and the framerate slows considerably.

I can understand the page load slowing due to the number of elements, but is there anything that can be done to ensure the frame rate remains smooth while dragging an element given large numbers of draggable elements in the DOM?

Note - The implementation here deliberately ignores various issues like scrolling and so on that I will be implementing later, and I believe will have a largely negligible effect on performance. If that's an incorrect assumption please let me know.

dragdrop.html

<!doctype html>

        <title>Drag + Drop</title>
        <link rel="stylesheet" type="text/css" href="dragdrop.css" />

            This is draggable

dragdrop.css

span {
    position:absolute;
    background: #FF8888;
    cursor: pointer;
}

.noselect {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

dragdrop.js

var dragDrop = (function() {
    var elementBeingDragged;
    var clickPointOffsetX;
    var clickPointOffsetY;

    function _dragging(e) {
        elementBeingDragged.style.left = (e.clientX - clickPointOffsetX) + "px";
        elementBeingDragged.style.top = (e.clientY - clickPointOffsetY) + "px";
    }

    function _stopDrag(e) {
        document.removeEventListener('mousemove', _dragging);
        document.removeEventListener('mouseup', _stopDrag);
    }

    function startDrag(e) {
        elementBeingDragged = this;
        document.addEventListener('mouseup', _stopDrag);
        document.addEventListener('mousemove', _dragging);

        var rect = elementBeingDragged.getBoundingClientRect();

        clickPointOffsetX = e.clientX - rect.left;
        clickPointOffsetY = e.clientY - rect.top;
    }

    var publicAPI = {
        startDrag: startDrag
    };

    return publicAPI;
})();

$(function() {
    $('#draggableItemContainer').on('mousedown', '.draggable', dragDrop.startDrag);
});


texts:
I have tried many possible methods here but I am still not able to reduce the time complexity of below algorithm.

The basic layout of my problem is as follows:
I have a string that is composed of only H's and V's. There can be not more than 10 H's and 10 V's possible. I need to find the Kth lexicographical order of such pattern. Also, inp[] array contains input is format:

2 2 3
4 5 4

which means that total H = 2, total V = 2 and I need to print 3rd lexicographical permutation of HHVV.
Similarly for 4 5 4, I need to print 4th lexicographical permutation of HHHHVVVVV.

//This function returns the next lexicographical permutation of the StringBuilder s
static StringBuilder getKRankString(StringBuilder s)
{
    char ch[] = (s.toString()).toCharArray();
    int i = 0, j=0;
    //This loop gets the highest i for which ch[i]<ch[i+1]
    for(int k=0;k<s.length()-2;k++){
        if(ch[s.length()-2-k]<ch[s.length()-1-k]){
            i = s.length()-2-k;
            break;
        }

    }
    //System.out.println(i);
    //This loop gets the highest j for which ch[j]>ch[i]
    for(int k=s.length()-1;k>i;k--){
        if(ch[k]>ch[i]){
            j = k;
            break;
        }

    }
    //System.out.println(j);
    //swap characters at i and j
    char temp = ch[i];
    ch[i] = ch[j];
    ch[j] = temp;
    //Append the original string till i to reversed string from i till end
    StringBuilder swapped = new StringBuilder(new String(ch));
    //System.out.println(swapped);
    String sb1 = swapped.substring(0, i+1);
    String sb2 = (new StringBuilder(swapped.substring(i+1, s.length())).reverse()).toString();
    StringBuilder str = new StringBuilder(sb1+sb2);
    return str;
}

static String[] gridLand(String[] inp) {
    String[] outputArr = new String[inp.length];
    for(int i=0;i<inp.length;i++){
    //get the first line of input and get integer x and y
        int x = Integer.valueOf(inp[i].split(" ")[0]);
        int y = Integer.valueOf(inp[i].split(" ")[1]);
        int k = Integer.valueOf(inp[i].split(" ")[2]);
        StringBuilder sb = new StringBuilder();
    //form the original string using x H's and y V's.
    //This will be the first String of this order
        for(int j = 0; j < x; j++)
            sb = sb.append("H");
        for(int j = 0; j < y; j++)
            sb = sb.append("V");
        //String s1 = sb.toString();
    //run the below functoin K times to get Kth lexicographical string
        for(int m = 0; m < k; m++)
            sb = getKRankString(sb);
        outputArr[i] = sb.toString();
    }
    return outputArr;

}


texts:
I have an html button that when the user clicks the button it will change color from blue to red and back.  Is there a better way to do this in jQuery?

HTML/jQuery

<html>
<head>
    <title>Button Fun</title>
    <script src = 'bower_components/jquery/dist/jquery.js'></script>
    <script type="home.js"></script>
    <link rel="stylesheet" type="text/css" href="styles.css"/>
    <script type="text/javascript">
    clicked = true;
    $(document).ready(function(){
        $("button").click(function(){
            if(clicked){
                $(this).css('background-color', 'red');
                clicked  = false;
            } else {
                $(this).css('background-color', 'blue');
                clicked  = true;
            }
        });
    });
    </script>
</head>
<body>

    <button>Press</button>

</body>
</html>

CSS

button{
    background-color: blue;
    height:100px;
    width:150px;
}


texts:
We have two C-strings and for their concatenation we need to know the size of resulting string. And we want to calculate it at compilation stage. How can I improve this solution?

char s1[] = "string1";
char s2[] = "string2";
constexpr auto SIZE =
sizeof(s1) / sizeof(*s1) + sizeof(s2) / sizeof(*s2) + 2; // + for space and \0
char ss[SIZE];


texts:
I wrote a quick and dirty auto-clicker for the StackEgg. Any comments, both on code and effectiveness?

function doRound() {
    var stats = [];
    $(".egg-stat").each(function () {
        // Find the number of hearts for each stat.
        var title = $(this).attr("title");
        title && stats.push(parseInt(title, 10));
    });

    // Find the lowest stat and click the button next to it.
    var i = stats.indexOf(Math.min.apply(Math, stats));
    var buttons = $(".egg-action").find("button");

    buttons[i].click();
}

window.setInterval(doRound, 7000);


texts:
Is my Python Script to play Hanoi Tower respectful of OOP spirit?

I have difficulties to create meaningful classes so I started an easy project. Here is one class at the plateau level and then a class to handle towers.

How can it be improved (on the OOP level and on script level)?

I want then a GUI with TKinter, a third class GUI would be suited ?

Thank you

import numpy as np
NB_DISKS = 3

class Plateau:
    """Class for the whole plateau"""
    def __init__(self):
        self.init_plateau()

    def init_plateau(self):
        """List of towers,first tower full"""
        self.nb_disks = NB_DISKS
        self.towers = [Tower(self.nb_disks), Tower(0), Tower(0)]

    def motion(self, tower_from, tower_to):
        """Motion from one tower to another one with checking"""
        from_tower = self.towers[tower_from-1]
        to_tower = self.towers[tower_to-1]

        if from_tower.get_last_disk()>to_tower.get_last_disk():  #Receive 0 if to_tower is empty
            disk = from_tower.get_last_disk()
            from_tower.delete_disk()
            to_tower.add_disk(disk)

            self.check_victory()
            self.print_towers()
        else:
            print('Last disk number from origin has to be bigger than reception one')

    def check_victory(self):
        """Check if last tower has an ordered list or not"""
        last_tower = self.towers[2].get_whole_tower()
        if len(last_tower) == self.nb_disks:
            diff_last_tower = np.diff(last_tower)
            if np.unique(diff_last_tower) == 1:
                print('victory:')
                self.print_towers()
                print('new plateau:')
                self.init_plateau()

    def print_towers(self):
        """Print the towers"""
        for elt in self.towers:
            elt.print_tower()
        print('\n')

class Tower:
    """Class for a tower"""
    def __init__(self,nb_disks):
        """Creation of a tower"""
        if nb_disks !=0:
            self.tower = list(range(1, nb_disks+1))
        else:
            self.tower = []

    def get_last_disk(self):
        """Return last element of the tower"""
        if self.tower == []:
            return 0
        else:
            return self.tower[-1]

    def delete_disk(self):
        """Delete last disk of the tower"""
        self.tower.pop()

    def add_disk(self,disk):
        """Add a disk to the top of the tower"""
        self.tower.append(disk)

    def get_whole_tower(self):
        """Return the complete tower"""
        return(self.tower)

    def print_tower(self):
        """Print the element of the tower"""
        print(self.tower)

if __name__ == '__main__':
    game = Plateau()
    game.motion(1,3)
    game.motion(1,3)   # Try to move a big disk on a small one
    game.motion(1,2)
    game.motion(3,2)
    game.motion(1,3)
    game.motion(2,1)
    game.motion(2,3)
    game.motion(1,3)


texts: Given an array of Strings, return the number of sets of anagrams

texts:
Please review my code:

public class Anagram {

    public static void main(String args[]) {
        String[] arr = { "abc", "cbc", "bcc", "dog", "god", "mary", "army",
                "rty" };
        HashMap<Integer, List<String>> mapList = new HashMap<Integer, List<String>>();

        for (int i = 0; i < arr.length; i++) {
            int hashcode = gethashcode(arr[i]);

            if (mapList != null && mapList.get(hashcode) == null) {
                List<String> list = new ArrayList<String>();
                mapList.put(hashcode, list);
                list.add(arr[i]);
            } else {
                List<String> list = mapList.get(hashcode);
                list.add(arr[i]);
            }
        }

        printMap(mapList);

        System.out.println("Count=" + mapList.size());
    }

    private static void printMap(HashMap<Integer, List<String>> mapList) {

        if (mapList != null && mapList.size() > 0) {
            for (Integer key : mapList.keySet()) {
                List<String> list = mapList.get(key);

                System.out.print("[");
                if (list != null && list.size() > 0) {
                    for (int k = 0; k < list.size(); k++) {
                        System.out.print(list.get(k) + " ");
                    }
                }
                System.out.print("]");
            }
        }

    }

    private static int gethashcode(String str) {
        int hashcode = 0;
        char ch[] = str.toCharArray();

        for (int i = 0; i < ch.length; i++) {
            if (hashcode != 0) {
                hashcode = hashcode + String.valueOf(ch[i]).hashCode();
            } else {
                hashcode = String.valueOf(ch[i]).hashCode();
            }
        }
        return hashcode;
    }
}

Output:

[mary army ][abc ][rty ][cbc bcc ][dog god ]    Count=5


texts: Suffix array construction in \$ O(n \log^2 n) \$

texts:
Here is my implementation of the suffix array construction algorithm which follows this paper (specifically, pages 4 and 6).

#!/usr/bin/env python3

from math import ceil, log2

def sufar(txt):

    txt = txt + chr(0)
    N, tokens = len(txt), sorted(set(t for t in txt))

    equivalence = {t: i for i, t in enumerate(tokens)}

    c, r = [equivalence[t] for t in txt], [(0, 0, 0)]

    for i in range(1, ceil(log2(N)) + 1):
        n = 2 ** (i - 1)

        r = sorted([(c[j],  c[(j + n) % N], j) for j in range(N)])

        c[r[0][2]] = 0
        for j in range(1, N):
            c[r[j][2]] = c[r[j - 1][2]]
            if r[j][0:2] != r[j - 1][0:2]:
                c[r[j][2]] += 1

    return [result[2] for result in r][1:]

This implementation looks correct, here are the unit tests I have tried.

My concerns are:

txt = txt + chr(0) to add a special symbol $ which is not supposed to be in txt.
using if r[j][0:2] != r[j - 1][0:2] to understand if the suffixes at positions j and j - 1 are from the same equivalence class. I would expect the comparison to be if r[j][0:1] != r[j - 1][0:1] but that fails the unit tests.


texts: Finding cointegrated pair with minimal t-score

texts:
The function findMinimal() receives a tuple from a list which contains 171 tuples, each of them go into the function one by one and, for each tuple, it searches the best pair via minimalTscore out of those that match by industry (approx. 20 names, for each one). How can I make the function to run faster? At the moment, it's quite slow.

def findMinimal(tup): #Finds cointegrated pair with minimal t-score
    stockPair = []
    stock = tup[0]
    industry = tup[1]
    minimalTscore = 0
    stockListLocal = [i for i in stockList if i[0] != stock]
    clf = linear_model.LinearRegression()
    for i in stockListLocal:
        if i[1] == industry and stock != i[0]:
            Y = data[stock][datesIterable[startTrain:endTrain]]
            X = data[i[0]][datesIterable[startTrain:endTrain]]
            clf.fit(np.array(X).reshape(len(X),1), np.array(Y).reshape(len(Y),1))
            beta_hr = clf.coef_[0]
            alpha = clf.intercept_[0]
            residuals = Y - beta_hr*X - alpha
            cadf = ts.adfuller(residuals)

            if cadf[4]['1%'] > cadf[0]:
                if hurst(residuals) < 0.4:
                    if minimalTscore == 0:
                        minimalTscore = cadf[0]
                        stockPair = i[0]
                    else:
                        if cadf[0] < minimalTscore:
                            minimalTscore = cadf[0]
                            stockPair = i[0]
    if (stockPair,stock) not in pairsOnlyStocks and len(stockPair) > 0:
        pairs.append((stock, stockPair, minimalTscore)) #Y, X, tscore
        pairsOnlyStocks.append((stock, stockPair)) #this is only for filtering


texts:
I just got into structs and I decided to create a list using them:

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
    char counter;

    struct list
    {

        int x;
        struct list *pointer1;

    };

    struct list test;
    struct list *pointer2;

    pointer2=&test;

    for(counter=0;counter<5;counter++)
    {

        pointer2->pointer1=malloc(sizeof(struct list));
        pointer2=pointer2->pointer1;

    }
}

I was wondering if there is another way to do the exact same thing.  Is the use of one pointer only possible? By the way, I am pretty sure I could do the same thing using an array of structs too.  Any advice would be really helpful!


texts:
I wrote my first ruby script, by this tutorial. It creates a local and remote git repo.

I have been working for about 3 years with PHP, and somehow I find that my ruby script looks incredibly ugly.

Is it correct to use a class for that?
What can I make better?
Are there any security gaps in it?
Is the usage in for true and false in the empty_name? and folder_exists? methods correct?

#!/usr/bin/env ruby

require 'fileutils'
#require 'colorize'

class Repo

  LOCAL_PATH = 'C:\xampp\htdocs'
  REMOTE_PATH = 'C:\Users\Windows\Desktop\Dropbox\repos'
  UPSTREAM_NAME = 'dropbox'

  def initialize
      print 'Name: '
      @name = gets.chomp

      if ! folder_exists?

          create_local_repo
          create_files_and_commit
          create_remote_repo

      end
  end

  private

  # Check if name is emtpy.
  def empty_name?
      if @name.empty?
          print "You need to pass a name: "
          @name = gets.chomp
          empty_name?

          true
      end

      false
  end

  # Check if folder exists on local and remote path.
  def folder_exists?

      empty_name?

      if File.exists? "#{LOCAL_PATH}/#{@name}"
          print "Directory `#{@name}` exists in #{LOCAL_PATH}. Pass a new name: "
          @name = gets.chomp

          folder_exists?
      elsif File.exists? "#{REMOTE_PATH}/#{@name}.git"
          print "Directory `#{@name}.git` exists in #{REMOTE_PATH}. Pass a new name: "
          @name = gets.chomp

          folder_exists?
      end

      false
  end

  # Create local folder and initialize git.
  def create_local_repo
      Dir.chdir "#{LOCAL_PATH}" do `git init #{@name}` end
  end

  # Create .gitignore and commit.
  def create_files_and_commit
      Dir.chdir "#{LOCAL_PATH}/#{@name}" do
          File.open ".gitignore", 'w+' do |f|
              f.write ".idea\n/vendor\n/node_modules\n.Thumbs.db\n.DS_Store"
          end

          `git add .`
          `git commit -m "initialize commit"`
      end
  end

  # Create empty remote repo.
  def create_remote_repo
      `git init --bare #{REMOTE_PATH}/#{@name}.git`

      Dir.chdir "#{LOCAL_PATH}/#{@name}" do
          `git remote add #{UPSTREAM_NAME} #{REMOTE_PATH}/#{@name}.git`
          `git push -u #{UPSTREAM_NAME} master`
      end
  end

end

Repo.new


texts: Assigning initial value via getter or viewDidLoad

texts:
I've been coding in a vacuum for several years and am trying to get up to speed on best practices, in anticipation of my eventual return to employment. I'm hoping this is the best forum in which to ask these types of questions. If not, please let me know.

My first question regards assigning the initial values of a UIViewController's properties. In general, is it better to do this in viewDidLoad or in the property's getter?

For example, I have a UIViewController with graphics that are based on the user's chosen graphics Theme. The first thing that needs to happen is to load an NSDictionary for the chosen theme, based on the current setting in NSUserDefaults.

So to start, I have:

#import "MainViewController.h"

@interface MainViewController ()
@property NSString *currentTheme;
@end

@implementation MainViewController
@synthesize currentTheme = _currentTheme;

My preferred method is to use lazy instantiation:

- (void)setCurrentTheme:(NSString *)currentTheme {
    _currentTheme = currentTheme;
}

- (NSString *)currentTheme {
    if (!_currentTheme) {
        _currentTheme = [[NSUserDefaults standardUserDefaults] objectForKey:@"currenttheme"];
    }
    return _currentTheme;
}

But since this is the first thing that needs to happen, anyway, I don't think there's any real difference in performance or utility from assigning this in viewDidLoad:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.currentTheme = [[NSUserDefaults standardUserDefaults] objectForKey:@"currenttheme"];
}

Is there a preferred way of doing this?