texts: Reverse character order of substrings delineated by white space chars

texts:
The Challenge: Given a string, return a string where each word is reversed individually without changing its position. EDIT: (i.e.: the input "hello world I am a frog?" should produce the output: "olleh dlrow I ma a gorf?")
Thoughts and questions: Perhaps I was cheating the spirit of the challenge by using string builder? What do you think?
Complexity? Would the complexity be? I feel like it is O(n) since it will basically look at almost every char twice. I'm thinking there is a more efficient way to do it where n is just looked at once, but I think that to achieve that we will double the use of memory. Not that that is a problem, but I think that is the trade off.
Coding tests tend to be timed and I did this quickly. In evaluating the code, how do you factor in the pressure of time as you administer the test? I am talking myself into the idea that the answer should have been creating a new string and entering the chars one at a time using pointers so that each string char is looked at once and moved once. Is that really better then this solution? Perhaps there are points for easily readable code? Do you think this is readable?
    public static string ReverseOnlyWords(string InitialValue)
    {
        if (InitialValue == null)
        {
            throw new System.NullReferenceException();
        }
        StringBuilder seperatedValue = new StringBuilder();
        StringBuilder currentWord = new StringBuilder();
        foreach (char c in InitialValue)
        {
            if (c == ' ' || c == '.' || c == ',')
            {
                seperatedValue.Append(Reverse(currentWord.ToString()));
                seperatedValue.Append(c.ToString());
                currentWord.Clear();
            }
            else
            {
                currentWord.Append(c.ToString());
            }
        }
        seperatedValue.Append(Reverse(currentWord.ToString()));

        string resultValue = seperatedValue.ToString();
        return resultValue;
    }

In Reverse, perhaps I should have simply created a copy of toBeReversed and inserted/replaced characters in the reversed order instead of a string builder?
    static public string Reverse(string toBeReversed)
    {
        if (toBeReversed == null)
        {
            throw new System.NullReferenceException();
        }
        StringBuilder reversedString = new StringBuilder();
        for (int i = (toBeReversed.Length - 1); i >= 0; i--)
        {
            reversedString.Append(toBeReversed[i].ToString());
        }
        return reversedString.ToString();
    }


texts: Multiplying a numeric string with the "vedic method"

texts:
This is vedic method multiplication.  This code takes time on a very long numeric string, and I want to optimize it.  I also apply recursion on multIndices (this function is multiplying two given indices values).

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

char str1[10000],str2[10000],resultant[10000000];
int carry=0,n=0;
void mulIndices(int i, int j){
    int result=0;
    for(;i<=j;i++,j--){
    result = result + carry + (str1[i]-48)*(str2[j]-48);
        if(i!=j)
            result += (str2[i]-48)*(str1[j]-48);
    carry=0;
    }
    if(result > 9){
        carry = result/10;
        result %= 10;
    }
    resultant[n++] = result+48;
}
void reverseStr(char str[]){
    int tmp,i=0,j=0,length = strlen(str);
    for(i=0,j=length-1;i<length/2;i++,j--){
            tmp = str[i];
            str[i] = str[j];
            str[j] = tmp;
    }
}
int main()
{
    int value=-1, i=0,u,v,j=0,mulVal=0,length1 = 0,length2 = 0,diffOfLen=0,maxLength=0;
    printf("Enter the first numeric value: ");
    gets(str1);
    printf("Enter the second numeric value: ");
    gets(str2);

    length1 = strlen(str1);
    length2 = strlen(str2);

    if(length2<length1){
        diffOfLen= length1-length2;
        maxLength = length2;
    }else{
        diffOfLen= length2-length1;
        maxLength = length1;
    }

    i = diffOfLen;
/*
    if(length2<length1){
        i += length2;
    }else if(length2>length1){
        i += length1;
    }
*/
    reverseStr(str1);
    reverseStr(str2);

    while(diffOfLen--){
        //printf("%d\n",diffOfLen);
        if(length2<length1){
            str2[i++] = '0';
            str2[i] = '\0';
        }
        else if(length2>length1){
            str1[i++] = '0';
            str1[i] = '\0';
        }
    }
/*
    puts(str1);
    puts(str2);
*/

    for(i=0;i<maxLength;i++){
            mulIndices(0,i);
            //printf("0 %d\n",i);
    }
    for(i=1;i<maxLength;i++){
            mulIndices(i,maxLength-1);
            //printf("0 %d\n",i);
    }if(carry != 0){
        resultant[n++] = carry+48;
    }
    resultant[n] = '\0';
    reverseStr(resultant);
    puts(resultant);

    return 0;
}


texts: Dynamically create a table of input fields

texts:
I'm trying to dynamically create a table of input fields (two per field) that I will then send off to a Python script.

Here's the expected behaviour:

User chooses "manual entry," specifies rows, columns, of table, clicks button.
Table is printed with two input fields per cell (e.g.: A(i,j), B(i,j)), user fills in all fields, hits button.
Data is sent off to Python (first-best would be two 2D arrays, one for in inputs in A, the other for B).

Questions:

Is there a simpler/smarter way to set up the table to get an array of input to pass to Python? I'm not sure how I will eventually pass the data to Python.
Is there a simpler/smarter way to set up the dynamic part? The way I'm doing it is far from perfect (for example, if the user changes his/her mind about manual entry and switches back to 'automatically fill table', the manual entry table stays there).

function tableCreate(men, women) {
  var body = document.body,
    tbl = document.createElement('table');
  tbl.style.width = '100px';
  // tbl.style.border = '1px solid black';

  for (var i = 0; i < women; i++) {
    var tr = tbl.insertRow();
    for (var j = 0; j < men; j++) {
      var td = tr.insertCell();
      // Following adds a text field:
      var input1 = document.createElement("input");
      input1.type = "text";
      input1.name = 'wPref-' + j + "-" + i;
      input1.size = '1';
      input1.maxLength = '2';

      var input2 = document.createElement("input");
      input2.type = "text";
      input2.name = 'mPref-' + j + "-" + i;
      input2.size = '1';
      input2.maxLength = '2';
      // input.className = "css-class-name"; // set the CSS class
      td.appendChild(input1); // put it into the DOM
      td.appendChild(input2); // put it into the DOM

      // td.appendChild(document.createTextNode('Cell'));
      td.style.border = '1px solid black';
    }
  }
  body.appendChild(tbl);
}

function getPlayers() {
  var x = document.getElementById("men");
  var men = x.options[x.selectedIndex].value;
  var y = document.getElementById("women");
  var women = y.options[y.selectedIndex].value;
  tableCreate(men, women);

}

  <form name="pyform" method=="POST" action="/cgi-bin/da_form.py" style='font-family:Arial,sans-serif;font-size:12px'>
    Number of men: &nbsp; &nbsp; &nbsp;
    <select name='men' id='men'>
      <option value='1'>1</option>
      <option value='2'>2</option>
      <option value='3'>3</option>
    </select>

Number of women:&nbsp;
    <select name='women' id='women'>
      <option value='1'>1</option>
      <option value='2'>2</option>
      <option value='3'>3</option>
      <option value='4'>4</option>
    </select>

    <input type="button" value="Draw table" onClick="getPlayers();">

  </form>


texts: Compute the probabilities of getting each of the possible sums when throwing 2 dice, n times

texts:
I'm struggling with some coding-inexperience. The code I've written below, is extremely inconvenient and ugly to look at.

My question to you is:
How can this be done more efficiently? The way I've chosen to do it, is rather inefficient. Pay attention to the def freq_2dice(n, N): section of the code, as well as the print statements. Those are the areas in which I need more efficiency as well as just nicer looking code.

The assignment is to create a function which records and stores each of the probabilities of getting each of the possible sums when throwing 2 dice, n times.

The rest of the code is comparing those probabilities to the exact probabilities.

from random import randint
import sys

def freq_2dice(n, N):
    M, A, E, R, T, Y, U, I, O, P, D = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    for reps in xrange(N):
        s = 0
        for dice in xrange(n):
            outcome = randint(1, 6)
            s += outcome
        if s==2:
            M += 1
        if s==3:
            A += 1
        if s==4:
            E += 1
        if s==5:
            R += 1
        if s==6:
            T += 1
        if s==7:
            Y += 1
        if s==8:
            U += 1
        if s==9:
            I += 1
        if s==10:
            O += 1
        if s==11:
            P += 1
        if s==12:
            D += 1
    return N*(float(M)/N), N*(float(A)/N), N*(float(E)/N), N*(float(R)/N), N*(float(T)/N), N*(float(Y)/N), N*(float(U)/N), N*(float(I)/N), N*(float(O)/N), N*(float(P)/N), N*(float(D)/N)

def chance_die():
    frequencies = {}
    for s in range(2, 13):
        frequency = 0
        for die1 in range(1, 7):
            for die2 in range(1, 7):
                if die1 + die2 == s:
                    frequency += 1
        frequencies[s] = frequency
    return frequencies

n = int(sys.argv[1])
N = int(sys.argv[2])

print 'No. of twos: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[0], freq_2dice(n, N)[0]/(N/100), chance_die()[2]/.36)
print 'No. of threes: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[1], freq_2dice(n, N)[0]/(N/100), chance_die()[3]/.36)
print 'No. of fours: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[2], freq_2dice(n, N)[0]/(N/100), chance_die()[4]/.36)
print 'No. of fives: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[3], freq_2dice(n, N)[0]/(N/100), chance_die()[5]/.36)
print 'No. of sixes: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[4], freq_2dice(n, N)[0]/(N/100), chance_die()[6]/.36)
print 'No. of sevens: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[5], freq_2dice(n, N)[0]/(N/100), chance_die()[7]/.36)
print 'No. of eights: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[6], freq_2dice(n, N)[0]/(N/100), chance_die()[8]/.36)
print 'No. of nines: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[7], freq_2dice(n, N)[0]/(N/100), chance_die()[9]/.36)
print 'No. of tens: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[8], freq_2dice(n, N)[0]/(N/100), chance_die()[10]/.36)
print 'No. of elevens: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[9], freq_2dice(n, N)[0]/(N/100), chance_die()[11]/.36)
print 'No. of twelves: %d, probability: %.2f, expected: %.2f' % (freq_2dice(n, N)[10], freq_2dice(n, N)[0]/(N/100), chance_die()[12]/.36)

MacBook-Air:python Leroy$ python freq_2dice.py 2 100000
No. of twos: 2680, probability: 2.80, expected: 2.78
No. of threes: 5612, probability: 5.51, expected: 5.56
No. of fours: 8169, probability: 8.43, expected: 8.33
No. of fives: 11099, probability: 10.96, expected: 11.11
No. of sixes: 13827, probability: 13.91, expected: 13.89
No. of sevens: 16610, probability: 16.51, expected: 16.67
No. of eights: 13808, probability: 13.72, expected: 13.89
No. of nines: 10947, probability: 11.22, expected: 11.11
No. of tens: 8249, probability: 8.35, expected: 8.33
No. of elevens: 5540, probability: 5.59, expected: 5.56
No. of twelves: 2805, probability: 2.74, expected: 2.78

'''


texts:
I'm working on creating a new jQuery modal plugin. I'm pretty good at jQuery but still pretty new to the whole object oriented plug-and-play style of plugins so I used a different plugin I found online and ripped it apart using it as a foundation to build mine. However, I don't feel like I'm taking full advantage of it and not using the whole object-oriented "self" declaration correctly.

Plugin:

(function ($) {
    var DasBtnResponse = {
         Close: "close",
         CloseNegative: "negative-close",
         ClosePositive: "positive-close"
    }
    var methods = {
        init : function (options) {
            var self = this;
            var settings = $.extend({
                    closeable: true,
                    size: "medium",
                }, options || {});
            this.each(function () {
                self.data('plugin', settings);
            });
            methods.setup(this);
            methods.setupButtons(this.find(".DasBtn"));
            return this;
        },
        setup : function (elem) { //Set up the nav DOM elements
            $data = elem.data('plugin');
                 self.wrapper = $("
")
                .addClass("DasModalWrapper")
                .click(function(e){
                    if (e.target === this && $data.closeable)
                        $(this).removeClass('open');
                })
                elem.replaceWith(wrapper);
                wrapper.append(elem);
            if ($data.closeable){
                close = $("
")
                .addClass("DasClose")
                .html('&#215')
                .click(function(e){
                    wrapper.removeClass('open');
                })
                .prependTo(elem.find('.DasModalHeader'));
            }
        },
        open: function (elem){
            $(elem).parent('.DasModalWrapper').addClass('open');
        },
        setupButtons : function (btns){
            btns.each(function(i, obj) {
                $btn = $(obj);
                switch($btn.data('response')) {
                    case DasBtnResponse.Close:
                        $btn.on("click", function(){alert("close")})
                        break;
                    case DasBtnResponse.CloseNegative:
                        $btn.on("click", function(){alert("negative")})
                        break;
                    case DasBtnResponse.ClosePositive:
                        $btn.on("click", function(){alert("positive")})
                        break;
                    default:
                        break;
                    }
            });
        }
    };
    $.fn.initModal = function () {
        methods.init.apply(this, arguments);
    }
    $.fn.openModal = function () {
        methods.open(this);
    }
})(jQuery);

Init/open example:

$(function(){
    $("#modal").initModal({
      closeable : true
    });
})
$(document).on("click", "#launchModal", function(){
    $("#modal").openModal();
});

Basic (empty) HTML Structure:

Cancel

No

Ok

My main concerns is that I want to avoid directly calling DOM elements/classes as much as possible e.g. this.closest('.wrapper'); and try to use variables instead. Also, there will be many more setting/options and functions this is just the foundation.


texts:
The goal this method was to emulate the way EF or Dapper return to you concrete POCO classes instead of recordsets when querying your db. Our current code is riddled with iterations over recordsets and I want to consolidate to an extension method that can convert the recordset into an Enumerable<T>.

Review

I'm concerned about how efficient this will be. When querying the db for a single or handful of records I'm not concerned but we sometimes query for an entire table (i.e. ~100,000 records) and in that case will the iterations in this start to cause performance issues? Is there a better way to resolve the recordsets to classes without iterating? Any other constructive remarks appreciated.

public static IEnumerable<T> AsList<T>(this Recordset rs) where T : new()
{
    IEnumerable<PropertyInfo> props = new List<PropertyInfo>(typeof(T).GetProperties()).Where(p => p.CanWrite);
    List<T> results = new List<T>();
    while (!rs.Eof)
    {
        T obj = new T();
        foreach (PropertyInfo property in props)
        {
            var val = rs[property.Name].Value;
            if (val != null) property.SetValue(obj, Convert.ChangeType(val, property.PropertyType));

        }
        rs.MoveNext();

        results.Add(obj);
    }

    return results.AsEnumerable();
}

used as...

Recordset rs = new Recordset();
rs.Open("select * from Users", connection)
IEnumerable<User> results = rs.AsList<User>();

Post Review Update

After great feedback from Heslacher and t3chb0t the following code has been finalized. Note there was a change in the requirements and sister method was created As<T>() to create a single class instance from a recordset. The feedback from the review has been applied to it as well.

public static IList<T> AsList<T>(this Recordset rs) where T : class, new()
{
    var results = new List<T>();

    if (rs == null) throw new ArgumentNullException("rs");
    if (rs.Eof) return results;

    IList<PropertyInfo> properties = GetProperties<T>();

    while (!rs.Eof)
    {
        results.Add(CreateInstance<T>(properties, rs));
        rs.MoveNext();
    }

    return results;
}

public static T As<T>(this Recordset rs) where T : class, new()
{
    if (rs.Eof) return default(T);
    IList<PropertyInfo> properties = GetProperties<T>();

    return CreateInstance<T>(properties, rs);
}

private static T CreateInstance<T>(IEnumerable<PropertyInfo> properties, Recordset rs) where T : new()
{
    T obj = new T();
    foreach (PropertyInfo property in properties)
    {
        var val = rs[property.Name].Value;
        if (val != null && !Convert.IsDBNull(val)) property.SetValue(obj, Convert.ChangeType(val, property.PropertyType));
    }

    return obj;
}

private static IList<PropertyInfo> GetProperties<T>()
{
    return new List<PropertyInfo>(typeof(T).GetProperties().Where(p => p.CanWrite));
}


texts: Given a vector and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum

texts:
I am trying to solve 4. Two Sum from this set of C++ interview questions. As far as I can think this solution has a time complexity of \$O(n \log n)\$ can it be further optimized?

  Write a function that, given a vector and a target sum, returns
  zero-based indices of any two distinct elements whose sum is equal to
  the target sum. If there are no such elements, the function should
  return (-1, -1).

  For example, findTwoSum({ 1, 3, 5, 7, 9 }, 12) should return a
  std::pair<int, int> containing any of the following pairs of indices:

  1 and 4 (3 + 9 = 12)
  2 and 3 (5 + 7 = 12)
  3 and 2 (7 + 5 = 12)
  4 and 1 (9 + 3 = 12)

Here is my approach  considering that negative numbers cannot be present in vector

static std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    std::vector<int> com;
    std::vector<int>::iterator it;
    for(unsigned count=0; count<list.size(); count++){
        it = std::find(com.begin(), com.end(), list[count]);
        if ( it != com.end() ){
            return std::make_pair(it - com.begin() + 1, --count);
        }
        else{
            if(sum >= list[count])
            com.push_back(sum-list[count]);
        }

    }
    return std::make_pair(-1,-1);
}


texts: Determine value in range, inject to HTML to be used in CSS

texts:
I want to show users what package they are, based on how many items they have in their cart. The code works, but I'm wondering if anything can be improved.

function new_thing (){

//decleare variables
global $x_subs;
$lim01 = get_option(woomps_limit01);
$lim02 = get_option(woomps_limit02);
$lim03 = get_option(woomps_limit03);
$x = $x_subs;
$plugin_url =(plugins_url("/", __FILE__ ));

//set CSS class based on value of $x
if  ($x >= 1 && $x < $lim02) {
    $active1 = "fb-sub-active";
    $active2 = "fb-sub-deactive";
    $active3 = "fb-sub-deactive";
} else if ($x >= $lim02 && $x < $lim03) {
    $active1 = "fb-sub-deactive";
    $active2 = "fb-sub-active";
    $active3 = "fb-sub-deactive";
} else if ($x >= $lim03) {
    $active1 = "fb-sub-deactive";
    $active2 = "fb-sub-deactive";
    $active3 = "fb-sub-active";
} else {
    $active1 = "fb-sub-deactive";
    $active2 = "fb-sub-deactive";
    $active3 = "fb-sub-deactive";
}

//generate the content that will be displayed
$content = <<<EOD

{$x_subs}

EOD;

return $content;
}

.fb-sub-img-holder {
    width: 95%;
    margin: 0 auto;
}

.fb-img {
    width: 30%;

.fb-sub-active {
    width: 50%;
}
.fb-sub-deactive {
    width: 20%;
}


texts: Find the shortest whole repetitive substring (part 3)

texts:
This is a new discussion from this post (Find the shortest whole repetitive substring) and since it is totally new code, I post as a new thread here.

The major initiative of posting a new thread is, RobAu has posted a smarter idea, and there is no implementation, and I implemented the ideas and has simple prove the ideas is correct. Post my code and simple prove here for advice.

The problem,

I'm working on a problem to find wholly repeated shortest substring of a given string, and if no match, return the whole original string.

Input and output example

catcatcat => cat
catcatcatdog=>catcatcatdog
aaaaaa = > a

Major idea of the algorithm,

Try to match the first shortest repetitive candidate as the first character of original string, if there is no match, treat the whole non-matched string as next candidate.

I have a simple prove why if there is no match, treat the whole non-matched string as next candidate is correct,

Let us say, previous candidate length is N and is not satisfied during current comparison, previous matched length is N*k (previous candidate matched for k times)
Suppose and there could be another satisfied candidate, whose length is N+x (1<x<N) and this candidate can match p times for previous matched string. Then,
N*k = (N+x)*p, in other words N*k/(N+x) = p, since N/(N+x) is not integer, but k and p are both integer, it could not be satisfied.
(At the same time, we know if N length string does not match, 2N, 3N, etc. does not match, it is why I choose x as as value between 1 and N in previous analysis.)
So, we have to treat the whole mis-matched string as next whole repetitive string candidate.

My code

def check_shortest(original_string):
    current_candidate = original_string[0]
    j = 0
    for i in range(len(original_string)):
        if original_string[i] == current_candidate[j]:
            j+=1
            if j == len(current_candidate):
                j = 0
        else:
            current_candidate= original_string[:i+1]

    return current_candidate if j == 0 else original_string

if __name__ == "__main__":
    print check_shortest('catcatcat') #cat
    print check_shortest('catcatcatdog') #catcatcatdog
    print check_shortest('aaaaaa') #a
    print check_shortest('aba')  # aba


texts:
I am trying to learn recursion and have a question involving an array that needs to be reversed. I am focusing on c# but the language probably doesn't matter a whole lot because my function is not using any libraries.
Here is my code:
char[] ReverseString(char[] s, int i = 0)
{
    char[] x = s;
    char temp = s[i];
    s[i] = s[s.Length - (i + 1)];
    s[s.Length - (i + 1)] = temp;

    i++;
    if (i < (s.Length) / 2)
    {
        ReverseString(s, i);
    }
    return x;
}

Any suggestions on how I should improve my function (maybe time complexity or using libraries (nuget packages)) is appreciated as well.


texts: Using static management class to control db transactions through an EF6

texts:
I have the class below to manage my specific implementation of a membership system using entity framework 6.1

Is the use of static access correct in this case? as far as I understood that EF context is not thread-safe so I'm instantiating one with every call through the using statement. My second question, is the use of Boolean variable okay to signal failure in db transactions? an important point about this class is that it's going to be used quite frequently as the authentication wont rely on any session established with the user, it's also important to note that the users of this system will be quite limited.

Edit: I'm aware I can use the new identity system or any of the membership providers offered by ASP.NET but this custom provider is quite specific to a Windows authentication system and the use of any cookie-based system is not possible.

public static class AccountManager
{
    private enum Role { User, Comment, CommentControl, Sysadmin }

    public static bool IsUserInRole(string username, string role)
    {
        using (var ctx = new AccountsDbCtx())
        {
            var status = false;
            var foundAcc = ctx.Accounts.Where(x => x.Username == username);
            if (foundAcc.Any())
            {
                var s = foundAcc.SingleOrDefault();
                if (s != null)
                {
                    var exitingRole = s.Roles.Where(x => x.Name.Equals(role, StringComparison.InvariantCultureIgnoreCase));
                    if (exitingRole.Any())
                    {
                        status = true;
                    }
                }
            }
            return status;
        }
    }

    public static bool IsUserCached(string username)
    {
        using (var ctx = new AccountsDbCtx())
        {
            var result = true;
            var foundAcc = ctx.Accounts.Where(x => x.Username == username);
            if (!foundAcc.Any())
            {
                result = false;
            }
            return result;
        }
    }

    public static bool CacheUser(string username)
    {
        using (var ctx = new AccountsDbCtx())
        {
            var status = false;

            try
            {
                var newAcc = new Account
                {
                    Active = true,
                    Username = username,
                };
                ctx.Accounts.Add(newAcc);
                ctx.SaveChanges();

                AssignRole(newAcc.Username, Role.User);
                status = true;
            }
            catch
            { }

            return status;
        }
    }

    public static bool AssignRoleComment(string username)
    {
        return AssignRole(username, Role.Comment);
    }

    public static bool AssignRoleCommentControl(string username)
    {
        return AssignRole(username, Role.CommentControl);
    }

    public static bool AssignRoleSysAdmin(string username)
    {
        return AssignRole(username, Role.Sysadmin);
    }

    private static bool AssignRole(string accountName, Role role)
    {
        using (var ctx = new AccountsDbCtx())
        {
            var completed = false;
            var roleToAssign = ctx.Roles.SingleOrDefault(x => x.Role1 == (int)role);

            try
            {
                var currentAccount = ctx.Accounts.SingleOrDefault(x => x.Username.Contains(accountName));

                if (currentAccount != null && roleToAssign != null) currentAccount.Roles.Add(roleToAssign);

                ctx.SaveChanges();

                completed = true;

            }
            catch
            {}

            return completed;
        }
    }
}


texts: A pattern to destructively extract items from an array

texts:
I want to efficiently (few intermediate objects) and neatly (few lines and easy to read) filter an array, removing and returning rejected items. So like a call to delete_if except instead of returning the remaining items, returning the deleted items.

Here's some code that works:

ary = (0..9).to_a
odds = ary.select {|i| i%2==1 }
ary -= odds

or:

ary = (0..9).to_a
(_,ary),(_,odds) = ary.group_by {|i| i.odd? }.sort {|a,b| a[0] ? 1 : -1 }

But I can't help but think there should be a better way...

Ideally something more like: odds = ary.delete_and_return(&:odd?)


texts: Determine if a file is either in JSON or XML format

texts:
The purpose of this function is to determine if report_input_file is either in JSON format or XML format, this is what I came up with, just want to know if this is best practice / pythonic way of achieving this?

def parse_report_file(self, report_input_file):
    """ Checks if input report file is of type json or xml """
    parsed_report_file = None
    try:
        parsed_report_file = self._parse_json_file(report_input_file)
        self.is_json_report_file = True
    except Exception, e:
        parsed_report_file = self._parse_xml_file(report_input_file)
        self.is_json_report_file = False

    return parsed_report_file


texts:
Implement data structure overflow queue. Overflow queue is a normal queue with one extra property. It never throw Stack overflow exception. So whenever queue becomes full, it replaces the oldest element present in the queue and front pointer simply shifted one step ahead. Constraint:- it should have public void enQueue(int n) and public int deQueue() methods of time complexity O(1) The implementation should be optimum and clean.

Here is my version of implementation. You review is highly appreciated.

public class OverflowQueue {
    private int[] queue;
    private int front = -1, rear = -1;

    public OverflowQueue(int size) {
        queue = new int[size];
    }

    public void enQueue(int n){
        rear = getNextIndex(rear);
        queue[rear] = n;
         if (rear == front || front == -1){
          front = getNextIndex(front);
        }

    }

    private int getNextIndex(int index){
        if (index == queue.length - 1 ){
            index = 0;
        } else {
            index ++ ;
        }
        return index;
    }

    public int deQueue(){
        if (front == -1 ){
           throw new NullPointerException("deQueue operation is called on empty queue.");
        }
        int elem = queue[front];
        if (front == rear ){
            front = -1;
            rear = -1;
        } else {
            front = getNextIndex(front);
        }
        return elem;
    }

    public static void main(String[] args) {
        OverflowQueue q = new OverflowQueue(5);
        q.enQueue(1);q.enQueue(2);q.enQueue(3);
        q.enQueue(4);q.enQueue(5);q.enQueue(6);
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
    }
}


texts:
In a Ruby on Rails application I want to have this routing:

for URL www.example.com/reports go to controller documents and action reports
for URL www.example.com/charts go to controller documents and action charts

In the routes.rb file I currently have:

scope controller: :documents do
  get 'reports' => :reports
  get 'charts'  => :charts
end

The code works as expected, but is there a way so I keep the code dry and don't repeat the action names?


texts: Automatically filled multiple forms in one view

texts:
I have some question because in my project I have 4 models, and one of models is parent for other 3 and they are connected to parent by foreign key. Then I have view which is used for automatically fill form of those models and save them in database, this is post function in my view:

    def post(self, request, *args, **kwargs):
        self.object = None
        form_2 = self.form_class_search(self.request.POST)
        if form_2.is_valid():
            keyword = form_2.cleaned_data['keyword']
            books = self.search_for_books(keyword)

            if books:
                for book in books:
                    title = self.add_title(book)
                    published_date = self.add_published_date(book)
                    pages = self.add_pages(book)
                    language = self.add_language(book)
                    form = self.form_class_book(
                        {'title': title,
                         'published_date': published_date,
                         'pages': pages,
                         'language': language}
                    )
                    if form.is_valid() and form.cleaned_data["title"] not in Book.objects.values_list('title', flat=True):
                        self.object = form.save()

                        small_thumbnail = self.add_small_thumbnail(book)
                        thumbnail = self.add_thumbnail(book)
                        form_thumbnail = self.form_class_thumbnail(
                            {'small_thumbnail': small_thumbnail,
                                'thumbnail': thumbnail,
                                'book': self.object.id}
                        )
                        if form_thumbnail.is_valid():
                            form_thumbnail.save()

                        if book['volumeInfo'].get('authors'):
                            for author in book['volumeInfo']['authors']:
                                author = self.add_author(author)
                                form_author = self.form_class_author(
                                    {'author': author,
                                        'book': self.object.id}
                                )
                                if form_author.is_valid():
                                    form_author.save()

                        if book['volumeInfo'].get('industryIdentifiers'):
                            for identifier in book['volumeInfo']['industryIdentifiers']:
                                identifier_type = self.add_identifier_type(identifier)
                                identifier = self.add_identifier(identifier)
                                form_industryidentifier = self.form_class_identifier(
                                    {'type': identifier_type,
                                        'identifier': identifier,
                                        'book': self.object.id}
                                )
                                if form_industryidentifier.is_valid():
                                    form_industryidentifier.save()

Code works exactly how I want and for me is also transparent and easy to understand but its quite long and I'm courious if my current code is good as it is now or maybe there is good way to make it shorter.


texts: Animated Ticker with JavaScript and Sass CSS

texts:
I've made this animation using JavaScript and Sass CSS.

Relevant is the code inside the IIFE. Because that's what I like to keep and develop further. Perhaps use it for future projects. Everything else is just quick & dirty made demo and less important.

My code with uncompiled Sass CSS:

document.querySelector('.reload a').addEventListener('click', () => {
  location.href = 'index.html';
});

(function(headline, duration) {
  'use strict'
  // ---- Declarations & Parameter Validation --------------
  var i = 0;
  var display = document.querySelector('.ticker-display');

  if (!display) {
    throw new Error(
      'HTML element with a CSS-class \".ticker-display\" expected.');
  }

  if ((typeof headline).toLowerCase() !== 'string') {
    throw new Error(
      `1. Param: String expected but ${typeof headline} found.`);
  }

  if (headline.length < 1) {
    throw new Error(
      '1. Param: String with a length greater 0 expected.');
  }

  if ((typeof duration) !== 'number') {
    throw new Error(
      `2. Param: Number expected but ${typeof duration} found.`);
  }

  if (duration < 10) {
    throw new Error(
      '2. Param: Duration has to be at least 10 ms.');
  }
  // -------------------------------------------

  var interval = setInterval(() => {
    let text;

    function createText(text) {
      i++;

      if (/\s/.test(text.charAt(i))) {
        createText(text + headline.charAt(i));
      } else {
        return text;
      }
    }

    text = createText(headline.charAt(i));

    let span = document.createElement('span');
    let textNode = document.createTextNode(text);

    span.appendChild(textNode);
    display.appendChild(span);

    if (i === headline.length) {
      clearInterval(interval);
    }
  }, duration)
})('Lorem ipsum dolor sit amet', 200);
$backgroundColor: #000;
$fontColor: #fff;
$tickerColor: rgb(100, 255, 0);
$fontStack: 'Audiowide',
'Lucida Console',
courier,
monospace;
$letterSpace: 3px;
html,
body {
  background-color: $backgroundColor;
  width: 100%;
  height: 100%;
}

.wrap {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  max-width: 800px;
  min-height: 100px;
}

.ticker-display {
  font-size: 3rem;
  text-transform: uppercase;
  letter-spacing: $letterSpace;
  font-weight: 900;
  font-family: $fontStack;
  white-space: pre;
}

.ticker-display span {
  opacity: 0;
  animation: appear 5s;
  animation-fill-mode: forwards;
  color: $tickerColor;
  text-shadow: 1px 1px 0 rgb(200, 255, 100), -1px -1px 0 rgb(200, 255, 100);
}

.reload {
  text-align: right;
  margin: 20px 40px 0 0;
}

.reload a {
  color: $fontColor;
  font-family: $fontStack;
  text-decoration: none;
  font-weight: 900;
  text-transform: uppercase;
  padding: 5px 10px;
  border: 3px solid;
  border-radius: 6px;
}

.reload a:hover {
  opacity: 0.8;
}

.reload a:active {
  color: $tickerColor;
}

@keyframes appear {
  to {
    opacity: 1.0;
    text-shadow: 1px 1px 1px rgb(230, 255, 130), -1px -1px 1px rgb(230, 255, 130);
  }
}

    Reload

Here's a working Live Demo.

The complete project folder on GitHub.

The recursion part is for to avoid weird looking delays which appear when the given string contains a sequence of more then one blank.

What do you think about the validation part?

Are there flaws with the validation? Is it exaggerated what I do there?

And what do you think about my solution with the recursive function for to avoid a delay of the next character?

Would appreciate your opinions as well as other hints, comments and recommendations.


texts: Checking whether a given timestamp is more than two weeks old

texts:
I am trying to see whether a given timestamp is more than two weeks old or not. If it is two weeks old, then print out "Hello" and if it is not more than two weeks old then print out "World".

I have a variable declared as uint64_t which contains the timestamp in milliseconds.

uint64_t data_timestamp;

How do I check whether this timestamp is more than two weeks old and if it is two weeks old, then print out "Hello" otherwise prints out "World".

This is the code I have which gives me the timestamp in milliseconds for two weeks back from the current date, which I then compare to see whether it is two weeks old or not.

#include <ctime>
#include <chrono>
#include <iostream>

int main()
{

    uint64_t data_timestamp = 1406066507000;

    const auto now = std::chrono::system_clock::now();
    auto twoWeeks = std::chrono::hours(24 * 14);
    auto lastTwoWeeks = now - twoWeeks;

    auto millis = std::chrono::duration_cast<std::chrono::milliseconds>\
                    (lastTwoWeeks.time_since_epoch()).count();

    std::cout << "Time stamp in milliseconds since UNIX epoch start: "\
              << millis << std::endl;

    if (data_timestamp < millis) {
        std::cout << "Hello";
    } else {
        std::cout << "World";
    }

    return 0;
}

I will be running this code on Ubuntu 12.04. What is a better way of doing this? Are there any improvements which I can do it here? In general, I need to check whether data_timestamp is more than two weeks old or not. If it is two weeks old, then print "hello" otherwise prints "world."

Do I even need to use chrono time here? There are 2 * 7 * 24 * 60 * 60 * 1000 = 1,209,600,000 milliseconds in two weeks, so a simple subtraction of that from the current should tell me what is more than 2 weeks old? right?


texts:
I have a function to request an update from the server. I provide the query and also indicate the expected length of the response.

    public Byte[] GetUpdate(Byte[] query, int expLength)
    {
        var response = new Byte[expLength];

        lock(Client)
        {
            Stream s = Client.GetStream();
            s.Write(query, 0, query.Length);

            var totalBytesRead = 0;
            var numAttempts = 0;

            while(totalBytesRead < expLength && numAttempts < MAX_RETRIES)
            {
                numAttempts++;
                int bytes;
                try
                {
                    bytes = s.Read(response, totalBytesRead, expLength);
                }
                catch (Exception ex)
                {
                    throw new IOException();
                }
                totalBytesRead += bytes;
            }

            if(totalBytesRead < expLength)
            {
                // should probably throw something here
                throw new IOException();
            }
        }

        return response;
    }

I don't like the way I have written this code esp with two exception throwing.
Is there a more elegant way to write the code?


texts: Logging observable values while extending service

texts:
I'm trying to extend a service function which returns an Observable<T>. The idea is to extend the function so I can add logging functionality whenever the observable emits a new value.

fromEvent<T>(eventName: string): Observable<T> {
    super.fromEvent(eventName).subscribe(
        function next(data) {
            console.group();
                console.log('----- SOCKET INBOUND -----');
                console.log('Action: ', eventName);
                console.log('Payload: ', data);
            console.groupEnd();
        }
    );

    return super.fromEvent(eventName);

How can I make my function more effective? Because whenever fromEvent() is invoked a subscription is created and an observable is returned from the base class. As I understand, all subscriptions should at some point be unsubscribed.

Or are there any other way you could implement a logging functionality on an observable that listens to a specific event?


texts:
here's my code for moving a square on a canvas. Basicly I'm creating this thinking of some simple simulations or maybe a simple game. Would love some feedback how to optimize the code.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

class Map {
    constructor (x, y,) {
        this.width = x;
        this.height = y;
    }
}

// NPCs / PLAYER

class Square {
    constructor(hp, dmg, speed, step) {
        // Combat stats
        this.hp = hp;
        this.dmg = dmg;
        this.speed = speed;
        this.step = step;

        // Init stats
        this.size = 10;
        this.color = 'black';
        this.pos = [0,0];
        this.step = 2;
    }
}

class Player extends Square {
    constructor() {
        super();
        this.speed = 50; // The higher the slower the player
        this.pos = [250, 250];
        this.step = 5;
    }
}

let player;

function drawPlayer() {
    ctx.fillStyle = player.color;
    ctx.fillRect(player.pos[0], player.pos[1], player.size, player.size);
}

function createSquare() {
    const square = new Square(100, 15, 20);
    ctx.fillStyle = square.color;
    ctx.fillRect(square.pos[0], square.pos[1], square.size, square.size);
}

function initPlayer() {
    player = new Player(100, 15, 1, 5);
    ctx.fillStyle = player.color;
    ctx.fillRect(player.pos[0], player.pos[1], player.size, player.size);
}

// MOVEMENT

function startMov() {
    initPlayer();
    movePlayer();
}

function moveUp(step) {
    ctx.clearRect(0,0, 500, 500);
    player.pos[1] -= step;
    drawPlayer();
}

function moveLeft(step) {
    ctx.clearRect(0,0, 500, 500);
    player.pos[0] -= step;
    drawPlayer();
}

function moveDown(step) {
    ctx.clearRect(0,0, 500, 500);
    player.pos[1] += step;
    drawPlayer();
}

function moveRight(step) {
    ctx.clearRect(0,0, 500, 500);
    player.pos[0] += step;
    drawPlayer();
}

let keyState = new Array();

function movePlayer() {
    console.log('start')
    checkIfStringInTable('a', keyState) ? moveLeft(player.step) : false;
    checkIfStringInTable('d', keyState) ? moveRight(player.step) : false;
    checkIfStringInTable('w', keyState) ? moveUp(player.step) : false;
    checkIfStringInTable('s', keyState) ? moveDown(player.step) : false;
    setTimeout(movePlayer,player.speed);
}

// Add keys to state
window.addEventListener('keydown', e => {
    addKeyToState(e.key);
})

// Remove keys from state
window.addEventListener('keyup', e => {
    removeKeyFromState(e.key);
})

function addKeyToState(key) {
    if((key == 'w' || key == 'a' || key == 's' || key == 'd') && !checkIfStringInTable(key,keyState)) {
        keyState.push(key)
    } else false;
}

function removeKeyFromState(key) {
    keyState = keyState.filter(e => e !== key)
}

function checkIfStringInTable(string, table) {
    if(table.indexOf(string) > -1) {
        return true;
    } else false;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>

</head>
<body>
    <button onclick="createSquare()">Click</button>
    <button onclick="startMov()">Click 2</button>
    <div class="main">
        <canvas class="canvas" id="canvas" width="500" height="500"></canvas>
    </div>

    <script src="main.js"></script>
</body>
</html>

To start press Click 2, I also suggest using SO's fullscreen mode for testing.


texts: Regex substitution using a variable replacement string containing backreferences in Perl

texts:
I have written a program where the user inputs a regular expression and a replacement string, and the program will search through a set of files and do the replacements.

The user is allowed to use backreferences in the replacement string (to refer to capture groups in the regex).
The part of the program I would like you to consider is the sub routine substitute_regex_backref below that searches a input string (for example the contents of a file) and does the replacements:

#! /usr/bin/env perl

use feature qw(say);
use strict;
use warnings;

my $old_str = '$1B<$ <hello> $> aba B<$ <kk> $>$1';
my $str = $old_str;
my $regex = qr'B<\$ <(.*?)> \$>';
my $replace = 'I<\$1$1\$1>';

(my $cnt, $str) = substitute_regex_backref( $str, $regex, $replace );

say "Old string: '$old_str'";
say "Number of replacements: $cnt";
say "New string: '$str'";

exit;

#
#
# ($num_substitutions, $new_str) =
#     substitute_regex_backref( $str, $regex, $replace )
#
#
# This sub routine is based on a stackoverflow.com answer
# by username Kent Fredric, see http://stackoverflow.com/a/392649/2173773
#
# Replace all occurences of $regex in $str with $replace.
# Returns number of replacements and the new string.
#
# The $regex input is assumed to be a regex quoted string. For example:
#  my $regex = qr/A simple (\w+) example/;
#
# The replacement string $replace is allowed to have backreferences:
#   Example: $replace = "a $1 b"
# "$1" is here treated as a backreference. It corresponds to capture group number 1
# in the $regex string.
#
# The replacement string $replace can also have backslash escaped dollar signs,
#  Example:  $replace = "\$1 a $1 b"
# Such escaped dollar signs should be replaced by
#  a literal '$' (and not treated as a backreference)

# Note: This subroutine was written to avoid using the ee modifier technique:
#   $var =~ s/$find/$replace/ee;
# which has sequrity risks if the $replace string comes from user input.
#
sub substitute_regex_backref {
    my ( $str, $regex, $replace ) = @_;

    # First obtain an array @m of matches
    my @m = $str =~ /$regex/g;
    if (@m == 0) {
        return (0, $str);
    }
    my $special_character_seq = "\x41\x42\x43\x44";

    # Remove any dollar signs from $str
    $str =~ s/\$/$special_character_seq/g;

    # If $regex contain escaped dollar signs (to be treated as
    # literal dollar signs), we need to replace
    # them with $special_character_seq since we have removed all
    # dollar signs in the previous line
    $regex =~ s/\\\$/$special_character_seq/g;

    # Do the replacement, but dollar signs in the $replace variable
    # are left as literal dollar signs
    $str =~ s/$regex/$replace/g;

    # Replace backslash escaped dollar signs with special string
    $str =~ s/\\\$/$special_character_seq/g;

    # use "reverse" function to cope with mixed one- and two-digit back references
    # For example, $12 should be dealt with before $1, in order to avoid confusion.
    for( reverse 0 .. $#m ){
        my $n = $_ + 1;
        my $val = $m[$_];

        # Replace "$n" with the value of capture group
        $str =~ s/\$$n/$val/g;
        }
        # Reinsert all literal dollar signs:
        $str =~ s/$special_character_seq/\$/g ;
    return (@m + 0, $str);
}

Any comments and suggestions are appreciated. I am especially concerned with the use of the $special_character_seq variable, if it is necessary or how to avoid using it..


texts:
My first go at a Higher Order Component in react.

Aims to give a component the ability to call an url repeatedly with a given refresh interval.

Seems to be working as I want. I'm not 100% confident that I'm using async/await correctly.

<MyComponent refresh={interval} url={`https://reqres.in/api/users?per_page=${count}`} />

The HOC:

import React  from 'react'
import PropTypes from 'prop-types';

const apiCaller = () => WrappedComponent =>
    class extends React.Component {

        static propTypes = {
            url: PropTypes.string.isRequired,
            refresh: PropTypes.number.isRequired
        }

        static defaultProps = {
            url: '',
            refresh: 0
        }

        state = {
            error: null,
      data: null,
      loading: false
    }

      componentWillUnmount() {
            clearInterval(this.timer)
      }

        async componentDidMount() {
            try {

                // Call URL and wait for complete.
                await this.callApi(this.props.url)

                // Set up the refresh
                this.timer = setInterval(
                    () => this.callApi(this.props.url),
                    this.props.refresh * 1000
                )

            } catch (e) {
                this.setState({
                    loading: false,
                    error: e
                })
            }
        }

        async componentWillReceiveProps(nextProps) {
            try {
              if(this.props.url !== nextProps.url || this.props.refresh !== nextProps.refresh) {

                    // Get rid of the old timer.
                    clearInterval(this.timer)

                    // Call URL and wait for complete.
                    await this.callApi(nextProps.url)

                    // Set up the refresh again.
                    this.timer = setInterval(
                        () => this.callApi(nextProps.url),
                        nextProps.refresh * 1000
                    )
              }
            } catch (e) {
                this.setState({
                    loading: false,
                    error: e
                })
            }
        }

        async callApi(url){
            this.setState({
                loading: true
            })

            const response = await fetch(url)

            const json = await response.json()

            this.setState({
                data : json.data,
                loading: false
            })
        }

        render(){
            return <WrappedComponent {...this.state} {...this.props}  />
        }
    }

export { apiCaller }


texts: SQL query on percentage share of different groups in total


texts: Generate unique random strings considering collisions

texts:
I'm coding a random strings generator. It's working, but I'm not sure if this is efficient.
/**
 * @param n          total number of strings to generate
 * @param length     length of generated strings
 * @param charsetStr charset to be used when generate
 */
public static List<String> generateRandomStrings(int n, int length, @NonNull String charsetStr) {
    if (n < 1 || length < 1 || charsetStr.length() < 1) {
        throw new IllegalArgumentException(String.format("Illegal argument(s): %d, %d, %s", n, length, charsetStr));
    }

    //remove duplicate chars
    Set<Character> charset = new HashSet<>(charsetStr.length());
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < charsetStr.length(); i++) {
        char c = charsetStr.charAt(i);
        if (charset.add(c)) {
            sb.append(c);
        }
    }
    charsetStr = sb.toString();

    BigDecimal caseNum = BigDecimal.valueOf(charsetStr.length()).pow(length);
    BigDecimal nBd = BigDecimal.valueOf(n);
    if (caseNum.compareTo(nBd) < 0) {
        throw new IllegalArgumentException(
                String.format("Number of possible strings cannot exceed the requested size: (length of '%s') ^ %d < %d", charsetStr, length, n));
    }

    if (nBd.divide(caseNum, 1, RoundingMode.HALF_UP).compareTo(BigDecimal.valueOf(5, 1)) < 0) {
        //when fill factor is below 50%
        //generate until target size is reached
        Set<String> results = new HashSet<>(n);
        while (results.size() < n) {
            results.add(RandomStringUtils.random(length, charsetStr));
        }
        return new ArrayList<>(results);
    }

    // when fill factor is above 50%
    // pre-generate all possible strings
    List<String> results = new ArrayList<>(caseNum.intValue());
    generateAllPossibleStrings(results, "", charsetStr, length);

    // then shuffle the collection and pick target sized sublist
    Collections.shuffle(results);
    return results.subList(0, n);
}

public static void generateAllPossibleStrings(@NonNull List<String> results, @NonNull String prefix, @NonNull String charset, int length) {
    if (prefix.length() >= length) {
        results.add(prefix);
        return;
    }

    for (int i = 0; i < charset.length(); i++) {
        generateAllPossibleStrings(results, prefix + charset.charAt(i), charset, length);
    }
}

Any advice would be grateful, but my main focus here is performance.
I'm using org.apache.commons.lang3.RandomStringUtils to generate strings if n is less than 50% of the number of all possible strings(let's call it "fill factor"). If not, to avoid unnecessary collisions, I generate all possible strings using generateAllPossibleStrings, then shuffle the result and get a sublist from it.
The reasons I used 2 methods for generating strings are:

If the fill factor is low(like 1~2%), using generateAllPossibleStrings seemed overkill. So I used org.apache.commons.lang3.RandomStringUtils, hoping collisions not matter much.
If the fill factor is high(like more than 90%), using org.apache.commons.lang3.RandomStringUtils seems inefficient since a lot of collisions will occur as time goes by. So I used generateAllPossibleStrings in this case, dropping without any collision looks more efficient than generating.

There is no big reason why I choose 50% as a diverging point; I just used my hunch. This too may need to be fixed.
While I mostly wrote about the collision, I'm looking for any advice on performance enhancements. How can I make this more time-efficient?


texts: SICP Exercise 1.3: Sum of squares of two largest numbers out of three, Haskell Version

texts:
The exercise 1.3 of the book Structure and Interpretation of Computer Programs asks the following:

  Exercise 1.3.  Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

My answer is this:

    import Data.List(sort)

    sumSquareLargest :: (Ord n, Floating n) => n -> n -> n -> n
    sumSquareLargest x y z = b ** 2 + c ** 2 where
        [a, b, c] = sort[x, y, z]

Am I doing unnecessary work here? How could I improve this answer, even if only stylistically-speaking?


texts:
I have a solution for a circular array. How can I improve this?

package oopdesign.CircularArrayNes;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;

public class ArrayIterator<T> implements Iterable<T> {

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

    @Override
    public void forEach(Consumer<? super T> action) {

    }

    @Override
    public Spliterator<T> spliterator() {
        return null;
    }
}

package oopdesign.CircularArrayNes;

public class CircularArray<T> {

    protected T[] array;
    protected int limit;
    protected int pointer;
    protected int index;

    protected CircularArray(){
        limit = 5;
        T[] array = (T[])new Object[limit];
        pointer = 0;
        index = 0;
    }

    public void add(T data){
        index = getCurrentIndex() + 1;
        array[index] = data;
        pointer++;
    }

    public int getCurrentIndex()
    {
        return (pointer) % limit;
    }

    public void delete(T data){
        // 4 5 9 11 1
        // delete 9
        int deleteIndex = findIndex(data);
        if (deleteIndex == -1) return;
        for(int i=deleteIndex;i< array.length-1;i++) {
            array[deleteIndex] = array[deleteIndex+1];
        }
        pointer-- ;
    }

    private int findIndex(T data) {
        for(int i=0;i< array.length;i++) {
          if (array[i] == data){
              return i;
          }
        }
        return -1;
    }

}


texts: A set of queries in PHP to show occupancy of various cabins

texts:
Okay so as I learn more about PHP and really strive to improve my code I have a few questions about a current setup of mine and how to approach it in the best way.

I think I have all the tools necessary to get this done the right way, but I am having trouble putting them together. I am also trying to separate my code better.

Scenario: the script in question is cabins.php which basically pulls information from the db to populate the page with cabin information based on the cabin id $_GET variable. So the user clicks on a cabin, then the page is populated with that cabins information. There are four sub menus to choose from for each cabin so I am accessing this information using a switch statement, but I am having trouble finding the best way to run my queries.

My data is structured that most of the cabin information is held in 'cabin_content' but I also have 'cabin_large_images' and 'cabin_small_images' which each hold images that are tied to the cabin_content table through cabin_id.

Each sub section requires different information from the cabin_content table, but each sub section ALWAYS requires all the images from cabin_large_images that match the cabin id.

So each section is like this:
-we must query cabin_content and get the specific information we need
-we must query cabin_large_images and get all the images with the cabin_id.

One section requires all of the above plus we have to query cabin_small_images and get all the images from that table with matching cabin id.

So right now I have it set up like this, which I know needs improvement...obviously that is why I am here...Pseudo code:

if(isset($_GET['cabin')){

 //run the query to get cabin_large_images because we know we need them regardless of the section

   if(isset($_GET['type'])){
      $type = $_GET['type'];

       switch ($type){

       case 'a':

//run the query on cabin_content for the specific info we need in this situation

       break;

       case 'b':

//run the query on cabin_content for the specific info we need in this situation

       break;

       case 'c':

//run the query on cabin_content for the specific info we need in this situation
//run an additional query on cabin_small_images

       break;

      }

 }

//populate content to view

Okay so obviously what I don't like about this is we are running as many as three queries per page load. I tried using inner joins, but I just could never access what I needed from the query properly:

SELECT cabin_name, peak_week, max_occupancy, image
FROM cabin_content
INNER JOIN cabin_images
  ON cabin_content.cabin_id = cabin_images.cabin_id
WHERE cabin_content.cabin_id = '$cabin'";

The issue here is that we can end up with multiple images from $row['images'] which we then need to iterate through in the view. Now, we complicate the situation even more when for case 'c' we also need to query cabin_small_images:

SELECT cabin_name, peak_week, max_occupancy, image, image_small
FROM cabin_content
INNER JOIN cabin_images
  ON cabin_content.cabin_id = cabin_images.cabin_id
INNER JOIN cabin_small_images
  ON cabin_images.cabin_id = cabin_small_images.cabin_id
WHERE cabin_content.cabin_id = '$cabin'";

So, from that I need all the regular content and I need to iterate through 'image' and 'small_images' and I just could never get it right.

Alright so in closing, if the way I have it structured is good, then fine, but I have a feeling the best way to do this is with the joins, in which case I need help accessing all the information from the query. Or I need your other conceptual suggestions on the best way to do this!


texts: Ansible playbook to install application from tarball

texts:
I'm doing this, but as I'm the expert here (because no-one else is doing it) I have no real idea how awesome my code actually is.

So the code should do the following:

Export the tarball from subversion on the target box
Untar it.
Run the install script, answering questions appropriately.

For this review, I'd love input into whether this can be done differently, should generally follow different rules or whether it's just he best code you've ever seen.

-
  hosts: localhost
  become: true
  remote_user: root
  become_user: root
  become_method: su
  tasks:
  - name: Grab the encrypted variables
    include_vars:
      file: secret_things
      name: secrets

  - name: Grab the non-encrypted variables
    include_vars:
      file: mech_cfg.yml
      name: mech_cfg

  - name: install pip
    yum:
      name: python-pip
      state: latest

  - name: install pexpect==3.3 -- required for the expect module
    pip:
      name: pexpect
      version: 3.3

  - name: Get the tarball from subversion
    subversion:
      repo: https://repo/path
      dest: /tmp/mechballs
      username: "{{ secrets.svn_user }}"
      password: "{{ secrets.svn_pass }}"
      export: yes
      force: yes

  - name: Expand the tarball
    unarchive:
      src: /tmp/mechballs/{{ mech_cfg.mech_tarball }}.tar.gz
      dest: /tmp/mechballs/
      remote_src: true

  - name: Install the tarball
    expect:
      chdir: /tmp/mechballs/{{ mech_cfg.mech_tarball }}
      command: ./doinstall
      echo: yes
      responses:
        "Where do you want to install.*": "/opt/location"
        "Do you want to proceed with the installation .*" : "y"


texts: count pairs of matching integers in a collection in Common Lisp

texts:
This defines count-pairs which

takes a collection of integers
returns the number of pairs of integers that are equal to each other.

If the input collection has these integers ...
1 2 0 2 1 3 2

... then count-pairs returns 2 because

one pair can be made with the 1's
a second pair can be made with the 2's
The leftover unpaired integers do not affect the answer.

(defun make-pair (table i)
  (setf
   ;; increment pair count:
   (gethash 'pairs table) (1+ (gethash 'pairs table 0))
   ;; make first half of the new pair unavailable:
   (gethash i table) nil)
  table)

(defun keep-first-half-of-pair (table i)
  (setf (gethash i table) t)
  table)

(defun first-half-available-p (table i)
  (gethash i table))

(defun consider-one (table i)
  (if (first-half-available-p table i)
      (make-pair table i)
      (keep-first-half-of-pair table i)))

(defun count-pairs (integers)
  (let ((table (reduce #'consider-one
                       integers
                       :initial-value
                       (make-hash-table))))
    (gethash 'pairs table 0)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; boilerplate for running as a hacker rank submission
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(read-line) ;; we don't need n

(defvar integers
  (read-from-string
   (concatenate 'string
                "(" (read-line) ")")))

(format t "~a~%" (count-pairs integers))

Some questions I have:

What changes would make this more idiomatic?
Is there an alternative for setf that returns the modified container instead of the multiple values returned by the storing form for the last altered place? (See how I really want the container as the result of make-pair and keep-first-half-available-p ...)
Should I stick with the -p naming convention for predicates? It seems ending with a ? is possible and looks more readable to me.
I guess Emacs knows if is a macro and is indenting it that way?
If there is an entirely different and better way to solve in Common Lisp, please do let me know.

Thanks in advance!


texts: Executor tasks for parallelizing a method

texts:
So I am trying to delete a list having n number of objects and thereby I divided the list in 4 parts and let it to be deleted in parallel. The intention here is to do it in parallel so as to make it fast rather than sequential. deleteObject(x) can be assumed as an API which finally deletes an object has the code to take care of concurrency. It returns true on successful delete and false otherwise

I have few question here

So as I have 4 parallel method which I am executing though invokeAll
and there are 4 threads declared by Executors.newFixedThreadPool(4)
would there always be 1 thread be assigned to 1 method?
Do I need to synchronize and use volatile for iterator 'i' in the for loop of parallelDeleteOperation() method. The reason I am asking this is supposing if 1st thread has not completed its task (deleting listDir1 and the for loop has not completed) and supposing in midway it got context switch and 2nd thread starts executing the same task(deleting listDir1). Just wondering if 2nd thread can get IndexOutOfBound exception in this case.
Is there any advantage of dividing list in 4 parts and executing this rather than having multiple threads executing delete operation on a very big list.
If one of the operation of ExecutorService returns false then on the whole deleteMain() API would return false

public boolean deleteMain(List<Integer> listDir) {
if(listDir.size()<4){
    return parallelDeleteOperation(listDir);
}
final List<Integer> listDir1 = listDir.subList(0, listDir.size() / 4);
final List<Integer> listDir2 = listDir.subList(listDir.size() / 4, listDir.size() / 2);
final List<Integer> listDir3 = listDir.subList(listDir.size() / 2, (listDir.size()/ 4) *3);
final List<Integer> listDir4 = listDir.subList((listDir.size()/ 4)*3, listDir.size());`
Set<Callable<Boolean>> callables = new HashSet<Callable<Boolean>>();
callables.add(new Callable<Boolean>() {
    @Override
    public Boolean call() throws Exception {
        return parallelDeleteOperation(listDir1);
    }
});
callables.add(new Callable<Boolean>() {
    @Override
    public Boolean call() throws Exception {
        return parallelDeleteOperation(listDir2);
    }
});
callables.add(new Callable<Boolean>() {
    @Override
    public Boolean call() throws Exception {
        return parallelDeleteOperation(listDir3);
    }
});
callables.add(new Callable<Boolean>() {
    @Override
    public Boolean call() throws Exception {
        return parallelDeleteOperation(listDir4);
    }
});

ExecutorService service = Executors.newFixedThreadPool(4);
try {
    List<Future<Boolean>> futures = service.invokeAll(callables);

for(Future<Boolean> future : futures){
    if( future.get() != true)
        return future.get();
}
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}finally{
service.shutdown();
}
return true;
}
public boolean parallelDeleteOperation(List<Integer> listDir) {
for (int i = 0; i < listDir.size(); i++) {
    int x = listDir.get(i);
    deleteObject(x);
    if(deleteObject(x)!=true)
        return false;
     }
return true;
}


texts: Extract Students with All Enrolments in the Past

texts:
I am trying to extract the students where all of their enrolments are in the Past.

Some students can have more than one Enrolment and one of its End Date is in the future while the other one is in the past

In the above Sample Data, I want to get only one Record 'BBB' in my result.

I managed to achieve it by using CTE by comparing no. of Total Records vs no. of Total Records in the Past.

WITH T1 AS
(SELECT
    RefNo
    , Total = COUNT(RecordID)
    , TotalPastRecords = SUM(IIF(EndDate < GETDATE(), 1, 0))
FROM
    Enrolments
GROUP BY
    RefNo)
SELECT
  *
FROM
  T1
WHERE
  Total = TotalPastRecords

Could you guy please review the above code and let me know if there is a way to improve it?

Our Enrolment Table contains around 200,000 rows and this query is going to join to another 4-5 tables to get the final Result.


texts: Fetching detail for a given ID, which might not exist

texts:
I'm actually working on a piece of code which use the following code:

public Detail GetDetail(int id)
{
    if (!_detail.ContainsKey(id))
    {
        GetDetailForNewObjects(id);
    }

    return _detail[id].Data;
}

The last line throws a NullReferenceException. Since it should not happen that this method is called in the way it returns an exception they propose not to catch it and rethrow a more specific and descriptive one.

I don't agree. The software readability and the maintainability of the cose falls dramatically when we get a NullReferenceException.

How would you write that piece of code?


texts: Check Three Dom Elements to See if they are empty or not and return detailed result

texts:
I am checking three elements on the DOM to see if they are empty or not so that I can run only the Ajax calls that I should run and save on overall bandwidth. The code works but it "smells bad". Here is my source.
const processValues = (area, city, text) => {
    if (area.val() && city.val() && text.val()) {
        return 'all';
    } else if (area.val() && city.val() && !text.val()) {
        return 'areaCity';
    } else if (area.val() && !city.val() && text.val()) {
        return 'areaText';
    } else if (area.val() && !city.val() && !text.val()) {
        return 'city';
    } else if (!area.val() && city.val() && text.val()) {
        return 'cityText';
    } else if (!area.val() && !city.val() && text.val()) {
        return 'text';
    } else if (!area.val() && city.val() && !text.val()) {
        return 'city';
    } else {
        return 'none';
    }
};

I will be repeating this check in a few methods and I will be using a switch statement in those methods with the returned string values. If there is a better way to do this, I would appreciate it.


texts: Loop whose endpoint (?) change during the loop

texts:
I have a loop which insert rows on specific cases. The loop goes through ~2000 rows and insert about 500.

Due to the inserted rows it doesn't loop the full range I want. I have solved that problem by counting the number of row I will insert with a first loop and then looping up to LastRow + Counter.

I feel as if there must have been a better way to do it.

Sub AddRows()
Dim i As Integer: i = 8
Dim LastRow As Integer: LastRow = Cells(8, 2).End(xlDown).Row
Dim counter As Integer: counter = 0

For i = 8 To LastRow
    If Cells(i, 1) <> "" Then
        counter = counter + 1
    End If
Next i

NewLastRowAfterAddingRows = LastRow + counter

For i = 8 To NewLastRowAfterAddingRows
    If Cells(i, 1) <> "" Then
        Range(i + 1 & ":" & i + 1).Insert CopyOrigin:=xlFormatFromRightOrBelow
        i = i + 1
    End If
Next i

End Sub


texts: List objects in a Amazon S3 folder without also listing objects in sub folders

texts:
I'm using the Amazon S3 Java SDK to fetch a list of files in a (simulated) sub-folder.  This code is rather standard (AWSConfiguration is a class that contains a bunch of account specific values):

String prefix = "/images/cars/";
int prefix_size = prefix.length();
AmazonS3 s3 = new AmazonS3Client(new AWSConfiguration());
ObjectListing objectListing = s3.listObjects(new ListObjectsRequest().
    withBucketName(AWSConfiguration.BUCKET).
    withPrefix(prefix));

Now this list will include objects like /images/cars/default.png as well as /images/cars/ford/Default.png (because they both contain the same prefix). To list only the objects that are directly inside the /images/cars/ "folder" I have the following function (in a class called S3Asset)

public static boolean isInsideFolder(int root_size, String key) {
  return (key.substring(root_size).indexOf("/") == -1);
}

This looks at the full key for any / after the prefix as a clue that it is inside a sub-folder.  This lets me iterate over the objects with the following code (I'm trimming the prefix for clarity):

for(S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
  if(S3Asset.isInsideFolder(prefix_size, objectSummary.getKey())) {
    System.out.println(objectSummary.getKey().substring(prefix_size));
  }
}

As near as I can tell this is the cleanest way to do this but it has one characteristic that I don't like. If I'm looking a root level folder I'm requesting the names of all files in all sub-folders only to iterate over them and learn that there is only one object in the actual root level folder.  I've considered associating a key with the value being the full path of the folder, which would allow me to request objects with a predictable key instead of the prefix, but the major downside to this is that the key would have to be generated in code and therefor assets uploaded directly in to the S3 Bucket (through the management console) would not have this key.  Anyone have a better idea?


texts: Implementing a Trie in Python using lists alone

texts:
I've been working on implementing a Trie in Python for educational purposes. I tried implementing one using dictionaries and I was successful.

The structure of a trie with the words in, inn, inner, innerr would be as follows:

[['i', [['n', [['n', [['e', [['r', [['r', [], 'end']], 'end']]]], 'end']], 'end']]]]

where end indicates the end of a word.

class TrieException(Exception):
    pass

def add_word(word, trie):
    END = "end"
    if word == '':
        raise TrieException("word empty")

    prev = None
    branch = trie

    for i, c in enumerate(word):
        found = False
        for each in branch:
            if each[0] == c:
                if i == len(word)-1:
                    if len(each) > 2:
                        raise TrieException("Word already present")
                    else:
                        each.append(END)
                prev = branch
                branch = each[1]
                found = True
                break
        if not found:
            nb = []
            if i == len(word)-1:
                branch.append([c, nb, END])
            else:
                branch.append([c, nb])
            branch = nb

def search_word(word, trie):
    if word == '':
        raise TrieException("empty word")

    branch = trie
    for i, c in enumerate(word):
        found = False
        for each in branch:
            if each[0] == c:
                found = True
                branch = each[1]
                if i == len(word)-1:
                    if len(each) <= 2:
                        raise TrieException("Word not found")
                break
        if not found:
            raise TrieException("Word not found")

Do you have any suggestions on how I can do this in a cleaner fashion?


texts: Unit testing a click event with asynchronous content

texts:
I'm writing unit tests for a web application that has quite a lot of UI interactions. I would like some feedback regarding on how to handle click events with asynchronous code.

My goal here is to simluate users interacting with the page. That's why I'm triggering events rather than making function calls.

Here is my idea so far:

$('#foo').on('click', function(){

     var dfd = $.Deferred();

     simulateAsync().done(dfd.resolve).fail(dfd.reject);
     $(this).data({ promise: dfd.promise() });
});

function simulateAsync(){

    var dfd = $.Deferred();

    setTimout(function(){
        $('body').text('foo');
        dfd.resolve();
    }, 1000);

    return dfd.promise();
}

Testing the code:

test('foo text set on body after 1000ms when clicking #foo', function(assert){

    var $foo = $('#qunit-fixture').find('#foo'),
        done = assert.async();

    $foo.trigger('click');

    var completePromise = $foo.data('promise');

    completePromise.done(function(){
        assert.equal($('#bar').text(), 'bar');
        done();
    });
});

http://jsfiddle.net/0m4t4ndt/2/


texts: Automating the installation and configuration of Vim

texts:
I am writing a script to automate the install and configuration of vim, zsh, ohmyzsh and tmux, on a Linux/Mac. I'd like to perform all operations in Python, rather than using subprocess to streamline some of the operations (e.g. git clone).

I would also like to use this script as an example to myself of good Python coding practice for file system operations. Code clarity, reuse and pythonic style are my primary objectives. Before I write the remainder of the script I'd like some input on the methods I've chosen for low level operations,  but all areas of the script are open for scrutiny.

from urllib.request import urlretrieve
from urllib.error import URLError
from zipfile import ZipFile
import sys
import os
import errno
import shutil

vim = ".vimtest"
vim_directories = [vim, (vim + "/bundle"), (vim + "/autoload"), (vim + "/colors")]
vim_files = [".vimrctest", vim + "/vimrc"]
flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY

def vim_install():

    # Create directories and files

    for sub in vim_directories:
        try:
            os.mkdir(os.path.expanduser('~/' + sub))
            print("mkkdir " + os.path.expanduser('~/' + sub))
        except OSError as e:
            if e.errno == errno.EEXIST:
                print("Directory " + vim + sub + " already exists.")
                sys.exit(1)
            else:
                raise

    try:
        file_handle = os.open(os.path.expanduser('~/' + vim_files[1]), flags)
    except OSError as e:
        if e.errno == errno.EEXIST:
            print("File " + vim_files[1] + " already exists")
            sys.exit(1)
        else:
            raise
    with os.fdopen(file_handle, 'w') as file_obj:
        file_obj.write("")
    print("Created file " + os.path.expanduser('~/') + vim_files[1])

    try:
        os.symlink(os.path.expanduser('~/') + vim_files[1],
        os.path.expanduser('~/') + vim_files[0])
        print("ln -s " + os.path.expanduser('~/') + vim_files[0] + " -> " +
        os.path.expanduser('~/') + vim_files[1])

    except OSError:
        print("Failed to make symbolic link.")
        print("ln -s " + os.path.expanduser('~/') +
        vim_files[0] + " -> " + os.path.expanduser('~/') +
        vim_files[1])
        sys.exit(1)

    # Download Pathogen, NerdTree, unpack

    try:
        urlretrieve("https://tpo.pe/pathogen.vim",
                        os.path.expanduser('~/' + vim + "/autoload/pathogen.vim"))
        print("Downloaded Pathogen")

        urlretrieve("https://github.com/scrooloose/nerdtree/archive/master.zip",
                        os.path.expanduser('~/' + vim + "/bundle/master.zip"))
        print("Downloaded NerdTree")

    except URLError as e:
        if hasattr(e, 'reason'):
            print('Scrip failed to reach a server.')
            print('Reason: ', e.reason)
        elif hasattr(e, 'code'):
            print('The server couldn\'t fulfill the request.')
            print('Error code: ', e.code)
       else:
            raise

    try:
        zip_ref = ZipFile(os.path.expanduser('~/') + vim +
        "/bundle/master.zip", 'r')
        zip_ref.extractall(os.path.expanduser('~/') + vim + "/bundle/")
        zip_ref.close()
        print("Unziped NerdTree")

    except OSError as e:
        print("Could not unzip: {0}".format(e))

    try:
        os.rename(os.path.expanduser('~/' + vim + "/bundle/nerdtree-master"),
        os.path.expanduser('~/' + vim + "/bundle/nerdtree"))
        print("Renamed " + os.path.expanduser('~/') + vim +
        "/bundle/nerdtree-master \n"
          + os.path.expanduser('~/') + vim + "/bundle/nerdtree")

    except OSError as e:
        print("OS error {0}".format(e))


texts: Boolean flags encoded as integer implemented with EnumSet

texts:
I'm a beginner in Java so I would appreciate a review of following simple class - in fact it's my first real usage of enums.

The background: I'm parsing MySQL internal client-server protocol. One of the fields in server greeting and client authorization packet is "Client capabilities" which is 32 bit integer encoding 18 boolean flags ( if anyone is interested: http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#Handshake_Initialization_Packet)

I've read that the most 'java way' to implement such thing will be using EnumSet class.

I'll welcome any suggestions and other solutions - my needs are:

I must be able to parse flags from 4 bytes big endian buffer
To encode flags back to 4 bytes big endian buffer
To check if some arbitrary flag is set

here's the code:

public class ClientCapabilities
{
    public enum Flag {
        CLIENT_LONG_PASSWORD (1<<0),
        CLIENT_FOUND_ROWS (1<<1),
        CLIENT_LONG_FLAG (1<<2),
        CLIENT_CONNECT_WITH_DB (1<<3),
        CLIENT_NO_SCHEMA (1<<4),
        CLIENT_COMPRESS (1<<5),
        CLIENT_ODBC (1<<6),
        CLIENT_LOCAL_FILES (1<<7),
        CLIENT_IGNORE_SPACE (1<<8),
        CLIENT_PROTOCOL_41 (1<<9),
        CLIENT_INTERACTIVE (1<<10),
        CLIENT_SSL (1<<11),
        CLIENT_IGNORE_SIGPIPE (1<<12),
        CLIENT_TRANSACTIONS (1<<13),
        CLIENT_RESERVED (1<<14),
        CLIENT_SECURE_CONNECTION (1<<15),
        CLIENT_MULTI_STATEMENTS (1<<16),
        CLIENT_MULTI_RESULTS (1<<17);

        public final int weight;

        Flag(Integer weight) {
            this.weight = weight;
        }
    }

    private final int originalInt;
    private final EnumSet<Flag> flags = EnumSet.noneOf(Flag.class);

    public ClientCapabilities(int capabilities)
    {
        originalInt = capabilities;
        for (Flag f : Flag.values()) {
            if ((capabilities & f.weight) > 0) {
                flags.add(f);
            }
        }
    }

    public int getAsInt()
    {
        return originalInt;
    }

    public EnumSet<Flag> getFlags()
    {
        return flags;
    }

    @Override
    public String toString() {
        return flags.toString();
    }

    //only tests ahead - TestNG, not JUnit!
    @Test
    public static void testDecodingClientCapabilities()
    {
        byte[] exampleBuffer = new byte[] { (byte) 0x85, (byte) 0xa6, (byte) 0x03, (byte) 0x00 };
        EnumSet<Flag> expectedEnumSet = EnumSet.of(
                Flag.CLIENT_LONG_PASSWORD,
                Flag.CLIENT_LONG_FLAG,
                Flag.CLIENT_LOCAL_FILES,
                Flag.CLIENT_PROTOCOL_41,
                Flag.CLIENT_INTERACTIVE,
                Flag.CLIENT_TRANSACTIONS,
                Flag.CLIENT_SECURE_CONNECTION,
                Flag.CLIENT_MULTI_STATEMENTS,
                Flag.CLIENT_MULTI_RESULTS
        );

        ClientCapabilities capabilities = new ClientCapabilities(
                PacketByteBuffer.readIntFromFourBytes(exampleBuffer,0));

        Assert.assertEquals(capabilities.getFlags(), expectedEnumSet);
    }

    @Test
    public static void testEncodingClientCapabilities()
    {
        byte[] exampleBuffer = new byte[] { (byte) 0x85, (byte) 0xa6, (byte) 0x03, (byte) 0x00 };
        byte[] targetBuffer = new byte[] { 0, 0, 0, 0, 0};

        ClientCapabilities capabilities = new ClientCapabilities(
                PacketByteBuffer.readIntFromFourBytes(exampleBuffer,0));

        PacketByteBuffer.writeIntToFourBytes(targetBuffer, 1, capabilities.originalInt);

        Assert.assertEquals(targetBuffer[1], (byte) 0x85);
        Assert.assertEquals(targetBuffer[2], (byte) 0xa6);
        Assert.assertEquals(targetBuffer[3], (byte) 0x03);
        Assert.assertEquals(targetBuffer[4], (byte) 0x00);
    }
}


texts:
I am working on rewriting an application in Laravel 5.1. I am new to the exception handling technique introduced in 5.0. I have overlooked taking advantage of throwing/catching exceptions frequently in the past, but am working on this now. I am most likely not up to speed on some of the best practices.

public function render($request, Exception $e)
{

    switch (true) {

        case $e instanceof Exceptions\Auctions\AuctionTypeException:
            // Should I throw a new exception here? Is passing the old exception message to a new exception good practice?
            throw new Exceptions\Notifications\AlertException($e->getMessage());
            break;

        case $e instanceof Exceptions\Auctions\AuctionArgumentException:
            // Should I throw a new exception here? Is passing the old exception message to a new exception good practice?
            throw new Exceptions\Notifications\AlertException($e->getMessage());
            break;

        ////////////////////////////////////////////
        // Custom errors to display in error view //
        ////////////////////////////////////////////
        case $e instanceof Exceptions\Notifications\AlertException:

            return response()->view('errors.notification', ['message' => $e->getMessage(), 500]);
            break;

        //////////////////////////////////////////////
        // Unknown exceptions are rendered normally //
        //////////////////////////////////////////////
        default:
            return parent::render($request, $e);
    }

}

Docs for the exception handler are here.

While most of my exceptions will fall under the "explicitly ignore and continue" umbrella, I feel like I will need to handle my exceptions in a more abstract/polymophic way later down the road, so I am preparing now. This is a huge app, and I will have several custom Exceptions.

This code currently works and behaves as excepted. Exceptions that I explicitly state I want to do something special with can be added as a case, and if it is new, or I just want to handle it normally...it falls under the default.

I would like to know if I am going down the right path - to me, this seems like a fairly clever way to handle this. Is it a good idea to catch an exception, only to throw another exception with the previous exceptions message? Are there any pitfalls to checking the instance and evaluating true like this?


texts: Implementing a Scheduler(something that implements a given schedule)

texts:
I am trying to implement a class that implements a given schedule. I am trying to design this Scheduler class so it can be paused and everything. I have just written some example code so I can better convey my requirements. I would be grateful if more experienced minds could take a look and tell me if what I have right now is the right way to go about things or if there are better ways to do this. I'd really appreciate some thoughts.

class Scheduler {

    private object locker = new object();
    private System.Timers.Timer timer = new System.Timers.Timer();
    private int[] schedule = null;
    private int scheduleIndex = 0;
    private bool offline = true;
    private bool timerElapsed;

    private Thread th;

    public Scheduler() {
        timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsedHandler);
        th = new Thread(RunSchedule);
        th.Start();
    }

    public void RunSchedule() {
        lock (locker) {
            while (schedule == null || scheduleIndex > schedule.length) // this will not throw a NullReferenceException since schedule == null is being checked first
                Monitor.Wait(locker);

            while (offline)
                Monitor.Wait(locker);

            // pick up next schedule and start timer and wait till timer finishes
            int nextSchedule = schedule[scheduleIndex];

            // call external program to execute schedule

            timer.Interval = 120 * 1000;
            timerElapsed = false;
            timer.Start();
            while(!timerElapsed)
                Monitor.Wait(locker);
        }
    }

    public void Offline() {
        lock (locker) {
            // pause thread executing RunThread
            offline = true;
            // also kill timer if running
            if (timer.Enabled) {
                timer.Stop();
                timerElapsed = true;
                Monitor.Pulse(locker);
            }
        }

    }

    public void Online() {
        lock (locker) {
            //Pulse thread executing RunThread
            offline = false;
            Monitor.Pulse(locker);
        }
    }

    public void OfflineTooLong() {
        lock(locker) {
            this.schedule = null;
        }
    }

    public void ScheduleReady(int[] schedule) {
        lock (locker) {
            this.schedule = schedule;
            this.scheduleIndex = 0;
            Monitor.Pulse(locker);
        }
    }

    private void TimerElapsedHandler(object sender, System.Timers.ElapsedEventArgs) {
        lock(locker) {
            scheduleIndex++;
            timerElapsed = true;
            Monitor.Pulse(locker);
        }
    }
}

As you can see from the code, the intent is to "pause" the thread implementing the schedule when Offline and restart the thread when Online. Also, if you've run through all schedules(ie either schedule == null because you've been Offline too long or scheduleIndex > schedule.length), it should wait to receive a new schedule.

Any thoughts and help will be much appreciated.


texts: Show that sum and product are both examples of accumulation

texts:
Given this task:

  Exercise 1.32

  a. Show that sum and
  product (exercise 1.31) are both
  special cases of a still more general
  notion called accumulate that combines
  a collection of terms, using some
  general accumulation function:

  (accumulate combiner null-value term a
  next b)

  Accumulate takes as arguments the same
  term and range specifications as sum
  and product, together with a combiner
  procedure (of two arguments) that
  specifies how the current term is to
  be combined with the accumulation of
  the preceding terms and a null-value
  that specifies what base value to use
  when the terms run out. Write
  accumulate and show how sum and
  product can both be defined as simple
  calls to accumulate.

  b. If your accumulate procedure
  generates a recursive process, write
  one that generates an iterative
  process. If it generates an iterative
  process, write one that generates a
  recursive process.

I wrote the following solution:

Recursive:

(define (accumulate combiner null-value term a next b)
  (if (> a b) null-value
      (combiner (term a)
                (accumulate combiner
                            null-value
                            term
                            (next a)
                            next
                            b))))

Iterative:

(define (i-accumulate combiner null-value term a next b)
  (define (iter a result)
    (if (> a b) result
        (iter (next a) (combiner (term a) result))))
  (iter a null-value))

Sum/Product using iterative accumulate:

(define (sum term a next b) (i-accumulate + 0 term a next b))
(define (product term a next b) (i-accumulate * 1 term a next b))

What do you think?


texts:
I recently wrote the following code:

def freq_progress
    user_flashcards = input_flashcards.includes(:term)
    terms_unicos = user_flashcards.map(&:term).compact.uniq

    freq_1, freq_2, freq_3, freq_4, freq_5 = 0, 0, 0, 0, 0
    terms_unicos.each do |term|
      case term.ranking
      when nil
        next
      when 1..100
        freq_1 += 1
      when 101..300
        freq_2 += 1
      when 301..1000
        freq_3 += 1
      when 1001..2000
        freq_4 += 1
      when 2001..5000
        freq_5 += 1
      else
        next
      end
    end
    {
        f1: freq_1,
        f2: freq_2,
        f3: freq_3,
        f4: freq_4,
        f5: freq_5
    }
  end

In the code review, our technical manager told me that parallel assignment is considered bad practice.

In the Ruby style guide, it says:

  Avoid the use of parallel assignment for defining variables. Parallel assignment is allowed when it is the return of a method call, used with the splat operator, or when used to swap variable assignment. Parallel assignment is less readable than separate assignment.

However, I figure that this would apply mostly to situations where each variable is set to a different value, and that my particular use case (setting all values to 0, the same "boring" value) would potentially be an exception to the readability rule.

In other words, it seems that this would emphasize the "equal" nature of the 5 variables.

This may be a matter of opinion, but since the Ruby style guide recommends against it, I’d love to hear what Rubyists more experienced than I have to say about this.

As well as any opportunities for refactoring!

Thanks, Michael

p.s. this question was originally posted on StackOverflow, but I was told to close the question and move it to Code Review.


texts: Implement metaclass for Maximumlikelihood estimator

texts:
For the purpose of defining a lot of Maximum Likelihood estimators,
I think I need a metaclass.

At the moment I have to copy/paste a lot of code for every new class definition and just substitute the corresponding scipy.stats functions.

from scipy.stats import fisk, t
from statsmodels.base.model import GenericLikelihoodModel
from inspect import signature

class Fisk(GenericLikelihoodModel):
    """A maximum likelihood estimator for the fisk distribution.
    """

    nparams = 3

    def loglike(self, params):
        return fisk.logpdf(self.endog, *params).sum()

    def fit(self, **kwargs):
        if 'start_params' not in kwargs:
            # This is for performance and! convergence stability.
            # The scipy function provides better starting params.
            kwargs['start_params'] = fisk.fit(self.endog)
        res = super().fit(**kwargs)
        res.df_model = self.nparams
        res.df_resid = len(self.endog) - self.nparams
        return res

class T(GenericLikelihoodModel):
    """A maximum likelihood estimator for the Student-T distribution.
    """

    nparams = 3

    def loglike(self, params):
        return t.logpdf(self.endog, *params).sum()

    def fit(self, **kwargs):
        if 'start_params' not in kwargs:
            # This is for performance and! convergence stability.
            # The scipy function provides better starting params.
            kwargs['start_params'] = t.fit(self.endog)
        res = super().fit(**kwargs)
        res.df_model = self.nparams
        res.df_resid = len(self.endog) - self.nparams
        return res

With a metaclass I automated this code definition

class ML_estimator(type):
    def __new__(cls, clsname, bases, dct, f):
        return super().__new__(cls, clsname, (GenericLikelihoodModel, ), dct)

    def __init__(cls, clsname, bases, dct, f):
        cls.nparams = len(signature(f.pdf).parameters)
        def loglike(self, params):
            return f.logpdf(self.endog, *params).sum()
        cls.loglike = loglike

        def fit(self, **kwargs):
            if 'start_params' not in kwargs:
                # This is for performance and! convergence stability.
                # The scipy function provides better starting params.
                kwargs['start_params'] = f.fit(self.endog)
            res = super(cls, self).fit(**kwargs)
            res.df_model = self.nparams
            res.df_resid = len(self.endog) - self.nparams
            return res
        cls.fit = fit

class Fisk(metaclass=ML_estimator, f=fisk):
    pass

class T(metaclass=ML_estimator, f=t):
    pass

Does this seem like a reasonable application of metaclasses?
What improvements do you have?

The ML-estimator can be tested with:

sample = fisk.rvs(c=1, size=1000)
res = Fisk(sample).fit()
res.summary()