texts: Implement C++11 multipart sending without copying to a single buffer

texts:
I am working on a C++11 project and am migrating the underlying communications library used.

The original library allowed sending messages in multiple parts using a SNDMORE flag:

socket_->send(str_1, SNDMORE);
socket_->send(str_2, SNDMORE);
socket_->send(str_3); // The last message

and receiving them in multiple parts as well:

socket_->recv(&msg);
... // do stuff
while(msg.more()) {
    socket_->recv(msg);
... // do stuff
}

The new library does not have this functionality, so I ended up creating a struct that merges upto 3 strings and then merges and sends, receives and splits them as required.

/**
*
* Created helper methods to merge 3 strings into 1 and reverse
* This is a helper to group 3 messages in a single string.
*
**/

struct MultipartSplitMerge {
   #define PADDING 8
   static std::string merge(std::string *s1, std::string *s2, std::string *s3) {
       std::string size_1 = std::to_string((*s1).size()); std::string size_2 = std::to_string((*s2).size());
       std::string padded_size_1 = std::string(PADDING - size_1.length(), '0') + size_1;
       std::string padded_size_2 = std::string(PADDING - size_2.length(), '0') + size_2;
       std::string ret_str(padded_size_1 + padded_size_2 + *s1 + *s2 + *s3);
       return ret_str; // Add the size of each piece
   }

   static void split(std::string *s, std::string *o1, std::string *o2, std::string *o3) {
       unsigned int size_1 = std::stoi((*s).substr (0, PADDING));
       unsigned int size_2 = std::stoi((*s).substr (PADDING, PADDING));
       *o1 = (*s).substr(2 * PADDING, size_1);
       *o2 = (*s).substr(2 * PADDING + size_1, size_2);
       *o3 = (*s).substr(2 * PADDING + size_1 + size_2);
   }
};

Using this splitter/merger, I now send as follows:

std::string nullstr(""); // I use this to leave one of the parts empty
socket_->send(MultipartSplitMerge::merge(&h_array, &msg, &nullstr));

The receive code now works like this:

std::string combined, temp_1, temp_2, temp_3;
socket_->receive(&combined);
MultipartSplitMerge::split(&combined, &temp_1, &temp_2, &temp_3);

I'd like to avoid the unnecessary copies if possible, and also general guidelines on improving this code.

Here's the REPL to play with (or go to source):

<script src="//repl.it/embed/MFW8/0.js"></script>

Currently, we assume that there are 3 or less splits in every communication.


texts: Parsing hex and decimal numbers in C++11

texts:
The function arg_to_uint64 takes a 0-terminated string and returns an unsigned int. The unsigned int is the integer presentation of arg in decimal or in hex (if prefixed with 0x) as defined in the C language standard.

constexpr char hexprefix[]="0x";

inline std::uint64_t
arg_to_uint64(const char* arg)
{
   constexpr std::size_t hexprefix_len=sizeof(hexprefix)-1;
   bool is_hex=std::strncmp(arg,hexprefix,hexprefix_len)==0;
   int base;

   if(is_hex)
   {
      arg+=hexprefix_len;
      base=16;
   }
   else
      base=10;

   std::size_t idx;
   std::uint64_t r=std::stoull(arg,&idx,base);

   if(idx!=std::strlen(arg))
      throw std::runtime_error("garbage at the end of input");
   return r;
}

Is there a better/shorter way to do this? My platform is Linux.

This is my improved code as described in the answer from William Morris:

inline std::uint64_t
arg_to_uint64(const char* arg)
{
   std::size_t idx;
   std::uint64_t r=std::stoull(arg,&idx,0);

   if(arg[idx]!='\x0')
      throw std::runtime_error("garbage at the end of input");
   return r;
}


texts: Maintaining session timeout globally in java spring configuration

texts:
Below is my code to maintain a session timeout globally in Java spring configuration and to load the session timeout value from a properties file. Do you have any suggestions to improve my code?

public class MySessionListener implements HttpSessionListener {
    @Override
        public void sessionCreated(HttpSessionEvent event) {
            try {
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                InputStream stream = classLoader.getResourceAsStream("bimspring.properties");
                Properties properties = new Properties();
                properties.load(stream);
                String sessionTimeout = properties.getProperty("cookieName", "No Value Found");
                event.getSession().setMaxInactiveInterval(Integer.parseInt(sessionTimeout));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void sessionDestroyed(HttpSessionEvent event) {

        }

    }


texts: Styling and activating radio buttons on condition

texts:
I have some php code to style a button and activate it, when a specific variable is true.
It's actually a radio button, styled with the bootstrap to a button.
As you can see below, this is how it looks when the variable is '1'.
Also, the buttons at the bottom are the same, but then with one extra option.
The HTML code for this is the following:

                    Navigation bar color:

                <?php

                    if ($navcolor == '1') {
                        $nav_color_i_active  = 'active';
                        $nav_color_i_checked = 'checked';
                        $nav_color_n_active  = '';
                        $nav_color_n_checked = '';
                    } else {
                        $nav_color_i_active  = '';
                        $nav_color_i_checked = '';
                        $nav_color_n_active  = 'active';
                        $nav_color_n_checked = 'checked';
                    }
                ?>

                    <label class="btn btn-primary <?= $nav_color_i_active ?>">
                        <input type="radio" name="navcolor" value="1" <?= $nav_color_i_checked ?>> Inverted

                    <label class="btn btn-primary <?= $nav_color_n_active ?>">
                        <input type="radio" name="navcolor" value="0" <?= $nav_color_n_active ?>> Normal

Navigation bar position:

                    <?php
                        if ($navpos == '2') {
                            $nav_pos_2_active  = 'active';
                            $nav_pos_2_checked = 'checked';
                            $nav_pos_1_active  = '';
                            $nav_pos_1_checked = '';
                            $nav_pos_0_active  = '';
                            $nav_pos_0_checked = '';
                        } elseif ($navpos == '1') {
                            $nav_pos_2_active  = '';
                            $nav_pos_2_checked = '';
                            $nav_pos_1_active  = 'active';
                            $nav_pos_1_checked = 'checked';
                            $nav_pos_0_active  = '';
                            $nav_pos_0_checked = '';
                        } else {
                            $nav_pos_2_active  = '';
                            $nav_pos_2_checked = '';
                            $nav_pos_1_active  = '';
                            $nav_pos_1_checked = '';
                            $nav_pos_0_active  = 'active';
                            $nav_pos_0_checked = 'checked';
                        }
                    ?>

                        <label class="btn btn-primary <?= $nav_pos_2_active ?>">
                            <input type="radio" name="navpos" value="2" <?= $nav_pos_2_checked ?>> Floating

                        <label class="btn btn-primary <?= $nav_pos_1_active ?>">
                            <input type="radio" name="navpos" value="1" <?= $nav_pos_1_active ?>> Sticky to top

                        <label class="btn btn-primary <?= $nav_pos_0_active ?>">
                            <input type="radio" name="navpos" value="0" <?= $nav_pos_0_active ?>> Dynamic, stick to top

As you can see, it's a lot of code for not a lot of buttons. I've used empty variables, because otherwise php would return errors, for unknown variables.
Is it possible that this code can look a lot cleaner, and that there can be less code?


texts: Defining a simple function-calling operator

texts:
I have been writing Swift code for a while and have read a lot of tutorials about how functional paradigms can be applied to Swift.

I defined a simple operator:

infix operator >>> {associativity left}
func >>><A,B>(a: A?, f: A -> B?) -> B? {
    if let a = a {
        return f(a)
    } else {
        return .None
    }
}

Now for instance I am gonna populate a UITableViewCell instance from Core Data entity:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    func getWalks(dog: Dog) -> NSOrderedSet? {
        return dog.walks
    }

    func getWalkAtIndex(walks: NSOrderedSet) -> Walk? {
        return walks[indexPath.row] as? Walk
    }

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    func setUpCell(walk: Walk) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = .ShortStyle
        dateFormatter.timeStyle = .MediumStyle

        cell.textLabel.text = dateFormatter.stringFromDate(walk.date)
    }

    self.currentDog >>> getWalks >>> getWalkAtIndex >>> setUpCell

    return cell
}

I am creating a function for every step, though right now I am not good at separating steps but I kind of like this style of coding. What is your opinion about this?


texts: Need help with my code using a base class?

texts:
I my class hierarchy looks like this:

P
I : P
O : P

I have this method. The goal of this method is to return a new object of type I or O depending on a certain condition.

 public P GetP()
 {
    this.Session.Begin();

    var pDetail = GetPDetail();

    if (pDetail == null)
    {
        this.Session.Close();
        return null;
    }

    switch (pDetail.Code)
    {
        case "1":
            var i = new I();
            i.PDetail = pDetail;
            FillBaseP(i);
            FillI(i);
            this.Session.Close();
            return i;
        case "3":
            var o = new O();
            o.PDetail = pDetail;
            FillBaseP(o);
            FillO(o);
            this.Session.Close();
            return o;
        default:
            throw new Exception("Code is invalid");
     }
 }

I'm looking to rewrite this in a more logical way. Both case "1" and case "3" are doing some of the same work.

If I'm constantly checking type like If(var is O) or If(var is I) I feel as though I'm doing something wrong. Is this the case?


texts: knockout binding handler for custom components

texts:
I am using a combination of knockoutJS and jQuery. I have a number of jQuery plugins which perform particular re-usable functions, such as a numeric spinbox.

I have written a binding handler to allow me to bind an observable property to the spinbox, it looks like this:

ko.bindingHandlers.spinbox = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var value = valueAccessor();
        $(element).spinbox({
            min: value.min === undefined ? -5 : ko.unwrap(value.min),
            max: value.max === undefined ? 5 : ko.unwrap(value.max),
            scale: value.scale === undefined ? 2 : ko.unwrap(value.scale),
            step: value.step === undefined ? 0.1 : ko.unwrap(value.step),
            bigStep: value.bigStep === undefined ? 0.5 : ko.unwrap(value.bigStep)
        }).change(function() {
            value.data(parseFloat($(this).val()));
        });
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var value = valueAccessor();
        var valueUnwrapped = ko.unwrap(value.data);
        $(element).val(valueUnwrapped.toFixed(1));
    }
};

and requires the binding to be set up something like:

data-bind="spinbox: {data: myProperty, min: -100, max: 100}"

As you can see, I have used the object notation to sent multiple parameters to the binding (min, max etc) - this is similar to the syntax that the knockout template binding uses. However I am not sure this is a sensible way to do this. Should I have instead used allBindings and passed these along as separate values like:

data-bind="spinbox: myProperty, min: -100, max: 100"

I am interested in opinions on complex knockout custom bindings.


texts:
I am trying to setup an odds calculator for a best of 7 series, given independent odds for each event.

The following code works, but I would like to add recursion to simplify the end.

public class Game
{
    public int No { get; set; }
    public List<decimal> Odds;

    public Game(int no, decimal odd1, decimal odd2)
    {
        No = no;

        Odds = new List<decimal>();

        Odds.Add(odd1);
        Odds.Add(odd2);
    }

  }

void Main()
{

    var games = new List<Game>();

    var homeodd = .6m;
    var awayodd = .4m;

    var winningOdds = 0m;

//Add  7 games each with a different odd of winning game
    games.Add(new Game(1,homeodd,awayodd));
    games.Add(new Game(2,homeodd,awayodd));
    games.Add(new Game(3,awayodd,homeodd));
    games.Add(new Game(4,awayodd,homeodd));
    games.Add(new Game(5,awayodd,homeodd));
    games.Add(new Game(6,homeodd,awayodd));
    games.Add(new Game(7,homeodd,awayodd));

//game one has 2 possible outcomes, 0 = win, 1 = loss =>same for all 7 games
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            for (int k = 0; k < 2; k++)
            {
                for (int l = 0; l < 2; l++)
                {
                    for (int m = 0; m < 2; m++)
                    {
                        for (int n = 0; n < 2; n++)
                        {
                            for (int o = 0; o < 2; o++)
                            {
                                if ((i+j+k+l+m+n+o)<4)  //if we have loss less than 4 games, we have won the series and we want to add the odds of that possibility to the total odds
                                {
                                    winningOdds += games[0].Odds[i] * games[1].Odds[j] * games[2].Odds[k] * games[3].Odds[l] * games[4].Odds[m] * games[5].Odds[n] * games[6].Odds[o];
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    Console.WriteLine(winningOdds);
}


texts: Custom tableview cell for displaying different foods

texts:
I have a custom tableview cell for displaying different foods, with a star next to each name. If the food has been favorited (i.e., it exists in the database), the star is filled in, otherwise it is empty.  I'm not sure if the logic that determines the color of the star should go in the view controller or the tableviewcell.

Currently, I have this in the view controller under didSelectRowForIndexPath:

cell.foodLabel.text= food.name;
if ([cell isStarredForName:food.name])
        [cell changeStarToState:StateFull];
else
        [cell changeStarToState:StateEmpty];

Also, I use this cell in two different view controllers, so I have to use the code above twice.

In the cell, I have:

- (BOOL) isStarredForName:(NSString*)foodName {

    PFInstallation *installation = [PFInstallation currentInstallation];
    NSArray *foodList = (NSArray*)[installation objectForKey:@"favorites"];
    return ([foodList containsObject:foodName]);
}

- (void)changeStarToState:(StarState)state{
    NSString *imgName;
    if (state == StateEmpty){
        imgName = @"star_none.png";
        _currentState = StateEmpty;
    }
    else {
        imgName = @"star_full.png";
        _currentState = StateFull;
    }
    [self.favButton setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];

}

I'm wondering if it's better to just have a [cell handleStarColor] function in the viewcontroller and have the cell decide whether it needs to fill in the star.


texts:
In an effort to keep all of the Google Maps Javascript API in it's own little world, I have created a googleMaps object that will contain all of the functions that directly make google maps webservice calls.  This object will be imported once on every page.  For now, it only has one function.

if (googleMaps === undefined || googleMaps === null)
{
  var googleMaps = {

    /**
    * Obtains the latitude and longitude of a location and then processes it with a callback function
    * @param {String} addressStr : comma separated string containing all pertinent address information
    * @param {Function} callback : handle to the function to call once the data lat/lng data has been retrieved successfully
    */
    getLatLngFromAddressString : function(addressStr, callback)
    {
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({'address': addressStr}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK)
        {
          var latitude = results[0].geometry.location.lat();
          var longitude = results[0].geometry.location.lng();
          callback({lat: latitude, lng: longitude});
        }
        else {
          // I have a custom error logging framework set up, but for simplicity i'll just console.log in code review snippet
          console.log("error");
        }
      });
    }
  }
}

In a separate file, I will call this function from verifyLocation(), shown below:

var showLocationCallback = function(loc)
{
  var latitude = loc.lat;
  var longitude = loc.lng;

  //other not important, totally unrelated processing stuff here
}

/**
 * makes a google maps geocode request for the provided address string
 */
function verifyLocation(addressStr)
{
  document.getElementById('verify-location').disabled = true;

  var location = googleMaps.getLatLngFromAddressString(addressStr, showLocationCallback);

}

I'm looking to get this bit of code reviewed.  I'm looking for any and all improvements, including:

making the code more efficient
rethinking the logic
completely restructuring the way I'm approaching this
best coding practices / naming conventions
-


texts: HackerEarth Challenge Find Maximum Taste of Fruits

texts:
Problem Statement:

  Samu had got N fruits. Sweetness of ith fruit is given by A[i]. Now
  she wants to eat all the fruits , in such a way that total taste is
  maximised.

  Total Taste is calculated as follow (Assume fruits sweetness array
  uses 1-based indexing) :

int taste=0;
for(int i=2;i<=N;i++){
    if (A[i]-A[i-1] >= 0){
       taste = taste + i*(A[i]-A[i-1]);
    }
    else{
       taste = taste + i*(A[i-1]-A[i]);
    }
}

  So, obviously the order in which she eat the fruits changes the Total
  taste. She can eat the fruits in any order. Also once she start eating
  a fruit she will finish that one before moving to some other fruit.

  Now she got confused in deciding the order in which she should eat
  them so that her Total taste is maximized. So she ask for help from
  you. Help her find the maximum taste she can have , if she can eat the
  fruits in any order.

  Input Format:

  First line contain number of test cases T. First line of each test
  case contains N, denoting the number of fruits. Next line contain N
  space separated integers denoting the sweetness of each fruit.

  Output Format:

  For each test case you need to print the maximum taste Samu can have
  by eating the fruits in any order she want to.

  Constraints:

  \$1 \le T \le 10\$   \$1 \le N \le 15\$

  Sweetness of each fruit, A[i] lies between 1 to 100 for 1 ≤ i ≤ N

  Sample Input:

1
3
2 5 4

  Sample Output:

13

  Explanation:

[2,4,5] -> 2*(2) + 3*(1) = 7
[2,5,4] -> 2*(3) + 3*(1) = 9
[5,4,2] -> 2*(1) + 3*(2) = 8
[5,2,4] -> 2*(3) + 3*(2) = 12
[4,5,2] -> 2*(1) + 3*(3) = 11
[4,2,5] -> 2*(2) + 3*(3) = 13

  The maximum is 13 that can be obtained by eating the fruits according to
  sweetness order [4,2,5].

from itertools import permutations
for _ in xrange(int(raw_input())):
    n=int(raw_input())
    val=map(int,raw_input().split())
    max_ = 0
    for A in permutations(val):
        taste=0;
        for i in xrange(1,len(A)):
            taste = taste + (i+1)*abs(A[i]-A[i-1])
        max_= max(max_,taste)
    print max_


texts:
This is code for filtering the data of webpage, for the web crawler I made for my project. I know python scripts can lag than other languages, but this takes a lot of time when processing even a single page.

I don't want to use any other external libraries for filtering content. Is there any way my current code can be improved to be cleaner and faster?

# -*- coding: utf-8 -*-
import urllib
url='http://designingadam2.wordpress.com'
def content(page,url):#FILTERS THE CONTENT OF THE REMAINING PORTION
    flg=0
    #REMOVES &nsbp LIKE CHARACTERS
    while page.find("&",flg)!=-1:
        page.replace('&nbsp;','')
        start=page.find("&",flg)
        end=page.find(";",start+1)
        if (end-start)<10:  #USED IF HERE TO CNFRM TAGS-->REMOVE IF NOT NEEDED
            pageO=page[:start]
            pageT=page[end+1:]
            page=pageO+pageT
            flg=start+1#TO CONTINUE FROM NEXT POS
        else:
            flg+=1
    flg=0

    #REMOVES CONTENT BETWEEN SCRIPT TAGS
    while page.find("<script",flg)!=-1:
            start=page.find("<script",flg)
            end=page.find("</script>",flg)
            end=end+9
            i,k=0,end-start
            page=list(page)
            while i<k:
                    page.pop(start)
                    i=i+1
            page=''.join(page)
            flg=start

    #REMOVES CONTENT BETWEEN STYLE TAGS
    flg=0
    while page.find("<style",flg)!=-1:
            start=page.find("<style",flg)
            end=page.find("</style>",flg)
            end=end+9
            i,k=0,end-start
            page=list(page)
            while i<k:
                    page.pop(start)
                    i=i+1
            page=''.join(page)
            flg=start

    #REMOVES THE TAGS
    s_list = list(page)
    i,j = 0,0
    while i < len(s_list):
            # find the <
            if s_list[i] == '<':
                while s_list[i] != '>':# and i!=(len(s_list)-1):
                    # remove everything between the < and the >
                    s_list.pop(i)

                # make sure we get rid of the > to
                s_list.pop(i)
            else:
                i=i+1
    #-------------------------------------------------------------------

    #REMOVES WHITESPACES
    s_list="".join(s_list)
    lst=s_list.split()
    #CONVERT TO LOWERCASE
    i=0
    while i<len(lst):
        lst[i]=lst[i].lower()
        i+=1

    #REMOVES DUPLICATES
    lst=list(set(lst))

    #REMOVE COMMON WORDS
    phrase=['to','a','an','the',\
            'for','from','that','their',\
            'i','my','your','you','mine',\
            'we','okay','yes','no','as',\
            'if','but','why','can','now',\
            'are','is','also',',','.',';',\
            ':','?','|','/','\n','\t']

    i=0
    while i<len(lst):
        if lst[i] in phrase:
            lst.pop(i)
        else:
            i+=1
    print lst
    print len(lst)

def pageContent(url):#EXTRACTS HTML CODE
    f = urllib.urlopen(url)
    page = f.read()
    f.close()
    #page=page.replace(u'\xa0', ' ').encode('utf-8','ignore')
    return page

page=pageContent(url)
content(page,url)

Please mind the comments. I left it so it could be of some help.


texts: Dynamic homepage with PHP - making things too complicated?

texts:
I am trying to show the 6 most popular products on my homepage from left to right, in two rows. My code actually works... but I have the feeling I am making things way too complicated. Is there a simpler way to do this?

Here is my code:

$dynamicList = "";
$sql = mysql_query("SELECT * FROM products ORDER BY popularity DESC LIMIT 6");
$productCount = mysql_num_rows($sql); //Count the output amount
if($productCount>0){
    $currentRow=0;
    $dynamicListLeft='
';
    $dynamicListMiddle='
';
    $dynamicListRight='
';
    while($row=mysql_fetch_array($sql)){
            $currentRow=$currentRow+1;
            $id = $row["id"];
            $product_name = $row["product_name"];
            $date_added=strftime("%b %d, %Y", strtotime($row["date_added"]));

            if($currentRow==1 || $currentRow==4) {
                $dynamicListLeft .='

';
            } else {
                    if($currentRow==2 || $currentRow==5) {
                        $dynamicListMiddle .='

';
                    } else {
                            if($currentRow==3 || $currentRow==6){
                                $dynamicListRight .='

';
                            }
                        }
                }

        }
        $dynamicListLeft .='
';
        $dynamicListMiddle .='
';
        $dynamicListRight .='
';
        $dynamicList .=$dynamicListLeft;
        $dynamicList .=$dynamicListMiddle;
        $dynamicList .=$dynamicListRight;

}

Later on in my body I echo the dynamiclist.

I hope somebody can show me the way to make this smoother?

Thanks!


texts: ”check” function – OK to throw in destructor?

texts:
My goal is to provide a function with the following functionality:

// Will throw iff a != 42.
check(a == 42) << a << " is not equal to 42!";

I have the following:

class check
{
public:
    check(bool everything_OK = false)
        : should_throw{!everything_OK}
    { }

    check(const check&) = delete;

    ~check() noexcept(false)
    {
        if (should_throw && !uncaught_exception()) {
            throw runtime_error(stream.str());
        }
    }

    template<typename T>
    check& operator << (T&& t)
    {
        if (!should_throw) {
            return *this;
        }

        stream << std::forward<T>(t);
        return *this;
    }

private:
    const bool should_throw;
    stringstream stream;
};

The thing is, all guidelines I have read forbid throwing in the destructor. I have also read experts saying they do not know of a good use of std:uncaught_exception. Can I still achieve what I want?

ADDITION:
Loki’s point below can be fixed by defining a macro:

#define my_check(expr) (expr) ? ((void)0) : check(false)

But once we allow ourselves to use macros, there are other solutions provided below.


texts: Efficiently detect datacenter based on server hostname

texts:
In our company we have a machine hostname as  -

dbx111.dc1.host.com
dbx112.dc2.host.com
dcx113.dc3.host.com

Here dc1, dc2, dc3 are our datacenter and we will be having only three datacenter. But it might be possible that they can have more dots in between separated by another domain.

Now I need to find in which datacenter my current machine is in. I will be running below code in some machine as shown above.. And below code will tell me which datacenter my code is running in. But is there any way to modify the below code to make it more efficient? I guess we can write this much better -

String datacenter = getCurrentDatacenter();

private String getCurrentDatacenter(){

    String s_hostName = null;;
    try {
        s_hostName = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
        s_logger.debug(LogLevel.ERROR+"\t"+e.getStackTrace().toString());
    }

    if (s_hostName != null && !s_hostName.isEmpty()){

        s_hostName.toUpperCase();
        if (s_hostName.contains(DatacenterEnum.DC1.name())){
            currentDatacenter = DC1;
        }
        else if (s_hostName.contains(DatacenterEnum.DC2.name())){
            currentDatacenter = DC2;
        }
        else if (s_hostName.contains(DatacenterEnum.DC3.name())){
            currentDatacenter = DC3;
        }
    }

    return currentDatacenter;
}

Below is my ENUM -

public enum DatacenterEnum {
    DC1, DC2, DC3;

    private static final Map<Integer, DatacenterEnum> BY_CODE_MAP = new LinkedHashMap<Integer, DatacenterEnum>();

    static {
    for (DatacenterEnum rae : DatacenterEnum.values()) {
        BY_CODE_MAP.put(rae.ordinal(), rae);
    }
    }

    public static String forCode(int code) {
    return BY_CODE_MAP.get(code).name();
    }
}


texts:
The Art and Science of Java, a course book that uses the ACM library, has an exercise that reads like this:

  Implement a new class called Card that includes the following entries:

  • Named constants for the four suits (CLUBS, DIAMONDS, HEARTS, SPADES)
  and the four ranks that are traditionally represented in words (ACE,
  JACK, QUEEN, KING). The values of the rank constants should be 1, 11,
  12, and 13, respectively.

  • A constructor that takes a rank and a suit and returns a Card with
  those values. • Accessor methods getRank and getSuit to retrieve the
  rank and suit components of a card.

  • An implementation of the toString method that returns the complete
  name of the card.

Now, this question is a little hard to understand, but nevertheless I've done a class that I think answers this:

/** Ficheiro: Carta.java
*
* Classe que vai representar os diferentes valores e naipes de uma carta de um baralho normal
* de 52 cartas. Exercício para construir uma classe completa juntamente com construtores,
* gets de Valores e Naipes e de método toString.  */

public class Carta {

// Constantes do Naipe (Rank) das Cartas
public static final String AS = "Ás";
public static final String REI = "Rei";
public static final String DAMA = "Dama";
public static final String VALETE = "Valete";

// Constantes do Valor Facial (Suit) das Cartas
public static final String COPAS = "Copas";
public static final String PAUS = "Paus";
public static final String OUROS = "Ouros";
public static final String ESPADAS = "Espadas";

/**
* Cria uma nova carta de um baralho regular de 52 cartas.
* @param valor O valor facial da carta (ex. Ás, Rei, 10...)
* @param naipe O naipe da carta
*/

public Carta (int valor, int naipe) {
    valorCarta = valor;
    numNaipe = naipe;
}

/**
 * Obtém o valor facial da carta (existem 13 valores faciais)
 * @return O valor facial da carta em String
 */

public String getValorCarta() {
    switch (valorCarta) {
    case 1: return AS;
    case 11: return REI;
    case 12: return DAMA;
    case 13: return VALETE;
    default: return "" + valorCarta;
    }
}

/**
 * Obtém o naipe da carta (existem 4 naipes)
 * @return O naipe da carta em String
 */

public String getNaipeCarta () {
    switch (numNaipe) {
    case 1: return COPAS;
    case 2: return PAUS;
    case 3: return OUROS;
    case 4: return ESPADAS;
    default: return ("Naipe Inválido");
    }
}

/**
 * Cria uma representação em String da Carta (Valor e Naipe)
 * @return Representação em String da Carta (Valor e Naipe)
 */

public String toString () {
    return getValorCarta() + " de " + getNaipeCarta();
}

// variáveis de instância que registam o Valor e o Naipe da Carta em integers.
private int valorCarta;
private int numNaipe;
}

Sorry about the commentaries.  I speak Portuguese and I've written the commentaries in that language. I hope the code is easy enough to understand.

I want to know if I have written well the class, according to specifications, especially the Public Constants and the Get Methods.

I am not sure if they wanted me to make the constants int types instead of Strings. Also I didn't assign any parameters to the Get Methods, so they will only give me the rank or suit of a new Card Object. I am not sure if they wanted me to attribute an int param to these methods.

As a sidenote, I wrote a short program that demonstrates this class in action, in choosing and displaying a random card (note that the run method is the main method in acm libraries):

import acm.program.*;
import acm.util.*;

public class testeCarta extends ConsoleProgram{

// Escolhe uma carta aleatóriade um baralho de 52 cartas e imprime no ecrã
public void run () {
    println ("Este programa vai seleccionar uma carta aleatória");
    Carta cartaAleat = new Carta (rGen.nextInt(1,13),rGen.nextInt(1,4));
    println (cartaAleat);
}

// variável de instància que permite a utilização de gerador de números aleatórios
public RandomGenerator rGen = RandomGenerator.getInstance();
}


texts:
I have been working on a script that automatically checks on the state of 2 services that I require to be running 24/7 on a server that I manage.

The script works as I need, but I would really like to optimize it if possible.
Specifically, I find that I want a way to reduce the need to type the command:

$(ps -ef | grep -v grep | grep zabbix_agentd | wc -l)

and

$(ps -ef | grep -v grep | grep zabbix_server | wc -l)

Any other feedback is greatly appreciated, I am new to bash scripting and trying to find the best way to get this to be as optimal as possible!

#!/bin/bash
zabbix_server="service zabbix-server"
zabbix_agent="service zabbix-agent"
logfile=/etc/scripts/zabbix/zabbix_auto_restart.log
zabbix_server_running=0
zabbix_agent_running=0

check_zabbix_agentd (){
        if (( $(ps -ef | grep -v grep | grep zabbix_agentd | wc -l) <= 0 ))
        then
           $zabbix_agent start
           echo `date` "$zabbix_agent was stopped... Restarting" >> $logfile
           echo "************************************************" >> $logfile

           #Send email to notify that the script ran
           echo "$(date) $zabbix_agent was restarted from zabbix_restart.sh" | mutt -s "Zabbix Auto-restart Script Just Ran" <admin email address>

        else
           let zabbix_agent_running=1
        fi
}

check_zabbix_server (){
        if (( $(ps -ef | grep -v grep | grep zabbix_server | wc -l) <= 0 ))
        then
           $zabbix_server start
           echo `date` "$zabbix_server was stopped... Restarting" >> $logfile
           echo "************************************************" >> $logfile

           #Send email to notify that the script ran
           echo "$(date) $zabbix_server was restarted from zabbix_restart.sh" | mutt -s "Zabbix Auto-restart Script Just Ran" <admin email address>

        else
           let zabbix_server_running=1
        fi
}

main_loop (){
        until ((zabbix_server_running == 1 && zabbix_agent_running == 1));
        do
            check_zabbix_agentd
            check_zabbix_server
            sleep 1.5
        done
}

main_loop


texts:
I built an app that allows users to add and remove images in a collection view. I want this to be useful online so I save the images into a database and retrieve them every time. I'm looking for constructive criticism on how I solved this problem. It is in swift. The code works just fine, but I notice some lag sometimes, and it may be because of the way I designed the software. This is why I'm looking for criticism.

ViewGallery.swift

import UIKit
import Firebase
import DKImagePickerController

class ViewGallery: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

let db = Firebase(url: "mydatabaseurl")
@IBOutlet var collectionView: UICollectionView!

 var imageDatas: [String] = []
 var selectedItems: [NSIndexPath] = []
 var keys: [AnyObject] = []

 override func viewDidLoad() {
  super.viewDidLoad()
  db.childByAppendingPath("Images").observeEventType(.Value, withBlock: {
    snapshot in
    let images = snapshot.value as! NSDictionary
    self.keys = images.allKeys
    self.imageDatas = []
    for key in self.keys {
      self.imageDatas.append(images[key as! NSString as String]!["image"] as! String)
    }
    self.selectedItems = []
    self.collectionView.reloadData()
  })
}

@IBAction func addPictures(sender: AnyObject) {
  let pickerController = DKImagePickerController()

  pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in
    print("didSelectAssets")
    for asset in assets {
      let imageData = asset.rawData?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
      self.saveImageStringToDatabase(imageData!)
    }
  }

  self.presentViewController(pickerController, animated: true, completion: nil)
}

@IBAction func removePicture(sender: AnyObject) {
  for indexPath in selectedItems {
    db.childByAppendingPath("Images").childByAppendingPath(self.keys[indexPath.item] as! String).removeValue()
  }
}

func saveImageStringToDatabase(imageString: String) {
  let value = ["image": imageString]
  db.childByAppendingPath("Images").childByAutoId().setValue(value)
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  if imageDatas.count == 0 {
    return 0
  } else {
    return imageDatas.count
  }
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
  if imageDatas.count == 0 {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("View Gallery Cell", forIndexPath: indexPath)
    return cell
  } else {
    let base64String = self.imageDatas[indexPath.item]
    let imageData = NSData(base64EncodedString: base64String, options: .IgnoreUnknownCharacters)
    let decodedImage = UIImage(data: imageData!)
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("View Gallery Cell", forIndexPath: indexPath) as! ImageCell
    cell.imageView.image = decodedImage
    return cell
  }
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
  let cell = self.collectionView.cellForItemAtIndexPath(indexPath) as! ImageCell
  if selectedItems.contains(indexPath) {
    print("unselected")
    cell.backgroundColor = UIColor.clearColor()
    let indexToBeDeleted = selectedItems.indexOf(indexPath)
    selectedItems.removeAtIndex(indexToBeDeleted!)
  } else {
    print("selected")
    cell.backgroundColor = UIColor.redColor()
    selectedItems.append(indexPath)
  }
}

}


texts:
I'm studying functional programming, and I have the following problem to solve. It's an simplified version of Caesars Cipher:

You need to write a function, which will take string encoded with Caesar cipher as a parameter and decode it.
The one used here is ROT13 where the value of the letter is shifted by 13 places. e.g. 'A' ↔ 'N', 'T' ↔ 'G'.
You have to shift it back 13 positions, such that 'N' ↔ 'A'.

I made the following implementation:

const head = (str) => str[0];
const tail = (str) => str.slice(1);
const code = (str) => str.charCodeAt(0);

const rot13 = (str) => str ? (code(str) < 65 || code(str) > 90) ? head(str).concat(rot13(tail(str))) : String.fromCharCode((((code(str) - 65)) + 13) % 26 + 65).concat(rot13(tail(str))) : '';

It works fine, I only want to know if there is performance issues, and what can I do to improve my code?


texts: Rotating an array by mentioned digit to rotate

texts:
I have developed the program to rotate the array in java request you to please check it and let me know if there are any flaws in it or where further it can be improved

    package com.dataStructures.Arrays;

// Java program for reversal algorithm of array rotation
//Let the array be arr[] = [1, 2, 3, 4, 5, 6, 7], d =2 and n = 7
//        A = [1, 2] and B = [3, 4, 5, 6, 7]
//
//        Reverse A, we get ArB = [2, 1, 3, 4, 5, 6, 7]
//        Reverse B, we get ArBr = [2, 1, 7, 6, 5, 4, 3]
//        Reverse all, we get (ArBr)r = [3, 4, 5, 6, 7, 1, 2]

import java.util.Arrays;

class ArrayRotate {

    static void leftRotate(int[] arr, int d) {

        if (d == 0)
            return;
        int n = arr.length;
        reveresArray(arr, 0, d - 1);
        reveresArray(arr, d, n - 1);
        reveresArray(arr, 0, n - 1);
    }

    static void reveresArray(int[] arr, int start, int end) {
        int temp;
        while (start < end) {
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    static void printArray(int[] arr) {
        Arrays.stream(arr).mapToObj(item -> item + " ").forEach(System.out::print);
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        int n = arr.length;
        int d = 2;
        leftRotate(arr, d); // Rotate array by d
        printArray(arr);
    }
}


texts: Basic calculator that takes 2 numbers and does an operation with them

texts:
The code works perfectly fine for me (compiled it in BlueJ and Eclipse) but I was wondering what other more experienced programmers thought of it. I'd specifically like to know if it could be shorter or be made more resource efficient.

    /**
* This program is just a simple addition calculator that can use whole numbers or decimals.
*
* @author Christopher Goodburn
* @version 6/4/2016
*/
import java.util.Scanner;
import java.math.*;

public class Calculator
{
private static final Scanner askScanner = new Scanner(System.in);
public static double answer;
public static double firstNumber;
public static double secondNumber; //makes variables for the whole class

public static void main(String[] args) {
    calculator();
}

    public static void calculator() {

    System.out.println("Basic calculator");
    System.out.println("Pick one:");
    System.out.println("1. Addition");
    System.out.println("2. Subtraction");
    System.out.println("3. Multiplication");
    System.out.println("4. Division");
    int pick = askScanner.nextInt();

    if(pick == 1) {
        addition();
    }
    else if(pick == 2) {
        subtraction();
    }
    else if(pick == 3) {
        multiplication();
    }
    else if(pick == 4) {
        division();
    }
    else {
        System.out.println("You need to choose 1, 2, 3, or 4");
        calculator();
    }
    askScanner.close();
}

    private static double getNumbers() {
        System.out.println("First number?");
        firstNumber = askScanner.nextDouble();
        System.out.println("Second Number?");
        secondNumber = askScanner.nextDouble();
        return firstNumber;
    }

    public static void subtraction() {
        System.out.println("Subtraction");
        getNumbers();
        answer = firstNumber - secondNumber;
        System.out.println("This is the difference of the two numbers:  " + answer);
        calculator();
    }

    public static void addition() {
       System.out.println("Addition");
       getNumbers();
       answer = firstNumber + secondNumber;
       System.out.println("This is the sum of the two numbers:  " + answer);
       calculator();
    }

    public static void multiplication() {
        System.out.println("Multiplication");
        getNumbers();
        answer = firstNumber * secondNumber;
        System.out.println("This is the product of the two numbers  " + answer);
        calculator();
    }

    public static void division() {
        System.out.println("Division");
        getNumbers();
        answer = firstNumber / secondNumber;
        System.out.println("This is the quotient of the two numbers:    " + answer);
        calculator();
    }

}


texts:
I have written the following meta-tags for SEO, please let me know if you think this could use any improvement. I have used this article to help me put it together. I have left out the page content on purpose, if you wish to see it I posted it here on CR and on Github (note the following updates have not been committed yet, they are only in my local directory).

<!DOCTYPE html>
<html class="" lang="en" itemscope itemtype="http://schema.org/Organization"> <!-- Schema.org is for Google+ meta-data - See other meta-tags within head section) -->
  <head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/favicon.ico" />

    <!-- META-TAGS -->

      <!-- Standard meta-tags -->
      <title>Cardshifter TCG</title>
      <meta name="description" content="Try Cardshifter trading card game (TCG), an open source multiplayer game!" />
      <meta name="author" content="https://github.com/Cardshifter" />
      <link rel="author" href="https://github.com/Cardshifter" />
      <link rel="publisher" href="https://github.com/Cardshifter" />

      <!-- Google+ Schema.org tags -->
      <meta itemprop="name" content="Cardshifter Trading Care Game">
      <meta itemprop="description" content="Try Cardshifter trading card game (TCG), an open source multiplayer game!">
      <meta itemprop="image" content="/images/cardshifter-logo.png">

      <!-- Facebook OpenGraph tags -->
      <meta property="og:title" content="Cardshifter Trading Care Game" />
      <meta property="og:type" content="website" />
      <meta property="og:image" content="/images/cardshifter-logo.png" />
      <meta property="og:url" content="http://www.CardShifter.com/" />
      <meta property="og:description" content="Try Cardshifter trading card game (TCG), an open source multiplayer game!" />
      <meta property="fb:admins" content="USER_ID" />  <!-- NEED TO MAKE USER ID FOR CARDSHIFTER -->

      <!-- Twitter tags -->
      <meta property="twitter:card" content="summary" />
      <meta property="twitter:url" content="https://twitter.com/Cardshifter" />
      <meta property="twitter:title" content="Cardshifter Trading Care Game" />
      <meta property="twitter:description" content="Try Cardshifter trading card game (TCG), an open source multiplayer game!" />
      <meta property="twitter:image" content ="/images/cardshifter-logo.png" />

    <!-- Bootstrap core CSS -->
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="cardshifter.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>
    <!-- page content removed -->
  </body>
</html>


texts:
In relation to the question I asked here, I myself came up with an answer. I would like constructive criticism and tips to improve it to make it efficient like the other answers that have been posted.

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

int main() {
    std::vector<int> job_list;
    std::set<std::vector<int>> permutations;
    for (unsigned long i = 0; i < 7; i++) {
        int job;
        std::cin >> job;
        job_list.push_back(job);
    }
    std::sort(job_list.begin(), job_list.end());
    std::vector<int> original_permutation = job_list;
    do {
        std::next_permutation(job_list.begin(), job_list.end());
        permutations.insert(std::vector<int>(job_list.begin(), job_list.begin() + 3));
    } while (job_list != original_permutation);

    for (auto& permutation : permutations) {
        for (auto& pair : permutation) {
            std::cout << pair << " ";
        }
        std::endl(std::cout);
    }

    return 0;
}


texts: Counting the number of consecutive 1's in binary

texts:
hackerrank.com Task:

  Given a base-10 integer, n, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation.

This question has already been answered but it was in Ruby and I couldn't quite understand the concept, I am just starting to code. What can you suggest me to improve on this piece of code? I think its quite long considering the work it does or is this the efficient solution?

count = 0
max_value = 1

if __name__ == '__main__':
    n = int(input())
    binary_num = bin(n).split("b")
    binary_num = binary_num[1]
    print(binary_num)
    for index, i in enumerate(binary_num):
        if i == "1":
            count += 1
            next_item = index + 1
            while next_item < len(binary_num):
                if binary_num[next_item] == "1":
                    count += 1
                    counter = count
                    temp = counter
                    next_item += 1
                    if temp > max_value:
                        max_value = temp
                else:
                    counter = count
                    count = 0
                    break
        if next_item == (len(binary_num)):
            break

    print("count is =",max_value)


texts: Experienced ruby programmer starting with Java

texts:
I'm a ruby programmer who's writing Java for university. I'd love to get some feedback on how my Java looks and how to improve it to conform with the norms.

import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;

public class Cell {
  private Set<Integer> possibles;
  private List<CellGroup> groups;

  public Cell() {
    this.possibles = new HashSet<Integer>(java.util.Arrays.asList(1,2,3,4,5,6,7,8,9));
    this.groups = new ArrayList<CellGroup>();
  }

  public void register_cell_group(CellGroup group) {
    this.groups.add(group);
  }

  public void set(Integer number) {
    // Make the only possibile the set number
    this.possibles = new HashSet<Integer>();
    this.possibles.add(number);

    this.inform_groups();
  }

  public void not(Integer number) {
    this.possibles.remove(number);

    if (this.possibles.size() == 1) {
      this.inform_groups();
    }
  }

  public boolean is_solved() {
    return this.possibles.size() == 1;
  }

  private void inform_groups() {
    for (int i = 0; i < this.groups.size(); i++) {
      this.groups.get(i).cell_solved(this, this.possibles.toArray(new Integer[0])[0]);
    }
  }
}


texts:
I've written a Sudoku puzzle generator. It currently runs through each line of the 9x9 grid and places numbers randomly if they're valid. It loops over all the numbers from 1-9 and then if it finds itself trapped in a corner with no valid answers it throws out the whole board and restarts.

I tested it by making 1000 puzzles and it took just under 100 seconds, so a single puzzle takes 0.1. In practical terms that's almost negligible but still seems wasteful to ditch the processing up to that point (as it takes, on average, hundreds of attempts to find a valid puzzle). I'm maybe just being impractical to want a more intelligent solution so I thought I'd ask how it looks to people on here and if anyone has suggestions on improving it.

import random
numbers = [1,2,3,4,5,6,7,8,9]

def makeBoard():
    board = None
    while board is None:
        board = attemptBoard()
    return board

def attemptBoard():
    board = [[None for _ in range(9)] for _ in range(9)]
    for i in range(9):
        for j in range(9):
            checking = numbers[:]
            random.shuffle(checking)
            x = -1
            loopStart = 0
            while board[i][j] is None:
                x += 1
                if x == 9:
                    #No number is valid in this cell, start over
                    return None
                checkMe = [checking[x],True]
                if checkMe in board[i]:
                    #If it's already in this row
                    continue
                checkis = False
                for checkRow in board:
                    if checkRow[j] == checkMe:
                        #If it's already in this column
                        checkis = True
                if checkis: continue
                #Check if the number is elsewhere in this 3x3 grid based on where this is in the 3x3 grid
                if i % 3 == 1:
                    if   j % 3 == 0 and checkMe in (board[i-1][j+1],board[i-1][j+2]): continue
                    elif j % 3 == 1 and checkMe in (board[i-1][j-1],board[i-1][j+1]): continue
                    elif j % 3 == 2 and checkMe in (board[i-1][j-1],board[i-1][j-2]): continue
                elif i % 3 == 2:
                    if   j % 3 == 0 and checkMe in (board[i-1][j+1],board[i-1][j+2],board[i-2][j+1],board[i-2][j+2]): continue
                    elif j % 3 == 1 and checkMe in (board[i-1][j-1],board[i-1][j+1],board[i-2][j-1],board[i-2][j+1]): continue
                    elif j % 3 == 2 and checkMe in (board[i-1][j-1],board[i-1][j-2],board[i-2][j-1],board[i-2][j-2]): continue
                #If we've reached here, the number is valid.
                board[i][j] = checkMe
    return board

def printBoard(board):
    spacer = "++---+---+---++---+---+---++---+---+---++"
    print (spacer.replace('-','='))
    for i,line in enumerate(board):
        print ("|| {} | {} | {} || {} | {} | {} || {} | {} | {} ||".format(
                    line[0][0] if line[0][1] else ' ',
                    line[1][0] if line[1][1] else ' ',
                    line[2][0] if line[2][1] else ' ',
                    line[3][0] if line[3][1] else ' ',
                    line[4][0] if line[4][1] else ' ',
                    line[5][0] if line[5][1] else ' ',
                    line[6][0] if line[6][1] else ' ',
                    line[7][0] if line[7][1] else ' ',
                    line[8][0] if line[8][1] else ' ',))
        if (i+1) % 3 == 0: print(spacer.replace('-','='))
        else: print(spacer)


texts: XSS Protection from Query Strings in Java

texts:
Looking for input on the code below. Generally, the idea is to take a String representing a URL query string such as param1=blah&param2=blah and encode them to protect against possible XSS attack. Using existing utilities (i.e. UrlEncodedUtils) is not an option.

public static Map<String, List<String>> getParamsFromQueryString(String queryString) throws UnsupportedEncodingException {

    Map<String, List<String>> params = new HashMap<>();

    for (String param : queryString.split("&")) {
        String[] pair = param.split("=");
        String key = ESAPI.encoder().encodeForHTML(URLDecoder.decode(pair[0], "UTF-8"));
        String value = "";
        if (pair.length > 1) {
            value = ESAPI.encoder().encodeForHTML(URLDecoder.decode(pair[1], "UTF-8"));
        }

        // skip ?& and &&
        if ("".equals(key) && pair.length == 1) {
            continue;
        }

        List<String> values = params.get(key);
        if (values == null) {
            values = new ArrayList<>();
            params.put(key, values);
        }
        values.add(value);
    }

    return params;
}


texts: Is this a proper callback implementation in Java?

texts:
I have a code which I believe is callback implementation. Can you please provide your more experienced opinions on whether this is a good way to callback?

public interface Callback {
    void run();
}

Test of callback with anonymous function

public class Test {
    static void method (Callback callback){
        callback.run();
    }

    public static void main(String[] args) {
        method(new Callback() {
            @Override
            public void run() {
                System.out.println("Printed!");
            }
        });
    }
}


texts:
as I was reading the Git Internals in the Pro Git book, I decided to see what objects I need to create to have the short hash say something funny. To do this, I have written the following code:

messages = ['badcafe','deaddad','badbeef','feedbac']
possible_letters = string.ascii_lowercase + string.ascii_uppercase + ' '

def getHash(data):
    return hashlib.sha1(str("blob " + str(len(data)) + "\0" + data).encode('utf-8')).hexdigest()

def populate(n):
    for data in product(possible_letters, repeat=n):
        s = getHash(''.join(data))[0:7]
        if s in messages:
            print(s,data)

Unfortunately, this is too slow for n > 4. For smaller n, it only finds badcafe. Is there any way to speed this up?


texts: Refactor Oxford Comma function (and other functions)

texts:
I wrote a program that managed projects and created a set of SQL files for each project. In the logic, I have a few functions that, each time I look at them, I wonder if they could be written in a better way. They are pretty straight forward and compact, however I feel like there are better, more efficient ways of computing their results.

I would appreciate any comments on coding style or improvements (either in readability or performance) that you may have.

Oxford Comma

This function takes a list as input then passes an Oxford comma-separated string off to another function:

# >>> obj._format_missing_message(['a','b','c'])
# 'a, b, and c'
def _format_missing_message(self, missing):
        length = len(missing)

        # Show the message if needed
        if length > 0:
            and_clause = '{} and '.format('' if length <= 2 else ',')
            message = and_clause.join([', '.join(missing[:-1]), missing[-1]])
            self._tab_pane.currentWidget().update_status(
                                            "Configs not found for: {}.".format(message))

SQL 'LIKE' String Creator

This next function takes a list of string inputs then finds the SQL LIKE syntax that recognizes all of the list:

import difflib

# >>> create_sql_regex(['123','124','125'])
# '12%'
def create_sql_regex(ids):
    ''' Creates a SQL regex from a list of strings for use in LIKE statement '''
    longest_match = ''

    # Raise an error if there is only one item in the list as there needs to be at least two
    # items to create the regex.
    length = len(ids)
    if length <= 1:
        raise NotEnoughComparisonData(
                 'Not enough data to compare. Passed list length: {}'.format(length))

    # Create the SequenceMatcher and loop through each element in the list, comparing it and
    # the previous item.
    matcher = difflib.SequenceMatcher()
    for item, next_item in zip(ids[:-1], ids[1:]):
        matcher.set_seqs(item, next_item)
        long_match = matcher.find_longest_match(0, len(item), 0, len(next_item))

        # If the match is shorter than the previous longest match or if we have not found
        # a match yet, store the match
        if long_match.size < len(longest_match) or longest_match == '':
            longest_match = item[long_match.a:long_match.a + long_match.size]

    # If not match was found, raise an error
    if longest_match == '':
        raise NoMatchFound('A match could not be found in this list: {0}'.format(ids))

    return '{}%'.format(longest_match)

Count Duplicates

This function is the simplest of the three. It takes a list as input and returns a hash that holds the count of each unique item found in the list:

# >>> count_duplicates(['a','a','b'])
# {'a':2, 'b':1}
def count_duplicates(values):
    counts = {}

    for val in values:
        if val in counts:
            counts[val] += 1
        else:
            counts[val] = 1

    return counts


texts: Switch / Dictionary containing multiple values with same keys

texts:
I have different strings that will return different integers, though some strings have the same value (usually 4 per code).

I used a Dictionary first, and still have them, but it's kinda messy. I also tried using switch, which is basically the same to me in this case.

Here are two examples:

public static int PPCFloatCalc4RegistersSwitch(string code)
    {
        switch (code)
        {
            case "fsel": return 23;
            case "fsel.": return 23;
            case "fmul": return 25;
            case "fmul.": return 25;
            case "fm": return 25;
            case "fm.": return 25;
            case "fmuls": return 25;
            case "fmuls.": return 25;
            case "fms": return 28;
            case "fms.": return 28;
            case "fmsub": return 28;
            case "fmsub.": return 28;
            case "fmsubs": return 28;
            case "fmsubs.": return 28;
            case "fmadd": return 29;
            case "fmadd.": return 29;
            case "fma": return 29;
            case "fma.": return 29;
            case "fmadds": return 29;
            case "fmadds.": return 29;
            case "fnmsub": return 30;
            case "fnmsub.": return 30;
            case "fnmsubs": return 30;
            case "fnmsubs.": return 30;
            case "fnmadd": return 31;
            case "fnmadd.": return 31;
            case "fnmadds": return 31;
            case "fnmadds.": return 31;
        }

        return -1;
    }

    public static readonly Dictionary<string, int> PPCFloatCalc4RegistersDictionary = new Dictionary<string, int>
    {
        ["fsel"] = 23,
        ["fsel."] = 23,
        ["fmul"] = 25,
        ["fmul."] = 25,
        ["fm"] = 25,
        ["fm."] = 25,
        ["fmuls"] = 25,
        ["fmuls."] = 25,
        ["fms"] = 28,
        ["fms."] = 28,
        ["fmsub"] = 28,
        ["fmsub."] = 28,
        ["fmsubs"] = 28,
        ["fmsubs."] = 28,
        ["fmadd"] = 29,
        ["fmadd."] = 29,
        ["fma"] = 29,
        ["fma."] = 29,
        ["fmadds"] = 29,
        ["fmadds."] = 29,
        ["fnmsub"] = 30,
        ["fnmsub."] = 30,
        ["fnmsubs"] = 30,
        ["fnmsubs."] = 30,
        ["fnmadd"] = 31,
        ["fnmadd."] = 31,
        ["fnmadds"] = 31,
        ["fnmadds."] = 31,
    };

As you can see, it's repetitive, which is kinda bad for readability. It's worth noting that performance is a bit needed here, so switch/Dictionary speed would be great.

I don't think I need to add any more examples be cause the functions pretty much show what it does quite clearly.


texts: Splitting a string into words or double-quoted substrings

texts:
For various reasons, I'm parsing a string, this code will explain what I'm after:

string baseString = "This is a \"Very Long Test\"";

string[] strings = baseString.Split(' ');

List<String> stringList = new List<string>();
string temp = String.Empty;
foreach (var s in strings)
{
    if (!String.IsNullOrWhiteSpace(temp))
    {
        if (s.EndsWith("\""))
        {
            string item = temp + " " + s;
            stringList.Add(item.Substring(1,item.Length - 2));
            temp = string.Empty;
        }
        temp = temp + " " + s;
    }
    else if (s.StartsWith("\""))
    {
        temp = s;
    }
    else
    {
        stringList.Add(s);
    }

}

stringList.ForEach(Console.WriteLine);

The output should be:

This
is
a
Very Long Test

Basically, given a string, it will split it on spaces, unless its grouped into speech marks, the same way the command line does it.

Any better way to do this code?


texts: Generic dynamic array implementation in C

texts:
I'm working on my own generic-type dynamic array in C99 and I would like to hear your input, suggestions, ideas, anything!

What I most care about is: 1) correctness and 2) performance.

So far, I've tested both with standard malloc and mimalloc, although with the standard implementation it seems to be running 50% faster.

I've also ran benchmarks against libsrt, vec and Nim's implementation of dynamic sequences and my code seems to be beating them all.

Also, of major importance is to note that this code is not meant to be used as a library, but as part of a bytecode VM/intepreter that I've been working on - which means I am the one who is going to use it.

Here's the source:

#ifndef __VARRAY_H__
#define __VARRAY_H__

/**************************************
  Type definitions
 **************************************/

#define Array(TYPE) \
    struct { \
        size_t size; \
        size_t cap; \
        size_t typeSize; \
        TYPE *data; \
    }

/**************************************
  Macros
 **************************************/

#define aInit(DEST,TYPE,CAP) { \
    int k=0;                                                                \
    while (powerOfTwo[++k]<CAP);                                            \
                                                                            \
    DEST = malloc(sizeof(Array(TYPE)));                                     \
    DEST->size = 0;                                                         \
    DEST->typeSize = sizeof(TYPE);                                          \
    DEST->cap = powerOfTwo[k];                                              \
    DEST->data = calloc(DEST->cap, DEST->typeSize);                         \
}

#define aNew(NAME,TYPE,CAP) \
    Array(TYPE)* NAME;                                                      \
    aInit(NAME,TYPE,CAP);

#define aResize(DEST) { \
    DEST->cap *= 2;                                                         \
    DEST->data = realloc(DEST->data, DEST->cap * DEST->typeSize);           \
}

#define aAdd(DEST,X) \
    if (++(DEST->size) >= DEST->cap) aResize(DEST);                         \
    DEST->data[DEST->size-1] = X

#define aAppend(DEST,X) \
    DEST->cap += X->cap;                                                    \
    DEST->data = realloc(DEST->data, DEST->cap * DEST->typeSize);           \
    memcpy(DEST->data + DEST->size, X->data, X->size * X->typeSize);        \
    DEST->size += X->size

#define aEach(DEST,INDEX) \
    for (int INDEX=0; INDEX<DEST->size; INDEX++)

#define aFree(DEST) \
    free(DEST->data);                                                       \
    free(DEST)

#endif

The powerOfTwo lookup constant:

/**************************************
  Constants
 **************************************/

static size_t powerOfTwo[] = {
    0,
    1, 2, 4, 8, 16, 32, 64, 128,
    256, 512, 1024, 2048, 4096, 8192, 16384, 32768,
    65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608,
    16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648,
    4294967296, 8589934592, 17179869184, 34359738368, 68719476736, 137438953472, 274877906944, 549755813888
};

And a little usage example:

Array(int)* arr;
aInit(arr,int,0);
aAdd(arr,0);
aAdd(arr,1);

aEach(fastArr,i) {
    printf("item @ %d = %d\n",i,arr->data[i]);
}

aFree(arr);


texts: Counting K-mers (words) in a sequence string

texts:
I recently found out how to use joblib for parallelization.  I want to iterate through this string seq in steps of 1 and count the number that word is seen.  I thought this would be really fast but for larger files it still takes long.

How could I make this word counter faster?

def iterSlice(seq, start_idx, end_idx):
    """
    Slice sequence
    """
    return seq[start_idx:end_idx]

def countKmers(seq, K=5, num_cores=multiprocessing.cpu_count()):
    """
    Count kmers in sequence
    """
    start_indices = np.arange(0, len(seq) - K + 1, step=1)
    end_indices = start_indices + K
    list_of_kmers = Parallel(n_jobs=num_cores)\
                        (delayed(iterSlice)\
                             (seq=seq, start_idx=start_idx, end_idx=end_idx)\
                                 for start_idx,end_idx in zip(start_indices,end_indices))
    return Counter(list_of_kmers)

seq = "ABCDBBBDBABCBDBABCBCBCABCDBACBDCBCABBCABDCBCABCABCABDCBABABABCD"
countKmers(seq=seq, K=3, num_cores=8)

Counter({'ABA': 2,
         'ABB': 1,
         'ABC': 7,
         'ABD': 2,
         'ACB': 1,
         'BAB': 5,
         'BAC': 1,
         'BBB': 1,
         'BBC': 1,
         'BBD': 1,
         'BCA': 6,
         'BCB': 3,
         'BCD': 3,
         'BDB': 2,
         'BDC': 3,
         'CAB': 6,
         'CBA': 1,
         'CBC': 4,
         'CBD': 2,
         'CDB': 2,
         'DBA': 3,
         'DBB': 1,
         'DCB': 3})

10 loops, best of 3: 186 ms per loop


texts:
I have the algorithm which splits DateTime range into multiple ranges based on night time range.
For example:
Night start: 22:00, Night end: 06:00
Start time: 2020-10-26 21:00:00 End time: 2020-10-27 07:00:00
Expected output:

2020-10-26 21:00:00 - 2020-10-26 22:00:00
2020-10-26 22:00:00 - 2020-10-27 06:00:00
2020-10-27 06:00:00 - 2020-10-27 07:00:00

It basically splits DateTime range by day and night/to day/night batches.
I wonder if there's something I could do to make the code shorter and possibly better performance-wise.
Code:
internal class Helper
{
    public static readonly TimeSpan NightStartTime = new TimeSpan(22, 0, 0);
    public static readonly TimeSpan NightEndTime = new TimeSpan(6, 0, 0);

    public static bool IsNightTime(TimeSpan time) => time >= NightStartTime || time < NightEndTime;
    public static bool IsDayTime(TimeSpan time) => !IsNightTime(time);
}

internal class Program
{
    private static void Main(string[] args)
    {
        var startTime = DateTime.Parse("2020-10-26 21:00:00");
        var endTime = DateTime.Parse("2020-10-27 07:00:00");

        DateTime? currentStartTime = startTime;
        DateTime? currentEndTime = null;
        var currentTimeIsDayTime = Helper.IsDayTime(startTime.TimeOfDay);
        for (var currentTime = startTime; currentTime <= endTime; currentTime = currentTime.AddMinutes(1))
        {
            var isDayTime = Helper.IsDayTime(currentTime.TimeOfDay);
            if (currentTimeIsDayTime != isDayTime)
            {
                currentEndTime = currentTime;
                currentTimeIsDayTime = isDayTime;
            }

            if (currentTime == endTime)
            {
                currentEndTime = endTime;
            }

            if (currentStartTime != null && currentEndTime != null)
            {
                Console.WriteLine($"{currentStartTime} - {currentEndTime}");

                currentStartTime = currentEndTime;
                currentEndTime = null;
            }
        }
    }
}


texts:
Write a program to implement stack which implements min a method
  which gives the minimum element below the top element in the stack.

const items = Symbol('Stack items');

class Stack {
  constructor() {
    this[items] = [];
  }

  pop() {
    return this[items].pop();
  }

  push(data) {
    this[items].push(data);
  }

  size() {
    return this[items].length;
  }

  isEmpty() {
    return this.size() === 0;
  }

  peek() {
    return this[items][this.size() - 1];
  }
}

class MinStack {
  constructor(iterable) {
    this.stack = new Stack();
    this.minStack = new Stack();
    if (iterable) {
      for (let val of iterable) {
        this.push(val);
      }
    }
  }

  min() {
    if (this.stack.isEmpty()) {
      throw new Error('Min of empty stack');
    }
    return this.minStack.peek();
  }

  pop() {
    if (this.stack.isEmpty()) {
      throw new Error('Popping from empty stack');
    }
    let val = this.stack.pop();
    if (val === this.minStack.peek()) {
      this.minStack.pop();
    }
    return val;
  }

  push(data) {
    if (this.minStack.isEmpty() && this.stack.isEmpty()) {
      this.minStack.push(data);
    } else if (data <= this.minStack.peek()) {
      this.minStack.push(data);
    }
    this.stack.push(data);
  }

  size() {
    return this.stack.size();
  }

  isEmpty() {
    return this.stack.isEmpty();
  }

  peek() {
    return this.stack.peek();
  }
}

const s = new MinStack();

console.log('//  Empty Stack  //');
try {
  console.log(s.min()); // Err
} catch (err) {
  console.log('Err: ' + err.message);
}

console.log('// Non-Empty Stack  //');
s.push(1);
s.push(2);
s.push(3);

console.log(s.pop() === 3);
console.log(s.min() === 1);
console.log(s.pop() === 2);
console.log(s.min() === 1);
console.log(s.pop() === 1);
try {
  console.log(s.min()); // Err
} catch (err) {
  console.log('Err: ' + err.message); // Err
}

console.log('// Using iterator  //');

const s2 = new MinStack([3, 2, 5, 1]);
console.log(s2.min() === 1);
console.log(s2.pop() === 1);
console.log(s2.min() === 2);
console.log(s2.pop() === 5);
console.log(s2.min() === 2);
console.log(s2.pop() === 2);
console.log(s2.min() === 3);
console.log(s2.pop() === 3);

/*
Space complexity: O(2n) ~ O(n)

Time complexities:
1. Construction
   Iterator: O(n) else O(1)
2. Push
   O(1) for both stacks
3. Pop
   O(1) for both stacks
4. Min
   O(1)
5. Size
   O(1)
6. isEmpty
   O(1)
*/


texts: Implementation of getUsersWithStatuses based on getUsersWithStatus

texts:
In my code I have method which gets users from database with concrete status. And now I have to add new method which gets users from database with list of statuses. I don't know, is it better to create new repository method or reuse existing code.

I created example method "getUsersWithStatuses" which reuse old method "getUsersWithStatus". But, is it good that this method read data from database in loop?

@Transactional(readOnly = true)
public List<UserDTO> getUsersWithStatus(Long locationId, UserDTO.Status status) {
    List<User> userList = userRepository.findByLocationWithStatus(locationId, orderStatus);
    return userMapper.asDTOs(userList);
}

//new functionality
@Transactional(readOnly = true)
public List<UserDTO> getUsersWithStatuses(Long locationId, EnumSet<UserDTO.Status> statuses) {
    List<UserDTO> result = new LinkedList<>();
    statuses.forEach(status -> result.addAll(getUsersWithStatus(locationId, status)));
    return result;
}


texts:
I started writing a new framework in C# which can be used for any server development. It contains the basic stuff, such as database, TCP and configuration. I did write the configuration last night and I would love to get some constructive criticism and tips on it.

I know I didn't document the code yet, planning on doing it once I'm 100% happy with it.

First off, we have the BaseConfiguration class. This class is basically the base (superclass) of all configuration modules.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;

namespace AuroraFramework.Configuration
{
    public abstract class BaseConfiguration
    {
        private readonly string filePath;
        private JObject jsonSettings;

        protected BaseConfiguration(string filePath)
        {
            this.filePath = filePath;
            ReadFile();
        }

        private void ReadFile()
        {
            StreamReader reader = new StreamReader(filePath);

            jsonSettings = JsonConvert.DeserializeObject<JObject>(reader.ReadToEnd());
        }

        protected T Get<T>(string key)
        {
            return jsonSettings[key].Value<T>();
        }
    }
}

What it does is simple. It reads the file you pass down in the constructor, and 'converts' it into a JObject. That JObject is used to get values from. Then the Get function is used to get values from the JObject and return it in the right datatype. The reason I chose for this is to have more control than when I use JsonConvert.DeserializeObject<TYPE>(string).

The whole class is used to it's easy to implement new configuration modules without reading the whole file on your own and without writing much code.

Next, we have the DatabaseConfiguration class, which is simply one of the configuration modules in the framework.

namespace AuroraFramework.Configuration.Types
{
    public class DatabaseConfiguration : BaseConfiguration
    {
        public string Server { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string Database { get; set; }

        public DatabaseConfiguration()
            : base("db.settings.json")
        {
            Server = Get<string>("server");
            Username = Get<string>("username");
            Password = Get<string>("password");
            Database = Get<string>("database");
        }
    }
}

This simply uses the BaseConfiguration class as superclass. This will let the superclass read the file and convert it to a JObject. The only thing for the configuration module itself to do is call the Get function on every property.

And then, you use DatabaseConfiguration dbConfig = new DatabaseConfiguration() in the framework and pass it down to the classes that need to use the configuration.


texts:
I've created a decorator in my Rails application. However, the initializer has 3 params. Is this generally acceptable in decorator or should I refactor this or try a different pattern?

class FileBinderDecorator
  attr_reader :binder, :credential, :page

  def initialize(binder, credential, page = 1)
    @binder = binder
    @credential = credential
    @page = page
  end

  def file_items
    file_items = credential.file_item_list(excluded_ids: binder.file_items.pluck(:id))
    file_items.page(page).per(7)
  end

  def method_missing(method_name, *args, &block)
    @binder.send(method_name, *args, &block)
  end

  def missing_responds_to?(method_name, include_private = false)
    @binder.respond_to?(method_name, include_private) || super
  end
end

manage.html.slim

.modal.binder-modal.fade data-selected-ids=[] [id="edit-files-modal"]
  .modal-dialog
    .modal-content
      .modal-header
        button.close aria-label="Close" data-dismiss="modal" type="button"
          span aria-hidden="true"  &times;
        h4.modal-title Edit Files
      .modal-body
        .container-fluid
          .row-fluid
            .credentials
              = select_tag 'credentials', options_from_collection_for_select(credentials_for_current_user_and_account(current_user, @account), :first, :last)
              .selectors
                .file-box-select-all
                  = link_to 'Select All', '#'
                .file-box-deselect-all
                  = link_to 'Deselect All', '#'
          .row-fluid
            .list-group[class="binder-#{decorator.id}"]
              = render partial: 'file_binders/filebox', locals: { file_items: decorator.file_items, binder: decorator.binder, credential: decorator.credential }
          .row-fluid
            .text-center
              .pagerx[class="pager-#{decorator.id}"]
                = render partial: 'file_binders/pager', locals: { file_items: decorator.file_items, binder: decorator.binder, credential: decorator.credential }
      .modal-footer
        button.add-selected.btn.btn-primary class="add-selected-#{decorator.id}" data-dismiss='modal' data-count=0 data-file-items=[]
          | Remove Selected
        button.btn.btn-cancel aria-label="Close" id="modalCloseButton#{decorator.id}" data-dismiss="modal" type="button" aria-hidden="true" Cancel


texts: Longest non-decreasing subsequence, in Haskell

texts:
OK, so I recently posted this solution in Python to the longest non-decreasing subsequence problem, and cleaned it up with some expert advice.  As a next step, I wanted to translate this solution into Haskell.  This presents a challenge because the algorithm as originally formulated depends heavily on mutable arrays with O(1) lookup and update behavior, which are standard in Python but a little harder to come by in Haskell.

Some excellent answers on Stackoverflow pointed me towards Data.Seq as a mutable, indexable array type, and Numeric.Search.Range for a generic binary search operation (which is key to making the algorithm efficient).

I wanted to express this algorithm as a fold over the input list because that seemed like a natural way to do it.  However the Python version depends on many O(1) lookups to arbitrary places in the input list - not really possible within a Haskell fold over an ordinary list.  I saw that this could be avoided by, rather than doing what the Python version does - namely storing indices into the input array of "the best subsequence of length n found so far" - storing the best actual subsequence as a Haskell list.  At first sight, this seems incredibly wasteful, because at the end of the calculation for an input list of length n there could be as many as n "best subsequence" lists which are on average n / 2 long, creating space requirements of order n^2!  However, since these are Haskell lists derived from each other, they actually share a lot of the same space... for example, in the case where the input list is already a non-decreasing list of length n, the calculation will involve creating n subsequence lists of lengths [1..n], but each one shares a tail with its predecessor and the total space requirement is just proportional to n.

The code is below.  What I am looking for is: 1) general comments on readability, correctness, etc. and 2) a way to prove an upper bound on the space requirement.

import Data.Sequence as DS
import Numeric.Search.Range

seqLast::Seq a -> a
seqLast xs = index xs ((DS.length xs) - 1)

-- Return the longest non-decreasing subsequence of an input sequence of integers
nonDecreasing::[Int]->[Int]
nonDecreasing = Prelude.reverse . seqLast . makeM
  where makeM = foldl updateM empty
          where updateM m x | DS.null m = singleton [x]
                            | insert_idx == Nothing = m |> (x:(seqLast m))
                            | just_insert_idx == 0 = update 0 [x] m
                            | otherwise = update just_insert_idx (x:(index m (just_insert_idx - 1))) m
                  where insert_idx = searchFromTo (\idx -> x < (head (index m idx))) 0 ((DS.length m) - 1)
                        just_insert_idx = maybe 0 id insert_idx


texts: Concurrent Stack with blocking and non-blocking methods

texts:
I wrote it this just for learning. Is there holes at this code?

public interface ConcurrentStack<T> {
    //blocking
    void put(T t) throws InterruptedException;

    //blocking
    T poll() throws InterruptedException;

    //non-blocking put
    boolean offer(T t);

    //non-blocking get
    T take();
}

class ConcurrentStackImpl<T> implements ConcurrentStack<T> {
    private volatile AtomicBoolean locked = new AtomicBoolean(false);
    private List<T> internalList = new ArrayList<T>();
    private final int maxSize; // this final mandatory? I am afraid about visibility

    public ConcurrentStackImpl(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException();
        }
        this.maxSize = maxSize;
    }

    @Override //blocking
    public void put(T t) throws InterruptedException {
        while (!locked.compareAndSet(false, true)) ;//busy waiting
        internalList.add(t);
        locked.set(false);
    }

    @Override // non-blocking
    public T poll() throws InterruptedException {
        while (!locked.compareAndSet(false, true)) ;//busy waiting
        T value = internalList.get(internalList.size() - 1);
        locked.set(false);
        return value;
    }

    @Override
    public boolean offer(T t) {
        if (locked.compareAndSet(false, true)) {

            if (internalList.size() >= maxSize) {
                return false;
            }
            boolean addResult = internalList.add(t);
            locked.set(false);
            return addResult;
        }
        return false;
    }

    @Override
    public T take() {
        if (locked.compareAndSet(false, true)) {
            T t = internalList.get(internalList.size() - 1);
            locked.set(false);
            return t;
        }
        return null;
    }

}


texts: Merge Sort Implementation and Optimization

texts:
This is Merge Sort that i implemented, i feel i can make it better esp the combination function.
So i split the code into functions because i don't like seeing a bunch of spaghetti code in a single function. I have the combination logic which combines the left and right array such lower elements go first.
def combine(left:list, right:list): #Combines both paths
    left.append(float('inf')) #So the Array is never empty
    right.append(float('inf')) #and the final element to compare is large

    combined_list = []
    while len(left) !=1 or len(right) != 1:
        if left[0] < right[0]:
            combined_list.append(left.pop(0))
        else:
            combined_list.append(right.pop(0))

    return combined_list

Next i have this recursive function which calls itself and combination logic then after reducing the array into singular pieces then returns the bigger sorted chunks and hence final array is hence sorted.
def merge_sort(array:list):
    half_length = len(array)//2
    left = array[:half_length]
    right = array[half_length:]

    if len(left) > 1:
        left = merge_sort(left)
    if len(right) > 1:
        right = merge_sort(right)

    return combine(left, right)

print(merge_sort([1,2,8,5,2,4,6,9,4,2]))

I feel that left.append(float('inf')) is a hack around, is there a better way of doing it spiting it into functions.


texts:
I have created a function that will take as a parameter a StorageFile and return a WriteableBitmap. I use this data type so that I can later encode the image into a base64 string.

My concern is with the intermediary BitmapImage that I create to get the original dimensions. Any other improvements would be welcomed as well.

Also, it should be noted that this is Windows 10 Universal code, so I am unable to use the System.Drawing libraries.

public static async Task<WriteableBitmap> ScaledWImage(StorageFile file, int maxWidth, int maxHeight)
{
    WriteableBitmap newImage;

    using (var fileStream = await file.OpenReadAsync())
    {
        var bitmap = new BitmapImage();
        bitmap.SetSource(fileStream);
        var origHeight = bitmap.PixelHeight;
        var origWidth = bitmap.PixelWidth;
        var ratioX = maxWidth / (float)origWidth;
        var ratioY = maxHeight / (float)origHeight;
        var ratio = Math.Min(ratioX, ratioY);
        var newHeight = (int)(origHeight * ratio);
        var newWidth = (int)(origWidth * ratio);

        if (ratio > 1)
        {
            newHeight = origHeight;
            newWidth = origWidth;
        }

        newImage = new WriteableBitmap(newWidth, newHeight);
        fileStream.Seek(0);
        var decoder = await BitmapDecoder.CreateAsync(fileStream);

        // Scale image to appropriate size
        var transform = new BitmapTransform()
        {
            ScaledWidth = Convert.ToUInt32(newImage.PixelWidth),
            ScaledHeight = Convert.ToUInt32(newImage.PixelHeight)
        };
        var pixelData = await decoder.GetPixelDataAsync(
            BitmapPixelFormat.Bgra8, // WriteableBitmap uses BGRA format
            BitmapAlphaMode.Straight,
            transform,
            ExifOrientationMode.IgnoreExifOrientation, // This sample ignores Exif orientation
            ColorManagementMode.DoNotColorManage
        );

        // An array containing the decoded image data, which could be modified before being displayed
        var sourcePixels = pixelData.DetachPixelData();

        // Open a stream to copy the image contents to the WriteableBitmap's pixel buffer
        using (var stream = newImage.PixelBuffer.AsStream())
        {
            await stream.WriteAsync(sourcePixels, 0, sourcePixels.Length);
        }
    }

    return newImage;
}

This code is adapted from a Microsoft sample found here.


texts:
At CodeFights I found a question about the validity of Sudoku grid. Given a grid, return true if it is valid, return false otherwise. The grid is valid when each row, each column and each 3x3 sub grid contains at most one occurrence of the numbers 1 to 9.

I solved it using C# and I would like some feedback on my solution.

The provided grid is guaranteed to be 9x9 and to only contain the characters 1 through 9 and . (for empty cells). So I did not include any error checking.

Solution

using System;

public static class Program
{
    public static void Main()
    {
        char[][] grid = {
            new char[] {'.', '.', '.', '1', '4', '.', '.', '2', '.'},
            new char[] {'.', '.', '6', '.', '.', '.', '.', '.', '.'},
            new char[] {'.', '.', '.', '.', '.', '.', '.', '.', '.'},
            new char[] {'.', '.', '1', '.', '.', '.', '.', '.', '.'},
            new char[] {'.', '6', '7', '.', '.', '.', '.', '.', '9'},
            new char[] {'.', '.', '.', '.', '.', '.', '8', '1', '.'},
            new char[] {'.', '3', '.', '.', '.', '.', '.', '.', '6'},
            new char[] {'.', '.', '.', '.', '.', '7', '.', '.', '.'},
            new char[] {'.', '.', '.', '5', '.', '.', '.', '7', '.'}
        };

        var sudoku = new Sudoku(grid);
        Console.WriteLine(sudoku.IsValid());
    }
}

public class Sudoku
{
    char[][] _grid;

    public Sudoku(char[][] grid)
    {
        _grid = grid;
    }

    public bool IsValid()
    {
        return RowsAreValid()
            && ColumnsAreValid()
            && SquaresAreValid();
    }

    bool RowsAreValid()
    {
        return Validate(GetNumberFromRow);
    }

    bool ColumnsAreValid()
    {
        return Validate(GetNumberFromColumn);
    }

    bool SquaresAreValid()
    {
        return Validate(GetNumberFromSquare);
    }

    bool Validate(Func<int, int, int> numberGetter)
    {
        for (var row = 0; row < 9; row++)
        {
            var usedNumbers = new bool[10];
            for (var column = 0; column < 9; column++)
            {
                var number = numberGetter(row, column);
                if (number != 0 && usedNumbers[number] == true)
                {
                    return false;
                }

                usedNumbers[number] = true;
            }
        }

        return true;
    }

    int GetNumberFromRow(int row, int column)
    {
        return ToNumber(_grid[row][column]);
    }

    int GetNumberFromColumn(int row, int column)
    {
        return ToNumber(_grid[column][row]);
    }

    int GetNumberFromSquare(int block, int index)
    {
        var column = 3 * (block % 3) + index % 3;
        var row = index / 3 + 3 * (block / 3);
        return ToNumber(_grid[row][column]);
    }

    int ToNumber(char c)
    {
        if (c == '.')
            return 0;
        return (int)(c - '0');
    }
}


texts:
I have a page where a user needs to click two checkboxes before continuing (agree to two terms of service). My jQuery is fairly straightforward, you have to have both check boxes checked to continue:

$("#agree1, #agree2").click(function () {
    if ($("#agree1").is(':checked') == true && $("#agree2").is(':checked') == true) {
        $("#nextPage").removeAttr("disabled");
    } else {
        $("#nextPage").attr("disabled", "disabled");
    }
});

I'm wondering if there is a simpler way of writing this. I expected a line like this to check for both boxes to be checked, but it doesn't:

if ($("#agree1 #agree2").is(':checked') == true)

Is there a way to simplify this?

Example code: jsFiddle


texts:
I have the following example app: http://dev.driz.co.uk/jsfunction/

Which runs two types of script files with the same outcome.

Script1:

var script1 = {

    showMessage: function( message ) {

        var el = document.getElementById('example1');

        el.innerHTML = message;

    }
}

and script 2:

window.script2 = function() {

    function showMessage( message ) {

        var el = document.getElementById('example2');

        el.innerHTML = message;

    }

    return {

        showMessage: showMessage

    }

}();

They are both namespaced so I can them like:

window.onload = function() {

    script1.showMessage('Hello world!');

    script2.showMessage('How are you?');

};

But what's the better way forward? Script1 is the type I would normally write but it requires you to sometimes call a init function first if you have some events that need running on document load.

For example:

var script = {

    init: function() {

        // some events such as onlick etc..

    }

};

script.init();

Script2 however is a self executing function and therefore would get around this but being a function itself would it allow the same flexibility?

Any thoughts? Suggestions or examples of how people namespace there script files to make them neater and more efficient?


texts: Finding whether a set and an array have any strings in common

texts:
I have the following code.  It looks through an array, called items, and checks to see if there are any items in that array that also exist in a certain set of strings, called stringSet.

    Set<String> stringSet = new HashSet<>();
    stringSet.add("A");
    stringSet.add("B");
    stringSet.add("C");

    String[] items = new String[2];
    items[0] = "A";
    items[1] = "D";

    boolean hasValue = false;

    for (String item : items) {
        if (stringSet.contains(item)) {
            hasValue = true;
        }
    }
    System.err.println(hasValue);

Is there any way to avoid using a for each loop to achieve same result in Java 8, like with a stream, a map, etc.?


texts:
I've two table (t1 and t2) with 3 identical integer columns: c1, c2 and c3. I want to count how many value in t1 are in t2.

SELECT count(t1.value) FROM t1 INNER JOIN t2 ON  (
    t1.c1 = t2.c1 OR t1.c1 = t2.c2 OR t1.c1 = t2.c3 OR
    t1.c2 = t2.c1 OR t1.c2 = t2.c2 OR t1.c2 = t2.c3 OR
    t1.c3 = t2.c1 OR t1.c3 = t2.c2 OR t1.c3 = t2.c3
)

It doesn't seems a good way to write it (I'll have to add some columns). Is there a better solution to write it without enumerated any possibilities?

I'm using MySQL version 5.6.


texts:
Given a string the task it to find its first word with some rules:

The string can have points and commas
A word can start with a letter, a point or space
One word can contain one apostrophe and it stills being a valid one

For example:

assert first_word("Hello world") == "Hello"
assert first_word(" a word ") == "a"
assert first_word("don't touch it") == "don't"
assert first_word("greetings, friends") == "greetings"
assert first_word("... and so on ...") == "and"
assert first_word("hi") == "hi"
assert first_word("Hello.world") == "Hello"

The code:

def first_word(text: str) -> str:
    """
        returns the first word in a given text.
    """
    text = re.sub("[^A-Za-z'\s.]",'',text)
    words = text.split()
    for word in words:
        for i in range(len(word)):
            if word[i].isalpha() or word[i] == "'":
                if i == len(word) - 1:
                    if word.find('.') != -1:
                        return word.split('.')[0]
                    else:
                        return word

How could we improve it?


texts:
I'm trying to make a random object spawning script in Unity.

Bellow is the code, any suggestions for improvement / changes?
I'm new to both Unity and C#.

// Game objects and Transforms
public Transform playerTransform;
public Transform[] obstaclePrefab;

// spawn params
public float minYDicstane = 6.0f;
public float maxYDistance = 11.0f;
private float boxPositionY;

public float minXDistance = 0.0f;
public float maxXDistance = 3.0f;
private float boxPositionX;

private float minSpawnTime;
private float maxSpawnTime;
private float spawnTime;
private float timeCounter;

// Distances
private float playerDistance;
private float boxDistance;
private float ySpread;

private void Start()
{
    // Count sequence
    minSpawnTime = 3.0f;
    maxSpawnTime = 8.0f;

    // Count timer
    timeCounter = 0;
    spawnTime = Random.Range(minSpawnTime, maxSpawnTime);

}

private void Update()
{
    // Count the random spawn time
    timeCounter += Time.deltaTime;
    Debug.Log ("Spawn Time: " + spawnTime + " spawnCount: " + timeCounter);

    if(timeCounter >= spawnTime)
    {
        // boxDistanceFromPlayer
        playerDistance = playerTransform.position.y;

        // Box spawn distance
        // X position
        boxPositionX = Random.Range(minXDistance, maxXDistance);
        boxPositionX = (boxPositionX-1)*2.0f;

        // Y Position
        boxPositionY = playerDistance + Random.Range(minYDicstane, maxYDistance);

        // Select box color
        int boxColor = Random.Range (0, 4);

        // Let the boxes awake!!!
        Instantiate (obstaclePrefab [boxColor], new Vector2 (boxPositionX, boxPositionY), Quaternion.identity);

        // Make new random spawn time
        spawnTime = Random.Range (minSpawnTime, maxSpawnTime);
        timeCounter = 0;
    }

}

Code after changes, using coroutines

// Game objects and Transforms
public Transform playerTransform;
public GameObject[] obstaclePrefab;

// spawn params
public float minYDicstane = 6.0f;
public float maxYDistance = 11.0f;

public float minXDistance = 0.0f;
public float maxXDistance = 3.0f;

public float minSpawnTime = 2.0f;
public float maxSpawnTime = 5.0f;

public float spawnTime = 4.0f;

IEnumerator SpawnBoxes()
{
    while (true)
    {
        float boxPositionY;
        float boxPositionX;

        //Distances
        float playerDistance;

        // Player position
        playerDistance = playerTransform.position.y;

        // Box position
        boxPositionX = Random.Range(minXDistance, maxXDistance);
        boxPositionY = playerDistance + Random.Range(minYDicstane, maxYDistance);

        // Select box
        GameObject box = obstaclePrefab[Random.Range(0, obstaclePrefab.Length - 1)];

        // Instantiate box
        Instantiate (box, new Vector2 (boxPositionX, boxPositionY), Quaternion.identity);

        // Coroutine random amount of time
        yield return new WaitForSeconds(Random.Range(minSpawnTime, maxSpawnTime));
    }
}

private void Start()
{
    StartCoroutine(SpawnBoxes());
}


texts:
I need to parse a space- delimited text file. I want to read the file and do operations for each cell. Here is how I am parsing the file:

String line;
BufferedReader reader = new BufferedReader(new FileReader(file));
Map<String,String> mapFile = new HashMap<String, String>(19);
while((line = reader.readLine()) != null) {
    mapFile.put("valueCol1", line.substring(0,19));
    mapFile.put("valueCol2", line.substring(19,45));
    mapFile.put("valueCol3", line.substring(45,50));
    mapFile.put("valueCol4", line.substring(50,54));
}

Is this right, or should I use other types of collections?