Image edge detection I have a Canny Edge Detection Code written in C++. I would like to know how can I make it more robust in terms of detecting all the edges correctly and save it? Is this the best possible edge detection possible? Can the coders find any error in my code? Below is a picture of how the code looks like.

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdlib.h>
#include <stdio.h>

using namespace cv;

/// Global variables

Mat src, src_gray;
Mat dst, detected_edges;

int edgeThresh = 1;
int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name = "Edge Map";

/**
 * @function CannyThreshold
 * @brief Trackbar callback - Canny thresholds input with a ratio 1:3
 */
void CannyThreshold(int, void*)
{
  /// Reduce noise with a kernel 3x3
  blur( src_gray, detected_edges, Size(3,3) );

  /// Canny detector
  Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );

  /// Using Canny's output as a mask, we display our result
  dst = Scalar::all(0);

  src.copyTo( dst, detected_edges);
  imshow( window_name, dst );
 }

/** @function main */
int main( int argc, char** argv )
{
  /// Load an image
  src = imread( argv[1] );

  if( !src.data )
  { return -1; }

  /// Create a matrix of the same type and size as src (for dst)
  dst.create( src.size(), src.type() );

  /// Convert the image to grayscale
  cvtColor( src, src_gray, CV_BGR2GRAY );

  /// Create a window
  namedWindow( window_name, CV_WINDOW_AUTOSIZE );

  /// Create a Trackbar for user to enter threshold
  createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );

  /// Show the image
  CannyThreshold(0, 0);

  /// Wait until user exit program by pressing a key
  waitKey(0);

  return 0;
  }

In terms of making more robust, a fairly obvious improvement would be to ensure that argv[1] exists before using it (that's what argc is for).  If there's no argument, or the file can't be read, emit a useful error message to std::cerr and return EXIT_FAILURE - negative return values from main() can vary by platform.

Why do we declare CannyThreshold with two arguments, but never use them?  Just declare it taking no arguments.

Your description mentions saving the result, but I don't see any code for that - did you perhaps show us the wrong version of the program?


Vectorizing a polar coordinate conversion loop in a fingerprint-matching process I am working on a fingerprint matching technique and it takes a lot of computation time to obtain the result. I am trying to implement the matching process given in A Minutia Matching Algorithm in Fingerprint Verification. I would like to know if there is any method available to reduce the for loop for this code:

[Tdrow,Tdcol]=size(Td);
[Idrow,Idcol]=size(Id);
matchingscore=zeros(Tdrow,Idrow);
rv = bsxfun(@minus,Td(:,3),permute(Id(:,3),[2 1]));
%convert each minutiae point to polar coordinates with respect to the
%reference minutiae in each case
for i=1:Tdrow
    for j=1:Idrow
        Tdp=zeros(Tdrow,Tdcol);
        Idp=zeros(Idrow,Idcol);
        tref=Td(i,:);
        iref=Id(j,:);
        Tdp(:,1)=sqrt((Td(:,1)-tref(1)).^2 + (Td(:,2)-tref(2)).^2);
        Tdp(:,2)=mod(atan2(tref(1)-Td(:,1),Td(:,2)-tref(2)) * 180/pi,360);
        Tdp(:,3)=mod(Td(:,3)-tref(3),360);
        Tdp(:,4)=Td(:,4);
        Idp(:,1)=sqrt((Id(:,1)-iref(1)).^2 + (Id(:,2)-iref(2)).^2);
        Idp(:,2)=mod((atan2(iref(1)-Id(:,1),Id(:,2)-iref(2)) * 180/pi) + rv(i,j),360);
        Idp(:,3)=mod(Id(:,3)-iref(3),360);
        Idp(:,4)=Id(:,4);
        Tdp1 {i,j}= Tdp(:,:);
        Idp1 {i,j}= Idp(:,:);
    end
end

Here, the variable Td is the fingerprint template to be compared and Id is the input fingerprint template. Both Td and Id have four columns, i.e. 1st and 2nd column provide x and y coordinate respectively, 3rd column is the angle and 4th column is the type of minutiae. Tdp and Idp are calculated using the equation provided in the attachment provided in the link.

Can this code be vectorized? I understand that the indexes have hardly been used. But without changing the index i cannot continue to the further steps. It would be very helpful is anyone could provide me with any suggestions.

The data values are available on Google Drive. These has both the input data and output data.

You said your code works good, as the input isn't too big, so I won't go ahead an try to vectorize this. So, I've provided a general review of the code.

Overall your code looks nice. You should however attempt to have a bit more spaces

[Tdrow, Tdcol] = size(Td);  <-- This
[Tdrow,Tdcol]=size(Td);     <-- Not this

There are only a few things I would do differently in the code:

You can speed this up quite a bit even without vectorization: The size of the cells Tdp1 and Idp1 are known, so these cells can be pre-allocated in front of the loop:

[Tdp1{1:Tdrow, 1:Idrow}] = zeros(Tdrow, Tdcol);
[Idp1{1:Tdrow, 1:Idrow}] = zeros(Idrow, Idcol);

This way you avoid creating Tdrow*Idrow arrays inside the loop. That should save you some time.
Tdp(:,:) is the same as just Tdp, so you can do:

Tdp1{ii,jj} = Tdp;

Note,  ii and jj are better than i and j as iterator names in Matlab.
You are converting angles from radians to degrees a few places atan2(x,y) * 180 / pi. Instead, use atan2d(x,y). It returns the value in degrees directly.


Constructing MongoDB document from a dict with character code-to-integer translation I have an class definition:

class ScoreDetail(Document):
    location            = StringField(help_text = "province")
    school              = StringField(help_text = "school")
    spec                = StringField(help_text = "major")
    bz                  = IntField(help_text = "1: Bachelor, 2: Academy, 0: exception")
    wl                  = IntField(help_text = "1: w, 2: l, 0: exception")
    batch               = StringField(help_text = "batch")
    score               = IntField(help_text = "score")
    average_score       = FloatField(help_text = "average score")
    average_score_rank  = FloatField(help_text = "rank of average score")
    low_score           = IntField(help_text = "the lowest score")
    low_score_rank      = IntField(help_text = "rank of the lowest score")
    high_score          = IntField(help_text = "highest score")
    high_score_rank     = IntField(help_text = "rank of the highest score")
    score_number        = IntField(help_text = "people in this score")
    spec_number         = IntField(help_text = "people in the major")
    rank                = IntField(help_text = "rank")
    year                = IntField('year')

Now I have a dict named item, like this:

{
  "school": u"Peking University",
  "average_score": u"255",
  "low_score_rank": u"195466",
  "wl": u"w",
  "batch": u"4",
  "score_number": u"1",
  "average_score_rank": u"178199",
  "low_score": u"150",
  "high_score": u"464",
  "score": u"150",
  "spec_number": u"62",
  "rank": u"195466",
  "year": u"14",
  "high_score_rank": u"60631",
  "spec": u"E-commerce",
  "bz": u"z",
  "location": u"US"
}

I want construct a ScoreDetail object from this dict, so I do this:

wl_map = {'w': 1, 'l': 2}
bz_map = {'b': 1, 'z': 2}
item['wl'] = wl_map[item['wl']]
item['year'] = '20' + item['year']
item['bz'] = bz_map[item['bz']]

s = ScoreDetail(
        school=item['school'],
        average_score=item['average_score'],
        low_score_rank=item['low_score_rank'],
        wl=item['wl'],
        batch=item['batch'],
        score_number=item['score_number'],
        average_score_rank=item['average_score_rank'],
        low_score=item['low_score'],
        high_score=item['high_score'],
        score=item['score'],
        spec_number=item['spec_number'],
        rank=item['rank'],
        year=item['year'],
        high_score_rank=item['high_score_rank'],
        spec=item['spec'],
        bz=item['bz'],
        location=item['location']
        )

Now I want to know these two things:

Can I simplify this code?
As you can see, this is a mongoengine schema. It inherits Document, so it can make '1' to int, '150' to float as default, but if I were not to use MongoEngine, this is just a common class. How can I make some type conversion as default?

If all attributes are in item, then you can create an instance simply with:

s = ScoreDetail(**item)

This is just a guess though. Your code looks like Django, where this would work, but even though this isn't Django, I suspect this to be supported similarly.

Without a friendly framework to convert between objects and json, you could use the serialization/deserialization features of the json package, with custom serializer/deserializer implementations.


Convert list/tuple of arguments into just arguments I am using a library that specifically needs me to provide arguments as strings one by one. However, different combinations are possible. Right now I am using a bunch of elif:

def get_all_users(times=False, groups=False, ips=False):
    """Get a list of all users online"""
    if times and groups and ips:
        return ts3conn.exec_("clientlist", "times", "groups", "ips")
    elif times and groups:
        return ts3conn.exec_("clientlist", "times", "groups")
    elif times and ips:
        return ts3conn.exec_("clientlist", "times", "ips")
    elif groups and ips:
        return ts3conn.exec_("clientlist", "groups", "ips")
    elif times:
        return ts3conn.exec_("clientlist", "times")
    elif groups:
        return ts3conn.exec_("clientlist", "groups")
    elif ips:
        return ts3conn.exec_("clientlist", "ip")
    else:
        return ts3conn.exec_("clientlist")

But I am wondering if this could be improved.

NOTE: I tried if I could use tuples but it won't work:

stuff = (times, groups, ips)
return ts3conn.exec_("clientlist", stuff)
>>> TypeError: can only concatenate str (not "tuple") to str

Update:
Library is at: https://github.com/benediktschmitt/py-ts3/blob/v2/ts3/query_builder.py

The code raises error on function compile:

for option in options:
    res += " -" + option

You could use itertools.compress in combination with the tuple

def get_all_users(times=False, groups=False, ips=False):
    """Get a list of all users online"""
    arguments = ("clientlist", "times", "groups", "ips")
    selectors = (True, times, groups, ips)

    return ts3conn.exec_(*itertools.compress(arguments , selectors))

or in python 3.6+, using the retained insertion order of dicts (earlier versions can use an collections.ordereddict

def get_all_users(times=False, groups=False, ips=False):
    """Get a list of all users online"""
    arguments = {
        "clientlist": True,
        "times": times,
        "groups" : groups,
        "ips": ips,
    }
    return ts3conn.exec_(*(key for key, value in arguments.items() if value))


Hand crafted longest common sub sequence I know that the below solution is not the best one and I am in the way to learn that stuff till then I have applied the brute force to see how far I can go with my intuition.

console.clear();

function allButLast(arr) {
  return arr.slice(0, arr.length - 1);
}

function last(xs) {
  return xs.slice(-1);
}

function map(xs, cb) {
  return [].map.call(xs, cb);
}

function powerset(xs) {
  if (xs.length === 0) return [[]];
  var res = powerset(allButLast(xs));

  return res.concat(map(res, function(el) { return el.concat(last(xs)); }));
}

console.log(powerset([]));           // [[]]
console.log(powerset([1]));          // [[], [1]]
console.log(powerset([1, 2]));       // [[], [1], [2], [1, 2]]
console.log(powerset([1, 2, 3]));    // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

function increasing(xs) {
  var i = 1,
      l = xs.length;
  for (;i < l; i++) {
    if (xs[i] < xs[i - 1]) return false;
  }
  return true;
}

console.log(increasing([1, 2]));

function LIS(xs) {
  var res = [];
  [].forEach.call(powerset(xs), function(subset){
    if (increasing(subset) && subset.length > res.length) res = subset;
  });
  return res;
}

console.log(LIS([2, 3, 1, 4, 0, 5])); // [2, 3, 4, 5]

I have tried to be as much naive as possible because sometimes the best solution doesn't come to your mind most probably in the case of interview etc. I need to know if the code is clear and readable?

Interesting question,

I would say for an interview, if you are given a task and you think you need combinations or permutations, then there is a good chance it's a trick question. Those are terrible for performance and I would avoid them as the plague during interviews.

Secondly, your code is hard to read. Only because of the comment on the very last line did things come together for me.

Other than that;

Try to be consistent

function allButLast(arr) {
  return arr.slice(0, arr.length - 1);
}

function last(xs) {
  return xs.slice(-1);
}

These functions both get an array, but in one the argument is called arr, in the other one xs. They should have the same name, I would go for list.
I like your powerset routine, and might borrow it
I dont understand [].reduce.call in sum, why not just xs.reduce ? From an interview perspective it makes me think you dont understand how reduce works :/

On the whole this implementation should be light years faster, though I only tested it with your test case which I got right the first time, so I have good hopes ;)

console.log(LIS([2, 3, 1, 4, 0, 5])); // [2, 3, 4, 5]

//Find the longest common sub sequence
function LIS( list ){

  var indexes = {},
      //Possibly too verbose variable name ;)
      lastIntegerofLargestSequence,
      largestSequenceLength = 0,
      output = [];

  for( n of list ){

    //Have we processed a predecessor yet?
    if( indexes[n-1 ] !== undefined ){
      //There is a predecessor, if we have never found n,
      //then put n with predecessor's length + 1
      if( indexes[n] === undefined ){
        indexes[n] = indexes[n-1] + 1;
      //Otherwise ONLY put that predecessor length + 1
      //if that would make a better (longer sequence)
      }else if( indexes[n-1] + 1 > indexes[n]  ){
        indexes[n] = indexes[n-1] + 1;
      }
      //First number in a possible sequence
    }else if( indexes.n === undefined ){ //That 0 ;/
      indexes[n] = 1;
    }

    //Keep track of the largest sequence
    if( indexes[n] > largestSequenceLength ){
      largestSequenceLength = indexes[n];
      lastIntegerofLargestSequence = n;
    }
  }

  for( var i = lastIntegerofLargestSequence - largestSequenceLength + 1; i <= lastIntegerofLargestSequence ; i++ )
    output.push(i);

  console.log(output)

}


Smart subscript indexing macro I need to go and rework a bunch of notation in a large body of work. But I might change my mind later, so I want to move to defining the notation a bit more semantically (e.g. writing \v x to represent a vector, so I can later decide to format vectors in different ways).

On thing that is currently wrong with it is that I write A_i to represent that \$i^{\text {th}}\$ column vector. After looking at other similar works, I have concluded that A_{:,i} would be clearer. So I have defined a macro to smartly determine if a : should be added.

I called it \i to be concise since I will be writing it often.

\documentclass{article}

\usepackage{xparse,xstring,etoolbox}

\renewcommand{\v}[1]{\tilde{#1}} % a vector

\newcommand{\ind}[2]{#1_{#2}} % indexed

%% Smart indexing and naming code

\newcommand{\ifupper}[3]{
    \normalexpandarg
    \exploregroups
    \StrCount{ABCDEFGHIJKLMNOPQRSTUVWXYZ}{#1}[\uppercount]
    \ifnumgreater{\uppercount}{0}{#2}{#3}
}

%smart index
\DeclareDocumentCommand{\i}{u{_} m}{
    \ifupper{#1}%
    {% just a single uppercase character, i.e. a matrix
        %make sure the index is the right length
        \StrCount{#2}{,}[\indcount]
        \ifnumgreater{\indcount}{0}
        { % Got multiple indexes so all good
            \ind{#1}{#2}
        }
        { % Only 1 index so grab the column
            \ind{#1}{{:,#2}}
        }
    }%
    {% Not just a single upper case character
        \ind{#1}{#2}
    }
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Example document
\begin{document}

        \begin{tabular}{r l}
  $\i {\v x}_i$ & the $i$th element of the vector $\v x$\\
  $\i{X}_{i,j}$ & the row $i$ and column $j$ element of the matrix $X$\\
  $\i{X}_i$ & the $i$th column vector of the matrix $X$\\
  $\i{X}_{i,:}$ & the $i$th row vector of the matrix $X$\\
 \end{tabular}

\end{document}

Example document output

Crossref

Redefining \v and \i is a bad thing. Don't, you'll regret it as soon as you want to need to cite a paper by Eduard Čech or by Erdal Arıkan.

You also have quite an inefficient usage of xstring and no error checking if a _ is forgotten.

Here's a complete implementation with xparse:

\documentclass{article}

\usepackage{xparse}

\NewDocumentCommand{\ind}{me{_}}{%
  \IfNoValueTF{#2}{\doind{#1}{???}}{\doind{#1}{#2}}
}

\ExplSyntaxOn
\NewDocumentCommand{\doind}{mm}
 {
  \tl_if_single:nTF { #1 }
   {% a single character
    \str_if_eq_x:nnTF { #1 } { \str_upper_case:n { #1 } }
     {% upper case, assume matrix
      \lyndon_index_matrix:nn { #1 } { #2 }
     }
     {
      \lyndon_index_do:nn { #1 } { #2 }
     }
   }
   {% not a single character
    \lyndon_index_do:nn { #1 } { #2 }
   }
 }

\cs_new_protected:Nn \lyndon_index_matrix:nn
 {
  \int_compare:nTF { \clist_count:n { #2 } > 1 }
   {% Got multiple indexes so all good
    \lyndon_index_do:nn { #1 } { #2 }
   }
   {% Only one index so grab the column
    \lyndon_index_do:nn { #1 } { {:},#2 }
   }
 }
\cs_new_protected:Nn \lyndon_index_do:nn
 {
  #1\sb{#2}
 }
\ExplSyntaxOff

% Example document
\begin{document}

\begin{tabular}{r l}
$\ind{A}$           & missing subscript\\
$\ind{\tilde{x}}_i$ & the $i$th element of the vector $\tilde{x}$\\
$\ind{X}_{i,j}$     & the row $i$ and column $j$ element of the matrix $X$\\
$\ind{X}_i$         & the $i$th column vector of the matrix $X$\\
$\ind{X}_{i,:}$     & the $i$th row vector of the matrix $X$\\
\end{tabular}

\end{document}

On the other hand, I see no much gain in using _ and also in doing checks for uppercase letters, which is quite limiting. I'd prefer a * version for vectors.

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\ind}{smm}
 {
  \IfBooleanTF{#1}
   {% *, a vector
    \lyndon_index_do:nn { #2 } { #3 }
   }
   {% normal, a matrix
    \lyndon_index_matrix:nn { #2 } { #3 }
   }
 }
\cs_new_protected:Nn \lyndon_index_matrix:nn
 {
  \int_compare:nTF { \clist_count:n { #2 } > 1 }
   {% Got multiple indexes so all good
    \lyndon_index_do:nn { #1 } { #2 }
   }
   {% Only one index so grab the column
    \lyndon_index_do:nn { #1 } { {:},#2 }
   }
 }
\cs_new_protected:Nn \lyndon_index_do:nn
 {
  #1\sb{#2}
 }

\ExplSyntaxOff

% Example document
\begin{document}

\begin{tabular}{r l}
$\ind*{\tilde{x}}{i}$ & the $i$th element of the vector $\tilde{x}$\\
$\ind{X}{i,j}$        & the row $i$ and column $j$ element of the matrix $X$\\
$\ind{X}{i}$          & the $i$th column vector of the matrix $X$\\
$\ind{X}{i,:}$        & the $i$th row vector of the matrix $X$\\
$\ind{\Gamma}{j}$     & Greek matrix
\end{tabular}

\end{document}


Add class based on checked checkbox I am looking to simplify this code as it is to bulky for what it is doing. I do not need to stick to jQuery.

Simple checkbox in html relates to adding underline to some text:

$("#houseOrCar").on("change", function () {
    if ($(this).is(":checked") ) {
        $("#houseChosen").css("text-decoration", "none");
        $("#carChosen").css("text-decoration", "underline");
    }
    else  {
        $("#houseChosen").css("text-decoration", "underline");
        $("#carChosen").css("text-decoration", "none");
    };
});

You could use a class that would only hold the property for the active element, in our case text-decoration: underline;. Then simply toggle each of the two labels to set on and off this "active" class (here called underline).
So you don't need to know which label is which, both will toggle anyway. Just set one of the two to have the class .underline on page load.

Plain JavaScript

const toggle = () => document.querySelectorAll('#labels > div')
  .forEach(label => label.classList.toggle('underline'))

document.querySelector('#houseOrCar').addEventListener('change', toggle);
.underline {
  text-decoration: underline;
}
<input type="checkbox" id="houseOrCar">

HOUSE

CAR

Note I'm using the .forEach method of the nodeList class:

  The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order.

jQuery

And here it is implemented with jQuery, which is shorter but very similar:

const toggle = () => $('#labels > div')
  .each((i,e) => $(e).toggleClass('underline'));

$('#houseOrCar').on('change', toggle);
.underline {
  text-decoration: underline;
}

<input type="checkbox" id="houseOrCar">

HOUSE

CAR

It's not worth using jQuery for this, personally, I would stick with the plain version. However, if you happen to already use jQuery in your project then go for it!


Calling API (with rate of 5 calls/second) using Jersey client I am using the Jersey client to make API calls to validate a session. This call is being made at a rate of around 5 calls/second. I want to ensure that the client call doesn't have performance issues.

String sessionUrlPrefix = Config.getInstance().getString(Helper.SESSION_SERVICE_URL);
String urlParameters = getParameters(sessionId);
String sessionURL = sessionUrlPrefix + "?" + urlParameters;
WebResource webResource = client.resource(sessionURL);
logger.debug("Session URL is " + sessionURL);
ClientResponse response = webResource
    .accept(MediaType.TEXT_PLAIN_TYPE)
    .type(MediaType.TEXT_PLAIN_TYPE)
    .get(ClientResponse.class);

String responseStr = response.getEntity(String.class);
logger.debug("Response received is " + responseStr);
if (response.getStatus() != HttpStatus.OK.value())
{
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    // Could throw more appropriate HttpException.
}
return responseStr;

I'm not familiar with Jersey at all, so just two generic notes:

You might want/could use HEAD instead GET which does not download the message body.
I don't know what is logging framework but if it's SLF4J you should use the {} pattern instead of string concatenation.

logger.debug("Session URL is {}", sessionURL);


Using reference to head node while reversing linked list using recursion Referring to my previous post, should I consider using current pointers for this code snippet for reversing a linked list using recursion?

public static List ReverseRecursion(List head){

        List newHead;
        List current = head;

        if(current == null){
            return null;
        }
        if(current.next == null){
            head = current;
            return head;
        }
        newHead = ReverseRecursion(current.next);
        current.next.next = current;
        current.next = null;
        return newHead;

    }

Or should I consider the solution without using current node as someone pointed out in their solution like this?

public static List ReverseRecursion(List head){
    List newHead;

    if(head == null){
        return null;
    }
    if(head.next == null){
        return head;
    }

    newHead = ReverseRecursion(head.next);
    head.next.next = head;
    head.next = null;
    return newHead;
}

Extra variable unnecessary

Your variable current in the first code snippet is assigned to head and never changes, so it is unnecessary.  You can just use head directly instead, as in the second code snippet.  Therefore I feel the second version is superior.

Iterative version

Consider using an iterative version to reverse the list instead of a recursive version.  An iterative solution uses \$O(1)\$ space instead of \$O(n)\$ space, and is much easier to understand as well.  All you need to do is take each element of the list and add it to the head of a new list, like this:

public static List ReverseList(List head)
{
    List newHead = null;

    while (head != null) {
        List next = head.next;

        head.next = newHead;
        newHead   = head;
        head      = next;
    }
    return newHead;
}


Spawning futures as an alternative to multithreading I was trying to do a sample threading program, where the spawning of thread is in a while loop. I DO NOT want to generate multiple number of threads. The while loop should keep on running, irrespective of whether the thread completed execution or not. There is a call to the .get() function of the above thread within the while loop. Again, this has to be called only when the thread executed correctly.

My code is given below:

#include <iostream>
#include <future>
#include <thread>
#include <chrono>

int thread(int varJ)
{
    std::cout<<"\t\t"<<varJ<<std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    return varJ;
}

int main()
{
    int varI = 0;
    std::future<int> future = std::async(std::launch::async, [](){return 0;});
    std::future_status status;
    bool flag = false;

    while(1)
    {
        status = future.wait_for(std::chrono::milliseconds(0));
        if(status == std::future_status::ready && !flag)
        {
            future = std::async(std::launch::async, thread, varI);
            flag = true;
        }
        status = future.wait_for(std::chrono::milliseconds(0));
        if(status == std::future_status::ready && flag)
        {
            std::cout << "\t result is " << future.get() << '\n';
            future = std::async(std::launch::async, [](){return 0;});
            flag = false;
        }
        varI++;
    }
}

The output obtained:

    0
 result is 0
    865
 result is 865
    1723
 result is 1723
    2632
 result is 2632
    3590
 result is 3590
    4551
 result is 4551
    5509
 result is 5509

The output is as I expected it to be. But is this the way to code or is there a better way?

I am not pleased to use a flag in between the code, calling future.wait_for a lot many times and especially using the dummy thread that returns 0.

I see some things that may help you improve your code.

Simplify your code using literals

There is nothing intrinsically wrong with std::chrono::milliseconds(0) but I would prefer to read (and to write) 0ms instead.  This can be done by adding this line to within main:

using namespace std::literals::chrono_literals;

Use more meaningful variable names

I understand that it's just a toy program, but I really think we can do better than varI and varJ!  Since it's just a freerunning counter, why not just call it count?

Understand the threading model

It's important to realize that std::future was designed to hold not only the future value (or exception) but also a flag for the future_status.  This renders the current code's flag unnecessary.  Here's a more concise rewrite of main:

int main()
{
    using namespace std::literals::chrono_literals;
    int count = 0;
    std::future<int> future = std::async(std::launch::async, thread, count);
    while(1) {
        if (future.wait_for(0ms) == std::future_status::ready) {
            std::cout << "\t result is " << future.get() << '\n';
            future = std::async(std::launch::async, thread, count);
        }
        ++count;
    }
}

Beware of sharing unsynchronized variables

Right now, both the thread running main and the thread running the function write to std::cout.  The way the code is currently structured (both in the original and in the rewrite above), they do not contend for that same variable but they could because there currently is no synchronization.  The effect is that the output of the two threads could easily be interleaved.  The easiest way to prevent this is to only access cout from a single thread.


Functional List in C++ This is rather toy example of immutable datatype in C++. I've tried to follow functional languages like Scheme, Racket - making list as a cons cell: list is list or is empty.

/*
 * Abstract class
 */
template <class T>
class ImmutableList {

public:
~ImmutableList() {std::cout << "base class destructor";}
virtual bool is_empty() = 0;
virtual T head() = 0;
virtual ImmutableList<T> * tail() = 0;
virtual int length() = 0;
};

/*
 * class non empty List
 */

template <class T>
class List: public ImmutableList<T> {

int size = 1;
T first;
ImmutableList<T> * rest;
public:

List(T _first, ImmutableList<T> * _tail){
    first = _first;
    rest = _tail;
    size += _tail->length();
}
~List() {std::cout << "List class destructor";}
bool is_empty() { return false; }

T head(){
    return first;
}

ImmutableList<T>* tail(){
    return  rest;
}

int length() {return size;}
};

/*
 * class empty list
 */
template <class T>
class Nil: public ImmutableList<T> {
    public:
    ~Nil();
    bool is_empty() {return true;}
    int length() {return 0;}
    T head() {
        throw std::logic_error("Head of empty list!");
    }
    ImmutableList<T> * tail() {
        throw std::logic_error("Tail of empty list!");
    }
};

There is more functions, like a reverse, there is also cons function - constructs a list.
Do this really need destructors? Will be better to use smart pointers?

Overview
The trouble here is ownership. Who owns the tail?
In C++ ownership is a very important topic and defines who is responsible for who should destroy an object. The problem with C like pointers is there are no explicit ownership semantics. So as part of the documentation you need to define who the owner (and people read documentation is the problem here) is otherwise things go wrong and the wrong person will delete the object or it will never get deleted.
This is why in modern C++ it is very uncommon to see C-pointers. Because there is no ownership defined. You can use smart pointers to explicitly define the owner of a pointer or you can use references to show that you are retaining ownership.
Note: Inside a class it's OK to use a pointer as you control everything inside a class. The problems happen when you leak a pointer through a public interface.
You don't show how you expect your class to be used, but given the interface it is easy to use it with pointers and leak object all over the place. Given the current interface I would expect the following to be standard usage:
 ImmutableList<int>* data = new List<int>(1, new List<int>(2, new List<int>(3, new Nil<int>())));

 // Do stuff.

 delete data;

This leads to all but the first element from being leaked (because the destructor does not delete the chain).
Now you can't just add a delete into the destructor as you can retrieve the tail and place it another object.
ImmutableList<int>* data1 = new List<int>(1, new Nil<int>());
ImmutableList<int>* data2 = new List<int>(2, data1->tail());

In this situation simply deleting the tail is not going to work as both data1 and data1 share the same tail. So you need some form of shared ownership semantics. Now you can do this yourself but if you try and implement your own ownership semantics then you need to define the copy and move operators for your class.
// Copy Operators
List& List::List(List const&);
List& List::operator=(List const&);

// Move Operators
List& List::List(List&&);
List& List::operator=(List&&);

This becomes exceedingly not trivial when you have shared objects. So really you need to use std::shared_ptr.
Code Review
If you have a base class with virtual methods then you your destructor should also be virtual:
template <class T>
class ImmutableList {
    public:
       // Destructor should be declared virtual
       ~ImmutableList() {std::cout << "base class destructor";}
       ...
}

This is because you are likely to use delete on a base class pointer that points at a derived type. If the destructor is not virtual you call the wrong destructor.
Your code is not const correct.
virtual bool is_empty() = 0;
virtual T head() = 0;
virtual ImmutableList<T> * tail() = 0;

All the above methods are const (as your class is Immutable). So you can change the object just query it.
virtual bool              is_empty() const = 0;
virtual T                 head()     const = 0;
virtual ImmutableList<T>* tail()     const = 0;
virtual int               length()   const = 0;
                                  // ^^^^^

You return the head by value. This causes a copy of the object. Now for int and other simple types this is not a problem. But for complex types (like vector) a copy may be much more expensive.
So normally you return by reference. Not because the class in Immutable you should return a const reference.
virtual const& T head()                 const = 0;
    //  ^^^^^^

Now you return a reference to the object (allowing it to be queried). If you actually want a copy you can assign it to a variable and it will be copied.
T val = data1->head();


Querying a database with PHP I'm new to PHP programming. I would love some feedback on this simple code I wrote which queries a database based on some arguments supplied by a user and returns an HTML table displaying the data.

The table in my db has three columns: Manufacturer, Model, ForSale.

The user picks from three drop down menus on the web page and this php script is called with the data.

<?php
$db = new SQLite3("db/mantisui.db");

$manufacturer= $_GET['mfr'];
$model = $_GET['mod'];
$forsale = $_GET['forSale'];

// create the query
$q = "SELECT * FROM vehicles";
$addwhere = true;

// if all mfrs chosen, skip WHERE clause
$pos = strpos($manufacturer, 'All');
if ($pos === false) {
    $q .= " WHERE Manufacturer='$manufacturer'";
    $addwhere = false;
}

// if any models chosen, skip WHERE clause
$pos = strpos($model, 'Any');
if ($pos === false) {
    if ($addwhere == false) {
        $q .= " AND";
    }
    else {
        $q .= " WHERE";
        $addwhere = false;
    }

    $q .= " Model='$model'";
}

// if any for sale status chosen, skip WHERE clause
$pos = strpos($forsale, 'Any');
if ($pos === false) {
    if ($addwhere == false) {
        $q .= " AND";
    }
    else {
        $q .= " WHERE";
        $addwhere = false;
    }

    $q .= " ForSale='$forsale'";
}

$response = $db->query($q);

// generate the output table
$output = "
";
$output .= "

MANUFACTURER	MODEL	FOR SALE

";
while ($res = $response->fetchArray()) {

    $id = $res['Id'];
    $txtMfr= $res['Manufacturer'];
    $txtModel= $res['Model'];
    $txtForSale = $res['ForSale'];

    $output .= "
$id	$txtMfr	$txtModel	$txtForSale	$status
";
}

$output .= "
";
echo $output;

$db->close();
?>

Generally, it is a good idea to separate your view logic from your business logic, e.g your data access.

The code you've presented is procedural, and whilst there's nothing wrong with that at this stage, it could become unsustainable in terms of future maintainability.

One thing that I am conscious about, is that you are directly plugging variables into your SQL query that you are constructing: there is a risk of SQL injection. I would suggest that you wrap your variables with sqlite_escape_string before placing them into your query. I note that you might want to look into PDO for database portability and a 'better' layer between your application and the database.

You seem to be be using strpost to ascertain whether a manufacturer was 'All'. I would suggest doing the following:

$whereSubClause = array();

/* Firstly identify if we have 'All' as the manufacture -
 * if we do, we don't need to add constraints to the query.
 */
if ( 'All' != $manufacturer ){

  $mfg = sqlite_escape_string($manufacturer);
  $whereSubclause[] = "`Manufacturer` = {$mfg}";

}

if ( 'Any' != $model ){

    $model = sqlite_escape_string($model);
    $whereSubclause[] = "`Model` = {$model}";

}

if ( 'Any' != $forsale ){

    $forSale = sqlite_escape_string($forsale);
    $whereSubclause[] = "`ForSale` = {$forSale}";

}

// We can now safely construct the SQL --
// I haven't provided the method for this, but you'd end up with:

$query = "SELECT * FROM `vehicles` WHERE (`Manufacturer` = 'AMG') AND (`Manufacturer` = 'AMG') AND (`ForSale` = '1')"

I would then personally output the data into an array, which can then be passed to a view. Using a foreach loop, I would construct the rows in the table.


Getting the value of a custom attribute from an enum Suppose we have an enum called "Planet" and it has a custom attribute of class "PlanetAttr",
these methods will give you the attribute value for a given Planet value:

private static PlanetAttr GetAttr(Planet p)
{
    return (PlanetAttr)Attribute.GetCustomAttribute(ForValue(p), typeof(PlanetAttr));
}

private static MemberInfo ForValue(Planet p)
{
    return typeof(Planet).GetField(Enum.GetName(typeof(Planet), p));
}

But is this a good way to retrieve the value of a custom attribute from an enum?  I am uncomfortable with the number of method calls involved.  Is there a more efficient way, e.g. can it be done without looking up the enum constant's name?

This code is from a StackOverflow question.

using System;
using System.Reflection;

class PlanetAttr: Attribute
{
    internal PlanetAttr(double mass, double radius)
    {
        this.Mass = mass;
        this.Radius = radius;
    }
    public double Mass { get; private set; }
    public double Radius { get; private set; }
}

public static class Planets
{
    public static double GetSurfaceGravity(this Planet p)
    {
        PlanetAttr attr = GetAttr(p);
        return G * attr.Mass / (attr.Radius * attr.Radius);
    }

    public static double GetSurfaceWeight(this Planet p, double otherMass)
    {
        return otherMass * p.GetSurfaceGravity();
    }

    public const double G = 6.67300E-11;

    private static PlanetAttr GetAttr(Planet p)
    {
        return (PlanetAttr)Attribute.GetCustomAttribute(ForValue(p), typeof(PlanetAttr));
    }

    private static MemberInfo ForValue(Planet p)
    {
        return typeof(Planet).GetField(Enum.GetName(typeof(Planet), p));
    }

}

public enum Planet
{
    [PlanetAttr(3.303e+23, 2.4397e6)]  MERCURY,
    [PlanetAttr(4.869e+24, 6.0518e6)]  VENUS,
    [PlanetAttr(5.976e+24, 6.37814e6)] EARTH,
    [PlanetAttr(6.421e+23, 3.3972e6)]  MARS,
    [PlanetAttr(1.9e+27,   7.1492e7)]  JUPITER,
    [PlanetAttr(5.688e+26, 6.0268e7)]  SATURN,
    [PlanetAttr(8.686e+25, 2.5559e7)]  URANUS,
    [PlanetAttr(1.024e+26, 2.4746e7)]  NEPTUNE,
    [PlanetAttr(1.27e+22,  1.137e6)]   PLUTO
}

Make it general purpose using generics.

Though I'd strongly suggest you rename your attribute to follow .NET guidelines.  It should always be in the form AttributeNameAttribute.  Enum values should be in CamelCase.  And it is common to name classes containing extension methods to be named the same as the class it is extending followed by Extensions.

Otherwise, that's pretty much how you'd get custom attributes of a field.

public static class EnumExtensions
{
    public static TAttribute GetAttribute<TAttribute>(this Enum value)
        where TAttribute : Attribute
    {
        var type = value.GetType();
        var name = Enum.GetName(type, value);
        return type.GetField(name) // I prefer to get attributes this way
            .GetCustomAttributes(false)
            .OfType<TAttribute>()
            .SingleOrDefault();
    }
}

public class PlanetInfoAttribute : Attribute
{
    internal PlanetInfoAttribute(double mass, double radius)
    {
        this.Mass = mass;
        this.Radius = radius;
    }
    public double Mass { get; private set; }
    public double Radius { get; private set; }
}

public enum Planet
{
    [PlanetInfo(3.303e+23, 2.43970e6)]  Mecury,
    [PlanetInfo(4.869e+24, 6.05180e6)]  Venus,
    [PlanetInfo(5.976e+24, 6.37814e6)]  Earth,
    [PlanetInfo(6.421e+23, 3.39720e6)]  Mars,
    [PlanetInfo(1.900e+27, 7.14920e7)]  Jupiter,
    [PlanetInfo(5.688e+26, 6.02680e7)]  Saturn,
    [PlanetInfo(8.686e+25, 2.55590e7)]  Uranus,
    [PlanetInfo(1.024e+26, 2.47460e7)]  Neptune,
    [PlanetInfo(1.270e+22, 1.13700e6)]  Pluto,
}

public static class PlanetExtensions
{
    public static double GetSurfaceGravity(this Planet p)
    {
        var attr = p.GetAttribute<PlanetInfoAttribute>();
        return G * attr.Mass / (attr.Radius * attr.Radius);
    }

    public static double GetSurfaceWeight(this Planet p, double otherMass)
    {
        return otherMass * p.GetSurfaceGravity();
    }

    public const double G = 6.67300E-11;
}

It should be pointed out that there are methods to retrieve custom attributes in the framework now as of .Net 4.5. See the CustomAttributeExtensions class. This should simplify the extension method a bit. It might be worth changing the name of the extension to GetCustomAttribute() as well since it will always be a custom attribute.

public static class EnumExtensions
{
    public static TAttribute GetAttribute<TAttribute>(this Enum value)
        where TAttribute : Attribute
    {
        var type = value.GetType();
        var name = Enum.GetName(type, value);
        return type.GetField(name) // I prefer to get attributes this way
            .GetCustomAttribute<TAttribute>();
    }
}


Calculating quiz score, with weights and partial credit There is a quiz-game with simple rules. You have to guess one of three options. Each option has a particular weight, for example:

Option 1: 20 points
Option 2: 30 points
Option 3: 50 points

If player guesses the right option, he gets all amount of points. If not, he gets a part of those points:

 User choice || Right Answer || Score
      1             1            100%
      2             1            75%
      3             1            50%
      1             2            75%
      2             2            100%
      3             2            75%
      1             3            25%
      2             3            50%
      3             3            100%

You can easilly write a method to calculate score:

calcRateScore: function(fact, user) {

    var rateScore = 0;

    switch (fact) {
        case 1:
            switch (user) {
                case 1:
                    rateScore = 20;
                    break;
                case 2:
                    rateScore = 20 * 0.75;
                    break;
                case 3:
                    rateScore = 20 * 0.5;
                    break;
            }
            break;
        case 2:
            switch (user) {
                case 1:
                    rateScore = 30 * 0.75;
                    break;
                case 2:
                    rateScore = 30;
                    break;
                case 3:
                    rateScore = 30 * 0.75;
                    break;
            }
            break;
        case 3:
            switch (user) {
                case 1:
                    rateScore = 50 * 0.25;
                    break;
                case 2:
                    rateScore = 50 * 0.5;
                    break;
                case 3:
                    rateScore = 50;
                    break;
            }
            break;
    }

    return rateScore;
}

It works, but it looks horrible. How do I get rid of all this switch statements?

You don't seem to have any concept of objects or other reusable code in what you have written.  I would take a step back and think about what real-word objects you are trying to model.  At a minimum, I would think you would need three different concepts:

Answer Option: a single answer option that will be related to the question and hold logic on it fractional value as an answer.
Question: which stores a related set of answers and provides logic on calculating score for the question.
Quiz: which represents an ordered collection of questions.

Let me start by modeling the objects noted above:

// let's build a question class
function Question(text, baseScore) {
   this.text = null;
   this.answerOptions = [];
   this.selectedAnswerIndex = null;
   this.baseScore = null;

   this.setText(text);
   this.setBaseScore(baseScore);
}

// add methods to question class
Question.prototype = {
    setText: function(text) {
        this.text = text;

        // return the question object to allow for chaining
        return this;
    },
    setBaseScore: function(score) {
        this.baseScore = score;

        return this;
    },
    addAnswerOption: function(answer) {
        if(!answer instanceof Answer) {
            console.log('Give me an answer object!');
            return null;
        }
        this.answerOptions.push(answer);

        return this;
    }
    setAnswerIndex: function(idx) {
        this.selectedAnswerIndex = idx;

        return this;
    },
    getScore: function() {
        if(this.selectedAnswerIndex === null || this.baseScore === null) {
            return null;
        }
        var ansIdx = this.selectedAnswerIndex;
        var scoreModifier = this.answerOptions[ansIdx].questionScoreModifier;
        if(scoreModifier === null) {
            return null;
        }

        return this.baseScore * scoreModifier;
    }
};

// build answer class
function Answer(text, modifier) {
    this.text = null;
    this.questionScoreModifier = null;

    this.setText(text);
    this.setScoreModifier(modifier);
};

// answer class methods
Answer.prototype = {
    setText: function(text) {
        this.text = text;

        return this;
    },
    setScoreModifier(value) {
        this.questionScoreModifier = value;

        return this;
    }
};

// build quiz class
function Quiz(title) {
    this.title = null;
    this.questions = [];
    this.score = null;

    this.setTitle(title);
}

// quiz class methods
Quiz.prototype = {
    setTitle: function(text) {
        this.title = text;

        return this;
    },
    addQuestion: function(question) {
        if(question instanceof Question) {
            console.log('Give me a Question object!');
            return null;
        }
        this.questions.push(question);

        return this;
    },
    answerQuestion: function(questionIndex, answerIndex) {
        this.questions[questionIndex].setAnswerIndex(answerIndex);

        return this;
    },
    getTotalScore: function() {
        var total = 0;
        for(i=0; i<this.questions.length; i++) {
            var questionScore = this.questions[i].getScore();
            if (questionScore !== null) {
                total +== questionScore;
            }
        }
        this.score = total;

        return total;
    }
}

You now have the basic building blocks to create your quiz. You could include this code anywhere and have a reusable quiz.

Now you need to build the quiz itself.  That may look like this:

// build your quiz
var myQuiz = new Quiz('My cool quiz');

// now let build some questions
var question1 = new Question(
    'This is text of question 1. What is correct answer?',
    50
);

// now attach answers to the question
question1
    .addAnswerOption(new Answer('Answer worth 50%', .5))
    .addAnswerOption(new Answer('Answer worth 100%', 1))
    .addAnswerOption(new Answer('Answer worth 25%', .25));

// add the question to the quiz
myQuiz.addQuestion(question1);

// you could continue code like above to fill out your quiz

Finally, we can start working with the quiz to set answers and get scores.

// now let's set a user answer on a question
// we can assume that we get both the question index
// and the answer index for the question from elsewhere in javascript
// for example from clicking on answer selection
var questionIdx = {some value};
var answerIdx = {some value};

// set the answer
myQuiz.answerQuestion(questionIdx, answerIdx);

// we can also get total quiz score
var totalQuizScore = myQuiz.getTotalScore();

// or we can get scores on individual questions
var question1Score = myQuiz.questions[0].getScore();

Note that the outcome here is very reusable code that could be pretty much dropped anywhere within a larger application to implement your quiz.  In a real application you may also add something like a quiz rendering class to be able to render the quiz using javascript (and to separate display of quiz from core quiz objects).

It also makes it much easier to modify your code in the future. You need to change how questions are scored? - well just change the scoring logic within the answer and question classes as implemented in those class properties and methods.  As long as you keep the contract (i.e method calls) with the quiz, the quiz class itself would likely not need to be modified.


BDD in PHP, Testing search in Wikipedia with Behat and Mink (Selenium2 Driver) I am trying to learn BDD in PHP with Behat and Mink and I am using Selenium2 driver for the same.

The scenario is given on this page and is as follows:

Feature: Search
    In order to see a word definition
    As a website user
    I need to be able to search for a word

    Scenario: Searching for a page that does exist
        Given I am on "/wiki/Main_Page"
        When I fill in "search" with "Behavior Driven Development"
        And I press "searchButton"
        Then I should see "Behavior-driven development"

    Scenario: Searching for a page that does NOT exist
        Given I am on "/wiki/Main_Page"
        When I fill in "search" with "Glory Driven Development"
        And I press "searchButton"
        Then I should see "Search results"

The file behat.yml is as follows:

default:
    extensions:
        Behat\MinkExtension:
            base_url: http://en.wikipedia.org/
            goutte: ~
            selenium2: ~

I have written the below code for FeatureContext.php that I am sure needs improvements. Can anyone suggest me the points for the same?

<?php

use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;

/**
* Defines application features from the specific context.
*/
class FeatureContext implements Context, SnippetAcceptingContext
{
    /**
    * Initializes context.
    *
    * Every scenario gets its own context instance.
    * You can also pass arbitrary arguments to the
    * context constructor through behat.yml.
    */
    public function __construct()
    {

        $this->driver = new \Behat\Mink\Driver\Selenium2Driver('firefox');
        $this->session = new \Behat\Mink\Session($this->driver);
        $this->session->start();
    }

    /**
    * @Given I am on :url
    */
    public function iAmOn($url)
    {
        $this->session->visit('http://en.wikipedia.org'.$url);
    }

    /**
    * @When I fill in :field with :text
    */
    public function iFillInWith($field, $text)
    {
        $this
            ->session
            ->getPage()
            ->find('css', '[type=' . $field . ']')
            ->setValue($text);
    }

    /**
    * @When I press :button
    */
    public function iPress($button)
    {
        $this
            ->session
            ->getPage()
            ->find('css', '[id=' . $button . ']')
            ->press();
    }

    /**
    * @Then I should see :text
    */
    public function iShouldSee($text)
    {
        $title = $this
            ->session
            ->getPage()
            ->find('css', 'h1')
            ->getText();

        if ($title !== $text) {
            new Exception('Invalid page');
        }
    }

    /**
    * @AfterScenario
    */
    public function tearDown()
    {
        $this->session->stop();
    }
}

There is one major point that we can do here. In the FeatureContext.php, if class FeatureContext extends MinkContext, then you do not need to write any of the function definitions at all!

Applying what I just said, will result to have FeatureContext.php to be as:

<?php

use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use Behat\MinkExtension\Context\MinkContext; //This line is add

class FeatureContext extends MinkContext // This line is changed
    implements Context, SnippetAcceptingContext
{
    public function __construct()
    {
    }
}

Note: To make the point more clear, I have removed the comments that are generated by behat.


Dice throwing simulation in Java For one of my labs I need to write a complete java program which will simulate a "very simple" dice betting game. The specifications are as follows: simulate the throw of 3 dice. If you throw three sixes then you win $20; if you throw three of any other value then you win $10; if you throw two dice which are the same value then you win $5. If none of the conditions above are met, then you would lose $1.
Example Runs: Dice Throw
Dice 1 : 2     Dice 2 : 1    Dice 3 : 2
Congratulations : You threw TWO - 2s
You win $5

Dice 1 : 2    Dice 2 : 2    Dice 3 : 2
Congratulations : You threw THREE - 2s
You win $10

Dice 1 : 4    Dice 2 : 6    Dice 3 : 3
Unfortunately : You did not throw anything of value
You lose $1

The resulting code that I wrote to solve this problem is as follows:
/**
 * SRN: 507-147-9
 */
public class Lab6_part3 {

    public static void main(String[] args) {

        // define vars
        int round = 1;
        int dice1, dice2, dice3;

        while (round <= 3) {

            dice1 = 1 + (int)(Math.random() * 6);
            dice2 = 1 + (int)(Math.random() * 6);
            dice3 = 1 + (int)(Math.random() * 6);

            System.out.println();
            System.out.println("Dice 1 : " + dice1 + "    Dice 2 : " + dice2 + "    Dice 3 : " + dice3);

            // Three of a kind
            if ((dice1 == dice2) && (dice1 == dice3)) { // 3-of-a-kind (D1)

                // Rolls three sixes
                if (dice1 == 6) {
                    System.out.println("Congratulations : You threw THREE - 6s");
                    System.out.println("You win $20");
                } else {
                    // Rolls three of anything else
                    System.out.println("Congratulations : You threw THREE - " + dice1 + "s");
                    System.out.println("You win $10");
                }
            }

            // Two of a kind (PRINT "dice1")
            else if (dice1 == dice2 || dice1 == dice3) {
                System.out.println("Congratulations : You threw TWO - " + dice1 + "s");
                System.out.println("You win $5");
            }

            // Two of a kind (PRINT "dice2")
            else if (dice2 == dice1 || dice2 == dice3) {
                System.out.println("Congratulations : You threw TWO - " + dice2 + "s");
                System.out.println("You win $5");
            }

            // Two of a kind (PRINT "dice3")
            else if (dice3 == dice1 || dice3 == dice2) {
                System.out.println("Congratulations : You threw TWO - " + dice3 + "s");
                System.out.println("You win $5");
            }
            // Did not throw anything of value
            else {
                System.out.println("Unfortunately : You did not throw anything of value");
                System.out.println("You lose $1");
            }
            round++;
        }
    }
}

The problem that I'm running into with this approach is that although the code functions as it's supposed to, I would like to have a simpler way to write the two-of-a-kind instead of having three "if" statements.
My goal in this, is to create a three-way "or" statement instead of comparing dice1 with dice 2 and 3, and dice 2 with dice 1 and 3, etc...
else if (dice1 == dice2 || dice1 == dice3 || dice2 == dice3) {
    System.out.println("Congratulations : You threw TWO - " + somethings?? + "s");
    System.out.println("You win $5");

If I were to do that, how would I then be able to print out the value of the pair which I've identified?

Welcome to CodeReview. Regarding your issue, a quick solution is:
else if (dice1 == dice2 || dice1 == dice3 || dice2 == dice3) {
    int doubleNum = dice1 == dice2 ? dice1 : dice1 == dice3 ? dice1 : dice3;
    System.out.println("Congratulations : You threw TWO - " + doubleNum + "s");
    System.out.println("You win $5");
}

The ternary operator makes the code more compact, but in this case I think it's a bit less readable than a chain of if-else.
Few other suggestions:

The while-loop can be replaced by a more convenient for-loop. From:
int round = 1;
while(round<=3){
    //...
    round++;
}

To:
for(int round = 1; round <= 3; round++) {
    //...
}

Declaring multiple variables in one line int dice1, dice2, dice3; is not considered good practice in Java.
Instead of generating a random float and then casting it to an int, generate directly an int with ThreadLocalRandom.current().nextInt(6). Docs.
You can print the first line with System.out.format. From:
System.out.println();
System.out.println("Dice 1 : " + dice1 + "    Dice 2 : " + dice2 + "    Dice 3 : " + dice3);

To:
System.out.format("%nDice 1 :  %d    Dice 2 : %d    Dice 3 : %n", dice1, dice2, dice3)

Class names should be PascalCase. Instead of Lab6_part3 you can name it Lab6Part3.
Declare a constant for the number of rounds, to make it easier to change. For example:
public class Lab6Part3 {

    private static final int ROUNDS = 3;

    public static void main(String[] args) {
        for(int round = 1; round <= ROUNDS; round++) {
            //...
        }
}

Another approach is to generate three numbers with Random#ints and calculate the frequencies:
Random r = new Random();
// Generate three random numbers from 1 to 6
IntStream diceRolls = r.ints(3, 1, 7);

// Generate map of frequencies
Map<Integer, Long> freq = diceRolls.boxed()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

boolean winner = false;
for (Entry<Integer, Long> entry : freq.entrySet()) {
    int number = entry.getKey();
    long times = entry.getValue();
    if (times == 3) {
        // Three of a kind ...
        winner = true;
    } else if (times == 2) {
        // Two of a kind...
        System.out.println("Congratulations : You threw TWO - " + number + "s");
        System.out.println("You win $5");
        winner = true;
    }
}
if(!winner) {
    // Did not throw anything of value
}


Color thresholding function I wrote an adaptive color thresholding function in Python (because OpenCV's cv2.adaptiveThreshold didn't fit my needs) and it is way too slow. I've made it as efficient as I can, but it still takes almost 500 ms on a 1280x720 image. I would greatly appreciate any suggestions that will make this function more efficient!

Here's what the function does:

It uses a cross-shape of one-pixel thickness as the structuring element. For each pixel in the image, it computes the average values of ksize adjacent pixels in four directions independently (i.e. the average of ksize pixels in the same row to the left, in the same column above, in the same row to the right, and in the same column below). I end with four average values, one for each direction. A pixel only meets the threshold criterion if it is brighter than either both the left AND right averages or both the top AND bottom averages (plus some constant C).

I compute those averages incrementally for all pixels at the same time using numpy.roll(), but I still need to do this ksize times. The ksize will usually be 20-50.

Here is the code, the relevant part is really just what happens inside the for-loop:

def bilateral_adaptive_threshold(img, ksize=20, C=0, mode='floor', true_value=255, false_value=0):

    mask = np.full(img.shape, false_value, dtype=np.int16)

    left_thresh = np.zeros_like(img, dtype=np.float32) #Store the right-side average of each pixel here
    right_thresh = np.zeros_like(img, dtype=np.float32) #Store the left-side average of each pixel here
    up_thresh = np.zeros_like(img, dtype=np.float32) #Store the top-side average of each pixel here
    down_thresh = np.zeros_like(img, dtype=np.float32) #Store the bottom-side average of each pixel here

    for i in range(1, ksize+1):
        roll_left = np.roll(img, -i, axis=1)
        roll_right = np.roll(img, i, axis=1)
        roll_up = np.roll(img, -i, axis=0)
        roll_down = np.roll(img, i, axis=0)

        roll_left[:,-i:] = 0
        roll_right[:,:i] = 0
        roll_up[-i:,:] = 0
        roll_down[:i,:] = 0

        left_thresh += roll_right
        right_thresh += roll_left
        up_thresh += roll_down
        down_thresh += roll_up

    left_thresh /= ksize
    right_thresh /= ksize
    up_thresh /= ksize
    down_thresh /= ksize

    if mode == 'floor':
        mask[((img > left_thresh+C) & (img > right_thresh+C)) | ((img > up_thresh+C) & (img > down_thresh+C))] = true_value
    elif mode == 'ceil':
        mask[((img < left_thresh-C) & (img < right_thresh-C)) | ((img < up_thresh-C) & (img < down_thresh-C))] = true_value
    else: raise ValueError("Unexpected mode value. Expected value is 'floor' or 'ceil'.")

    return mask

I found a solution using cv2.filter2D that cuts the time to 25% of the original time:

def bilateral_adaptive_threshold_f2d(img, ksize=30, C=0, mode='floor', true_value=255, false_value=0):

    mask = np.full(img.shape, false_value, dtype=np.int16)

    left_thresh = cv2.filter2D(img, ddepth=cv2.CV_32F, kernel=np.ones((1,ksize+1)), anchor=(ksize,0), delta=0, borderType=cv2.BORDER_CONSTANT)
    right_thresh = cv2.filter2D(img, ddepth=cv2.CV_32F, kernel=np.ones((1,ksize+1)), anchor=(0,0), delta=0, borderType=cv2.BORDER_CONSTANT)
    up_thresh = cv2.filter2D(img, ddepth=cv2.CV_32F, kernel=np.ones((ksize+1,1)), anchor=(0,ksize), delta=0, borderType=cv2.BORDER_CONSTANT)
    down_thresh = cv2.filter2D(img, ddepth=cv2.CV_32F, kernel=np.ones((ksize+1,1)), anchor=(0,0), delta=0, borderType=cv2.BORDER_CONSTANT)

    left_thresh /= ksize
    right_thresh /= ksize
    up_thresh /= ksize
    down_thresh /= ksize

    if mode == 'floor':
        mask[((img > left_thresh+C) & (img > right_thresh+C)) | ((img > up_thresh+C) & (img > down_thresh+C))] = true_value
    elif mode == 'ceil':
        mask[((img < left_thresh-C) & (img < right_thresh-C)) | ((img < up_thresh-C) & (img < down_thresh-C))] = true_value
    else: raise ValueError("Unexpected mode value. Expected value is 'floor' or 'ceil'.")

    return mask

Also, see the amazing response to this post for more details:
https://stackoverflow.com/questions/42540173/python-how-to-make-this-color-thresholding-function-more-efficient


CodeWars: Gap in Primes I wrote JavaScript code for finding the first two consecutive prime numbers (that doesn't have divisors except one and itself) with a specific gap between them. It works well but take too much time to give results for large numbers.

When I tested this, it took about 48s to give the result:

  gap = 8 ,start = 3,000,000 and end = 4,000,000

I read about how to cache to minimize access for properties as length and put variables in local scope to make the code more efficient, but it didn't help me a lot. I then tried to optimize the for loops, but it affects the functionality of the code.

Link to challenge

function gap(gap, start, end){
 var arr = [];
 var counter = [];
 var result;
 for(var x = start; x <= end; x++){
  if(x % 2 == 1){
   arr.push(x)
  }
 }
 for(var cache = arr.length, j = cache ; j >= 0; j--){
  for(var i = 2; i <= Math.sqrt(arr[j]); i++){
   if(arr[j] % i === 0){
    if(i != arr[j]/i || i * i == arr[j]){
      counter.push(arr[j] / i)
      arr.splice(j, 1)
      break;
    }
   }
  }

  if((arr[j+1] - arr[j]) == gap){
   result = [arr[j], arr[j+1]]
  }else if (result == undefined){
   result = null
  }
 }

 return result
}

In order of significance for performance

Don't use array to store prime numbers. You only need one previous
prime to remember. And even if you ever do this, don't remove
elements from its middle, as shifting array contents is very costly.
Store number from expensive Math.sqrt(), don't re-calculate it every iteration. Basically, this is rule for every loop - precalculate limits if possible.
There is only one even prime number: 2. It gives you great opportunities to quickly remove some edge cases:
If gap is odd, only 2 can be a first number. This condition is worth checking at the very start of your function
If number is greater than 2, it can be prime only if it is odd. This allows you to skip half of testing numbers by increasing counter by 2 each iteration, not just ++
Prime testing can be further improved by using 6k ± 1 pattern. It saves you one extra check every 3 odd numbers
You are testing prime numbers in loop. Create a function for this, isPrime or something

function gap(gap, start, end) {
  //cut off odd gaps
  //bitwise AND can test least significant bit
  //odd numbers have 1, even have 0
  if (gap & 1) { //is it odd?
    if (start > 2 || end < gap + 2) return null; //check if 2 is in range
    return isPrime(gap + 2) ? [2, gap + 2] : null; //check additionally the other part
  }
  var previous = null; //no initial value
  //loop over odd numbers to check for primes
  for (var current = start | 1; //set last bit to 1: /odd numbers stay same, even numbers become next odd
       current <= end;
       current += 2 // skip any even number
      ) {
    if (isPrime(current)) {
      if (current - previous === gap) //is it a match?
        return [previous, current];
      //no need for "else" here as the other branch has "return"
      previous = current; // anyway, save it
    }
  }

  return null; //no early return from loop = nothing matches

  /**
    Tests if n is prime
  */
  function isPrime(n) {
    if (n <= 6) //cut away small primes explicitly
      return n === 2 || n === 3 || n === 5;
    //cut away small divisors (2 and 3) explicitly
    if (n & 1 === 0 || //using bitwise AND for even numbers
        n % 3 === 0) return false;

    var limit = Math.floor(Math.sqrt(n)); //precalculate loop limit
    // loop is checking every divisor using 6k ± 1 pattern
    for (var t = 5; //start with 5, first 6k - 1 number
         t <= limit;
         t += 6 //step by 6
        ) {
      if (n % t === 0 || //6k - 1
          n % (t + 2) === 0) //6k + 1
        return false;
    }
    return true;
  }
}
console.log(""); //this makes console output timestamp
console.log("gap(8,3000000,4000000)", "->", gap(8,3000000,4000000)); // ~5ms
console.log("gap(120,3000000,4000000)", "->", gap(120,3000000,4000000)); // ~600ms

Working fiddle. I submitted it on CodeWars, it passes :)


Least Recently Used Cache Daily Coding Practice I have the following challenge problem for which I was able to get a solution working, but not in \$O(1)\$ time as the problem asks for.  Could someone point me in the right direction to optimize this? I am also open to other criticisms of my coding style.

QUESTION:

  Implement an LRU (Least Recently Used) cache. It should be able to be initialized with a cache size n, and contain the following methods:

  set(key, value): sets key to value. If there are already n items in the cache and we are adding a new item, then it should also remove the least recently used item.
  get(key): gets the value at key. If no such key exists, return null.

  Each operation should run in \$O(1)\$ time.

CODE:

class LRUcache():

    def __init__(self,n):
        self.vals = dict()
        self.max_size = n

    def set(self,key,value):
        if key in self.vals:
            del self.vals[key]
            self.vals[key] = value
        else:
            if(len(self.vals) < self.max_size):
                self.vals[key] = value
            else:
                del self.vals[list(self.vals)[0]]
                self.vals[key] = value

    def get(self,key):
        if key in self.vals:
            tempval = self.vals[key]
            del self.vals[key]
            self.vals[key] = tempval
            return self.vals[key]
        return None

Your code reads very much like you have written some Java and are trying to translate it to Python. You need to "drink the Kool-Aid" and start embracing idiomatic Python, instead.

First, start by noting that storing None as a value is a legitimate thing to do in Python. So the idea of returning None to mean "no key found" is weak. A better approach would be to raise an exception -- probably a KeyError.

However, since it's part of your problem statement, we can ignore that issue (except to note that your problem statement likely came from Java or C++ or someplace like that).

In your set() method:

def set(self,key,value):
    if key in self.vals:
        del self.vals[key]
        self.vals[key] = value
    else:
        if(len(self.vals) < self.max_size):
            self.vals[key] = value
        else:
            del self.vals[list(self.vals)[0]]
            self.vals[key] = value

You can overwrite items in a dictionary directly. Just assign to them:

if key in self.vals:
    self.vals[key] = value

And your missing-key code is redundant. You assign value in both branches of the if/else statement. Just refactor the assignment down:

if len(self.vals) >= self.max_size:
    del self.vals[list(self.vals)[0]]

self.vals[key] = value

Once you do that, you realize that the assignment is also present in the upper (key-found) condition, and you can refactor it again:

def set(self, key, value):
    vals = self.vals
    if key in vals and len(vals) >= self.max_size:
        del vals[list(vals)[0]]
    vals[key] = value

In your get() method:

You are doing things pretty much spot-on, here, but you are depending on dictionaries to preserve insertion order. That is a somewhat new feature in python (added as an implementation detail in 3.6, and guaranteed in 3.7) that won't work in 3.5. You should at least comment this, and probably should add code at the top of your module to verify the version of python.

On the other hand: there is a collections.OrderedDict in the standard library that has been around for a while, and which even includes an example of building an LRU cache in the documentation. Just sayin'. ;-)


Binary search on a uniformly distributed vector I am trying to write a binary search using recursion in C on a sorted vector that we can assume comes from a uniform distribution between the start and end values. What I am trying to write is an algorithm that performs best in expected time. I am having some issue with picking the correct index to 'split' at and while it passes my tests, it feels a bit hacky.

int weighted_binary_split(int *x, int start_limit, int start_idx, int end_idx,
                          int val, int *depth) {
    // For a vector of length `n` with known starting and ending values,
    //     x[start_idx:end_idx+1] = [start, ..., end]
    // searches for `val` in `x`, assuming `x` is uniformly distributed and
    // ordered. Note that we always get the first occurence of `val` in `x`.
    // I say 'best' because it is simply intuition.
    // Note that when initially calling this, we will have
    //     start_limit = start_idx
    // however when we are within the recursion this is no longer the case.
    int n = end_idx - start_idx + 1;
    int start = x[start_idx];
    int end = x[end_idx];
    int out;
    int i;

    // Keep track of how many iterations/depth we have gone in binary search
    // tree.
    *depth += 1;

    // Catch the case where end == start (causing divide by 0 below).
    if (end - start == 0) {
        return start_idx;
    }

    // Catch the case where val == start (can just return start_idx).
    if (val == start) {
        return start_idx;
    }

    // We want to find
    //     (val - start)/((end - start)/n) = n*val/(end - start),
    // rounded to the nearest integer.
    // Note there is no point using
    //     1) idx = start_idx
    //        as if val == x[start_idx] ==> val == start, caught above.
    //     2) idx = start_idx + n = end_idx + 1, too big for vector.
    // Hence we use (n - 1). THIS PART FEELS HACKY.
    int idx = start_idx + ((n-1)*(val - start))/(end - start);
    if (idx == start_idx) {
        idx += 1;
    }

    if (x[idx] > val) {
        // Search again with idx as the new `end_idx`.
        out = weighted_binary_split(x, start_limit, start_idx, idx, val, depth);
    } else if (x[idx] < val) {
        // Search again with idx as the new `start_idx`.
        out = weighted_binary_split(x, start_limit, idx, end_idx, val, depth);
    } else {
        // In this case we have found val in x at x[idx].
        // We finally get the first occurence of `val` in x[start_limit:idx+1].
        for (i=1; i<idx-start_limit+1; i++) {
            if (x[idx - i] != x[idx]) {
                // We have found our first value!
                return idx - i + 1;
            }
        }

        // If we reach this point, then x[start_limit] was the first value.
        return start_limit;
    }

    return out;
}

Below is a test template you can use.

int example_split() {
    // Test that our weighted binary split works correctly.
    int x[10] = {0, 1, 2, 2, 4, 5, 6, 6, 7, 9};
    int start_idx = 0;
    int end_idx = 9;
    int val = 2;
    int idx;
    int i;
    int depth = 0;

    idx = weighted_binary_split(x, start_idx, start_idx, end_idx, val, &depth);
    printf("\nFirst index into:\n\tx = (");
    for (i=0; i<10; i++) {
        printf("%d,", x[i]);
    }
    printf(")");
    printf("\nfor:\n\tval = %d", val);
    printf("\nis\n\tidx = %d", idx);
    printf("\nwith\n\tx[idx]=%d", x[idx]);
    printf("\nat\n\tdepth=%d\n", depth);

    return 0;
}

Bug
Generally code should prevent stack overflows from occurring. The search implemented here causes a stack overflow when the item searched for is not in the array. I tested the code using 8 as the value to search for which caused a recursive stack overflow.

I searched the internet for Weighted Binary Search and couldn't find it, instead I found Weighted Binary Tree.

Wikipedia defines a binary search as "In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. ..."

The search implemented is not a binary search. A binary search always divides the search area by two.

I'm not really sure why there is a for loop in the function weighted_binary_split(), it doesn't comply with a binary search.

Handling Errors
Since the code is keeping track of the depth of the search a possible solution to a stack overflow problem would be to check the value of depth against Log(N) where N is the number of items in the array. A secondary check might be to check the value of depth against N itself because N would be the limit in a linear search.

The function weighted_binary_split() could return -1 in the case of an error or use setjmp(jmp_buf env) and longjmp(jmp_buf env, int value) if negative values are valid in the search.

Always check for possible errors when developing code.

Array Initializations
In the function example_split() the following line:

    int x[10] = { 0, 1, 2, 2, 4, 5, 6, 6, 7, 9 };

would be easier to modify if it was written as:

    int x[] = { 0, 1, 2, 2, 4, 5, 6, 6, 7, 9 };

There is no need to include the size of the array for x because the compiler does it for you.

The size of the array can be calculated:

    int arr_size = (sizeof(x) / sizeof(x[0]));

The variable end_idx can then be calculated as well.

    int end_idx = (sizeof(x) / sizeof(x[0])) - 1;

For Loop Control Variables
In the function example_split() there is no need to create the variable i at the top, it can be created inside the for loop itself:

    for (int i = 0; i < arr_size; i++) {
        printf("%d,", x[i]);
    }

It's generally better to create the variables as they are needed. This is a change from the original version of the C Programming Language that was quite helpful.


Listing all the chars in a given UnicodeBlock I want to visually inspect all the characters that Java thinks are in any given UnicodeBlock. The following method, as far as I can tell, does the task. But, it sure feels like awful design.

public static void displayUnicodeBlock(Character.UnicodeBlock block) {
    int maxCharVal = (int) Math.pow(2, 16);
    for(int cInt = 0; cInt <= maxCharVal; cInt++) {
        char c = (char) cInt;
        if(Character.UnicodeBlock.of(c) == block) {
            System.out.println("_" + c + "_");
        }
    }
}

Would reflection be the ideal solution?
Can reflection actually show every character in a UnicodeBlock? How?
My solution is stupid because it is inefficient?
My solution is stupid because it is hardwired with 2^16?

It is truly unfortunate that Character.UnicodeBlock doesn't have a min() and max().  In fact, the way it is implemented in OpenJDK is as a private static  blockStarts table, which is entirely unhelpful to you.

I don't have a better solution, but rather a complication.  The Java char type only covers the Basic Multilingual Plane.  To be pedantic, you would need to cover even larger codepoints, with Character.UnicodeBlock.of(int)!  (For example, Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B starts at U+20000, which cannot be encoded using a single char, and therefore iterating up to 216 would not find it.)

It appears that existing Unicode blocks have sizes that are multiples of 16, so you could take advantage of that instead of testing every single codepoint.

Code blocks are contiguous.  Therefore, a possible optimization is that once you have found a character that is in the desired block, if you then encounter a character that is not in the block, then you're done.


Python decryption of Caesar Cipher Given this ciphertext from a Caesar cipher:

fxeyaxklqxhkltkxqebobxtbobxplxjykvxfaflqpxfkxqebxtloiaxrkqfixfxpqyoqbaxrpfkdxqebxfkqbokbq

The task is to decrypt it without being given the key.
My solution:
napis = "fxeyaxklqxhkltkxqebobxtbobxplxjykvxfaflqpxfkxqebxtloiaxrkqfixfxpqyoqbaxrpfkdxqebxfkqbokbq".upper()
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
napis = [ALPHABET.index(i) for i in napis]

for x in range(0,4):
    wynik = [ALPHABET[i+x] if i+x<len(ALPHABET) else ALPHABET[i+x-len(ALPHABET)] for i in napis]
    print("".join(wynik))

output:
FXEYAXKLQXHKLTKXQEBOBXTBOBXPLXJYKVXFAFLQPXFKXQEBXTLOIAXRKQFIXFXPQYOQBAXRPFKDXQEBXFKQBOKBQ
GYFZBYLMRYILMULYRFCPCYUCPCYQMYKZLWYGBGMRQYGLYRFCYUMPJBYSLRGJYGYQRZPRCBYSQGLEYRFCYGLRCPLCR
HZG CZMNSZJMNVMZSGDQDZVDQDZRNZL MXZHCHNSRZHMZSGDZVNQKCZTMSHKZHZRS QSDCZTRHMFZSGDZHMSDQMDS
I HAD NOT KNOWN THERE WERE SO MANY IDIOTS IN THE WORLD UNTIL I STARTED USING THE INTERNET

Don't use meaningless names like "napis" and "wynik".
x and i are meaningful in some contexts, but not for what you're using them, so use better names for those as well.
You could take advantage of negative indices, i.e., remove ALPHABET[i+x] if i+x<len(ALPHABET) else  and just use ALPHABET[i+x-len(ALPHABET)]. Or, more generally, ALPHABET[(i+x) % len(ALPHABET)].
You could assume that spaces are the most frequent characters and do x = ALPHABET.index(' ') - max(napis, key=napis.count) instead of the loop.


Function that enables fields based on checkbox state I have simple code that just has to check if a checkbox is checked and if so enable some fields that, by default, should be disabled.

I have written the next code which I know can be severely improved. Could anyone tell me how? I tried getting the siblings of the checkbox also but that just caused some trouble.

$(function(){
$('#amount').attr('disabled','disabled');
            $('#period').attr('disabled','disabled');
            $('#key').attr('disabled','disabled');
            $('#api').change(function(){
                if($('#apiEnabled').is(':checked')){
                    $('#amount').attr('disabled','');
                    $('#period').attr('disabled','');
                    $('#key').attr('disabled','');
                }else{
                    $('#amount').attr('disabled','disabled');
                    $('#period').attr('disabled','disabled');
                    $('#key').attr('disabled','disabled');
                }
            });
});

It's difficult to answer accurately without seeing your markup, but maybe you can use a multiple selector to alleviate code redundancy. You can also use prop() to enable or disable your elements more easily:

$(function() {
    var $elements = $("#amount, #period, #key");
    $elements.prop("disabled", true);
    $("#api").change(function() {
        $elements.prop("disabled", !$("#apiEnabled").is(":checked"));
    });
});


TypeScript definitions for Server-Sent Events I could not find any definitions of the EventSource object that belongs to Server-Sent Events, so I create the definitions. That's how they look like:

declare var EventSource : sse.IEventSourceStatic;

declare module sse {

    enum ReadyState {CONNECTING = 0, OPEN = 1, CLOSED = 2}

    interface IEventSourceStatic extends EventTarget {
        new (url: string, eventSourceInitDict?: IEventSourceInit);
        url: string;
        withCredentials: boolean;
        CONNECTING: ReadyState; // constant, always 0
        OPEN: ReadyState; // constant, always 1
        CLOSED: ReadyState; // constant, always 2
        readyState: ReadyState;
        onopen: Function;
        onmessage: (event: IOnMessageEvent) => void;
        onerror: Function;
        close: () => void;
    }

    interface IEventSourceInit {
        withCredentials?: boolean;
    }

    interface IOnMessageEvent {
        data: string;
    }
}

Also available on GitHub.

I am new to TypeScript so I wonder if this definition is OK with common best practices and whether it could be improved.

According to your definition file, I'm assuming there's a global class called EventSource

If that's the case, I have the following improvements:

Avoid Function (or Object or Array), describe the signature accurately (like you did with onmessage). If you don't know the return type or the argument, apply any liberally. At least you're explicit about not knowing.
TypeScript has literal string, number and enum types, so you could do something like CONNECTING: ReadyState.CONNECTING

All in all, it's a fine definition file.


Function that produces \$a^nb^nc^n\$ I'm trying to write a function that produces an infinite list containing strings of the form \$a^nb^nc^n\$.

My first idea was to do it using comprehensions.

f = [replicate n 'a' ++ replicate n 'b' ++ replicate n 'c' | n <-[0..]]

But this does a lot of duplicate work. I then decided it would be better to do the following

import Data.List

f = "" : (abc "")

abc s = string : (abc string)
        where string = sort $ "abc" ++ s

How can I do this more efficiently without having to sort and use ++ as frequently? Would changing to ByteStrings help?

Your first solution could be more elegantly written as:

f :: [String]
f = [concatMap (replicate n) "abc" | n <- [0..]]

The basic operating principle would be the same, though.

A general sorting algorithm would be O(n log n) at best, so I don't believe that sort would be a good idea.


Golang - Splitting a string by a separator not prefixed by an escape string I need to split a string by a separator but don't want to split if the separator is prefixed by the escape string.
For example:
"This works\\ but it\\ isn't pretty." with " " as the separator and "\\" as the escape string should produce the following: []string{"This", "works but", "it isn't", "pretty."}
I wrote the following code for it:
func SplitWithEscaping(s string, separator string, escapeString string) []string {
    untreated := strings.Split(s, separator)
    toReturn := make([]string, 0, len(untreated))
    for i := 0; i < len(untreated); i++ {
        next, ii := t(untreated, i, separator, escapeString)
        i = ii - 1
        toReturn = append(toReturn, strings.ReplaceAll(next, escapeString+separator, separator))
    }
    return toReturn
}

func t(stringSlice []string, i int, seperator, escapeString string) (string, int) {
    if !strings.HasSuffix(stringSlice[i], escapeString) {
        return stringSlice[i], i + 1
    }
    next, ii := t(stringSlice, i+1, seperator, escapeString)
    return stringSlice[i] + seperator + next, ii
}

This is the playground link for my working code: https://play.golang.org/p/jfHFt9_vtE7
How can I make my code prettier but also more performant?

One approach that's simple, but is a bit of a dirty trick: first replace sequences of escape+separator with a string that's never going to occur in your text (for example a NUL byte "\x00"), then do the split, then do the reverse replace on each token. For example (Go Playground link):
func SplitWithEscaping(s, separator, escape string) []string {
    s = strings.ReplaceAll(s, escape+separator, "\x00")
    tokens := strings.Split(s, separator)
    for i, token := range tokens {
        tokens[i] = strings.ReplaceAll(token, "\x00", separator)
    }
    return tokens
}

Your approach of splitting and then re-joining if the last character was an escape works, but it's a bit tricky, and it does more work than necessary. You may also want to name the t function a bit more meaningfully.
An alternative approach would be more of a tokenizer, where you loop through all the bytes in the string, looking for escape and space. Here's the code for that, but note that I've made the separator and escape a single byte to simplify it -- I'm guessing they will be in most cases anyway (Go Playground link):
func SplitWithEscaping(s string, separator, escape byte) []string {
    var token []byte
    var tokens []string
    for i := 0; i < len(s); i++ {
        if s[i] == separator {
            tokens = append(tokens, string(token))
            token = token[:0]
        } else if s[i] == escape && i+1 < len(s) {
            i++
            token = append(token, s[i])
        } else {
            token = append(token, s[i])
        }
    }
    tokens = append(tokens, string(token))
    return tokens
}

The other approach that came to mind is regexes, but you have to be able to say "match space, but only if it's not preceded by this escape", which I think you can only do with lookbehind expressions like ?<, and Go's regexp package doesn't support those.


Getting the character index of recurring substring I created this function that allows you to declare a string, then multiple instances of a substring. This uses a hash map to keep track of strings that have already been searched for and upon each call of its returning function will give you the next instance of that substring.

I'm wondering if there's a way to do this without crypto. I have the option of applying the strings as a object property but I didn't want to overload memory with those.

I'm not sure if there's a native JavaScript way to do this, either, so I'm open to suggestions of native code or other libraries that achieve this.

var crypto = require('crypto')
var S = require('underscore.string')
var _ = require('lodash')

/** returns a md5 hash of the content */
function getHash (content) {
  var shasum = crypto.createHash('md5')
  return shasum.update(content).digest('hex')
}

function multiIndexOf (s) {
  var map = []
  return function (ss) {
    var hash = getHash(ss)
    var indexes = indexesOf(s, ss)
    var countMap = _.countBy(map)
    var instance = countMap[hash] || 0
    map.push(hash)
    return indexes[instance]
  }
}

function indexesOf (s, ss) {
  var instances = S.count(s, ss)
  return _.chain(instances)
  .range()
  .reduce(function (indexes, instance) {
    var lastIndex = _.last(indexes)
    var start = (typeof lastIndex === 'undefined') ? 0 : lastIndex + ss.length
    var index = s.indexOf(ss, start)
    indexes.push(index)
    return indexes
  }, [])
  .value()
}

var find = multiIndexOf('hello world, hello darling')

console.log(find('hello')) // => 0
console.log(find('hello')) // => 13

I don't believe hashing the key provides any functionality: storing the searched string directly into the map would work.

Your map variable is effectively working as a list of hashed keys, not as an actual key-value mapping. Instead of pushing the keys to the collection, override the existing key if it exists, and set the value to be the last found index.

Utilizing the map this way, your code simplifies immensely, and it no longer relies on third-party libraries:

function multiIndexOf (s) {
  var map = [];
  return function (key) {
    var nextIndex = map[key] + 1;
    map[key] = s.indexOf(key, nextIndex);
    return map[key];
  }
}

var find = multiIndexOf('hello world, hello darling')

// Example usage
console.log(find('hello')) // => 0
console.log(find('hello')) // => 13
console.log(find('hello')) // => -1
console.log(find('hello')) // => 0
console.log(find('hello')) // => 13
console.log(find('el')) // => 1
console.log(find('ell')) // => 1
console.log(find('ell')) // => 14


Simple front end TODO list I have implemented a very basic TODO List with no database or backend support. Though I have coded in C++ and Python before, this is my first HTML and JavaScript code. Please review the code and let me know where it can be improved.

var numericalID = 1
function addNewTask() {
var container = document.getElementById("taskContainer")

var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
var idStr="id:"+numericalID
checkbox.id = idStr
checkbox.addEventListener('change',function() {
    var idSplitArray=this.id.split(':')
    var labelStr="label:"+idSplitArray[1]
    var labelTask=document.getElementById(labelStr)
    //alert(idSplitArray)
    if(this.checked) {
       labelTask.style.setProperty("text-decoration", "line-through");
    } else
    {
       labelTask.style.setProperty("text-decoration","none");
    }})

var label = document.createElement('label')
var labelStr="label:"+numericalID
label.id=labelStr
label.htmlFor = "id";
label.appendChild(document.createTextNode(document.getElementById('taskName').value +"                  "));

var delButton=document.createElement('input')
delButton.type="image"
delButton.src="delButton.png"
delButton.id="del:"+numericalID
delButton.addEventListener('click',function(){
    var idSplitArray=this.id.split(':')
    var checkBoxId="id:"+idSplitArray[1]
    var labelStrId="label:"+idSplitArray[1]
    var delButton="del:"+idSplitArray[1]
    var lineBreakId="line:"+idSplitArray[1]
    console.log(lineBreakId)
    console.log(checkBoxId)
    console.log(labelStrId)
    console.log(delButton)
    document.getElementById(checkBoxId).remove();
    document.getElementById(labelStrId).remove();
    document.getElementById(delButton).remove();
    document.getElementById(lineBreakId).remove();

})

container.appendChild(checkbox);
container.appendChild(label);
container.appendChild(delButton)

var linebreak=document.createElement("br")
linebreakID="line:"+numericalID
linebreak.id=linebreakID
numericalID+=1
container.appendChild(linebreak)
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>To Do</title>

  <form action="">
  Task Name: <input type="text" id="taskName" name="fname">

  <input type="submit"  value="Submit" onclick="addNewTask() ; return false;">

</form>

I have several comments about styling:

check the indentation and fix it. There are some different styles that can be observed but universally lines that are inside a function (or even more generally - a scope) would have one indentation level more than before.
Spacing - be consistent. In one line you have checkbox.value = "value"; with spaces around the equals sign. The next line you have var idStr="id:"+numericalID - no spaces around the equals or the operator. I personally put spaces around each but that's personal preference. You can have spaces only around equals signs, or even only on the right side of equals signs or only around operators, etc. Whatever you pick - be consistent.
Semicolons at the end of the line. In JavaScript, they are not strictly required due to a feature called automatic semicolon insertion (ASI). So, a lot of times you can get away without putting them. Although occasionally, you may find your code doesn't behave as expected. Still, as long as you understand how ASI works, you should be fine. Just pick a style - with or without a semicolon and stick with it. I personally prefer putting them in because I find the ASI rules quite annoying to try and remember every time.
Opening curly brackets - they should be either at the same line as the statement they accompany or the next line. You're pretty consistent with having it on the same line aside from where the else shows up.
Super tiny issue - you don't have linebreakID declared properly. It's missing the var keyword, so the variable is now an implied global. I'm mentioning it here with the style issues because you've been consistent with having var statements, so it seems like a simple typo, rather than a different problem.

Styling is pretty important for readable and understandable code. You can employ a linter like ESLint or JSCS (JavaScript Code Style) where you can define the style you want (indentation using spaces/tabs, spaces around equals signs, etc) and then they will scan your code and report back any style violations. They even have an autofix option that takes care of all the style changes, so you don't have to, for example, manually go and fill in every missing semicolon in the file. Linters are a pretty useful tool.

Other than styles, I'd say the function is quite long. It can be broken down into smaller ones for the sake of readability. This is subjective, I know, but having to scroll to read everything is usually too much. There is no duplicate code but you can still just do something like this:

function createCheckbox() {
  var checkbox = document.createElement('input');
  checkbox.type = "checkbox";
  checkbox.name = "name";
  checkbox.value = "value";

  var idStr = "id:" + numericalID;
  checkbox.id = idStr;

  checkbox.addEventListener('change', function() {
    var idSplitArray = this.id.split(':');
    var labelStr = "label:" + idSplitArray[1];
    var labelTask = document.getElementById(labelStr);

    if (this.checked) {
      labelTask.style.setProperty("text-decoration", "line-through");
    } else {
      labelTask.style.setProperty("text-decoration", "none");
    }
  });

  return checkbox;
}

So you don't have all the boring details about setting up a checkbox around more important code. It's a judgement call how you'd split off the code, though - you might elect to have the event handler defined back in the addNewTask function or even split off into a separate function. Whatever it is, the point is to make the main function shorter by splitting off logical portions of the code. In effect, you get code comments - only instead of //creating checkbox you have checkbox = createCheckbox(). But the latter is also self-documenting and has less of a chance to drift away from the code and become an irrelevant and/or inaccurate comment.

For actual logic improvements - right now, there is string manipulation to determine which HTML ID corresponds to which element ID by employing string splitting and conversely creating complex ID values to accommodate that. That works and it's honestly something even big name libraries out there do. Still, it's possible to do better - you can use data-* attributes in HTML. In short, you can have custom attributes attached to HTML elements. The custom attribute is prefixed with data- and you can define the rest of the name. So, you can add a data-id="1", for example, to all elements that will operate on the element with ID 1. That way, you don't need to do string manipulation to get the correct data out of it, you can directly reference the custom attribute.

And that's most of my advice. I think there are other things, too but I don't consider them that important. I'm honestly quite pleased with this code and my main issue is really formatting inconsistency. I am especially pleased that you create the HTML elements programmatically via document.createElement followed by setting the attributes. That is a very good style and amazing to see in a beginner. I very often see even experienced JS developers opting to just do something like parentElement.innerHTML = '<input type="checkbox" id="id:"' + numericalID +'" /> which can be quite annoying to read and has some potentially disadvantages, some even potential security vulnerabilities.

Overall, I'd applaud this effort, especially from a beginner.