Huffman Coding in C++ I have written this code after studying from Introduction to Algorithm and from GeeksForGeeks. I know there is a lot to improve because I don't know much C++11. Please help me to improve this code.

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>

class HuffmanCodes
{
 struct Node
 {
  char data;
  size_t freq;
  Node* left;
  Node* right;
  Node(char data, size_t freq) : data(data),
                                 freq(freq),
                                 left(nullptr),
                                 right(nullptr)
                                 {}
 ~Node()
 {
   delete left;
   delete right;
 }
 };

 struct compare
 {
  bool operator()(Node* l, Node* r)
  {
    return (l->freq > r->freq);
  }
};

Node* top;

void printCode(Node* root, std::string str)
{
  if(root == nullptr)
   return;

 if(root->data == '$')
 {
  printCode(root->left, str + "0");
  printCode(root->right, str + "1");
 }

 if(root->data != '$')
 {
   std::cout << root->data << " : " << str << "\n";
   printCode(root->left, str + "0");
   printCode(root->right, str + "1");
 }
}

public:
  HuffmanCodes() {};
  ~HuffmanCodes()
  {
    delete top;
  }
  void GenerateCode(std::vector<char>& data, std::vector<size_t>& freq, size_t size)
  {
   Node* left;
   Node* right;
   std::priority_queue<Node*, std::vector<Node*>, compare > minHeap;

   for(size_t i = 0; i < size; ++i)
   {
      minHeap.push(new Node(data[i], freq[i]));
   }

    while(minHeap.size() != 1)
    {
      left = minHeap.top();
      minHeap.pop();

      right = minHeap.top();
      minHeap.pop();

      top = new Node('$', left->freq + right->freq);
      top->left  = left;
      top->right = right;
      minHeap.push(top);
     }
    printCode(minHeap.top(), "");
 }
};

 int main()
 {
  HuffmanCodes set1;
  std::vector<char> data({'d', 'e', 'b', 'c', 'a', 'f'});
  std::vector<size_t> freq({16, 9, 13, 12, 45, 5});
  size_t size = data.size();
  set1.GenerateCode(data, freq, size);

  return 0;
}

When you declare a class, initialize all member variables

char data = '\0';
size_t freq = 0;
...

(depending on your compiler you may need to do that in the
constructor instead)

especially pointers, since a delete on an uninitialized pointer is undefined behavior but a delete on a nullptr is OK (NOP).

void GenerateCode(std::vector<char>& data, std::vector<size_t>& freq, size_t size)

is your intention to modify 'data'? if not, then write const in front

void GenerateCode(const std::vector<char>& data, std::vector<size_t>& freq)

why do you pass 'size'? 'data' already has a size: data.size()

you have an unitialized member variable called 'top', you use it in GenerateCode and it
will be set there, but if you never call GenerateCode, just a simple class declaration will
invoke undefined behavior since delete top is called in HuffManCodes destructor.

memory ownership is not easy to follow in your code

avoid using raw pointers. By using smart pointers ownership is always
clear and you dont need to bother about where to delete.

struct Node
{
    std::unique_ptr<Node> left;
    std::unique_ptr<Node> right;  // here it's clear that 'right' owns what it points to
    ...
}


Codechef Deforestation problem: Finding maximum rope length between trees Here is the CodeChef page to the problem.  Given N trees, each at x-position x with height T, string a rope between two trees Ti and Tj such that:

A rope connecting the tops of the trees is at 45 degrees from the x-axis
The rope does not pass through any other trees
The length of the rope, minus the total height reduction by cutting trees, is maximized
Trees Ti and Tj themselves are not cut

Here is my code that need to process 100 × 250,000 data in less than 3 seconds (I don't know the exact spec of the running machine).  As I'm quite new to coding, what can I improve or change to make it faster, and more optimized?

// codechef_deforestation.cpp : définit le point d'entrée pour l'application console.
//

#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <ctime>

int main()
{
    clock_t startTime = clock();
    //Read input
    freopen("C:\\somepath\\input.in", "r", stdin);
    freopen("C:\\somepath\\output.out", "w", stdout);
    int t;
    std::cin >> t;
    //std::cout << t << std::endl;
    for (int i = 0; i < t; i++)
    {
        double result = -1;
        int n;
        std::cin >> n;
        //std::cout << t << std::endl;
        std::vector <int> x, h;
        x.resize(n);
        h.resize(n);
        //chargement des données
        for (int j = 0; j < n; j++)
        {
            std::cin >> x[j] >> h[j];
            //std::cout << x[j] << h[j] << std::endl;
        }
        //calcul
        for (int j = 0; j < n; j++)
        {
            for (int k = j+1; k < n; k++)
            {
                //std::cout << "k : " << k << std::endl;
                int diff_x = x[k] - x[j];
                int diff_h = h[k] - h[j];
                if (diff_x == diff_h) //si 45 deg
                {
                    double res_int = sqrt(diff_x*diff_x + diff_h* diff_h);
                    for (int l = j + 1; l < k; l++)
                    {
                        //std::cout << "l : " << l << std::endl;
                        if (h[l] > x[l])
                        {
                            res_int = res_int - (h[l] - x[l]);
                        }
                    }
                    if (res_int > result)
                    {
                        result = res_int;
                    }
                }
            }
        }
        std::cout << std::setprecision(6) << std::fixed << result << std::endl;
        x.clear();
        h.clear();
    }
    clock_t testTime=clock();
    std::cout << testTime - startTime;
    return 0;
}

The freopen() function needs to stay.

There appears to be a bug in your program. In particular, I think this line is wrong:

if (h[l] > x[l])

Starting from location j, the question is not whether h[l] > x[l] but whether h[l] - h[j] > x[l] - x[j]. The 45 degree angle will be relative to the start-point of the line, not the origin, I think.

That said, your loop over l is duplicating the results of looping over k. I think you could profit by keeping a running total of lossage during your k loop, and just adding it in when appropriate.

Viz:

for (j...)
    auto hj = h[j], xj = x[j];

    for (k...)
        auto dx = x[k] - xj;
        auto dh = h[k] - hj;

        auto over_height = dh - dx;

        if (over_height > 0) deforestation += over_height;

        if (over_height == 0) {
            // this k is a candidate
            rope_len = sqrt(...) - deforestation;

        }


Cleaning sensitive information returned from a REST API I am working with an API of coupons from sites like Groupon. There are 2 fields in the JSON response (url and imgUrl) that return a url which directs them to the actual coupon and a picture of the business, respectively. Problem is that they contain sensitive information (my API KEY).
Below is my service (using spring boot) which "cleans" the API key from the urls before servicing them to the client:
@Service
public class SanitationService {

public List<Deal> cleanApiKeys(List<Deal> deals) {
    List<Deal> cleanList = new ArrayList<>();
    deals.forEach(item -> {
        //Catching "dirty" URLs containing API keys
        List<String> dirtyUrls = Arrays.asList(item.getUrl(), item.getImageUrl()); //maybe map?
        List<String> cleanUrls = cleanUrls(dirtyUrls);
        cleanList.add(cleanDeal(item ,cleanUrls));
    });
    return cleanList;
}
public Deal cleanDeal(Deal deal, List<String> cleanUrls) {
    deal.setUrl(cleanUrls.get(0));
    deal.setImageUrl(cleanUrls.get(1));
    return deal;
}
public List<String> cleanUrls(List<String> urls) {
    return urls.stream()
            .map(url -> url =  url.split("\\?")[0])
            .collect(Collectors.toList());
}
//Helper method for other services to extract a list of Deal from the DealWrapper JSON
public List<Deal> dealUnwrap(List<DealWrapper> dealWrappers) {
    return dealWrappers.stream()
            .map(DealWrapper::getDeal)
            .collect(Collectors.toList());
}

}
Here is the code I use to test the service (still figuring out how to mock a list of Deal)
@SpringBootTest
class SanitationServiceTest {
@Autowired
private SanitationService service;

@Test
void cleanUrls() {
    List<String> dirtyUrls = Arrays.asList("https://api.discountapi.com/v2/deals/1988753/click?api_key=secret",
            "https://api.discountapi.com/v2/deals/1988753/click?api_key=secret");
    assertTrue(service.cleanUrls(dirtyUrls).stream()
                .noneMatch(url -> url.contains("api_key")));
}

}
What is the quality of my code? Is my testing headed in a good direction? Is my code readable and concise?

The solution is clear but seems too complicated for just sanitizing two URLs. Few suggestions:

The test only covers the method cleanUrls and only the expected case. There should be at least one test for each public method with the expected input, plus other tests for edge cases.
Limit the interface of SanitationService by setting internal methods to private. For example cleanDeal.
The name cleanUrls is too general. The result is removing the query parameters from the URLs so a better name might be stripUrlsParams.

My suggestion is to simplify cleanApiKeys like this:
public List<Deal> cleanApiKeys(List<Deal> deals) {
    deals.stream().forEach(deal -> {
        deal.stripUrlsParams();
    });
    return deals;
}

The class Deal will "deal" with its URLs:
public class Deal{
    //...
    public void stripUrlsParams() {
        this.url = this.url == null ? null : url.split("\\?")[0];
        this.imageUrl = this.imageUrl == null ? null : imageUrl.split("\\?")[0];
    }
}

If for some reason you can't change Deal then add a private method in SanitationService.


Generating Robot Name Problem:

  Write a program that manages robot factory settings.

  When robots come off the factory floor, they have no name.

  The first time you boot them up, a random name is generated, such as
  RX837 or BC811.

  Every once in a while we need to reset a robot to its factory
  settings, which means that their name gets wiped. The next time you
  ask, it will respond with a new random name.

  The names must be random: they should not follow a predictable
  sequence. Random names means a risk of collisions. Your solution
  should not allow the use of the same name twice when avoidable. In
  some exercism language tracks there are tests to ensure that the same
  name is never used twice.

Code:

import java.util.Random;
import java.util.Set;
import java.util.HashSet;

public class Robot {
  private static final String ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  private static final Set<String> generatedNames = new HashSet<>();
  private String name;

  public String getName() {
    while (name == null) {
      name = generateName();
      if (generatedNames.contains(name)) name = null;
    }
    generatedNames.add(name);
    return name;
  }

  public void reset() {
    name = null;
  }

  private String generateName() {
    StringBuilder builder = new StringBuilder();
    int i;
    for (i = 0; i < 2; i++) {
      builder.append(ALPHABETS.charAt(generateRandomInRange(0, 25)));
    }
    for (i = 0; i < 3; i++) {
      builder.append(generateRandomInRange(0, 9));
    }
    return builder.toString();
  }

  private int generateRandomInRange(int min, int max) {
    return new Random().nextInt((max - min) + 1) + min;
  }
}

Test Suite:

import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertEquals;

public class RobotTest {

    private static final String EXPECTED_ROBOT_NAME_PATTERN = "[A-Z]{2}\\d{3}";
    private final Robot robot = new Robot();

    @Test
    public void hasName() {
        assertIsValidName(robot.getName());
    }

    @Test
    public void differentRobotsHaveDifferentNames() {
        assertThat(robot.getName(), not(equalTo(new Robot().getName())));
    }

    @Test
    public void resetName() {
        final String name = robot.getName();
        robot.reset();
        final String name2 = robot.getName();
        assertThat(name, not(equalTo(name2)));
        assertIsValidName(name2);
    }

    private static void assertIsValidName(String name) {
        assertThat(name.matches(EXPECTED_ROBOT_NAME_PATTERN), is(true));
    }
}

Question:

Apart my naming and data structure I am interested in knowing if my solution would scale well or not?

Reference: Exercism

Quality of random numbers

You are generating a random integer in a range with the method

private int generateRandomInRange(int min, int max) {
  return new Random().nextInt((max - min) + 1) + min;
}

This method creates a new Random object each time it is called. This is not a good idea. A random number generator should only be instantiated once and be reused throughout the application.

There is a FindBugs warning for exactly that (emphasis mine):

  This code creates a java.util.Random object, uses it to generate one random number, and then discards the Random object. This produces mediocre quality random numbers and is inefficient.

What you want instead is to have a single Random object. You could create it as a constant and then reuse it, like this:

private static final Random RANDOM = new Random();

private int generateRandomInRange(int min, int max) {
    return RANDOM.nextInt((max - min) + 1) + min;
}

But, in this case, since you're using it to return a random integer in a range, it would be even simpler to use the built-in ThreadLocalRandom class:

private int generateRandomInRange(int min, int max) {
    return ThreadLocalRandom.current().nextInt(min, max + 1);
}

This will directly return a random integer in the range [min, max].

Pre-allocating the StringBuilder

Small nit-pick, but you're using

StringBuilder builder = new StringBuilder();

to instantiate the StringBuilder. Since we know that the result will have 5 characters, we might as well initialize it with that:

StringBuilder builder = new StringBuilder(5);

It will create in memory an array of 5 characters instead of 16 (which is the default). As commented by Insane, you could extract that 5 (along with the 2 and 3 in the for loop) into a constant (named, for example, ROBOT_NAME_LENGTH).

Variable scope

In your generateName method, you have:

int i;
for (i = 0; i < 2; i++) {
  builder.append(ALPHABETS.charAt(generateRandomInRange(0, 25)));
}
for (i = 0; i < 3; i++) {
  builder.append(generateRandomInRange(0, 9));
}

which first declares i and uses it afterwards. There is no need to do that and it is a lot clearer to just have

for (int i = 0; i < 2; i++) {
  builder.append(ALPHABETS.charAt(generateRandomInRange(0, 25)));
}
for (int i = 0; i < 3; i++) {
  builder.append(generateRandomInRange(0, 9));
}

About the unicity of the names

Currently, you are storing all the generated names inside a Set. This is great because you can then check in constant-time if a given name was already generated. The small hiccup is that you will keep generating names until you find one that hasn't been generated before.

I don't see an easy way to optimize that or do better. The brute-force solution of generating all possible names up-front is possible in this case (since there are "only" 26 * 26 * 10 * 10 * 10 = 676000 possibilites) but not very pretty, and it wouldn't scale well at all.

Your solution is the best with regard to difficulty to write / understand versus the time it takes to generate the name. I tested with by generating a name for all the 676000 possible robots and it did it in a couple of seconds.

However, it leads to a possible bug.

Possible bug

There are only 676000 possible names. This means that if you want to name the robot 676001, your code will loop forever: it will try again and again to generate a name and will never terminate since they have all been generated.

A possible solution is to test whether all the names have been generated: if it is the case, you can simply clear the generated names set (remove all values). The problem description says:

  Your solution should not allow the use of the same name twice when avoidable.

In the case when they have all been generated, it is unavoidable, and one solution could be to decide to start again from 0. Another solution could also be to simply return one by one the already generated names (since we know they are unique) and not generate them again.

Oh, and also, generatedNames should be named GENERATED_NAMES since it is declared as static final.


Single class which holds response and error message I am working on a library which will make HTTP call to my rest service basis on inputs passed to this library. And whatever response comes back from service whether it is successful response or failure coming from the service or something happened in this library like timeout or any other errors, I am returning a response object back to the customer which customer can look into and iterate the object accordingly.

My response object is like this as of now and this is what I am returning back to the customer and customer will use this object and iterate it to figure out whether it is successful response or some failure and use it accordingly.

public class DataResponse {

    // response data
    private final String response;
    private final String date;
    private final String confidence;
    private final String mask;
    // what are the errors?
    private final ErrorCode error;
    // whether it is successful response or not
    private final StatusCode status;

    public DataResponse(String response, String date, String confidence, String mask, ErrorCode error, StatusCode status) {
        this.response = response;
        this.date = date;
        this.confidence = confidence;
        this.mask = mask;
        this.error = error;
        this.status = status;
    }

    // getters here

}

And below is my ErrorCode class which contains all the errors happened at client level or service level so that the customer can know what happened.

public enum ErrorCode {

    OK(200, "NONE", "Response is success."),
    NO_CONTENT(204, "No Content", "Response is success."),
    CLIENT_TIMEOUT(1007, "Timeout", "Timeout has occured on the Client.");
    // some more error messdates, keeping it short to show the idea

    private final int code;
    private final String status;
    private final String description;

    private ErrorCode(int code, String status, String description) {
        this.code = code;
        this.status = status;
        this.description = description;
    }

    // getters here

    @Override
    public String toString() {
        return code + " : " + status;
    }
}

And below is StatusCode class basis on which customer will decide whether it is successful response or not.

public enum StatusCode {
    SUCCESS, ERROR;
}

Customers of this library - they will use this DataResponse object in two ways:

Firstly, they can serialize DataResponse object to JSON as per their needs if they want to do it but it's up to them.
Secondly they will use this DataResponse object as it is and just iterate it normally.

So wanted to make sure from both the perspectives if the current design is good? If not what can be the improvements.

Please review my code. If you have any questions, please ask. If you have any comments, please give them.

Is that error, or status, or both, or neither?

This API is a bit confusing.
You have ErrorCode and StatusCode enums. But ErrorCode contains things like:

OK(200, "NONE", "Response is success."),
NO_CONTENT(204, "No Content", "Response is success."),
CLIENT_TIMEOUT(1007, "Timeout", "Timeout has occured on the Client.");

So two of the "error codes" indicate success.

public enum StatusCode {
    SUCCESS, ERROR;
}

... And StatusCode can indicate success or error.

... The confusing nature of these elements make it difficult to understand the API, and the distinction of its building blocks.

Your error codes resemble HTTP status codes. Why not go a bit further in following HTTP practices, and have just one Status enum, that contains status codes like in the HTTP protocol, some of which are success, and others are error.

DataResponse

I like that the class is immutable.
But I'm concerned about the long parameter list of the constructor,
especially considering that the first 4 values are all of String type,
which can lead to errors such as mistaken ordering.

I would suggest to consider adding a builder,
that will have well-named setters to set the parameter values,
possibly allowing some sensible defaults.

Lastly, the type of the date field is a String.
It would be good to add a JavaDoc about the required format.
(For that matter, a JavaDoc for the other String parameters would be good too.)


Simple C++ program that calculates the measures of a sphere I have another home work from school and would like to see if I am on the right path to learning C++.

We have to do the calculation of the measures of a sphere. I did it two ways:

Just calculating everything at the main
Using a function

#include "stdafx.h"
#include "iostream"
#include <cmath>

double *calcSphereMesures(double r);

double *calcSphereMesures(double r)
{
const double PI = 3.1416;
double d, area, circumference, volume;
double results[4];

d = 2*r;
circumference = PI * d;
area = (4 * PI * pow(r,2));
volume = (4 * PI * pow(r,3))/3;

results[0] = area;
results[1] = circumference;
results[2] = volume;
results[3] = d;
return results;
}

int main()
{
double r;
std::cout << "Please enter the radius of a circle: ";
std::cin >> r;
double *results = calcSphereMesures(r);

std::cout << "\n**************************************" << "\n"
<< "* Area and Circumference of A Sphere *" << "\n"
<< "**************************************" << "\n"
<< "\nRadius: " << r << "\n"
<< "Diameter: " << results[3] << "\n"
<< "Area: " << results[0] << "\n"
<< "Circumference: " << results[1] << "\n"
<< "Volume: " << results[2];
return 0;
}

I tried to check all the tips that were given to me the last time. Is that still bad code? What can I improve here and remember for future exercises?

I see a number of things that may help you improve your code.

Prefer portable code

This code could be entirely portable if the #include "stdafx.h" were omitted.  It's Windows specific and doesn't really help here, even on Windows.

Understand header include paths

There is a subtle difference between #include "iostream" and #include <iostream>.  Although it's implementation defined, most compiler implementations is that the quotation mark form searches locally first (e.g. the current directory) and then searches system include directories if that fails.  The angle bracket form usually searches in system include directories.  See https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename for more.

Fix your formatting

The code is all jammed up on the left margin with no indenting.  I don't know if that's how you wrote it or if it's a cut-and-paste error when posting the question, but it really makes the program hard to read.  It makes no difference to the compiler, but you should strive for a good consistent style that includes visual clues for the human reader of your code.

Fix the bug

The calcSphereMesures routine is returning the address of a variable that's local to that routine.  That's a bug.  If you need to return multiple values, either pass in a pointer to an appropriate structure to be filled in by the routine or allocate one using new and returning that.  I'd prefer the former, because it makes ownership of the structure a little cleaner (that is, the caller must both allocate and free the structure).  Note that although I'm using the word structure, here, that isn't necessarily a struct -- it could just as well be an array or some other data structure.

Consider using an object

The area, circumference, etc., could all be attributes of a Sphere class.  This would have the advantage that one could write sphere.diameter() instead of results[3] for example.

Use name spaces

When you #include <cmath>, it brings those functions into the std:: namespace and may also put the symbols into the global namespace.  You're counting on the latter which is not guaranteed by the standard.  You can fix that by using std::pow instead of just pow.

Use a better value of \$\pi\$

There's little point in asking for the precision of a double if you're going to approximate \$\pi\$ as 3.1416.

Understand the use of function declarations

A function declaration is required before the use of the function.  Your separate declaration and implementation of the calcSphereMesures() function would make sense if the declaration were in its own header file, but that's not the case here.  For that reason, I'd suggest eliminating the declaration -- keeping them synchronized is just another task that you can eliminate.

Check your spelling

The word "measure" is consistently misspelled within the code.  It would be nice to fix that.


Frequency analysis for simultaneous dice rolls - follow-up I had another question for my Perl class assignment.

Related question:

Frequency analysis for simultaneous dice rolls

use warnings;
use diagnostics;
use GD::Graph::hbars;
use List::Util qw(max);
my $number_of_dice=0;
my $number_of_rolls=0;
my @total_sum_of_eyes;
my %count;
my $counter=0;

print "\n Please insert the number_of_dice: ";
chomp($number_of_dice=<STDIN>);
print "\n Please instert the number_of_rolls: ";
chomp($number_of_rolls=<STDIN>);

while ($counter< $number_of_rolls){
    push(@total_sum_of_eyes,roll($number_of_dice));
    $counter++;
}
frequency(@total_sum_of_eyes);
representation(%count);

sub roll{
    my $number=0;
    my $sum_of_throw=0;
    $sum_of_throw = 0;
    for($i=0;$i<$number_of_dice;$i++){
        $number = int(rand(6) +1);
        $sum_of_throw+=$number;
    }
    return $sum_of_throw;
}
sub frequency{

    for($i=0;$i<$number_of_rolls;$i++){
        $count{$total_sum_of_eyes[$i]}++;
    }
    return;
}
sub representation{
    my @single_sum_of_eyes;
    my @frequency;
    print "\n the frequencys-distribution is: \n";
    print "\n total_sum_of_eyes\t frequency\t frequencys-distribution in %\n";
    foreach my $eyes (sort{$a <=> $b} keys %count){
        push(@frequency, $count{$eyes});
        push(@single_sum_of_eyes, $eyes);
        printf "\n\t $eyes\t\t\t  $count{$eyes}\t\t%g",($count{$eyes}/$number_of_rolls)*100;
    }
    print "\n";
    my $graph = GD::Graph::hbars->new(1600, 600);
$graph->set(
    x_label             => 'total_sum_of_eyes',
    y_label             => 'frequency',
    title               => 'frequencys-distribution',
    y_max_value         =>  max(@frequency)+1,
    y_tick_number       => 8,
    transparent         => 0,
    long_ticks          => 1,
) or die $graph->error;
my @data = (\@single_sum_of_eyes,\@frequency);
$graph->set( dclrs => [ qw(green) ] );
my $gd = $graph->plot(\@data) or die $graph->error;
open(IMG, '>gd_bars.gif') or die $!;
binmode IMG;
print IMG $gd->gif;
return;
}

frequency(@total_sum_of_eyes);
representation(%count);

Is this necessary?

foreach my $eyes (sort{$a <=> $b} keys %count){
        push(@frequency, $count{$eyes});
        push(@single_sum_of_eyes, $eyes);
        printf "\n\t $eyes\t\t\t  $count{$eyes}\t\t%g",($count{$eyes}/$number_of_rolls)*100;
    }

I can't seem to find a simple for-loop for this one.

Found a solution without foreach

@single_sum_of_eyes = sort{$a <=> $b} keys %count;
    for($j = 0; $j<scalar @single_sum_of_eyes; $j++)
    {
        push(@frequency,$count{$single_sum_of_eyes[$j]});
    }
    for($i=0; $i<scalar @frequency; $i++)
    {
    printf "\n\t$single_sum_of_eyes[$i]\t\t\t $frequency[$i]\t\t%g", ($frequency[$i]/$number_of_rolls)*100;
    }
    print "\n";


SwiftUI Dot indicator I want to understand if I got this concept correctly.

I should start work from ViewState; a reference type object holding the state of a view. Here it is called PageIndicatorVM. It is bad-to-impossible to have any internal state in a View.
No logic in the View or so they say. Yet here and there in the code samples I see ternary operators and loops.
@Bidindg property wrapper seems quite dangerous for me. It breaks unidirectional data flow and I have doubts if I used it correctly here.

Please point out my mistakes. Will appreciate if you point me to best practices.

This is a dot indicator component. It switches when vm.next() is called or user taps on a dot.
struct DotIndicator: View {
    let pageIndex: Int

    @Binding var isOn: Int

    var body: some View {

        Button(action: {
            self.isOn = self.pageIndex
        }) {
            Circle()
                .scaleEffect( isOn == pageIndex ? 1.3 : 0.9)
                .animation(.spring())
        }

    }
}

class PageIndicatorVM: ObservableObject {
    @Published var currentPage: Int

    let numPages: Int

    init(numPages: Int, currentPage: Int = 0) {
        self.numPages = numPages
        self.currentPage = currentPage
    }

    func next() {
        currentPage = (currentPage + 1) % numPages
    }
}

struct PageIndicator: View {
    @ObservedObject private var vm = PageIndicatorVM(numPages: 5)

    private let spacing: CGFloat = 2
    private let dotSize: CGFloat = 8

    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: spacing) {
                ForEach((0..<vm.numPages ), id: \.self) {
                    DotIndicator(pageIndex: $0, isOn: self.$vm.currentPage)
                    .frame(
                        width: self.dotSize,
                        height: self.dotSize
                    )
                }
            }
        }
    }
}

Your code is perfectly fine. Just a couple of comments:

It is bad-to-impossible to have any internal state in a View.

Actually SwiftUI was designed to handle state changes directly in a view. For simple cases you can easily do:
struct PageIndicator: View {
    @State private var currentPage = 0
    let numPages: Int = 5

    private let spacing: CGFloat = 2
    private let dotSize: CGFloat = 8

    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: spacing) {
                ForEach(0 ..< numPages, id: \.self) {
                    DotIndicator(pageIndex: $0, isOn: self.$currentPage)
                        .frame(width: self.dotSize, height: self.dotSize)
                }
            }
        }
    }
}

PageIndicator(numPages: 5)

What's more sometimes an @ObservedObject may be reinitialised contrary to a @State property (unless you use a @StateObject available in SwiftUI 2.0).
For more information see: What is the difference between ObservedObject and StateObject in SwiftUI.

No logic in the View or so they say. Yet here and there in the code
samples I see ternary operators and loops.

True, but for simple cases creating a whole new ViewModel can actually make code less readable (as in the example above). Note that a ForEach loop is perfectly valid in a view.

Apart from the comments above you can use an Image(systemName:) instead of a Circle:
struct DotIndicator: View {
    let pageIndex: Int

    @Binding var isOn: Int

    var body: some View {
        Button(action: {
            self.isOn = self.pageIndex
        }) {
            Image(systemName: "circle.fill")
                .imageScale(.small)
                .scaleEffect(isOn == pageIndex ? 1.0 : 0.7)
                .animation(.spring())
        }
    }
}

Because a Circle consumes all available space, you need to constrain it with the .frame modifier. You don't have to do that with an Image - it reduces the code (dotSize is no longer needed) and scales automatically.


Inter module communication I have two modules, Notification which basically contains SignalR hubs and CoreSetup which contains core setup logic in it.

I have a class in CoreSetup module which keeps track of employee location . I want SignalR hubs to be notified and those locations to be on MAP when new data are inserted through Web API.
I don't want CoreSetup module to have dependency on SignalR module.
This is what I have done currently.

[Route("api/salesman-location")]
[ApiController]
public class SalesmanLocationController : BaseController
{
    private readonly SalesmanLocationService _salesmanLocationService;
    private readonly IHubContext<ChatHub> _hubContext;

    public SalesmanLocationController(SalesmanLocationService salesmanLocationService,IHubContext<ChatHub> hubContext)
    {
        _salesmanLocationService = salesmanLocationService;
        _hubContext = hubContext;
    }

    [Route("save")]
    [HttpPost]
    public IActionResult save([FromBody]List<SalesmanLocationDto> datas)
    {
        try
        {
            _hubContext.Clients.All.SendAsync("SalesManLocationfromHub", datas);
            _salesmanLocationService.save(datas);
            return Ok();
        }
        catch (CustomException ex)
        {
            return ApiResponse.getErrorResponseJson(ex.Message);
        }
        catch (Exception ex)
        {
            return ApiResponse.getErrorResponseJson("Failed to save data.");
        }
    }
}

It works pretty well but I have some logic inside save() method of SalesmanLocationService . It would be great if hub can subscribe to save() method of SalesmanLocationService without  SalesmanLocationService knowing anything about Hub.Under some condition, I should not broadcast data through hub.

This is how my interface of SalesmanLocationService looks like:

 public interface SalesmanLocationService
    {
        void save(List<SalesmanLocationDto> datas);
    }

This is the actual implementation of SalesmanLocationService

 public class SalesmanLocationServiceImpl : SalesmanLocationService
    {
        public SalesmanLocationServiceImpl()
        {
        }

        public void save(List<SalesmanLocationDto> datas)
        {
           foreach (var data in datas)
           {
            save(data);
           }
        }

        private void save(SalesmanLocationDto data)
        {
           if(someCondition){
             //broadcast to hub
           }
        }
    }

Its very much hard coded for that single domain type, SalesmanLocation. I would instead use some kind of event aggregation pattern. The domain fires off these events and the singalr hub listenes to these events.

I have made a singalr library that seamlessly forwards events to signalr. Maybe it can give you some ideas

https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki

Bascily with my design you would do

private void Save(SalesmanLocationDto dto)
{
    repository.Save(dto);
    eventAggregator.Publish(new SalesmanLocationSavedEvent{ /* map data from dto */ });
}

Its completely decoupled and nor the domain or the signalr parts know about each other


Calculate SHA1 hash from binary and verify with a provided hash I applied for a job and they asked me to write code with the following requirements:

  Get a "toolbar offer" description from
  http..update.utorrent.com/installoffer.php?offer=conduit.  Parse the
  bencoded (see http://en.wikipedia.org/wiki/Bencode) response and
  extract the URL of the binary and its SHA1 hash.  The hash is contained
  in the value of the key 'offer_hash'. The binary is in list for the
  key 'offer_urls' — please use the one prefixed with
  "http..download.utorrent.com/".

  Download the binary and calculate its hash

  Verify that the calculated SHA1 hash is identical to the one provided
  in the offer details.  It is okay to use existing libraries for
  bencoding, hashing, etc.

What is wrong with my code? The recruiter said it didn't meet their bar.

# Script that verifies the correctness of a toolbar offers

import urllib, bencode , hashlib
from hashlib import sha1

url = "http://update.utorrent.com/installoffer.php?offer=conduit"

filename = "content.txt"

f= urllib.urlretrieve(url, filename)

#Bdecoding the response

with open (str(filename), 'rb') as myfile:
           data=myfile.read()
           decoded = bencode.bdecode(data)

# Returning the list for the key 'offer_urls'

list = decoded['offer_urls']

#print list

# Returning the URL of the binary that is prefixed with "http://download3.utorrent.com/"

length = len (list)

prefix = "http://download3.utorrent.com/"

i= -1

while i < length:
     i = i + 1
     if list[i].startswith(prefix) :
        break
binary= list[i]

print "The URL of the the binary is: " , binary

# Returning the sha1 hash contained in the value of the key 'offer_hash'

encrypted_hash = decoded['offer_hash']
sha1_hash1 = encrypted_hash.encode('hex')
print "The sha1 hash contained in the value of the key 'offer_hash' is: " , sha1_hash1

# Downloading the binary and calculating its hash

urllib.urlretrieve ( binary , "utct2-en-conduit-20130523.exe")
file = "C:\Python27\utct2-en-conduit-20130523.exe"
with open (file, 'rb') as myfile:
           downloaded=myfile.read()

k = hashlib.sha1()
k.update(downloaded)
sha1file = k.hexdigest()
print "The sha1 hash of the downloaded binary is: " , sha1file

# Verify that the calculated sha1 hash is identical to the one provided in the offer details

if (sha1file == sha1_hash1) :
    print "Test result = Pass"
else :
    print "Test result = Fail"

I'm going to tell you the things in your code that made me wonder.

# Script that verifies the correctness of a toolbar offers

import urllib, bencode , hashlib

Extra space after bencode suggests lack of attention to detail.

from hashlib import sha1

url = "http://update.utorrent.com/installoffer.php?offer=conduit"

filename = "content.txt"

f= urllib.urlretrieve(url, filename)

Use of single-letter variables suggests lack of attention to clean code.

#Bdecoding the response

with open (str(filename), 'rb') as myfile:

filename is already a string.  Converting it to a string again suggests confusion as to what is going on.

           data=myfile.read()
           decoded = bencode.bdecode(data)

Massive indentation suggests disregard for consistent indentation style.

Downloading the file to disk then reading it into memory is poor use of available APIs. You should download the file directly into memory.

# Returning the list for the key 'offer_urls'

Excess whitespace suggests someone is enter-happy.

list = decoded['offer_urls']

"Returning" is technically incorrect here. You aren't in a function, so you aren't returning anything. Use of list is a bad name for a variable since it's a built-in Python type.

#print list

# Returning the URL of the binary that is prefixed with "http://download3.utorrent.com/"

length = len (list)

Putting spaces after function calls is odd, and you don't do it consistently. There's also rarely a good reason to store the length of a list.

prefix = "http://download3.utorrent.com/"

i= -1

No space before the =.

while i < length:
     i = i + 1
     if list[i].startswith(prefix) :
        break
binary= list[i]

You are using a while loop when you should be using a for loop. It is also going to cause an IndexError, rather than fail gracefully, if the prefix isn't found.

print "The URL of the the binary is: " , binary

# Returning the sha1 hash contained in the value of the key 'offer_hash'

encrypted_hash = decoded['offer_hash']

Is that hash really encrypted?

sha1_hash1 = encrypted_hash.encode('hex')
print "The sha1 hash contained in the value of the key 'offer_hash' is: " , sha1_hash1

# Downloading the binary and calculating its hash

urllib.urlretrieve ( binary , "utct2-en-conduit-20130523.exe")
file = "C:\Python27\utct2-en-conduit-20130523.exe"

Hard-coded filename will be easy to break. You shouldn't even need to do it. The string also contains "\" which should be escaped, or the whole string should be raw. i.e.

"C:\\Python27\\utct2-en-conduit-20130425.exe"

or

r"C:\Python27\utct2-en-conduit-20130425.exe"

or in most cases you can use the other slashes, even on Windows.

"C:/Python27/utct2-en-conduit-20130425.exe"

You got away with what you did, but that's mostly because you are lucky.

with open (file, 'rb') as myfile:
           downloaded=myfile.read()

This last piece of code did pretty much the same thing as a previous bit of code, but you didn't use a function.

k = hashlib.sha1()
k.update(downloaded)
sha1file = k.hexdigest()
print "The sha1 hash of the downloaded binary is: " , sha1file

# Verify that the calculated sha1 hash is identical to the one provided in the offer details

if (sha1file == sha1_hash1) :

You've put parentheses, which are not necessary.

    print "Test result = Pass"
else :
    print "Test result = Fail"

Your basic problems:

Your style is poor and inconsistent
A few things suggest you don't quite understand what's going on
You haven't taken care to make the code readable

Here's my take on the problem:

# Script that verifies the correctness of a toolbar offers

import urllib
import bencode
import hashlib
import contextlib

# it's common practice to put input details like this
# as global constants at the start of your script
URL = "http://update.utorrent.com/installoffer.php?offer=conduit"
PREFIX = "http://download3.utorrent.com/"

# by breaking down your task into functions
# you can make the code easier to follow
def read_bencoded_url(url):
    with contextlib.closing(urllib.urlopen(url)) as offer_file:
        return bencode.bdecode(offer_file.read())

def find_string_with_prefix(strings, prefix):
    for string in strings:
        if string.startswith(prefix):
            return string
    else:
        raise Exception("Did not find prefix: {}".format(prefix))

# this function is a bit more complicated
# but it avoids saving the file to disk or loading it entirely into memory.
# instead it hashes it 4096 bytes at a time
def hash_of_url(url):
    hasher = hashlib.sha1()
    with contextlib.closing(urllib.urlopen(url)) as binary_file:
        while True:
            data = binary_file.read(4096)
            if not data:
                break
            hasher.update(data)
    return hasher.hexdigest()

# the actual high level logic just calls the functions
# this avoid obscuring the logic with lower level details
def main():
    decoded = read_bencoded_url(URL)
    binary = find_string_with_prefix(decoded['offer_urls'], PREFIX)
    reported_hash = decoded['offer_hash'].encode('hex')
    actual_hash = hash_of_url(binary)
    print "The sha1 hash contained in the value of the key 'offer_hash' is: ", reported_hash
    print "The sha1 hash of the downloaded binary is: " , actual_hash

    if reported_hash == actual_hash:
        print "Test result = Pass"
    else:
        print "Test result = Fail"

if __name__ == '__main__':
     main()


StopWatch for users C# I have tried to create a stopwatch and I have done but I don't know how to improve it, and I want the user control the stopwatch whether it (Start) or (Stop), I'll be thankful if you tell me what I can do to improve my code.

StopWatch.cs

public class StopWatch
{
    private DateTime _startTime;
    private DateTime _stopTime;
    private bool _timeRunning = false;

    public void Start(DateTime Start)
    {
        if (!_timeRunning)
        {
            _startTime = Start;
            _timeRunning = true;
        }
        else
            throw new InvalidOperationException("Stopwatch is already running!");
    }

    public void Stop(DateTime Stop)
    {
        if (_timeRunning)
        {
            _stopTime = Stop;
            _timeRunning = false;
        }
    }

    public TimeSpan GeTime()
    {
        var duration = _stopTime - _startTime;
        return duration;
    }
}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        var stopwatch = new StopWatch();

        stopwatch.Start(DateTime.Now);

        for (int i = 0; i < 1000; i++)
        {
            Thread.Sleep(10);
        }

        stopwatch.Stop(DateTime.Now);

        Console.WriteLine(@"Time Elapsed : {0:hh\:mm\:ss}", stopwatch.GeTime());
    }

Normally I wouldn't recommend creating a class with almost exactly the same name as a framework class (your StopWatch vs the existing Stopwatch), but you mentioned that this is an exercise, so let's ignore that for now.

The basic approach here seems fine: Start stores the start time, Stop stores the end time, and GetTime returns the difference. But there's a bug: GetTime does not work correctly if the stopwatch is still running. In that case, instead of looking at the (incorrect) stop time, it should look at the current time.
Why do Start and Stop take a DateTime as argument? That's something that the stopwatch itself should be doing. If, for some reason, you really must allow calling code to pass in their own times, then your stopwatch class should probably verify that the stop time is not earlier than the start time.
Why does Start throw an exception if the stopwatch is already running? Is that really something that should not be allowed? If so, why is it allowed to call Stop on a stopped stopwatch? I see no real reason for this inconsistency.
If starting a running stopwatch is not allowed, why can't a caller determine whether a stopwatch is running? A read-only IsRunning property that returns _timeRunning would be useful.
As you know, there's already a Stopwatch class in System.Diagnostics, so I would encourage you to look at its source code. You'll see several differences. One in particular is that it remembers the total elapsed time across multiple start/stop calls. Related to that are the Reset and Restart methods, and there's a convenient static StartNew method. It also uses lower-level methods for more accurate timing.


Basic Brainfuck interpreter (part 2) I have this obsession with esoteric programming languages. So I decided to spiff up my previous Brainfuck interpreter.

# Simple BrainF*** interpreter

# Class that stores lang variables
class Lang(object):
    step = 0
    cell = [0] * 30000
    test_cell = [0] * 30000
    pos = 0
    test_pos = 0
    loop = False
    loop_ret = 0

# Main interpreter function
def interpreter():

    code_input = raw_input('Code: ')
    steps = len(code_input)

    while Lang.step < steps:

        if code_input[Lang.step] == '+':
            Lang.cell[Lang.pos] += 1

        elif code_input[Lang.step] == '-':
            Lang.cell[Lang.pos] -= 1

        elif code_input[Lang.step] == '>':
            if Lang.pos < 30000:
                Lang.pos += 1
            elif Lang.pos > 30000:
                Lang.pos = 0

        elif code_input[Lang.step] == '<':
            if Lang.pos > 0:
                Lang.cell_pos -= 1
            elif Lang.pos < 0:
                Lang.pos = 30000

        elif code_input[Lang.step] == '[':
            if Lang.loop == False:
                Lang.loop_ret = Lang.step
                Lang.loop = True

        elif code_input[Lang.step] == ']':
            if Lang.cell[Lang.pos] != 0:
                Lang.step = Lang.loop_ret
            elif Lang.cell[Lang.pos] == 0:
                Lang.loop = False

        elif code_input[Lang.step] == '.':
            print str(chr(Lang.cell[Lang.pos]))

        elif code_input[Lang.step] == ',':
            Lang.cell[Lang.pos] = int(raw_input())

        elif code_input[Lang.step] == ":":
            Lang.test_cell[Lang.test_pos] += 1

        elif code_input[Lang.step] == ";":
            Lang.test_cell[Lang.test_pos] -= 1

        elif code_input[Lang.step] == "}":
            if Lang.test_pos > 30000:
                Lang.test_pos += 1
            elif Lang.test_pos < 30000:
                Lang.test_pos = 0

        elif code_input[Lang.step] == "{":
            if Lang.test_pos > 0:
                Lang.test_pos -= 1
            elif Lang.test_pos < 0:
                Lang.test_pos = 30000

        elif code_input[Lang.step] == "$":
            if Lang.test_cell[Lang.test_pos] == Lang.cell[Lang.pos]:
                print True
            elif Lang.test_cell[Lang.test_pos] != Lang.cell[Lang.pos]:
                print False

        Lang.step += 1

# Running the program
if __name__ == "__main__":
    interpreter()

If there are any issues, please mention them. All I'm looking for is any general improvements.

In a word: dictionaries.

You have a class that only has class attributes and lacks any methods; that could just be a dictionary:

lang = dict(
    step = 0,
    cell = [0] * 30000,
    test_cell = [0] * 30000,
    pos = 0,
    test_pos = 0,
    loop = False,
    loop_ret = 0
)

(Alternatively, if you really want attribute (foo.bar) rather than key (foo['bar']) access to the values, look into collections.namedtuple.)

You have a whole bunch of elifs; that could also be a dictionary (with some judiciously-named functions):

commands = {
    "+": increment_byte,
    "-": decrement_byte,
    ...
}

This makes your interpreter loop:

def interpreter():

    lang = dict(...)
    commands = {...}

    code_input = raw_input('Code: ')
    steps = len(code_input)

    while lang['step'] < steps:
        command = code_input[lang['step']]
        if command in commands:
            commands[command](lang)
        lang['step'] += 1

along with e.g.:

def increment_byte(lang):
    """Increment the byte at the data pointer."""
    val = lang['cell'][lang['pos']]
    lang['cell'][lang['pos']] = ((val + 1) % 256)

(Note use of % per @user50399's answer.)

This has two advantages:

very simple loop in interpreter; and
commands acts as a syntax guide (covering @Dagg's comment).

You could also add some input validation:

def accept_input(lang):
    """Accept one char of input, storing its value in the byte at the data pointer."""
    while True:
        try:
            i = ord(raw_input("Enter char: "))
        except TypeError:
            pass
        else:
            if i in range(256):
                lang['cell'][lang['pos']] = i
                break
        print("Not a valid input.")

(Note switch to ord per @user50399's answer.)


"Group" animation events in jQuery I have a number of jQuery animation effects applied to certain elements on the page:

jQuery("#bgd_balance").animate({
        backgroundPositionY: "0px",
        backgroundPositionX: "0px",
        'background-size':'100%'
},800,"swing");

jQuery(".balance_left_box").delay(2000).slideDown(200,"easeInCirc");

jQuery(".balance_left_box p.first-line").delay(2400).slideDown(600,"easeInCirc");

jQuery(".balance_left_box").delay(1000).animate({
    height:"270px",
    top:"64px"
},100,"easeInCirc");

The problem I'm facing is that when I'm tweaking delay of a certain element, I have to go through everything and adjust all other delays accordingly.

Is it possible to have something like this instead (pseudocode):

queue.add(
       delay(2000),
       jQuery(".balance_left_box").slideDown(200,"easeInCirc"),
       delay(2000),
       jQuery(".balance_left_box p.first-line")X.slideDown(600,"easeInCirc");
       delay(1000),
       jQuery(".balance_left_box").animate({
            height:"270px",
            top:"64px"
        },100,"easeInCirc");
).run();

I know I can achieve this "queuing" by adding callback function to animate() call but then resulting code will be really bulky and hard to read, in my opinion.

The way I see it, you have 2 options; either use Deferreds, or store your delay in a variable:

var delay = 0,
    $left_box = $(".balance_left_box");

$("#bgd_balance").animate({
    backgroundPositionY: "0px",
    backgroundPositionX: "0px",
    'background-size':'100%'
}, 800, "swing");

$left_box.delay(delay += 2000).slideDown(200, "easeInCirc");

$left_box.find("p.first-line").delay(delay += 2400).slideDown(600, "easeInCirc");

$left_box.delay(delay += 1000).animate({
    height:"270px",
    top:"64px"
}, 100, "easeInCirc");


Efficiently counting '1' bits in the first n bits I have two functions to count the number of set '1' bits in the first offset bits of either a 64 bit number, or a bitmap struct.

After some profiling, particularly the latter is quite a bottleneck in our system.

What can we do to make it faster?

#define POPCOUNT16(x) __builtin_popcount(x)
#define POPCOUNT64(x) __builtin_popcountl(x)

static __always_inline __constant int32 count64(int64 const bitmap, int32 const offset) {
    return offset == 0 ? 0 : POPCOUNT64(bitmap & (0xffffffffffffffffUL << (64 - offset)));
}

typedef struct {
    int64 hi;
    int16 lo;
} __packed int80;

static __always_inline __constant int32 countBitmap(int80 const bitmap, int32 const offset) {
    int32 count = 0;
    if (offset > 0) {
        count += POPCOUNT64(bitmap.hi & (0xffffffffffffffffUL << (sizeof (bitmap.hi)*8 - MIN(offset, sizeof (bitmap.hi)*8))));
        if (offset > sizeof (bitmap.hi)*8)
            count += POPCOUNT16(bitmap.lo & ((int16)0xffff << (sizeof (bitmap.hi)*8+sizeof (bitmap.lo)*8 - offset)));
    }
    return count;
}

first issue: you hardcode 8 as the number of bits per sizeof unit: portability says it should be CHAR_BIT which may be something else on some architectures

second issue: both members of int80 are signed, only hi should be while lo can be unsigned

if you can guarantee that offset is between 0 and 80 then you don't need to test for 0, and just document that exceeding the bounds is undefined behavior

static __always_inline __constant int32 countBitmap(int80 const bitmap, uint32 const offset) {
    int32 count = 0;
    if (offset <= sizeof (bitmap.hi)*CHAR_BIT) {
        count = POPCOUNT64(bitmap.hi >>> (sizeof (bitmap.hi)*CHAR_BIT - offset));
        // logical right shift to do away with the AND
    }else{
        count = POPCOUNT64(bitmap.hi)+
                POPCOUNT16(bitmap.lo >>> (sizeof (bitmap)*CHAR_BIT - offset));
    }
    return count;
}

here there is only 1 branch compared to the 2 you had before (possibly 3 depending on how MIN was implemented)


"Guess my Number" game I have recently just started learning Perl, so I decided to program the classic 'Guess my Number' game. I was wondering if anyone can spot any areas for improvement.  As it's my first program, I expect there to be some unoptimized areas.

#!\usr\bin\perl
print"Welcome to guess my number!\n";
    $compNumber=int rand 100;
    while($n<6){
        print"Guess a number between 1 and 100: ";
        chomp($userNumber=<STDIN>);
        if($compNumber>$userNumber){
            print"Your guess was too low, try again.\n";
        }
        if($compNumber<$userNumber){
            print"Your guess was too  high, try again.\n";
        }
        $n++
    }
    if($compNumber==$userNumber){
        print"Well done, $compNumber was my number! You got it correct in $n guesses!";
    }
    if($compNumber!=$userNumber){
        print"Unfortunately, you couldn't guess my number in 6 guesses, it was actually ${compNumber}.";
    }

First, always use strict; use warnings; at the top of your code. The strict pragma restricts you to a sensible subset of Perl, which removes many sources for errors. Also, it forces you to declare all your variables with my. The warnings are very helpful, but non-fatal errors.

If you are on a fairly modern perl (10 or later), you can use the say function. This works exactly like print, but appends a newline at the end. Enable this feature with use feature 'say' or use 5.010.

If you have a set of mutually exclusive conditions in an if-cascade, you might want to look into the if/elsif/else structure.

Your while-loop is meant to execute up to six times. Instead of while, you might want to use a range, and a foreach loop:

for (1 .. 6) {
  # this stuff executes six times
}

Inside your loop, you only test if the user didn't hit the number. If his guessed number is equal to the secret num, then you continue with a new iteration. Don't.

Also, I would pack the whole algorithm into a subroutine. This is a good habit, and allows us to do an early exit:

sub guess_my_number {
  my %args = @_; # cast the subroutine arguments to a hash
  my $maxnum = $args{maxnum} || 100; # unpack named arguments,
  my $tries =  $args{tries}  ||   6; #   or give default value

  my $secret = int rand $maxnum;

  GUESS:  # a labeled loop
  for my $try (1 .. $tries) {
    say "Guess a number between 0 and $maxnum:";

    chomp( my $guess = <STDIN> );

    if ($guess == $secret) {
      say "Yay, that was right! $secret was my number.";
      say "You managed in $try tries.";
      return 1; # exit the subroutine
    } elsif ($guess < $secret) {
      say "Your guess was too low.";
    } elsif ($guess > $secret) {
      say "Your guess was too big."
    }
    # This is executed for both too low or too large numbers:
    say "You have ", $tries - $try, " tries left.";
  }

  # we land here if we didn't manage the guess
  say "You failed to guess the correct number $secret in $tries guesses.";
  return 0;
}

And then in the main code:

guess_my_number(maxnum => 50, tries => 5);

All arguments are optional.

The above might produce a session like

Guess a number between 0 and 50:
25
Your guess was too low.
You have 4 tries left.
Guess a number between 0 and 50:
37
Your guess was too low.
You have 3 tries left.
Guess a number between 0 and 50:
44
Your guess was too big.
You have 2 tries left.
Guess a number between 0 and 50:
40
Your guess was too low.
You have 1 tries left.
Guess a number between 0 and 50:
42
Yay, that was right! 42 was my number.
You managed in 5 tries.

What you could (or should) implement is input validation. Without strict and warnings, Perl will transform any string into a number, which will be zero for non-numeric strings. To assert that the input only contains ASCII digits, run a regex over it:

if (not $guess =~ /^[0-9]+$/) {
  say qq(Your guess "$guess" was not a number.); # special qq() quotes
  redo GUESS; # redo this iteration, without incrementing the counter
}

About your updated code:

Use whitespace. Whitespace is good and improves readability.
use warnings. use 5.016 should already be activating strict for you. More warnings = more bugs found early.
We don't call subs like &foo except when you know what you are doing. This style has a number of side effects that don't matter for your example, but can introduce bugs in complex applications. Always prefer foo().
Why on earth are you using our? The our is just like my, except that it declares globals. Don't use globals. Use lexicals with my. In either case, declare your variable once and use it throughout the remaining scope. I.e. declare the variable outside the loop.
If you look at all your execution paths, you test for duplicate conditions: $compNumber == $userNumber is tested two times. Look at my code again, which manages with one test. The real reason I used a sub is that I could return early, as soon as the correct number was guessed. This made my loop control easier.
You currently have this sequence of conditions inside the loop:

if    $compNumber == $userNumber
elsif $compNumber >  $userNumber
    if $_ == 5
        last
    else
elsif $compNumber <  $userNumber
    if $_ == 5
        last
    else

As soon as $compNumber != $userNumber, we can test for the last iteration. This structure is logically equivalent, but shorter:

if    $compNumber == $userNumber
elsif $_ == 5
    last
elsif $compNumber >  $userNumber
elsif $compNumber <  $userNumber

In my code, I simply drop of the last iteration of the loop, after telling the user if his guess was too small or too large, as usual.
You use the topic variable $_. This makes for short code, but also makes it hard to understand. Consider using a better name, like $try or $guess. The topic variable is the topic of the current code (you can often pronounce it this or it). Your topic is the guess the user made, not the number of the iteration.
The $n is always zero. You don't increment it. This is good, as it should be the same as your loop variable. As I print the congratulatory message inside the loop, I can use the loop variable, which will yield the correct value.
My subroutine argument unpacking code may seem a bit arcane if you are new to Perl, but using hardcoded constants is an anti-pattern in any language. (Also, named arguments make for really nice interfaces.)


IE compatibility mode detection This method is written for much larger Web application, but I just extracted it and added class and main method around it so that it can be debugged locally.

Browser detection is done in another method, then this one is called to precisely determine IE version, i.e. if it is in compatibility mode or not. All other checks are done previously.

String headerUserAgent = "headerUserAgent mozilla/5.0 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko"; is "REAL" IE 11 so the output will be 11.0

String headerUserAgent = "mozilla/4.0 (compatible; msie 7.0; windows nt 6.1; wow64; trident/7.0; slcc2; .net clr 2.0.50727; .net clr 3.5.30729; .net clr 3.0.30729; media center pc 6.0; .net4.0c; .net4.0e; infopath.3; gwx:reserved)"; is one of compatibility modes so output will be as expected: 00

Code works according to my tests.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnsupportedBrowserMode
{
    public static void main(String[] args)
    {
        String headerUserAgent = "mozilla/4.0 (compatible; msie 7.0; windows nt 6.1; wow64; trident/7.0; slcc2; .net clr 2.0.50727; .net clr 3.5.30729; .net clr 3.0.30729; media center pc 6.0; .net4.0c; .net4.0e; infopath.3; gwx:reserved)";
        //String headerUserAgent = "headerUserAgent mozilla/5.0 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko";
        String version = getInternerExplorerVersion(headerUserAgent);
        System.out.println(version);
    }

    public static String getInternerExplorerVersion(String headerUserAgent)
    {
        String version = null;
        String TrueVersion = null;
        String ActingVersion = null;

        if (headerUserAgent != null)
        {
            headerUserAgent = headerUserAgent.toLowerCase();

            // Try to find the Trident version number
            Matcher trident = Pattern.compile("trident\\/(\\d+)").matcher(headerUserAgent);

            if (trident.find() && trident.groupCount() > 0)
            {
                // Convert from the Trident version number to the IE version number
                TrueVersion = trident.group(1);

                // If it is IE 11 TrueVersion will be overwritten with revision number
                int x = headerUserAgent.indexOf("rv:");
                if (x > 0)
                {
                  int y = headerUserAgent.indexOf(")", x);
                  if (y > x)
                  {
                      TrueVersion = headerUserAgent.substring(x + 3, y);
                  }
                }
            }

            // Try to find the MSIE number
            Matcher msie = Pattern.compile("msie[ \\(]+([^ ;\\)]+)").matcher(headerUserAgent);
            if (msie.find() && msie.groupCount() > 0)
            {
                // Find the IE version number from the user agent string
                ActingVersion = msie.group(1);
            } else
            {
                // Must be IE 11 in "edge" mode
                ActingVersion = TrueVersion;
            }

            // If we have both a Trident and MSIE version number, see if they're different
            if (Float.parseFloat(TrueVersion) > 0 && Float.parseFloat(ActingVersion) > 0)
            {
                // In compatibility mode if the trident number doesn't match up with the MSIE number
                if (TrueVersion != ActingVersion)
                {
                    version = "00";
                } else {
                    version = TrueVersion;
                };
            }
        }

        return version;
    }
}

Returning Early

You can remove one level of nesting, and make your code generally easier to understand by returning early:

if (headerUserAgent == null) {
    return null;
}

Now it's also more obvious what happens if the agent is null. But is returning null really what you want? It will lead to a lot of if (agent == null) in the calling code. I would suggest throwing an exception instead. Java also has a nice utility method for this:

Objects.requireNonNull(headerUserAgent, "User Agent is Null");

(This method should be used if the agent being null is not expected. If you do expect it, because it's part of your program logic, this might not be the best approach)

Bugs

Your code doesn't work for quite a lot of input:

empty string, , ua, etc as input results in a NullPointerException.
Some Firefox user agents also result in NullPointerException, eg Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0.
You can see a list of some possible IE user agents here. I tried some of them, and a lot result in exceptions, such as Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US)), which should be IE 9, Mozilla/5.0 (MSIE 7.0; Macintosh; U; SunOS; X11; gu; SV1; InfoPath.2; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648) which should be IE 7, or Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1) which should be IE 10 (or 00 in your case).

Misc

Your placement of the { is not really following Java conventions.
Some of your variable names could be more descriptive, eg x and y.
Variables should start with a lower-case character.
You have an unnecessary ;.
A JavaDoc style comment describing the exact return values might be a good idea, especially since the method name is a bit confusing (it doesn't always return the version, but 00 for compatibility mode).


Add active class to current menu with extension method or jQuery In the layout, I have a menu that contains some ul and li.
I have three levels`. This code is a bit of a sample:

     reports

            text

text

 text

To select the current menu item, I use this code:

 public bool IsAny(params string[] controllers)
    {
        return controllers.Any(c => Is(c));
    }

    public bool Is(string controller, string action = null)
    {
        if (ViewContext.RouteData.Values["Controller"].ToString().ToLower() == controller.ToLower()
            && (action == null ||
             ViewContext.RouteData.Values["Action"].ToString().ToLower() == action.ToLower()))
            return true;
        return false;
    }

If I use jQuery, is it better than this one on page load speed?  Or is there a way to do this in faster way?

The jQuery code looks like this:

(function(){
    var current = 'current location';
    $('#nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})

Regardless of whether you use jQuery or C# to handle the operation it won't have a dramatic effect on page load speed, the only difference will be latency perceived by the user. Because of the manner in which JavaScript operates, you will likely find that the button does not appear as 'active' when the user first loads the page for 0.25 to 0.5s, which may not  be a big deal to you, but a user would potentially see that flicker and wonder what they did.

The only changes I would make for you is to rewrite your method just a little to read a bit cleaner:

public bool Is(string controller, string action = null)
{
    if (ViewContext.RouteData.Values["Controller"].ToString().ToLower() == controller.ToLower()
        && (action == null ||
         ViewContext.RouteData.Values["Action"].ToString().ToLower() == action.ToLower()))
        return true;
    return false;
}

To something like the following:

public bool Is(string controller, string action = null)
{
    var routeData = ViewContext.RouteData;
    var actController = routeData.Values["Controller"].ToString();
    var actAction = routeData.Values["Action"].ToString();

    return actController.ToLower() == controller.ToLower() && (action == null || actAction.ToLower() == action.ToLower());
}

Same number of LoC, but it's a little more clear what's happening.

As far as performance, I don't see any obvious bottlenecks. I think the biggest bottleneck you'll end up having is in the LINQ (this is all speculation, but we're talking microseconds, not even nanoseconds). You shouldn't be concerned of your performance until there's a measurable performance issue.


Haversine Formula in Clojure I implemented the Haversine formula to calculate the distance between two (latitude, longitude) coordinates.

I was wondering if it looks natural to Clojure programmers.  What could be improved?

(ns br.com.reactive-poc.calc)

(def raio 6372.795477598)

(defn calculate-distance
"Calcula distância entre duas coordenadas geográficas"
([source to]
  {:pre [every? (every-pred map? #(contains? % :lgt) #(contains? % :ltd)) [source to]]}
  (let [delta-latitude (Math/toRadians (- (:source/ltd source) (:to/ltd to)))
        delta-longitude (Math/toRadians (- (:source/lgt source) (:to/lgt to)))
        ]
    (* (* raio (* 2 (Math/atan2 (Math/sqrt (+ (Math/pow (Math/sin (/ delta-latitude 2)) 2)
                                              (* (Math/cos (Math/toRadians (:source/ltd source))) (Math/cos (Math/toRadians (:to/ltd to))) (Math/sin (/ delta-longitude 2)) (Math/sin (/ delta-longitude 2)))))
                                (Math/sqrt (- 1 (+ (Math/pow (Math/sin (/ delta-latitude 2)) 2)
                                                   (* (Math/cos (Math/toRadians (:source/ltd source))) (Math/cos (Math/toRadians (:to/ltd to)) ) (Math/sin (/ delta-longitude 2)) (Math/sin (/ delta-longitude 2))))))))) 1000)
    )
  )
)

Naming and interface

Please avoid mixing English (calculate-distance) with Portuguese (raio).  The code should be in English; write your comments in whatever language you prefer.

ltd and lgt seem like awkward abbreviations; lat and lon or lat and lng seem more conventional.  The latter is what Google uses for the Maps and Android APIs, for example.

Putting "calculate" in the name of a function seems redundant, especially in a functional programming language.

One of the most surprising behaviours is that your function gives the result in meters, even though your raio constant is in kilometers.  To discover that quirk, you would have to scroll all the way to column 219 at the end of the function, at the end of a very long line of code!  A better comment on the function would help; better naming would be beneficial as well.

Implementation

As I mentioned, those are very long lines of code — almost unreadable.  It would be more readable if you broke down the calculation into subexpressions.

In fact, (+ (Math/pow (Math/sin (/ delta-latitude 2)) 2) (* (Math/cos (Math/toRadians (:source/ltd source))) (Math/cos (Math/toRadians (:to/ltd to))) (Math/sin (/ delta-longitude 2)) (Math/sin (/ delta-longitude 2)))) is a common subexpression that you evaluate twice.  So, not only is your code unreadable, it's also inefficient.

I would convert the latitudes and longitudes to radians right away, since degrees are useless for trigonometry.  Half the difference in angles are easily recognizable quantities.  Defining the \$\sin^2(\theta)\$ function as a lambda is also useful.

(def earth-radius-km 6372.795477598)

(defn distance
    "Calcula distância entre duas coordenadas geográficas em metros"
    ([latlng1 latlng2]
        {:pre [every? (every-pred map? #(contains? % :lat) #(contains? % :lng)) [latlng1 latlng2]]}
        (let [lat1 (Math/toRadians (:latlng1/lat latlng1))
              lng1 (Math/toRadians (:latlng1/lng lnglng1))
              lat2 (Math/toRadians (:latlng2/lat latlng2))
              lng2 (Math/toRadians (:latlng2/lng lnglng2))
              half-dlat (/ (- lat2 lat1) 2)
              half-dlng (/ (- lng2 lng1) 2)
              sin2 (fn [x] (Math/pow (Math/sin x) 2))
              a (+ (sin2 half-dlat) (* (Math/cos lat1) (Math/cos lat2) (sin2 half-dlng)))]
             (* 2000 earth-radius-km (Math/atan2 (Math/sqrt a) (Math/sqrt (- 1 a)))))))


Which Java string value is preferred to return: blank or null? I came across this snippet and am wondering if I should return blank in this case.

Which is more practical to return: blank or null?

public String getInfo() {
    String result = "";
    String uri = clientConfiguration.getUri();
    String regex = "http://(.*)/consolidate";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(uri);
    if (matcher.find()) {
        result = matcher.group(1);
    }
    return result;
}

Edit: Should I change it to:

 if(matcher.find()) {
   return matcher.group(1);
 }
 return null;

The general question you ask "Which is better, "" or null?" is off-topic for CodeReview, but your code snippet has a number of reviewable items....

Regex Usage

Compiled Pattern performance

  String regex = "http://(.*)/consolidate";
  Pattern pattern = Pattern.compile(regex);
  Matcher matcher = pattern.matcher(uri);
  if(matcher.find()){
      result = matcher.group(1);
  }

This snippet makes it look like you know what you are doing, with the Pattern compile, etc. But, there is no performance benefit in the way you have done this. Compiled Java Pattern instances are thread-safe, and compiling them for one-time-use is not useful. It is common practice to make the Pattern a static-final field:

private static final Pattern MYPATTERN = Pattern.compile("http://(.*)/consolidate");

Then you can re-use that compiled pattern as much as you like, in any method, in any thread, like:

  Matcher matcher = MYPATTERN.matcher(uri);
  if(matcher.find()){
      result = matcher.group(1);
  }

find vs. matches

Now, matcher.find() and matcher.matches() are different methods.

find() will scan the input looking for any point inside the input where the pattern will match....
matches() does just one scan, and it matches the entire input string against the entire pattern.

With the input junkhttp://a/consolidate/junk:

find() will find your pattern
matches() will not find your pattern

The pattern

Now, as for the actual Regex... it appears that you want your pattern to match the HTTP 'host' against which you have the 'consolidate' path.... but, your pattern will match a lot of things which I would consider to be unexpected... for example, your pattern will return the following:

http://myhost/consolidate   from  http://http://myhost/consolidate/consolidate
myhost/consolidate          from  http://myhost/consolidate/consolidate
myhost:8080                 from  http://myhost:8080/consolidate
                            from  http:///consolidate

Each of the above input values will produce unexpected results.

Correct Regex

There is not a correct regex for matching URL's.... even if a regex appears that it will match, it is still not the correct solution ;-)

Solution

Use the java.net.URI class to validate your input. I have an example here, where I choose to return null if there is no configured URI, or throw an exception if there is a configured URI and that URI is not a valid value. This would be 'sensible' for many configurations, I expect.

public String getInfo() {
      String urival = clientConfiguration.getUri();
      if (urival == null || urival.isEmpty()) {
          return null;
      }
      try {
          URI uri = new URI(urival);
          return uri.getHost();
      } catch (URISyntaxException e) {
          throw new IllegalStateException("The configured URI is not valid: " + e.getMessage(), e);
      }
}


Checking against user input and returns a response based on that input How could I use enums in the following block of code to simplify it? The block is a program that has a command interpreter that returns different data based on user input. Is there a way I could easily apply enums and a match statement to the logic here?

use std::io;

fn main() {
    let version = String::from("0.0.1");
    let mut input = String::new();

    shell(&mut input, &version);
}

fn shell(input: &mut String, version: &String) {
    input.clear();
    match io::stdin().read_line(input) {
        Ok(b) => {
            if &input.trim() == &"ver" || &input.trim() == &"what are you" {
                println!("C ute R ust A mateur B eginner Shell ver: {}", version);
                shell(input, version);
            } else {
                println!("Command '{}' Not Recognized", input);
                shell(input, &version);
            }
        }
        Err(err) => panic!("incorrect"),
    }
}

Use rustfmt. I know the code you've presented is formatted correctly now, but that's because I reformatted it for you over on Stack Overflow (I wouldn't have touched it here).
Read and address the compiler's warning messages!

warning: unused variable: `b`
  --> src/main.rs:13:12
   |
13 |         Ok(b) => {
   |            ^ help: consider using `_b` instead
   |
   = note: #[warn(unused_variables)] on by default

warning: unused variable: `err`
  --> src/main.rs:22:13
   |
22 |         Err(err) => panic!("incorrect"),
   |             ^^^ help: consider using `_err` instead

warning: function cannot return without recursing
  --> src/main.rs:10:1
   |
10 | fn shell(input: &mut String, version: &String) {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot return without recursing
...
16 |                 shell(input, version);
   |                 --------------------- recursive call site
...
19 |                 shell(input, &version);
   |                 ---------------------- recursive call site
   |
   = note: #[warn(unconditional_recursion)] on by default
   = help: a `loop` may express intention better if this is on purpose

    Finished dev [unoptimized + debuginfo] target(s) in 2.16s
     Running `target/debug/playground`

Don't have infinite recursion; that's almost always a bad idea and you will run out of stack space. Write an infinite loop instead.
There's no reason to put input outside of the function, as it's only ever used inside it.
Use clippy. It will point out things like:

warning: writing `&String` instead of `&str` involves a new object where a slice will do.
 --> src/main.rs:9:19
  |
9 | fn shell(version: &String) {
  |                   ^^^^^^^ help: change this to: `&str`
  |
  = note: #[warn(clippy::ptr_arg)] on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg

warning: needlessly taken reference of both operands
  --> src/main.rs:15:16
   |
15 |             if &input.trim() == &"ver" || &input.trim() == &"what are you" {
   |                ^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: #[warn(clippy::op_ref)] on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
help: use the values directly
   |
15 |             if input.trim() == "ver" || &input.trim() == &"what are you" {
   |                ^^^^^^^^^^^^    ^^^^^

See also:

Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?

Use Result::expect instead of doing the match yourself. This has the beenfit of printing out the underlying error message as well.
Store the result of trim to avoid doing the work multiple times.
Consider using a match on the trimmed string to decide what to work on.

use std::io;

fn main() {
    let version = "0.0.1";

    shell(version);
}

fn shell(version: &str) {
    let mut input = String::new();
    loop {
        input.clear();
        io::stdin().read_line(&mut input).expect("incorrect");
        let input = input.trim();

        match input {
            "ver" | "what are you" => {
                println!("C ute R ust A mateur B eginner Shell ver: {}", version)
            }
            _ => println!("Command '{}' Not Recognized", input),
        }
    }
}

Now we can consider how best to use enums here. An enum is good for a type that can be one of many values. You have that structure in your "command" decisions. You could create an enum from those strings:

use std::io;

fn main() {
    let version = "0.0.1";

    shell(version);
}

fn shell(version: &str) {
    let mut input = String::new();
    loop {
        input.clear();
        io::stdin().read_line(&mut input).expect("incorrect");
        let command = input.trim().parse::<Command>();

        use Command::*;
        match command {
            Ok(Version) | Ok(WhatAreYou) => {
                println!("C ute R ust A mateur B eginner Shell ver: {}", version)
            }
            Err(_) => println!("Command '{}' Not Recognized", input),
        }
    }
}

#[derive(Debug)]
enum Command {
    Version,
    WhatAreYou,
}

impl std::str::FromStr for Command {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        use Command::*;
        Ok(match input {
            "ver" => Version,
            "what are you" => WhatAreYou,
            _ => return Err(()),
        })
    }
}


Fastest way to find if a lot numbers are in multiple intervals So I have a task. I've been given \$n\$ numbers and \$m\$ intervals and I need to figure out how many numbers are in the \$m\$ \$i\$-th interval. I've written some code with a complexity of \$O(n \times m)\$, though I need to optimize it more. Any help? Code:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    cin.tie(0);
    ios_base::sync_with_stdio(0);
    cout.tie(0);
    int n,m,temp,temp1;
    vector <pair<int, int>> uogienes;
    vector <int> erskeciai;

cin >> n >> m;
for (int i = 0; i< n; i++){
    cin>>temp;
    erskeciai.push_back(temp);
}
temp = 0;
for (int i = 0; i<m; i++){
    cin>> temp >> temp1;
    uogienes.push_back(make_pair(temp, temp1));
}
for(int i = 0; i<m; i++){
        temp=0;
    for(int h = 0; h<n; h++){
       if(uogienes[i].first <= erskeciai[h] && uogienes[i].second >= erskeciai[h]){
        temp++;
        }
    }
cout  << temp << "\n";
}
return 0;
}

Review

Please don't use using namespace; on the gobal scope. It's considered bad practice. Next, try to keep the scope of your variables smaller. Also indent your code properly to make it easier for you (and others) to see the program flow.

Don't include bits/c++. It's not a standard header. It's somewhat OK in programming challenges, but you should use the proper includes in your real/production code.

If you use a smaller scope for your variables, you will also be able to use better names for them, for example lower instead of temp and upper instead of temp1.

If we apply these changes (and translate your names into English), we end up with

#include <iostream>
#include <utility>
#include <vector>

int main()
{
    std::cin.tie(0);
    ios_base::sync_with_stdio(0);
    std::cout.tie(0);

    std::vector<std::pair<int, int>> ranges;
    std::vector<int> numbers;

    int number_count, range_count;

    std::cin >> number_count >> range_count;

    for (int i = 0; i < number_count; i++){
        int number;
        std::cin >> number;
        numbers.push_back(number);
    }

    for (int i = 0; i < range_count; i++){
        int lower, upper;
        std::cin >> lower >> upper;
        ranges.push_back({lower, upper});
    }

    for(int i = 0; i < range_count; i++){
        int count = 0;

        for(int h = 0; h <number_count; h++){
            if(ranges[i].first <= numbers[h] && ranges[i].second >= numbers[h]){
                count++;
            }
        }
        std::cout << count << "\n";
    }
    return 0;
}

It would be even better to use the proper types and more functions for I/O.

Performance

Instead of \$\mathcal O(nm)\$, you can get \$\mathcal O((n+m) \log n)\$ if you std::sort the numbers and then use std::lower_bound and std::upper_bound.


Endless stream: stream a range and return default value if the range is exhausted Introduction:

Motivation

Sometimes there is a need to merge N > 1 ranges, and they don't have equal length, but there is a value which can be used in case the range is already exhausted. It is especially apparent in this question, in which most of the complexity comes from handling the nullness of either or both lists.

Solution

The solution constitutes a parody to std::optional's value_or(), but being the only option to retrieve a value. The idea is that users don't care if it is value from the range or it is default value. The stream will keep issuing values from range, until iterator hits end iterator, then it will return default value.

Problems by design

Not modelled after standard library iterator

The problem lies in the ValueType. I don't want to apply greater constraints on it, other than being constructible and destructible. One would think that since there is next(), the value should copy/move constructible.

No support for std::vector<bool>

std::vector<bool> for C++ is like older versions of IE for javascript. To return dereferenced value from iterator, the reference must be constructible from outside of std::vector<bool>, but that is not possible, so no, no support for std::vector<bool>.

Not compatible with standard library at all

The reason is that I didn't see much usage and discussion about this, thus I decided to take opportunity to look at more usage examples, before making more concrete interface.

Code

#include <utility>
#include <iterator>

namespace shino {
template <typename InputIterator,
          typename Sentinel = InputIterator,
          typename ValueType = typename std::iterator_traits<InputIterator>::value_type>
class endless_stream {
    InputIterator first;
    Sentinel last;
    ValueType default_value;
public:
    template <typename ... ArgTypes>
    endless_stream(InputIterator first, Sentinel last, ArgTypes&& ... args) :
        first(first),
        last(last),
        default_value(std::forward<ArgTypes>(args)...)
    {}

    ValueType& next() {
        if (first == last) {
            return default_value;
        } else {
            return *first++;
        }
    }

    bool has_next() const {
        return first != last;
    }

    InputIterator current_position() const {
        return first;
    }

    Sentinel end() const {
        return last;
    }
};
}

Usage example

As it was born from this question, I thought that it would be only natural to target the problem in the demo on Wandbox:

using iterator = std::list<int>::iterator;
void add_digit_lists(shino::endless_stream<iterator> left,
                     shino::endless_stream<iterator> right,
                     std::list<int>& output) {
    bool has_carry = false;
    std::stack<int, std::vector<int>> prev_sums; //default is std::deque, not desired
    while (left.has_next() || right.has_next() || has_carry) {
        auto sum = left.next() + right.next() + has_carry;
        has_carry = false;
        if (sum > 9) {
            sum -= 10;
            has_carry = true;
        }
        prev_sums.push(sum);
    }

    while (not prev_sums.empty()) {
        output.push_back(prev_sums.top());
        prev_sums.pop();
    }
}

Concerns

Non-descriptive name of the class

One would need to read the docs to figure out the exact behavior of the facility. Is there a better one?

Is it C++14 compatible?

I tried to keep the code C++14 friendly, but still allow C++17 users to not type too much.

Is implicit class template argument deduction from constructor sufficient?

I'm worried that in some cases compiler won't be able to deduce some of the types if they are not provided and C++17 mechanism is used.

Any other suggestions are welcome.

Design

Iterator categories: You try to make sure to support InputIterator, but then expose current_position(). Since callers of that function can do anything with the returned iterator, including dereferencing and/or advancing it, for pure InputIterators this can invalidate first.
To support this, you'd need at least ForwardIterators, since they have to provide a multipass guarantee. As a side effect, it would fix the std::vector<bool> issue, since its iterator isn't complying to one of the ForwardIterator requirements: reference must be equal to value_type& or const value_type&.

Note: Just removing current_position wouldn't fix this, you'd also need to disable copying (same issue).

endless_stream interface: This is neither a range (doesn't contain begin() and end() member functions) nor an iterator. Instead, it looks like some range-like construct (maybe inspired from other languages?). As mentioned, this doesn't fit in well with usual standard library constructs.
Is there any specific reason this implementation doesn't orient itself on usual iterator semantics?

Is there any specific reason for allowing output operations, i.e. allowing modification of default_value? I'd think it wouldn't be too much of a restriction to only return const ValueType& from next (basically adhering to const_iterator semantics).

Implementation

Most member functions can be made conditionally noexcept.

Some names are off:

has_next: I'd expect that one to always return true for an infinte range. From the implementation, I guess something like end_reached or fully_traversed was meant.

end suggests there should be an begin, which there isn't (usually expected iterator semantics). I'd suggest renaming to end_iterator (or maybe last_iterator), or removing this function entirely.

current_position: The position irks me a bit, as an iterator doesn't always conceptually represent a position (e.g. in a generator). current_iterator might be better.

endless_stream isn't a stream as it would usually be understood in C++. Maybe it could be reworked into an infinite_filler_range (when matching the range criteria)?

There is no way to get the same value multiple times (since next always advances first, if possible). I'd suggest splitting this operation into two parts: advance() and value() (or current_value()).

member initializer list: The general advice is to prefer aggregate initialization (using {}) over direct initialization (using ()), unless the latter is absolutely required. So, first and last can and should use aggregate initialization, and default_value can go either way (though I prefer direct initialization in this case).

Usage example
I don't think an implementation detail like endless_stream should leak into the interface. Instead, it might be better to create those endless_stream instances inside of add_digit_lists, taking either iterators or const std::list<int>& as parameters.
Also, the output is in normal order, whereas the inputs are reversed. This might not be intended.


Solution to King Kohima problem in Python King Kohima problem:

  King Kohima has reserved a new exclusive street for his executive class employees where they can build their homes. He has assigned you to plan that street. You have to decide on which plots along the street are new building allowed to be built. In order to this, you first want to calculate the number of possible ways of assigning free plots to buildings while keeping in mind this restriction – No two consecutive plots can have buildings on them. This is done to ensure a sense of free space in the arena. The street is divided in M sections. Each section corresponds to 2 plots, one on each side of the street. Find the number of possible assignments.

  Input

  In the first line you’re given M ( M ≤ 1000 ). Output In the first and only line output the result/ Example Input: 3 Output: 25 Example explanation: If we just look at the one street side and mark X as a plot where building is allowed and Y as a free plot, we have: XYX, YXY, YYX, XYY, YYY. Since the same number exists on the other side, we have 5*5 = 25 combinations.

For example, if the input is 3, then only five layouts (YYY, YYX, YXY, XYY, XYX) of the eight possible combinations (YYY, YYX, YXX, YXY, XYY, XYX, XXY, XXX) are valid.  For both sides of the street, it's 5*5=25.

Please critique this solution.

def binary(i):
    r=str(0)
    while(i):
        x=str(i%2)
        if(x=='1' and r[-1]=='1'): #two consecutive X are not possible
            return None
        else:
            r=r+str(x)
        i=i/2
    return r
m=3 #input
l=[]
for i in range(0,2**m):
    l.append(binary(i)) #converted the number to binary
print(l)
c=0 #count possible plot available
for i in l:
    if i:
        c=c+1
print(c*c) #both side of the lane

There is a much faster solution to this problem. If the ending character is Y, two strings can be created. But if the ending character is X, only one valid string can be created: XY. This results in the following equation, complexity O(n):
def king_kohima(number: int) -> int:
    x = [0, 1, 1]
    y = [0, 1, 2]
    for i in range(3, number + 1): # Start at 3 so we skip results already stored.
        x += [y[i - 1]]
        y += [x[i - 1] + y[i - 1]]
    result = x[number] + y[number]
    return result * result

After benchmarking, this code is substantially faster than your original code.
Benchmarks:
Iterations king_kohima_op:      100     1.52433s
Iterations king_kohima:         100     0.00154s
Iterations king_kohima_op:      200     2.80376s
Iterations king_kohima:         200     0.00617s
Iterations king_kohima_op:      300     4.28752s
Iterations king_kohima:         300     0.01403s
Iterations king_kohima_op:      400     5.65897s
Iterations king_kohima:         400     0.02699s
Iterations king_kohima_op:      500     7.35554s
Iterations king_kohima:         500     0.04244s
Iterations king_kohima_op:      600     8.48669s
Iterations king_kohima:         600     0.06066s
Iterations king_kohima_op:      700     9.78000s
Iterations king_kohima:         700     0.08022s
Iterations king_kohima_op:      800     10.87804s
Iterations king_kohima:         800     0.10385s
Iterations king_kohima_op:      900     12.21734s
Iterations king_kohima:         900     0.13148s
Iterations king_kohima_op:      1000    13.80984s
Iterations king_kohima:         1000    0.16195s


Is this roulette selection extension method beautiful or disgusting? So I just wrote the following extension method to do roulette selection on a generic list. I'm specifically unsure of the use of the while loop. Is this beautiful or a disgusting mess?

// This is either yuck or beautiful
public static T rouletteSelect<T>(this List<T> list, Func<T, double> fitnessFunc, double max)
{
    T selected;
    while (fitnessFunc(selected = list.getRandom()) / max <= Rand.NextDouble()) { }
    return selected;
}

I am on the it's disgusting side.

I usually think at extension methods as something that could be useful by themselves. In your case you need to provide some external context with max, which could lead to confusing code. Who should be in charge of updating it? In my opinion you should have something that has both the responsibilities of keeping track of the current max values and to select the next one.

Also, I'm not sure if you're talking about this selection method, but there they divide the fitness value of an item by the sum of the fitness values of all the items, not by a maximum value.

You cannot test it. The calls to list.getRandom() and Rand.NextDouble() make it impossible. I'd rather make the dependencies on random number generators explicit.

As a matter of style I don't like having an empty body for a loop.

Given that you want to implement the selection method I linked earlier, I'd probably go for another different approach. I'm not sure yours actually implements it (but I have not looked at it for long enough to be sure it doesn't work as you would expect to).

public static T RouletteSelect<T>(this List<T> list, Func<T, double> fitnessFunction, double randomValue)
{
    var fitnessValues = list.Select(x => fitnessFunction(x));
    var totalFitness  = fitnessValues.Sum();
    var probabilities = fitnessValues.Select(x => x/totalFitness).ToList();
    var i = 0;
    var sum = probabilities[0];
    while(randomValue <= sum)
    {
      i = i + 1;
      sum += probabilities[i];
    }
    return list[i];
}


Optimizing game camera I'm moving some octagons around and I found a serious bottleneck:

@win.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    for o in octagons:
        o.vertices = tuple(chain.from_iterable( (o.vertices[i]+dx, o.vertices[i+1]+dy) for i in range(0, 18, 2)))

The program starts lagging when about 1000 points (111 octagons) are moved at once. I must find a way to optimize it but OpenGL is the last straw I want to draw because I don't want to use an API I don't understand. Could someone suggest a way to make it faster? Any internal solution or should I use NumPy? Here's the whole code (mere 30 lines) if you want to run it on your machine:

import pyglet
from circle import octagon
from random import randrange
from itertools import chain

SIZE = 800
RADIUS = 50
COUNT = 50
WIN = SIZE, SIZE, 'Camera', True, 'tool' # x, y, caption, resizable, style

def rnd_c():
    return (randrange(256), randrange(256), randrange(256)) * 9

def rnd_pos():
    return randrange(SIZE)

win = pyglet.window.Window(*WIN, vsync=False) # vsync off to unlimit FPS
batch = pyglet.graphics.Batch()
octagons = [octagon(rnd_pos(), rnd_pos(), RADIUS, rnd_c(), batch, None) for _ in range(COUNT)]
fps = pyglet.clock.ClockDisplay()

@win.event
def on_draw():
    win.clear()
    batch.draw()
    fps.draw()

@win.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    for o in octagons:
        o.vertices = tuple(chain.from_iterable( (o.vertices[i]+dx, o.vertices[i+1]+dy) for i in range(0, 18, 2)))

def on_step(dt):
    pass
pyglet.clock.schedule(on_step)

pyglet.app.run()

Graphics are fine (I think). I can render 1000 steady octagons @ 300 FPS.

NumPy is just plain awesome! Now I can move 3X more octagons without any lag at all! And it greatly shortens the length of lines so I can use more descriptive names, too! Here's the NumPy version:

import pyglet
import numpy as np
from circle import octagon
from random import randrange

R = 50
SIZE = 800
COUNT = 333 # NO LAG! RUNS @ >60 FPS!
WIN = SIZE, SIZE, 'Camera', True, 'tool' # x, y, caption, resizable, style

def clr():
    return (randrange(256), randrange(256), randrange(256)) * 9

def coord():
    return randrange(SIZE)

win = pyglet.window.Window(*WIN, vsync=False) # to unlimit FPS
batch = pyglet.graphics.Batch()
shapes = [octagon(coord(), coord(), R, clr(), batch, None) for _ in range(COUNT)]
coords = np.array( [shape.vertices for shape in shapes], dtype=int)
fps = pyglet.clock.ClockDisplay()

@win.event
def on_draw():
    win.clear()
    batch.draw()
    fps.draw()

@win.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    global coords
    for i, shape in enumerate(shapes):
        coords[i][::2] += dx
        coords[i][1::2] += dy
        shape.vertices = tuple(coords[i])

def on_step(dt):
    pass
pyglet.clock.schedule(on_step)

pyglet.app.run()