texts: Function to grab stdin, stdout, stderr of a child process

texts:
I've managed to create a function to pipe the stdin, stdout and stderr of a child process and provide them as file descriptors to read and write to:

pid_t opencmd(pipes, path, argv)
    int *const pipes;
    const char *const path;
    char *const *const argv;
{
    if (!pipes || !path || !argv)
        goto error_in;

    int in[2];
    int out[2];
    int err[2];
    pid_t pid;

    /*
     * Creating pipes in between ...
     */
    if (pipe(in))
        goto error_in;
    if (pipe(out))
        goto error_out;
    if (pipe(err))
        goto error_err;

    /*
     * Starting actual processing ...
     */
    pid = fork();
    switch (pid) {
     case -1:       /* Error */
         goto error_fork;
     case 0:        /* Child */
         close(in[1]);
         close(out[0]);
         close(err[0]);

         dup2(in[0], 0);    /* redirect child stdin to in[0] */
         dup2(out[1], 1);   /* redirect child stdout to out[1] */
         dup2(err[1], 2);   /* redirect child stderr to err[1] */
         execv(path, argv); /* actual command execution */
         return -1; /* shall never be executed */
     default:       /* Parent */
         close(in[0]);  /* no need to read its stdin */
         close(out[1]); /* no need to write to its stdout */
         close(err[1]); /* no need to write to its stderr */

         pipes[0] = in[1];  /* Write to child stdin */
         pipes[1] = out[0]; /* Read child stdout */
         pipes[2] = err[0]; /* Read child stderr */
         return pid;
    }
/* This section is never be reached without a goto */
  error_fork:
    close(err[0]);
    close(err[1]);
  error_err:
    close(out[0]);
    close(out[1]);
  error_out:
    close(in[0]);
    close(in[1]);
  error_in:
    return -1;
}

A cleaning function for it:

int closecmd(pid, pipes)
    const pid_t pid;
    int *pipes;
{
    int status;

    close(pipes[0]);
    close(pipes[1]);
    close(pipes[2]);
    waitpid(pid, &status, 0);
    return status;
}

Are there any issues I'm overlooking with them?


texts: Returns the year for each month by period - nested case statements

texts:
def return_year_by_month_and_period(month)
pw = self.property_water.first().billing_increment
case pw
  when "12"
    self.property_water.where(period: month).first().year
  when "6"
    case month
      when 1, 2
        self.property_water.where(period: 1).first().year
      when 3, 4
        self.property_water.where(period: 2).first().year
      when 5, 6
        self.property_water.where(period: 3).first().year
      when 7, 8
        self.property_water.where(period: 4).first().year
      when 9, 10
        self.property_water.where(period: 5).first().year
      else
        self.property_water.where(period: 6).first().year
    end
  when "4"
    case month
      when 1, 2, 3
        self.property_water.where(period: 1).first().year
      when 4, 5, 6
        self.property_water.where(period: 2).first().year
      when 7, 8, 9
        self.property_water.where(period: 3).first().year
      else
        self.property_water.where(period: 4).first().year
    end
  when "2"
    case month
      when 1, 2, 3, 4, 5, 6
        self.property_water.where(period: 1).first().year
      else
        self.property_water.where(period: 2).first().year
    end
  else
    self.property_water.first().year
end
end

"Period" in the text above is one of months, bi-monthly, quarterly, semi-annually or annually.

For each of the 12 months in the calendar year, we want to associate a year (e.g. 2015) with the month depending on what year is associated with the period.

First let me say - I think the database modeling for this particular thing is horribly FUBAR.  I inherited the project - and re-making the database is on the roadmap, but not the immediate need.

So in the example above, if I had a period of 2 (bi-monthly) - I would only have 6 records in the property_waters table.  But I still have 12 months, so I need to say "the 1st period is Jan and Feb" and this logic has to carry.  The property_waters table does NOT have a 'month' column, meaning my two attributes are period and year.  From the period, I can determine which months belong in which group, and return the year of the period.

The code works - but even after I wrote it I knew I could do better.  I just can't see it, so please help me learn a better way to do this.

EDIT:
Billing increment for every record is always the same integer as the period. So if we have 6 records for billing period of bi-monthly, all 6 records have billing_increment = 6.

Ridiculous I know. We can just count the records to return this same thing...


texts:
I'm generating all combinations of an array, so for instance, ["a", "b", "c", "d"] will generate:

[
  "a",    "b",    "ab",   "c",    "ac",
  "bc",   "abc",  "d",    "ad",   "bd",
  "abd",  "cd",   "acd",  "bcd",  "abcd"
]

Here's the code I've written that does complete this task.

What I'd like to know is if there is a better way, as iterating over the array twice feels like I'm cheating, or the complexity of the code is much more computationally expensive than it needs to be.

Also, the name for a function that takes an array and returns the combinations, what might that be called? Combinator seems inappropriate.

var letters = ["a", "b", "c", "d"];
var combi = [];
var temp= "";
var letLen = Math.pow(2, letters.length);

for (var i = 0; i < letLen ; i++){
    temp= "";
    for (var j=0;j<letters.length;j++) {
        if ((i & Math.pow(2,j))){
            temp += letters[j]
        }
    }
    if (temp !== "") {
        combi.push(temp);
    }
}

console.log(combi.join("\n"));


texts: Merge entities which have the same children

texts:
The C# code below, using LINQ to Entities, aims to merge all Class entities which have the same SubjectId and the same Students.

var sb = new StringBuilder();
var counter = 0;

using (var ctx = new Ctx())
{
  var allClasses = ctx.Classes.Where(o => o.SubjectId > 0).OrderBy(o => o.Id).ToList();
  foreach (var c in allClasses)
    ctx.LoadProperty(c, o => o.Students);

  // For each class...
  for (var i = 0; i < allClasses.Count; i++)
  {
      var c = allClasses[i];
      var duplicates = allClasses
             .Where(o => o.SubjectId == c.SubjectId && o.Id != c.Id &&
                         o.Students.OrderBy(s => s.Id).Select(s => s.Id)
                              .SequenceEqual(c.Students.OrderBy(s => s.Id)
                                                  .Select(s => s.Id)))
             .ToList();

      // Does it have any duplicates?
      if (duplicates.Count == 0)
          continue;

      ctx.LoadProperty(c, o => o.PeriodsTimetable);
      // For each duplicate...
      for (var j = 0; j < duplicates.Count; j++)
      {
          var d = duplicates[j];
          // If the duplicate class has a timetable slot that's not also allocated to
          // the class we are keeping, then allocate it (otherwise MySql will delete it).
          ctx.LoadProperty(d, o => o.PeriodsTimetable);
          var dt = d.PeriodsTimetable.ToList();
          for (var k = 0; k < dt.Count; k++)
          {
              var dtp = dt[k];
              var tpIsDuplicate = false;
              foreach (var ctp in c.PeriodsTimetable)
              {
                  if (dtp.TeacherId == ctp.TeacherId &&
                      dtp.PeriodTime == ctp.PeriodTime)
                  {
                      tpIsDuplicate = true;
                  }
              }

              if (!tpIsDuplicate)
                  dtp.ClassId = c.Id;
      }

      // Now update all other entities which reference the duplicate to instead
      // reference the class we are keeping.
      var dPeriods = ctx.Periods.Where(o => o.ClassId == d.Id).ToList();
      for (var k = 0; k < dPeriods.Count; k++)
          dPeriods[k].ClassId = c.Id;

      var dAssessments = ctx.Assessments.Where(o => o.ClassId == d.Id).ToList();
      for (var k = 0; k < dAssessments.Count; k++)
          dAssessments[k].ClassId = c.Id;

      var dSeatingPlans = ctx.SeatingPlans.Where(o => o.ClassId == d.Id).ToList();
      for (var k = 0; k < dSeatingPlans.Count; k++)
          dSeatingPlans[k].ClassId = c.Id;

      var dMerits = ctx.Merits.Where(o => o.ClassId == d.Id).ToList();
      for (var k = 0; k < dMerits.Count; k++)
          dMerits[k].ClassId = c.Id;

      sb.Append(d.LongName).Append(" merged with ").Append(c.LongName).Append(".
");
      // Finally, delete the duplicate
      ctx.Classes.DeleteObject(d);
      allClasses.Remove(d);
      counter++;
    }
  }
  ctx.SaveChanges();
  lblOutput.Text = "Merged " + counter + " duplicate classes.

" + sb.ToString();
}

For an idea of scale, there are about 1600 classes with 30 students each, and counter comes out at just over 300.

I'd really appreciate any suggestions.


texts:
Is there a way I could somehow have all this classes condensed into one, while keeping the code as clean as possible?

They are all doing essentially the same thing, just for the different number type. I don't know how to "generalize" TryParse() without using switch or if tree which doesn't seem very clean to me.

Base class:

public class TextBoxNum<T> : TextBox where T : IComparable<T>
{
    protected T min;
    protected T max;

    protected Value<T> value;

    public virtual void Update(object sender, EventArgs e)
    {

    }

    protected T Clamp(T input)
    {
        if (input.CompareTo(max) > 0)
        {
            return max;
        }

        if (input.CompareTo(max) < 0)
        {
            return min;
        }

        return input;
    }

    public TextBoxNum(Value<T> value, T min, T max)
    {
        this.value = value;
        this.min = min;
        this.max = max;

        LostFocus += new EventHandler(Update);
    }
}

Int variant:

public class TextBoxInt : TextBoxNum<int>
{
    public override void Update(object sender, EventArgs e)
    {
        int newValue;

        if (int.TryParse(Text, out newValue))
        {
            if (newValue < min || newValue > max)
            {
                newValue = Clamp(newValue);
            }

            value.Set(newValue);
            Text = value.Get().ToString();
        }

        else
        {
            Text = value.Get().ToString();
            Focus();
        }
    }

    public TextBoxInt(Value<int> value, int min, int max) : base(value, min, max)
    {

    }
}

UInt variant:

public class TextBoxUInt : TextBoxNum<uint>
{
    public override void Update(object sender, EventArgs e)
    {
        uint newValue;

        if (uint.TryParse(Text, out newValue))
        {
            if (newValue < min || newValue > max)
            {
                newValue = Clamp(newValue);
            }

            value.Set(newValue);
            Text = value.Get().ToString();
        }

        else
        {
            Text = value.Get().ToString();
            Focus();
        }
    }

    public TextBoxUInt(Value<uint> value, uint min, uint max) : base(value, min, max)
    {

    }
}

ULong variant:

public class TextBoxULong : TextBoxNum<ulong>
{
    public override void Update(object sender, EventArgs e)
    {
        ulong newValue;

        if (ulong.TryParse(Text, out newValue))
        {
            if (newValue < min || newValue > max)
            {
                newValue = Clamp(newValue);
            }

            value.Set(newValue);
            Text = value.Get().ToString();
        }

        else
        {
            Text = value.Get().ToString();
            Focus();
        }
    }

    public TextBoxULong(Value<ulong> value, ulong min, ulong max) : base(value, min, max)
    {

    }
}

Float variant:

public class TextBoxFloat : TextBoxNum<float>
{
    public override void Update(object sender, EventArgs e)
    {
        float newValue;

        if (float.TryParse(Text, out newValue))
        {
            if (newValue < min || newValue > max)
            {
                newValue = Clamp(newValue);
            }

            value.Set(newValue);
            Text = value.Get().ToString();
        }

        else
        {
            Text = value.Get().ToString();
            Focus();
        }
    }

    public TextBoxFloat(Value<float> value, float min, float max) : base(value, min, max)
    {

    }
}


texts: Removing jQuery event handler from single element bound by delegate

texts:
I'm binding a handler to the keyup event of all input and textareas in a document:

$(document).on('keyup','input,textarea',$.debounce(600, editor.handleGlobalChange));

I don't want the handler to fire on a specific input field. So I want to unbind the keyup event:

$('#afield').off('keyup');

However this does not unbind the keyup event, the handler is still called. I assume this is because there is no keyup event bound to the $('#afield') element, the event is just bubbling up to the $(document) where the actual handler is bound.

So to stop it triggering I can do the following:

$('#afield').on('keyup',function(e) {
    e.stopImmediatePropagation();
});

This works, but it feels grim, setting a handler to stop another.

Is this acceptable or should I just no bind the event in the first place?

I could ignore certain classes or a custom data-nokeyup attribute:

$(document).on('keyup','input,textarea,not([data-nokeyup]',$.debounce(600, editor.handleGlobalChange));

I have to use a delegated event handler because my inputs and textareas are created after the initialisation code is run. $('input,textarea').keyup(...) would return no elements. $(document).on('keyup','input,textarea',...) catches all keyup events and inspects the event's target element.


texts:
I've discovered that using hashed passwords with salts is a much better idea than MD5/SHA256, so I'm not hashing them with PBKDF2. However, I'm wondering if this is a correct approach to authorizing my user. I also have logic for logging authorizations. When the same IP has entered an incorrect login/pass, it becomes banned for 5 minutes.

Administrator a is passing Username and Password.
Checking if Username exists.
Checking if the password is correct for this user.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Authorize(Administrator a)
{
    // Check if there are no failed login attempts in last 5 minutes
    if (!this.CanAdminLogin)
    {
        TempData["loginTooManyAttempts"] = true;
        return RedirectToAction("index", "home");
    }

    // If model is not validated return login view to show error messages (javascript disabled)
    if (!TryValidateModel(a))
    {
        return View("Authorize", a);
    }

    // Check if username exists, if not then log and show that login failed
    var admin = _db.Administrators.Where(x => x.Username == a.Username).SingleOrDefault();
    if (admin == null || admin.Username != a.Username)
    {
        this.LogAuthorization(a, false);
        TempData["loginFailed"] = true;
        return RedirectToAction("index", "home");
    }

    // Username exists, check if passwords match
    ICryptoService cryptoService = new PBKDF2();
    string hash = cryptoService.Compute(a.Password, admin.PasswordSalt);
    if (hash == admin.Password)
    {
        this.LogAuthorization(a, true);
        Session["adminId"] = admin.ID;
    }
    else
    {
        this.LogAuthorization(a, false);
        TempData["loginFailed"] = true;
    }

    // Login successfull
    return RedirectToAction("index", "home");
}


texts: Filtering users in socket.io and seeing who is online

texts:
While implementing socket.io on my server, I ran into some problems and eventually fixed them. The code below is fired on the connection event of socket.io:

var newarray = []; //a new array
data.map(function(inde) { //data is an array which contains the data of the user's acc_id and some more information,
    newarray.push({
        enc: inde.fjbngh, //encrypted acc_id
        hmac: inde.asdty2 //hmac
    })
});
var users = []; // a new array which will contain the decrypted acc_id's
newarray.forEach(function(llol) {
    var dec = _SOME_DECRYPTION_FUNCTION_WITH_HMAC;
    users.push(dec); // decrypted acc_id stored in the array
})
uniq = [...new Set(users)]; // To get one values out of any unique values as with every user, i'm getting the logged in user's id, so this code whole code is executed once (not in a foreach loop)
var idst = {}; // a new object
idst['socket_id'] = socket.id;
idst['acc_id'] = Number(uniq[0]);
ids.push(idst);// ids is the main global array which contains the socket_id with a unique acc_id.

The job of the code above is to procure the acc_id of the logged in user and store it in a global array, by which we can know if a user is online or not.

This code fires up on the connection event of socket.io, and the reason why I'm storing acc_id with socket_id is that, whenever a user opens a new tab, web sockets gets 2 unique clients from the same browser but different tabs, so I saved it with an acc_idto avoid multiple clients from the same browser.

The reason for all the filtering is because, it's the connection event and with that, I'm sending all the acc_id(s) of the users, the logged in user needs to chat. I have settled that procedure.

Example of the data array object:

[{ id_of_another_user:'xx', hmac:'xx', id_of_logged_in_user:'xx', hmac:'xx'}]

On disconnection, the user is removed from the ids array. My question is, does this code perform its job in the most efficient way possible?

I have another doubt that might make this question broad, so I'll ask it later.


texts: Perfect Hash Family Non-Distinct t Columns Calculator

texts:
Perfect Hash Families (PHFs) are a widely studied combinatorial object. Essentially, they are 4-tuples (N; t, k, v), where the PHF is an N by k array of v symbols. For any t columns chosen, there is at least one row of those chosen columns that has no symbol duplicated in that row.

I want to be able to count how many "non-distinct" t-column choices there are in a given PHF. My code is below, with some sample inputs that I made up:

from itertools import combinations

def get_column(phf, c):
    return [x[c] for x in phf]

# returns the PHF as if we restrict to the "cs" columns (a list)
def combine_columns_into_array(phf, cs):
    r = []
    for c in cs:
        r.append(get_column(phf, c))
    return list(map(list, zip(*r)))

# returns the number of t-column choices that have no distinct rows
def count_non_distinct_combinations(phf, t):
    k = len(phf[0])
    true_count = 0
    # get all combinations
    for c in combinations([i for i in range(k)], t):
        b = False
        choices = combine_columns_into_array(phf, list(c))
        for row in choices:
            # if the row is completely distinct
            if len(row) == len(set(row)):
                b = True
        # if all rows are non-distinct:
        if not b:
            true_count += 1
    return true_count

phf = [
    [4, 2, 3],
    [2, 1, 3],
    [1, 1, 4]]

# first 2 columns have no distinct rows
phf2 = [
    [4, 4, 3],
    [2, 2, 3],
    [1, 1, 4]]

print(count_non_distinct_combinations(phf, 2)) # 0
print(count_non_distinct_combinations(phf2, 2)) # 1

I plan to use this code as a metric for how "good" the array is - what I mean by this is that I want, given the number of rows N, try to reduce this metric as much as possible. Therefore, speed/efficiency is the most important part of any review of this code.


texts: Simple binary search tree for use in programming competitions

texts:
I made a binary search tree implementation in C++ for my personal use in programming competitions.

#include <iostream>

using namespace std;

struct Node {
    int key;
    Node *leftnode;
    Node *rightnode;
    string value;
};

Node root_node; // Binary search tree

string inline query_bst(const int key) {
    Node *cur_node = &root_node;
    while (cur_node != NULL) {
        if (key == cur_node->key) {
            return cur_node->value;
        }
        if (key < cur_node->key) { /* value already returned, no need for else */
            cur_node = cur_node->leftnode;
        } else {
            cur_node = cur_node->rightnode;
        }
    }
    return ""; // Return empty string if not found
}
void inline insert_bst(int key, string value) {
    Node *cur_node;
    Node *next_node = &root_node;
    // Search through bst for key
    while (next_node != NULL) {
        cur_node = next_node;
        if (key < cur_node->key) {
            next_node = cur_node->leftnode;
        } else {
            next_node = cur_node->rightnode;
        }
    }
    Node new_node;
    new_node.key = key;
    new_node.value = value;
    next_node = &new_node;
    if (key < cur_node->key) {
        cur_node->leftnode = next_node;
    } else {
        cur_node->rightnode = next_node;
    }
}

int main() {
    /* Test code */
    root_node.key = 1;
    insert_bst(2, "Node #3");
    insert_bst(3, "Node #4");
    cout << query_bst(3) << '\n';
}

I'm not generalizing the code or using OOP because I typically will only need one BST for programming competitions. insert_bst should be able to be redesigned so next_node is not required thereby reducing computation time and shortening the code. query_bst returns an awkward string when it fails to find an element. Overall, I believe the code is a bit bulky and requires optimization to be feasible for use in a programming competition.


texts:
I inhereted an implementation of a singleton template.  Althoug I read that singletons are bad, my program uses singletons throughout and I can not get rid of them at the moment.

This is the implementation I started with:

template <typename T>
class Singleton
{
public:
    static T* ms_singleton;

    Singleton()
    {
        assert(!ms_singleton);
        long offset = (long)(T*) 1 - (long)(Singleton <T>*)(T*) 1;
        ms_singleton = (T*)((long) this + offset);
    }

    virtual ~Singleton()
    {
        assert(ms_singleton);
        ms_singleton = 0;
    }

    static T &instance()
    {
        assert(ms_singleton);
        return (*ms_singleton);
    }

    static T &Instance()
    {
        assert(ms_singleton);
        return (*ms_singleton);
    }

    static T* instance_ptr()
    {   return (ms_singleton); }
};

template <typename T>
T* Singleton <T>::ms_singleton = NULL;

And the new implementation.

#pragma once

template<typename T>
class Singleton
{
public:
    static T &Instance()
    {
        static T* myInstance;
        return (*myInstance);
    }

    Singleton(Singleton const &) = delete;
    Singleton(Singleton &&) = delete;
    Singleton &operator=(Singleton const &) = delete;
    Singleton &operator=(Singleton &&) = delete;

protected:
    Singleton() = default;
    virtual ~Singleton() = default;
};

The first code doesn't create the class and only sets a pointer to an existing instance; the new implementation does the same.

Do you think the second implementation is correct? Is there something that should be optimized or changed? There may be problems if I use it like that? Should I also handle the  creation of classes?

This new implementation should behave the same as first, because I have a big project and I just can't get rid of this singleton.

How good is the new singleton?


texts: Project Euler Problem #4 - Palindromic number (Revision 1)

texts:
I've cobbled together as best I could an answer using the format found here provided. I lack full understanding of how the LINQ query works and don't want to use it without understanding well the how and why of what's occurring.

Regarding NumberIsAPalindrome, I tried to use number.ToString().Reverse().ToString() but was unable to achieve the results I expected, so I reverted to a for...loop. Is this achievable?

class PalindromNumber
{
    public string GetPalindromeNumber(int maxNumber = 999)
    {
        var query = from first in ThreeDigitNumbers()
                    from second in ThreeDigitNumbers()
                    let product = first * second
                    where NumberIsAPalindrome(product)
                    select product;
        return query.Max().ToString();
    }

    public int[] ThreeDigitNumbers()
    {
        int[] numberArray = new int[900];
        for (int i = 0; i < numberArray.Length; i++)
        {
            numberArray[i] = 999 - i;
        }
        return numberArray;
    }

    public bool NumberIsAPalindrome(int number)
    {
        int reversedValue=0;
        string stringNumber = number.ToString();
        for (int i= stringNumber.Length-1; i >= 0; i--)
        {
            reversedValue += (int.Parse(stringNumber[i].ToString()) * (int)Math.Pow(10,i) );
        }
        return number == reversedValue;
    }
}


texts: How can I Implement a better version of my function find the closest number to zero?

texts:
I recently had to do a test for a job interview, and the prompt was to code a function that returns the closest number to 0 given an array of negative and positive numbers.

My function works correctly but I heard back from the recruiter saying that my function is not very performant and that the readability was not great, here are the problem that they mentioned:

Performances à double check (filter + sort + for + push + reserve + shift, 4 identical call to Math.abs)
Lack of readability ( 4 if / else if)
I would like to know how I could have improved my function to make it more performant and more readable?

here's my function:

const closestToZero = (arr) => {
  // 1-a variables:
  let positiveNumbers = [];
  let negativeNumbers = [];

  // 1-b returns 0 if the input is either undefined or an empty array
  if(typeof(arr) === 'undefined' || arr.length === 0) {
    return 0
  }

  // 2- filter out non-number values then sort the array
  const onlyNumbers = arr.filter(item => typeof(item) === 'number').sort((a,b) => a-b);

  // 3- split the numbers into positive numbers and negative numbers
  for(let i = 0; i < onlyNumbers.length; i++) {
    if(onlyNumbers[i] > 0) {
      positiveNumbers.push(onlyNumbers[i])
    } else if (onlyNumbers[i] < 0) {
      negativeNumbers.push(onlyNumbers[i])
    }
  }

  // 4- reverse the negative array to get the closest to 0 at the first index
  let reversedNegativeArray = negativeNumbers.reverse()

  // 5- get rid of all the other values and keep only the closest to 0, if array empty return 0
  let closestPositiveNumber = positiveNumbers.length > 0 ? positiveNumbers.shift() : 0
  let closestNegativeNumber = reversedNegativeArray.length > 0 ? reversedNegativeArray.shift() : 0

  // 6- Compare the result of the substraction of the closestPositiveNumber and the closestNegativeNumber to find the closestToZero
  if(closestPositiveNumber - Math.abs(closestNegativeNumber) > 0 && closestNegativeNumber === 0 ) {
    return closestPositiveNumber
  } else if (closestPositiveNumber - Math.abs(closestNegativeNumber) < 0 && closestPositiveNumber === 0) {
    return closestNegativeNumber
  } else if(closestPositiveNumber - Math.abs(closestNegativeNumber) > 0) {
    return closestNegativeNumber
  } else if (closestPositiveNumber - Math.abs(closestNegativeNumber) <= 0) {
    return closestPositiveNumber
  }
}

requirements:

if the closest number in input could be either negative or positive, the function returns the positive one
if the input array is undefined or empty, the function returns 0

when input is [8, 5, 10] the function returns 5

when input is [5, 4, -9, 6, -10, -1, 8] the function returns -1

when input is [8, 2, 3, -2] the functions return 2


texts: A basic Object Orientated REPL Implementation

texts:
Here is a very basic object orientated implementation of a read evaluate print loop AKA REPL. I encluded REShell to demonstrate how one could use Reple

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

import re
import sre_constants

PS1 = '>> '

DEFAULT_EVALUATOR = print

class Repl(object):
    def __init__(self, evaluator=DEFAULT_EVALUATOR):
        self.ps1 = PS1
        self.evaluator = evaluator

    def read(self):
        return input(self.ps1)

    def evaluate(self):
        return self.evaluator(self.read())

    def run(self):
        while 1:
            try:
                self.evaluate()
            except KeyboardInterrupt:
                sys.exit(0)

class REShell(Repl):
    def __init__(self, data):
        self.data = data
        self.ps1 = PS1

    def evaluate(self):
        try:
            expression = re.compile(self.read())
            print(*expression.findall(self.data), sep='\n')
        except sre_constants.error as error:
            print(error)

def source_code():
    with open(__file__, 'r') as source:
        return source.read()

if __name__ == '__main__':
    data = source_code()
    print(data)
    shell = REShell(data)
    shell.run()


texts: Reverse Groups challenge at CodeEval.com

texts:
I am working through challenges at CodeEval.com and wanted to get your input on my code for this challenge.

  Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time. If the number of elements is not a multiple of k, then the remaining items in the end should be left as is.

  Input sample:

  Your program should accept as its first argument a path to a filename. Each line in this file contains a list of numbers and the number k, separated by a semicolon. The list of numbers are comma delimited.

  E.g. input:

1,2,3,4,5;2
1,2,3,4,5;3

  Output sample:

  Print out the new comma separated list of numbers
  obtained after reversing. E.g.

2,1,4,3,5
3,2,1,4,5

-(void)reversedGroups
{
    NSString *line = @"22,23,24,25,26,27,28,29,30;3";   //input sample
    NSArray *lineArray = [line componentsSeparatedByString:@";"];
    NSUInteger numbElements = [[lineArray lastObject] intValue];
    NSArray *elementsArray = [[lineArray objectAtIndex:0] componentsSeparatedByString:@","];
    NSMutableArray *resultLineArray = [[NSMutableArray alloc]init];

    NSUInteger pos = 0;
    while (pos<[elementsArray count]) {
        //itterating through the elements
        if (pos+numbElements <= [elementsArray count]) {
            //make sure that i have enough elements to reverse
            for (NSUInteger i = pos+numbElements; i>pos; i--) {
                //add elements in reverse to the result array
                [resultLineArray addObject:[elementsArray objectAtIndex:i-1]];
            }
        }else {
            for (NSUInteger j = pos; j<[elementsArray count]; j++) {
                //add elements that are left to the result array
                [resultLineArray addObject:[elementsArray objectAtIndex:j]];
            }
        }
        pos += numbElements;  // move the postion by number of elements to reverse
    }
    //convert results array to string and add comma after each element as required for output
    NSString *resultString = [[resultLineArray valueForKey:@"description"] componentsJoinedByString:@","];
    NSLog(@"%@",resultString);

}


texts: Creation of playlist to fake-split a full-album video

texts:
I created this snippet to "split" my full-album videos into its individual songs without the need of actually splitting the video file.

I personally created this snippet because I enjoy reading all musics from a directory in shuffle mode and stumbling upon a full album kinda ruins the point.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

__author__ = 'JeromeJ'
__website__ = 'http://www.olissea.com/'

# Match example for this regex:
#   32. Random song title - 1:33:05
DEFAULT_PATTERN = '^[0-9]+\.\s*(?P<SONG_TITLE>.*?)\s*-\s*(?P<START_TIME>[0-9]+\:[0-9]+(?:\:[0-9]+)?)'

SONG_TITLE = '{ALBUM_TITLE}: {SONG_TITLE}'  # What the song will be titled
ALBUM_TITLE = ''

import pathlib
import re

import pdb

print('M3U8 PLAYLIST MAKER')
print('Please put a .txt file containing the songs\' list next to the album')
print('with the same name as the album file.')
print()
print('The playlist will be saved in current directory.')
print('The links in the playlist are relative, not absolute.')
print()

# TODO: Idea: Allow to drag-and-drop the file on the script to run it.
#   -> Doesn't seem to work (Tried on W7 only so far)
filename = input('Path to album? ')

txt_file = str(pathlib.Path(filename).with_suffix('.txt'))

# Saves the playlist in the current directory with the same name as the album
playlist_file = pathlib.Path(filename).stem + '.m3u8'

pattern = input('Pattern for the songs\' list? (Default: {})\n'.format(DEFAULT_PATTERN)) or DEFAULT_PATTERN
song_title = input('Song title? (Default: {}) '.format(SONG_TITLE)) or SONG_TITLE
album_title = input('Album title? (Default: {}) '.format(ALBUM_TITLE)) or ALBUM_TITLE

playlist_entries = []

with open(txt_file, mode='r', encoding='utf-8') as song_list:
    for i, line in enumerate(song_list):
        r = re.search(pattern, line)

        # pdb.set_trace()

        start_time = r.group('START_TIME').split(':')
        start_time = \
            int(start_time[-1]) \
            + int(start_time[-2])*60 \
            + (int(start_time[-3])*60*60 if len(start_time) > 2 else 0)

        playlist_entries.append(
            """#EXTVLCOPT:start-time={start_time}
#EXTVLCOPT:stop-time={stop_time}
#EXTINF:0, - {album_title}: {song_title}
{filename}""".format(
                start_time=start_time,
                stop_time='{stop_time}',  # To be set by the next iteration
                album_title=album_title,
                song_title=r.group('SONG_TITLE'),
                filename=filename
            )
        )

        if i:
            playlist_entries[i-1] = playlist_entries[i-1].format(stop_time=start_time)

# Up until the end of the file
playlist_entries[-1] = playlist_entries[-1].format(stop_time=0)

with open(playlist_file, 'w', encoding='utf-8') as f:
    f.write('\n\n'.join(playlist_entries))

print()
input('Done. Press Enter to leave.')

Any advice/opinion about how to improve this code in its Python-ness is welcome!

What 'could' be improved?
What is wrong or advised against?

EDIT: As I've been suggested I could/should turn this into a lib. For my excuse this is "just a snippet".

Also I want to keep it as KISS as possible.

Example:
The script turns this:

01. Once Upon a Time - 00:00
02. Start Menu - 01:28
03. Your Best Friend - 02:00

Into this:

#EXTVLCOPT:start-time=0
#EXTVLCOPT:stop-time=88
#EXTINF:0, - Undertale: Once Upon a Time
..\Full albums\Undertale OST.mp4

#EXTVLCOPT:start-time=88
#EXTVLCOPT:stop-time=120
#EXTINF:0, - Undertale: Start Menu
..\Full albums\Undertale OST.mp4

#EXTVLCOPT:start-time=120
#EXTVLCOPT:stop-time=144
#EXTINF:0, - Undertale: Your Best Friend
..\Full albums\Undertale OST.mp4


texts:
I have a list of raw data like following mockData and need to generate to a object[] format, some key-value pair are required from raw data like first, last, state. but some key-value pair are option like nickname. Eventually, I need to build a object array with some same key-value like raw data, and some key's value depends on another key's value like fullname, address. If there is a better way for me to do it and make it more dynamically? because I will have more than 20 different key-value set like fullname, address that need to be built by some function related on raw data

export const mockData: Human[] = [
  {
    first: 'name1',
    last: 'v1',
    state: 'ny',
  },
  {
    first: 'name2',
    last: 'v2',
    state: 'pa',
    nickname: 'rocketman',
  }]

export interface Human {
  first: string;
  last: string;
  state: string;
  nickname?: string;
}

export interface Student extends Human{
  fullname: string;
  address: string;
}

function setFullName(first: string, last: string): string {
    return `${first} ${last}`
}

function setAddress(first: string, last: string, state: string): string {
    return `${first} ${last} live a ${state}`
}

function buildStudentData(jsons: Human[]): Student[] {
  return jsons.map((json) =>  <Student> {
      first: json.first,
      last: json.last,
      nickname:  json.hasOwnProperty('nickname') ? json.nickname : json.first,
      fullname: setFullName(json.first, json.last),
      address: setAddress(json.first, json.last, json.state)})
}

console.log(buildStudentData(mockData));


texts:
With the comments on the same line as the code, it refers to. e.g

NumBob = 0
s = 'sexbobombob'
i = range(len(s)+1) #Generates a list from 0 to the length of s
u = 0 # This would be the variable storing each value of the list
for ans in i: # this allows me to extract each value of i
    if ans > 0: # Completely arbitrary. i just used any condition that allows me to pick up all values in the list.
        u = ans
    x = s[u:u+3] #By using indexing to pick u, u+1, and u +2 i can pick up 3 letters at a time
    if "bob" in x: # Checking if the term i picked up is a Bob
        numBob += 1 # increasing the Bob count
print "Number of times bob occurs is:" + str(numBob) # Printing the number of Bobs

With the comments beneath the line of code, it refers to. e.g

numBob = 0
s = 'sexbobombob'
i = range(len(s)+1)
#Generates a list from 0 to the length of s
u = 0
# This would be the variable storing each value of the list
for ans in i:
    # this allows me to extract each value of i
    if ans > 0:
        # Completely arbitrary. i just used any condition that allows me to pick up all values in the list.
        u = ans
    x = s[u:u+3]
    #By using indexing to pick u, u+1, and u +2 i can pick up 3 letters at a time
    if "bob" in x:
        # Checking if the term i picked up is a Bob
        numBob += 1
        # increasing the Bob count
print "Number of times bob occurs is:" + str(numBob)
#Printing the number of Bobs

Or with the comments preceding the line of code. e.g

numBob = 0
s = 'sexbobombob'
#Generates a list from 0 to the length of s
i = range(len(s)+1)
# This would be the variable storing each value of the list
u = 0
# this allows me to extract each value of i
for ans in i:
    # Completely arbitrary. i just used any condition that allows me to pick up all values in the list.
    if ans > 0:
        u = ans
    # By using indexing to pick u, u+1, and u +2 i can pick up 3 letters at a time
    x = s[u:u+3]
    # Checking if the term i picked up is a Bob
    if "bob" in x:
        # increasing the Bob count
        numBob += 1
        # Printing the number of Bobs
print "Number of times bob occurs is:" + str(numBob)


texts:
The Problem

  Sam Morose served for many years as communications officer aboard the U.S.S. Dahdit, a U.S. Coast Guard frigate
  deployed in the South Pacific. Sam never quite got over the 1995 decision to abandon Morse code as the primary ship-to
  shore
  communication scheme, and was forced to retire soon after because of the undue mental anguish that it was causing.
  After leaving the Coast Guard, Sam landed a job at the local post office, and became a model U.S. Postal worker…
  That said, it isn’t surprising that Sam is now holding President Clinton hostage in a McDonald’s just outside the
  beltway. The FBI and Secret Service have been trying to bargain with Sam for the release of the president, but they find it
  very difficult since Sam refuses to communicate in anything other than Morse code. Janet Reno has just called you to write a
  program that will interpret Sam’s demands in Morse code as English.
  Morse code represents characters of an alphabet as sequences of dits (short key closures) and dahs (longer key
  closures). If we let a period (.) represent a dit and a dash (-) represent a dah, then the Morse code version of the English
  alphabet is:

  Sample Input

  Your program must takes its input from the ASCII text file morse.in. The file contains periods and dashes representing
  a message composed only of the English alphabet as specified above. One blank space is used to separate letters and three
  blanks are used to separate words. Sample contents of the file could appear as follows:

.... . .-.. .-.. ---   -- -.--   -. .- -- .   .. ...   ... .- --

  Sample Output

  Your program must direct its output to the screen and must be the English interpretation of the Morse code found in the
  input file. There must be no blanks between letters in the output and only one blank between words. You must use all
  capital letters in the output. The output corresponding to the input file above is:

HELLO MY NAME IS SAM

code.py

import re

codes = {
    '.-':'A',
    '-...':'B',
    '-.-.':'C',
    '-..':'D',
    '.':'E',
    '..-.':'F',
    '--.':'G',
    '....':'H',
    '..':'I',
    '.---':'J',
    '-.-':'K',
    '.-..':'L',
    '--':'M',
    '-.':'N',
    '---':'O',
    '...':'S',
    '-':'T',
    '..-':'U',
    '...-':'V',
    '.--':'W',
    '-..-':'X',
    '-.--':'Y',
    '--..':'Z'
}

with open('morse.in') as f:
    for line in f:
        t = []
        for s in line.strip().split(' '):
            t.append(codes.get(s) if s else ' ')
        print(re.sub(' +', ' ', ''.join(t)))

Any advice on performance enhancement and solution simplification is appreciated, as are topical comments!


texts: Displaying orders and customers in a table, filtering out duplicates

texts:
Can I make any further improvements to simplify / speed up this code? My reason for creating new arrays for the variables $name, $business, $email, $orderstatus is because when displaying results there will be identical order ID numbers stored in $orderid.

My script filters out the duplicates then with the remaining results matches up the keys from $orderid with the correct key in $name, $business, $email, $orderstatus

 <?php
session_start();
if (!isset($_SESSION['username'])){
header("location:login.php");
}
// DB Credentials
$dbusername = 'xxxx';
$dbpassword = 'xxxx';

// Connect to order database
$conn = new PDO('mysql:host=localhost;dbname=xxxx_orders', $dbusername, $dbpassword);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Select Order IDs from database
try {
$stmt = $conn->prepare('SELECT  o.*, c.fname, c.lname, c.business FROM xxxx_orders.orders o, xxxx_customers.customers c WHERE c.email = o.email');
$stmt->execute();
}
catch(PDOException $e) {
    echo "I'm sorry, xxxx. I'm afraid I can't do that.";
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}

// For each result create or add to the arrays $orderid,$name,$business,$email,$orderstatus
foreach ($stmt as $result) {

$orderid[]=$result['orderid'];
$name[]=$result['fname'] . " " . $result['lname'];
$business[]=$result['business'];
$email[]=$result['email'];
$orderstatus[]=$result['orderstatus'];

}

// Filter out duplicate order IDs from $orderid array
$orderid = array_unique($orderid);

// Display results section

foreach ($orderid as $key => $value) {
        echo "
";

        // Display First/Last name from array $name with $key being equal to the corresponding key from array $orderid.
        // The key is necessary to properly display the correct result
        echo "" . $name[$key] . "	";

        // Display business name from array $name with $key being equal to the corresponding key from array $orderid.
        // The key is necessary to properly display the correct result
        echo "" . $business[$key] . "	";

        // Display email from array $name with $key being equal to the corresponding key from array $orderid.
        // The key is necessary to properly display the correct result
        echo "" . $email[$key] . "	";

        // Display order status from array $name with $key being equal to the corresponding key from array $orderid.
        // The key is necessary to properly display the correct result
        echo "" . $orderstatus[$key] . "	";

        // Display First/Last name from array $name with $key being equal to the corresponding key from array $orderid.
        // The key is necessary to properly display the correct result
        echo "" . $orderid[$key] . "	";

        echo "
";
}
?>


texts: Determining if two strings are anagrams of each other

texts:
Is this code a good solution for the question, or is there a better way to do it?

package ArraysAndStrings;

import java.util.Arrays;

public class anagram{

    private boolean isAnagram = false;

    public boolean Anagrams(String str1, String str2){

        if(str1.length() != str2.length()){
            return isAnagram;
        }

        boolean [] char_set = new boolean[256];
        boolean [] char_set1 = new boolean [256];

        for(int i =0;i<str1.length();i++){

            int val1 = str1.charAt(i);
            int val2 = str2.charAt(i);

            char_set[val1] = true;
            char_set1[val2] = true;
        }

        if(Arrays.equals(char_set, char_set1)){
            isAnagram = true;
        }

        return isAnagram;

    }

    public static void main(String [] args){

        anagram ang = new anagram();

        System.out.println(ang.Anagrams("mary","army"));

    }

}


texts:
I wrote a simple, yet disgusting video thumbnail image generator method—which uses the MediaToolkit .NET library.

The code is not self-explanatory whatsoever, and it's extremely inefficient.

It accepts a video byte array & MIME type—and writes it to a video file. Then, it obtains the video file's duration, stores the middle frame, and writes it to an image file. Finally, it retrieves the image file bytes and returns them ... after deleting the video & image file.

How can I make it more efficient?

    public static byte[] GetVideoThumbnail(byte[] bytes, string mediaType)
    {
        var video = new MediaFile
        {
            Filename = Path.GetTempPath() + Guid.NewGuid() + MimeTypeMap.GetExtension(mediaType)
        };
        var image = new MediaFile { Filename = Path.GetTempPath() + Guid.NewGuid() + ".jpg" };
        File.WriteAllBytes(video.Filename, bytes);
        using (var engine = new Engine())
        {
            engine.GetMetadata(video);
            engine.GetThumbnail(video, image,
                new ConversionOptions { Seek = TimeSpan.FromSeconds(video.Metadata.Duration.TotalSeconds / 2) });
        }
        var thumbnail = File.ReadAllBytes(image.Filename);
        File.Delete(video.Filename);
        File.Delete(image.Filename);
        return thumbnail;
    }


texts: Multiple return statements smells like what?

texts:
Here's some code of mine that I don't like (this was my very first attempt at DI/IoC!). It's a small C# application that runs scheduled on one of our servers and is responsible for fetching the latest version of a VB6 codebase, compiling it and packaging an installer for it.

There's an Execute method in there that smells like... well you tell me what it smells like:

    /// <summary>
    /// Executes the build process.
    /// </summary>
    public override void Execute()
    {
        var errors = new List<string>();
        var logger = _logProvider.GetLogger(GetType().Name);

        DoArchiveOldInstallers(errors, logger);
        if (Properties.Settings.Default.StopOnBackupCurrentInstallerFailure && !DoBackupCurrentVersion(errors, logger))
        {
            OnExecutedCompleted(false);
            return;
        }

        if (Properties.Settings.Default.StopOnUpdateCodeBaseFailure && !DoGetLatestVersion(errors, logger))
        {
            OnExecutedCompleted(false);
            return;
        }

        if (Properties.Settings.Default.StopOnCompileFailure && !DoCompileCodeBase(errors, logger))
        {
            OnExecutedCompleted(false);
            return;
        }

        if (Properties.Settings.Default.StopOnBuildInstallerFailure && !DoBuildInstaller(errors, logger))
        {
            OnExecutedCompleted(false);
            return;
        }

        OnExecutedCompleted(true);
    }

    private void OnExecutedCompleted(bool success)
    {
        if (Completed != null) Completed(this, new CompletedEventArgs(success));
    }

Mea Culpa

Sorry this was posted like this. The conditions should read as follows:

if (!DoXXXXX(errors, logger) && !settings.StopOnXXXXXFailure)

This was a last-minute untested change I made just minutes prior to posting, without realizing it would totally mess up the method's logic.


texts: Moving mean square error between 2 arrays, 'valid', where they fully overlap

texts:
You can find my original post here on SO. I was very surprised that I couldn't find a pre-coded function doing a mean square error between a signal (array A, size a) and a pattern (array B, size b<a) in a sliding window fashion. Thus I made one... and obviously it needs a lot of code improvement. I don't really know how to vectorize the implementation.
The goal is to take the pattern, slide it across the signal one step at a time, and determine everytime the mean square error between the signal and the pattern.
from sklearn.metrics import mean_squared_error
import numpy as np

def correlate_edge_pattern(signal, pattern):

    ms_errors = list()
    k=0

    while True:

        data = signal[k:k+pattern.size]

        if data.size != pattern.size:
            break

        err = mean_squared_error(pattern, data)
        ms_errors.append(err)
        k+=1

    m = np.argmin(ms_errors)

    return m

As you can observe below, it works as expected:

Here is a small code sample to test it:
signal = -np.ones(1000)*20
signal[:100] = 0
signal[900:] = 0
noise = np.random.normal(0,1,size=1000)
noisy_signal = signal + noise

pattern = np.zeros(50)
pattern[:25] = -20


texts:
Code first, elaboration later:

// Fizzbuzz: 1..100, %3->fizz, %5->buzz, %15->fizzbuzz
// noif: do not use if/switch statements or ternary expressions
// LIMIT must be a power of 10
// WIDTH must be equal to log10(LIMIT)

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

#define LIMIT 100
#define WIDTH 2

char *
itoa(int n)
{
    static char out[WIDTH + 1];

    for(char *outp = out + WIDTH - 1; outp >= out; --outp, n /= 10)
        *outp = '0' + n % 10;

    return out;
}

void
fizzbuzz(int n)
{
    static char *FBSTR[4] = {"", "Fizz", "Buzz"};

    FBSTR[3] = itoa(n);
    fputs(FBSTR[1 * (n%3 == 0)], stdout);
    fputs(FBSTR[2 * (n%5 == 0)], stdout);
    fputs(FBSTR[3 * (n%3 > 0 && n%5 > 0)], stdout);
    putchar('\n');
}

int
main(void)
{
    for(int i = 1; i <= LIMIT; ++i)
        fizzbuzz(i);

    return 0;
}

I've been reading a little bit about the anti-if campaign, and decided to try my hand at a challenge: Fizzbuzz but without if statements.

Because I'm not trying to be cheap, that also means no switch statements,

switch(n % 3){
    case 0: fputs("fizz", stdout); break;
}

no ternary expressions,

fputs((n % 3 == 0) ? ("fizz") : (""), stdout);

and no contrived while loops.

int lock = 0;

while(lock++ == 0 && n % 3 == 0)
    fputs("fizz", stdout);


texts: Priority Queue implementation for top k frequent elements leetcode in Ruby

texts:
While working on the following leetcode problem: https://leetcode.com/problems/top-k-frequent-elements/ I used a Priority Queu implementation in Ruby. I have learned how to implement a Priority Queu in Java in  Robert Sedgewick's Algorithms book. When inserting Hashes into the Priority Queue for example { 1 => 3} this made me refactored the Priotity's Queue in such a way so I was able to compare two hashes values.
The implementation is much straight forward when your dealing with numbers and characters but it made me wonder what would be the best implementation with using objects or hashes.
def top_k_frequent(nums, k)
  ans = []
  h = Hash.new(0)

  nums.each do |num|
    h[num] += 1
  end

  heap = Heap.new
  h.each do |k,v|
    heap.insert({k => v})
  end

  k.times do
    a = heap.del_max
    ans.push(a.keys[0])
  end

  ans
end

class Heap
  def initialize
    @n = 0
    @pq = []
  end

  def insert(v)
    @pq[@n += 1] = v
    swim(@n)
  end

  def swim(k)
    while k > 1 && less((k / 2).floor, k)
      swap((k / 2).floor, k)
      k = k/2
    end
  end

  def swap(i, j)
    temp = @pq[i]
    @pq[i] = @pq[j]
    @pq[j] = temp
  end

  def less(i, j)
    @pq[i].values[0] < @pq[j].values[0]
  end

  def del_max
    max = @pq[1]
    swap(1, @n)
    @n -= 1
    @pq[@n + 1] = nil
    sink(1)
    max
  end

  def sink(k)
    while 2 * k <= @n
      j = 2 * k

      if !@pq[j + 1].nil?
        j += 1 if j > 1 && @pq[j].values[0] < @pq[j + 1].values[0]
      end
      break if !less(k, j)

      swap(k, j)
      k = j
    end
  end
end

There are a few things that come to mind that I wish to probably learn. Keep in mind that I would like to prepare for algorithm interviews and so I would like to avoid as much synthetic sugar as possible.

@pq[j].values[0] check for example how to get to a hash values I need to use values[0] is there a better way for this?
There are 3 loops in the top_k_frequent method. How would yo go about optimizing this implementation?
a.keys[0] notice how I get the key of the element in Ruby is there a cleaner way of doing this?

This brought to my attention that in case of dealing with more complex objects the Priority Queue's API might be needed to refactored to be able to compare between objects, what would be the best way of dealing with that? Would creating another class which you pass to the Priority Queue would be a better solution?
Here is the implementation I have for Priority Queue's prior to editing to deal with hashes.
class Heap
  attr_accessor :pq, :n

  def initialize
    @pq = [] # heap order complete binary tree
    @n = 0 # in pq[1..N] with pq[0] unused
  end

  def empty?
    @n == 0
  end

  def size
    @n
  end

  def insert(v)
    @pq[@n += 1] = v
    swim(@n) # position in heap
  end

  # trickleup
  def swim(k)
    while k > 1 && less((k / 2).floor, k) # parent: k/2 parent less than child?
      swap((k/2).floor, k)
      k = k / 2
    end
  end

  def del_max
    max = @pq[1]  # Retrieve max key from top.
    swap(1, @n) # Exchange with last item.
    @n -= 1
    @pq[@n + 1] = nil # Avoid loitering. max added to end on swap make nil
    sink(1) # Restore HEAP property
    max
  end

  # Trickledown
  def sink(k)
    while 2 * k <= @n
      j = 2 * k # child

      if !@pq[j + 1].nil? # check if there is a right child
        j += 1 if j > 1 && @pq[j] < @pq[j + 1] # if left child less than right child
      end
      break if @pq[k] > @pq[j] # If parent greater than child break

      swap(k, j)
      k = j
    end
  end

  def less(i, j)
    @pq[i] < @pq[j]
  end

  def swap(i, j)
    temp = @pq[i]
    @pq[i] = @pq[j]
    @pq[j] = temp
  end
end


texts:
I created a class to prevent the default delay which happens when holding down the key on Windows Forms. It seems like the class is working correctly but I don't know if I'm using the best practice.

KeyboardController class;

class KeyboardController
{
    public event EventHandler kbEvent;
    private DispatcherTimer timer;
    private HashSet<Key> keyPressed;

    public KeyboardController(Window c, EventHandler function)
    {
        c.KeyDown += WinKeyDown;
        c.KeyUp += WinKeyUp;
        kbEvent = function;
        keyPressed = new HashSet<Key>();

        timer = new DispatcherTimer();
        timer.Tick += new EventHandler(kbTimer_Tick);
        timer.Interval = new TimeSpan(0, 0, 0, 0, 10);
        timer.Start();
    }

    public bool KeyDown(Key key)
    {
        if (keyPressed.Contains(key))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private void WinKeyDown(object sender, KeyEventArgs e)
    {
        keyPressed.Add(e.Key);
    }

    private void WinKeyUp(object sender, KeyEventArgs e)
    {
        keyPressed.Remove(e.Key);
    }

    private void kbTimer_Tick(object sender, EventArgs e)
    {
        kbEvent(null, null);
    }
}

MainWindow.xaml.cs;

public MainWindow()
{
    EventHandler eh = new EventHandler(KeyboardFunction);
    kbc = new KeyboardController(this, eh);
}

private void KeyboardFunction(object sender, EventArgs e)
{
    if (kbc.KeyDown(Key.Right))
    {
        // do something.
    }
    else
    {
        // do something.
    }
}


texts: Side effects in functions that find boolean conditions

texts:
Here's an example of a logic structure I've refactored into something more complex on many occasions because I feel like it's wrong to have a side effect in a function that determines a yes/no answer to a question.

If I were to break this into multiple functions I would add to the main logic to call another function that handles the found conflict.

What is you opinion of logic like this?  Should it be refactored?

(also I welcome any/all code critiques)

namespace DirectAgents.SynchService.Commands
{
    public class CreateCampaign : Command<Campaign, bool>
    {
        private IFactory<DADatabase> eom;
        public CreateCampaign(IFactory<DADatabase> eomDatabase)
        {
            this.eom = eomDatabase;
        }
        public override bool Execute(Campaign input)
        {
            bool result = false;
            using (var db = eom.Create())
            {
                if (this.CanAdd(input))
                {
                    db.Campaigns.AddObject(input);
                    Log("Saving new {0} [{1}].", input.GetType().Name, input.campaign_name);
                    db.SaveChanges();
                    result = true;
                }
            }
            return result;
        }
        private bool CanAdd(Campaign campaign)
        {
            using (var db = eom.Create())
            {
                var conflictingID = from c in db.Campaigns
                                    where (c.pid == campaign.pid) && (c.campaign_name == campaign.campaign_name)
                                    select c.pid;

                bool conflictExists = (conflictingID.FirstOrDefault() == default(int));
                if (conflictExists)
                {
                    this.CampaignConflicts.Add(new CampaignConflict {
                        Campaign = campaign,
                        ConflictingId = conflictingID.First()
                    });
                }
                return (!conflictExists);
            }
        }
        [Dependency("CampaignConflicts")]
        public ICollection<CampaignConflict> CampaignConflicts { get; set; }
    }
}


texts: Multiple object instantiation prevention

texts:
I have a class with a private variable used to store an object.
I have a function that checks first if that variable already contains an object or not; if not, it instantiates the needed object and sets it to that variable, otherwise it just returns the content of that variable.

I was wondering if the getSessionCustomer() here is an overkill/unnecessary or if it has real benefits. I simply based this on the Album tutorial by Zend, but I haven't fully tested it out yet to really see the advantages (or disadvantages).

class JobController extends AbstractActionController
{
    private $SessionCustomer;

    public function saveJobAction()
    {
        $SessionCustomer = $this->getSessionCustomer();

        if(empty($SessionCustomer->offsetGet('customer_id'))) {
            return $this->redirect()->toRoute('login');
        } else {
            $JobService = $this->getServiceLocator()->get('Job\Factory\JobServiceFactory');
            $job_id     = $JobService->saveJob();

            return $this->redirect()->toUrl('/job/' . $job_id);
        }
    }

    public function viewJobAction()
    {
        $sm                 = $this->getServiceLocator();
        $SessionCustomer    = $this->getSessionCustomer();

        if(empty($SessionCustomer->offsetGet('customer_id'))) {
            return $this->redirect()->toRoute('login');
        } else {
            $JobTable       = $sm->get('Job\Model\JobTable');
            $JobItemTable   = $sm->get('Job\Model\JobItemTable');

            $jobId          = $this->params()->fromRoute('id');
            $Job            = $JobTable->getJobById($jobId);
            $JobItems       = $JobItemTable->getJobItemsByJobId($jobId);

            $this->layout()->setVariable('title', 'Order #' . $jobId);

            $viewModel = new ViewModel();
            $viewModel->setVariables(array(
                'Job' => $Job,
                'JobItems' => $JobItems
            ));

            return $viewModel;
        }
    }

    private function getSessionCustomer()
    {
        if(!$this->SessionCustomer) {
            $this->SessionCustomer = $this->getServiceLocator()->get('Session\Customer');
        }

        return $this->SessionCustomer;
    }
}


texts:
Question: Given an array numbers
$$a := [2, 7, 8, 5, 1, 6, 3, 9, 4]$$
Check the below conditions, both the conditions should be satisfied.
\begin{gather}
\text{If }a[i] > a[i-1]\text{ or if first element }a[i] > a[i+1]
\end{gather}
\begin{gather}
\text{If }a[i] > a[i+1]\text{ or if last element }a[LastIndex] > a[LastIndex - 1]
\end{gather}

1st Iteration - 8, 6, 9 are peak values.

Remove the smallest ele.
Remove 6.
New arr {2, 7, 8, 5, 1, 3, 9, 4}.
Output Arr - {6}

2nd Iteration - 8, 9 are peak values.

Remove the smallest ele.
Remove 8.
New arr {2, 7, 5, 1, 3, 9, 4}.
Output Arr - {6, 8}

3rd Iteration - 7, 9 are peak values.

Remove the smallest ele.
Remove 7. New arr {2, 5, 1, 3, 9, 4}.
Output Arr - {6, 7, 8}

4th Iteration - 5, 9 are peak values.

Remove the smallest ele.
Remove 5.
New arr {2, 1, 3, 9, 4}.
Output Arr - {6, 7, 8, 5}

5th Iteration - 2, 9 are peak values.

Remove the smallest ele.
Remove 2.
New arr {1, 3, 9, 4}.
Output Arr - {6, 7, 8, 5, 2}

6th Iteration - 9 are peak values.

Remove the smallest ele.
Remove 9.
New arr {1, 3, 4}.
Output Arr - {6, 7, 8, 5, 2, 9}

7th Iteration - 4 are peak values.

Remove the smallest ele.
Remove 4.
New arr {1, 3}.
Output Arr - {6, 7, 8, 5, 2, 9, 4}

8th Iteration - 3 are peak values.

Remove the smallest ele.
Remove 3.
New arr {1}.
Output Arr - {6, 7, 8, 5, 2, 9, 4, 3}

9th Iteration - 1 are peak values.

Remove the smallest ele.
Remove 1.
New arr {1}.
Output Arr - {6, 7, 8, 5, 2, 9, 4, 3, 1}

Output: {6, 8, 7, 5, 2, 9, 4, 3, 1}
My solution is working but I am looking for optimized solution. Please let me know.
Here is my code:
public int[] findMinimumPeaks(int[] arr){
        List<Integer> list1 = new ArrayList<Integer>(arr.length);
        int[] output = new int[arr.length];
        for(int i: arr)
            list1.add(i);

        for(int i =0; i<arr.length; i++){
            int minIndex = minimumPeakElement(list1);
            output[i] = list1.get(minIndex);
            list1.remove(minIndex);
        }
        return output;
    }

    public int minimumPeakElement(List<Integer> list1){
        int minIndex = 0, peakStart = Integer.MAX_VALUE, peakEnd = Integer.MAX_VALUE;
        int peak = Integer.MAX_VALUE, minPeak = Integer.MAX_VALUE;

        if(list1.size() >= 2){
            if(list1.get(0) > list1.get(1)) peakStart = list1.get(0);
            if(list1.get(list1.size() - 1) > list1.get(list1.size() - 2)) peakEnd = list1.get(list1.size() - 1);
            if(peakStart < peakEnd){
                minPeak = peakStart;
                minIndex = 0;
            }
            else if(peakEnd < peakStart){
                minPeak = peakEnd;
                minIndex = list1.size() - 1;
            }
        }

        for(int i=1; i<list1.size() - 1; i++){
            if(list1.get(i) > list1.get(i + 1) && list1.get(i) > list1.get(i-1)) peak = list1.get(i);
            if(peak < minPeak){
                minPeak = peak;
                minIndex = i;
            }
        }
        return minIndex;
    }

```


texts: Program for helping people practice their maths

texts:
Please mention anything that could help me.

from easygui import *
import random

choice = ["+", "-", "x"]
question_number = 1
correct = 0
msgbox("This program is to help you get better at doing maths, you will get given a random set of random questions including +, - and x , at the end the program will tell you how many right you got out of 10.")
while question_number <=10:
        question = random.choice(choice)
        num_1 = random.randint(1,10)
        num_2 = random.randint (1,10)
        user_answer = integerbox(msg="What is " + str(num_1) + question + str(num_2) +" ?",lowerbound=-1000, upperbound = 1000, title="Maths Question Number " + str(question_number))
        question_number = question_number + 1
        if question==("+"):
                    realanswer = num_1+num_2
                   if user_answer==realanswer:
                        correct = correct + 1
        elif question==("x"):
                    realanswer = num_1*num_2
                    correct = correct + 1
        elif question==("-"):
                    realanswer = num_1-num_2
                    correct = correct + 1
    msgbox ("You got " + str(correct) + " correct " + "out of 10. ", title="Maths Question")


texts:
I'm using (abusing) collections.Counter to hold non-negative floats. Something like Counter(a=4.5, b=3.4). The problem I faced is that in some case, when comparing two counters, I ran into accuracy issues. Thus, I needed to use something like unittest.TestCase.assertAlmostEqual. However, abs is not supported for Counter's. So, I wrote the following utility:

def assert_almost_equal_counters(c1,c2):
    testcase = unittest.TestCase()
    testcase.assertEqual(type(c1), type(c2))
    testcase.assertEqual(c1.keys(), c2.keys())
    for key in c1.keys():
        testcase.assertAlmostEqual(c1[key], c2[key])

Is it enough? Did I miss something?


texts:
I have a procedure for conducting ANOVA, the details of which can be viewed in this white paper.

I would like to be able to make the routine scalable to handle any number of groups. Below is the R code for a 2 group example.  Any insights or comments are appreciated.

Partial Moments:

LPM<- function(degree,target,variable){
 sum((target - (variable[variable < target]))^degree)/length(variable)
}

UPM<- function(degree,target,variable){
 sum(((variable[variable > target]) - target)^degree)/length(variable)
}

ANOVA:

VN_ANOVA<- function(group1,group2){

  mean_of_means <- mean(c(mean(group1),mean(group2)))

#Continuous CDF for each group from Mean of Means
  LPM_ratio_1 <- LPM(1,mean_of_means,group1)/
    (LPM(1,mean_of_means,group1)+UPM(1,mean_of_means,group1))

  LPM_ratio_2 <- LPM(1,mean_of_means,group2)/
    (LPM(1,mean_of_means,group2)+UPM(1,mean_of_means,group2))

#Continuous CDF Deviation from 0.5
  MAD_CDF<- mean(c(abs(LPM_ratio_1 - 0.5),abs(LPM_ratio_2 - 0.5)))

#Certainty associated with samples
  VN_ANOVA_rho <- (0.5 - MAD_CDF)/0.5

#Graphs
  boxplot(list(group1,group2), las=2, names=c("Group 1","Group 2"),
      xlab= "Means", horizontal = TRUE,
      col=c("grey","white"), main="ANOVA")

#For ANOVA Visualization
  abline(v=mean_of_means,col="red",lwd=4)
  text(mean_of_means,pos=4, 2.5, "Mean of means", col = "red")

  return(c("Certainty of Same Population"=VN_ANOVA_rho))

}


texts:
I wanted to get the boolean status from a function. Here is my sample code, wherein I used return in try and catch, to get the status of function.

public static void main(String[] args) {
        System.out.println(getState() ? "successful" : "failed");
}

public static boolean getState() {
        SAXBuilder builder = new SAXBuilder();
        File xmlFile = new File("tile.xml");
        Set<String> set = new TreeSet<String>();
        try {
            Document document = (Document) builder.build(xmlFile);
            Element rootNode = document.getRootElement();
            System.out.println(rootNode);
            return true;
        } catch (IOException io) {
            System.out.println(io.getMessage());
            return false;
        } catch (JDOMException jdomex) {
            System.out.println(jdomex.getMessage());
            return false;
        }
    }

Does it makes sense ? Can I improve it ?
Assuming, that there might be more than 10 catch blocks, then should I use 10 return statements, in each catch block.


texts: Check deep object property and find duplicate value

texts:
I use the following code to find if there is duplicate value in property path:

return new Promise((resolve, reject) => {
            var data = [];
            Parser.parse()
             //configObj is the value from the screen shot
                .then((configObj) => {
                    configObj.forEach((providers) => {
                        _.each(providers, (provider) => {
                            _.each(provider, (entry) => {
                                for (var prop in entry) {
                                    if (_inArray(entry[prop].path, data)) {
                                        return reject(new Error(`Duplicate path ${entry[prop].path}`));
                                    }
                                    data.push(entry[prop].path);
                                }
                            })
                        })
                    })
                    resolve("validObject");
                }, err => {
                    reject(err);
                });

For example, this is the object configObj and as you can see I need to find duplicate in object 'replace' and object 'save' for the value in field 'path'; if they have the same value, it rejects with error; otherwise it resolves the promise. Is there is more elegant way to write it?

In this example, the path is different (test2 & command1) but it can also be the same.

update

[
  {
    "providers": [
      {
        "replace": {
          "path": "command1",
          "function": "updateResources",
          "method": "post"
        },
        "save": {
          "path": "test2",
          "function": "updateResources",
          "method": "post"
        }
      }
    ]
  }
]


texts:
I have a list of segment lengths and I want to convert it into array slices:

segment_lens = [2, 5, 5]

last_end = 0
start = 0
end = 0

for s_i in range(len(segment_lens)):
    start = last_end
    end += segment_lens[s_i]
    print("Slice: [%s,%s]" %(start, end,))
    last_end = end

Here is the intended output, which in my application I would use to slice a list:

Slice: [0,2]
Slice: [2,7]
Slice: [7,12]

Is there a better way to do this? I feel like there should be a python built-in for this, but I'm not sure.


texts: Invalidate a JS Object when any of its values is null or empty

texts:
I created a simple Javascript method to recursively parse a JS Object and find out if any of its values or sub values is set to null or is empty string.

I could't break on when using Array.map() or Array.forEach() so I went with this :

const isValidObject = (obj) => {
  let invalid = []
  const validate = (obj) => {
    Object.values(obj).map(el => {
      if (typeof el === 'object') {
        validate(el)
      } else if (el === null || el === '') {
        invalid.push(el)
      }
    })
    return invalid.length === 0
  }
  return validate(obj)
}

If you have any opinonated or objective thought about this way of doing, please share it with me.

const isValidObject = (obj) => {
  let invalid = []
  const validate = (obj) => {
    Object.values(obj).map(el => {
      if (typeof el === 'object') {
        validate(el)
      } else if (el === null || el === '') {
        invalid.push(el)
      }
    })
    return invalid.length === 0
  }
  return validate(obj)
}

let toto = {
 name: 'toto',
  age: 12,
  pony: {
    name: 'rainbow dash',
    age: ''
  }
}

console.log('test :', isValidObject(toto))


texts: Single Producer/Multiple Consumers in Node

texts:
I've done my best to contrive an example of the problem I'm trying to simplify. I have a pool of workers, and each worker can do several tasks at a time. Each task takes an unspecified amount of time. The goal is to drain the task queue by keeping each each worker as busy as possible.
In order to accomplish this, once the taskQueue has a nonzero number of tasks, each Worker is given tasks up to maxTasks. When a worker completes any one task, he uses the callback he was given to return the result. The worker is then assigned a new task in that callback. Workers are continually given new tasks untilthe taskQueue is empty..
This doesn't feel like an elegant solution. Would this be better accomplished using a stream or an event emitter? Any thoughts would be greatly appreciated.
function WorkerPool(numWorkers) {
  const workers = [];
  const taskQueue = [];

  for (let i = 0; i < numWorkers; i += 1) {
    workers.push(Worker());
  }

  function supplyNewTask(worker) {
    if (taskQueue.length) {
      const task = taskQueue.pop();
      console.log(`task queue length decremented to ${taskQueue.length}`);
      worker.work(task, supplyNewTask);
    }
  }

  return {
    work: function(task) {
      for (const worker of workers) {
        if (worker.availableTasks()) {
          worker.work(task, supplyNewTask);
          return;
        }
      }

      // if couldn't find a buyer...
      taskQueue.push(task);
      console.log(`task queue length incremented to ${taskQueue.length}`);
    }
  }
}

function Worker() {
  let activeTasks = 0;
  let maxTasks = 5;

  return {
    availableTasks: () => maxTasks - activeTasks,
    work: function(task, callback) {
      activeTasks += 1;
      console.log(`workers active tasks incremented to ${activeTasks}`);

      // do some work that takes an unspecified
      // amount of time, then callback with the
      // result.
      setTimeout(() => {
        activeTasks -= 1;
        console.log(`workers active tasks decremented to ${activeTasks}`);
        callback(this);
      }, Math.floor(Math.random() * 100));
    },
  };
}

const pool = WorkerPool(3);
for (let i = 0; i < 6000; i++) {
  pool.work({ /* some work to be done */ });
}
```


texts: Haskell requires more memory than Python when I read map from file. Why?

texts:
I have this simple code in Python:

input = open("baseforms.txt","r",encoding='utf8')
S = {}
for i in input:
    words = i.split()
    S.update( {j:words[0] for j in words} )
print(S.get("sometext","not found"))
print(len(S))

It requires 300MB for work. "baseforms.txt" size is 123M.

I've written the same code in Haskell:

{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Map as M
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Text.Lazy.Encoding(decodeUtf8)
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as I
import Control.Monad(liftM)

main = do
    text <- B.readFile "baseforms.txt"
    let m = (M.fromList . (concatMap (parseLine.decodeUtf8))) (B.lines text)
    print (M.lookup "sometext" m)
    print (M.size m)
    where
        parseLine line = let base:forms = T.words line in [(f,base)| f<-forms]

It requires 544 MB and it's slower than Python version. Why? Is it possible to optimise Haskell version?

Data file can be downloaded here

I've tried non-lazy version of Data.Text and Data.Text.IO - memory usage is near 650MB

I've also tried hashtables, but  memory usage growth up to 870 MB


texts:
Obviously there are better ways of obtaining Pi, but for educational purposes, how is the code below?

(defn leibniz-numerator [x] (* (- (rem x 4) 2) -4.0))

(defn calc-pi-leibniz
    "Calculate pi with Leibniz formula
    4/1 - 4/3 + 4/5 - 4/7 + 4/9 etc
    Very slow convergence"
    [terms]
    (reduce + (map #(/ (leibniz-numerator %) %) (range 1 terms 2))))

(print (calc-pi-leibniz 10000000))


texts: Create a function with an undetermined number of successive calls

texts:
As part of a programming challenge, we are tasked with creating a function with an undetermined number of successive calls. As an example, let's say the function returns simply the sum of the provided arguments, it should work as follows :

sum(4)() // 4
sum(4)(5)() // 9
sum(4)(5)(9)() // 18
sum(4)(5)(9)(1)() // 19
// etc...

The problem is simplified by the allowed empty function call at the end as an indication of end of calls.

I have worked on a solution that does the job but using global variables inside the function itself :

var sum = function (a) {
    if (!sum.init) {
        sum.total = 0;
        sum.init = true;
    }
    if (!arguments.length) {
        sum.init = false;
        return sum.total;
    }
    sum.total += a;
    return sum;
};

This solution works but uses state, global variables and function object trickery which is not ideal. My question here is whether there is a way to solve the problem in a purely recursive way.

As a side note, I do not believe the problem can be solved if that last empty call () is not provided, but if I'm wrong please let me know.


texts: Using a dependency container to load a parent/child class

texts:
In PHP, I have a parent/child class and am using dependency container to load them.  I am trying to use the same database connection on all of them without duplicating the object.

I used $this->_db to pull data from the database in a child class method (and my class stores that in the property $this->_db->result). I then went into the parent class and print_r($this->_db->result) and it worked. That leads me to believe that I am passing the database object and not duplicating it (maybe?).

However, would still be nice if someone could tell me why my code would not be considered OOP, as someone had commented that it was not OOP. Can someone who understands this stuff better than me please have a look and let me know if I'm doing it right and if not, what I need to change in my code?

<?php

    include('mysqliClass.php');
    $db = new mysqliObject();

    depCon::$_database = $db;
    $myObject = depCon::createNewObject();

    class depCon {

      public static $_database;

      public static function createNewObject() {

        $newObject = new myChild();
        $newObject->setDatabase(self::$_database);

        return $newObject;
      }
    }

    class myParent {

      private $_db;

       public function __construct() {
        }

      public function setDatabase($databaseConnection) {
        $this->_db = $databaseConnection;
      }

    }

    class myChild extends myParent {

        private $_db;

        public function __construct() {
            parent::__construct();
        }

        public function setDatabase($databaseConnection) {
            $this->_db = $databaseConnection;
            parent::setDatabase($this->_db);
        }

    }

    ?>


texts: Systematically analyzing dice roll outcomes

texts:
I created a generator function to iterate through all possible dice rolls, and then applied it the ability score generating methods in Pathfinder RPG. (Obviously, there are more efficient ways to approach probability outcome analysis from a number theoretic perspective, but this allows generic and quick analysis without too much mathematical understanding of the particular situation.)

My question is, using this iterator, is there any way to generically split the iterator into different numbers of dice? My current approach feels sloppy and is definitely not scalable to more varied numbers of dice. Obviously, I could just use separate dice iterators, but that would be a generally less efficient approach.

Also, as always, any other feedback is appreciated, even PEP 8 stylistic feedback.

math_supplement.py

from fractions import Fraction

def dice_outcomes(num, min=1, max=6):
    '''
    A generator function returning all outcomes of num dice as lists. Dice values are inclusively between min (default 1) and max (default 6).
    '''
    output = [min] * num
    try:
        while True:
            yield output
            i = 0
            while True:
                output[i] += 1
                if output[i] <= max:
                    break
                output[i] = min
                i += 1
    except IndexError:
        return

def sample_space_report(stats, size):
    '''
    Reports on stats relative to a sample space.

    stats
        a dict, with each key being an outcome and the
    size
        the sample space
    '''
    probsum = 0
    for outcome, occurences in stats.items():
        prob = Fraction(occurences, size)
        probsum += prob
        print(f'{outcome}: {prob} ({float(prob):.2%})')
    print(f'Validation sum = {probsum}')

Pathfinder_ability_score_probability.py

from collections import Counter

from math_supplement import dice_outcomes, sample_space_report

class AbilityScoreStats:
    def __init__(self, roll_handler, sample_space):
        self.roll_handler = roll_handler
        self.sample_space = sample_space
        self.outcomes = Counter()

    def add(self, l):
        self.outcomes[self.roll_handler(l)] += 1

MIN = 1
MAX = 6
DICE_FACES = MAX - MIN + 1
ability_score_methods = {'Standard':
                             AbilityScoreStats(lambda rolls: sum(rolls) - min(rolls),
                             DICE_FACES ** 4),
                         'Classic':
                             AbilityScoreStats(lambda rolls: sum(rolls),
                             DICE_FACES ** 3),
                         'Heroic':
                             AbilityScoreStats(lambda rolls: sum(rolls) + 6,
                             DICE_FACES ** 2)
                        }
for rolls in dice_outcomes(2, min=MIN, max=MAX):
    ability_score_methods['Heroic'].add(rolls)
    for dice_three in range(1,7):
        working_rolls = rolls + [dice_three]
        ability_score_methods['Classic'].add(working_rolls)
        for dice_four in range(1,7):
            working_rolls = rolls + [dice_three, dice_four]
            ability_score_methods['Standard'].add(working_rolls)
for name, method in ability_score_methods.items():
    print(f'    {name}:')
    sample_space_report(method.outcomes, method.sample_space)


texts: Shortest distance from point to line segment in 3D

texts:
This function returns the shortest distance from a 3D point P to a line segment defined by two 3D points A and B. It projects P onto the line, then checks if this projected point lies between A and B. If it does, then the distance is calculated using this projected point.

If the projection is outside the line segment, then the distance is calculated to either point A or B, depending on which is closer.

I wanted to get feedback on if this is a clean solution to the problem.

function d = point_seg_dist(P, A, B)
% Returns distance from a 3D point to a line segment
%
% Inputs
%
%   P : vector
%       Position in space
%
%   A : vector
%       Position of line segment endpoint
%
%   B : vector
%       Position of other line segment endpoint
%
% Outputs
%
%   d : double
%       Distance from point to line segment

AP = P - A; % Vector from A to point
AB = B - A; % Vector from A to B

% Project point onto line
P_line = A + dot(AP, AB) / dot(AB, AB) * AB;

if all(A < P_line) && all(P_line < B)
    % The point projected onto the line is in between A and B

    % Projection of point onto segment is the same
    % as projection of point onto line
    P_seg = P_line;
else
    % The point projected onto the line is outside of A and B

    if all(P_line <= A)
        % The projected point is closer to A
        P_seg = A;
    else
        % The projected point is closer to B
        P_seg = B;
    end
end

d = norm(P - P_seg); % Distance to line segment

end


texts:
I am having a simple foreach where I add objects to a list:

    List<SoonestDrawDateModel> soonestDrawDateModel = new List<SoonestDrawDateModel>();

    foreach (var item in drawDates)
    {
        SoonestDrawDateModel sdModel = new SoonestDrawDateModel();
        sdModel.DrawDay = item;
        sdModel.DrawDayId = item.DayId;
        sdModel.CutOffDayId = item.CutOffDayId;

        soonestDrawDateModel.Add(sdModel);

        sdModel = new SoonestDrawDateModel();
        sdModel.DrawDayId = item.DayId + 7;
        sdModel.CutOffDayId = item.CutOffDayId;
        sdModel.DrawDay = item;
        soonestDrawDateModel.Add(sdModel);
    }

    var realDrawDates = soonestDrawDateModel.OrderBy(x => x.DrawDayId);

Is there any way to do this with Linq with fewer lines?


texts:
I am trying to decide between two designs of a class. The basic difference is the one calculates properties when they are called, and the other when the object is instantiated.

I would usually just take the first one, but the calculations call each other, so when calling all of them, they get recalculated multiple times.

I, however, still prefer the first code. It is cleaner. Easier, for me, to read. I also feel the calculations are probably small enough to not worry about as opposed to storing extra values.

Is there anything else I should be considering, or looking out for? Or any reason one is amazingly better than the other?

public class Angle1
{
    private decimal angle;

    public int Degree => (int)Math.Floor(angle);
    private decimal MinuteSecond => (angle - Degree) * 60;
    public int Minute => (int)Math.Floor(MinuteSecond);
    public decimal Second => (MinuteSecond - Minute) * 60;

    public Angle1(decimal angle)
    {
        this.angle = angle;
    }
}

public class Angle2
{
    private decimal angle;

    public int Degree { get; private set; }
    public int Minute { get; private set; }
    public decimal Second { get; private set; }

    public Angle2(decimal angle)
    {
        this.angle = angle;
        Degree = (int)Math.Floor(angle);
        var minSec = (angle - Degree) * 60;
        Minute = (int)Math.Floor(minSec);
        Second = (minSec - Minute) * 60;
    }
}

I have also thought of a "hybrid" option. Store values in private values. When a property is called the first time, the value is calculated, and the private value is set. When it is called again, the private value is returned.

This hybrid option is the one I naturally go to when properties are larger objects, datasets, or binary data. I feel in this instance, it would "dirty" the code more than necessary, for the size of the stored values (integers and decimals).


texts: Generating Norwegian National Identification Numbers in Python

texts:
I've written some Python-code to generate the Norwegian National Identification Numbers.

Being fairly new to Python, I'd really appreciate a review on this code in regards to best practices and style.

import calendar

def is_valid_date(d):
    dd,mm,yyyy = [int(i) for i in [d[:2],d[2:4],d[4:]]]
    days = {
        1: 31, 2: 29 if calendar.isleap(yyyy) else 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
    }

    if yyyy < 1900 or yyyy > 2039: return False
    if mm < 1 or mm > 12: return False
    if dd < 1 or dd > days[mm]: return False

    return True

def get_range(year):
    if year >= 1990 and year <= 1999: return range(500)
    if year >= 2000 and year <= 2039: return range(500,1000)
    return range(0)

def pad(n):
    return '{:03}'.format(n) if n < 100 else n

def generate(d):
    if type(d) is not str or is_valid_date(d) != True:
        raise ValueError('Expected a valid date-string with the form: ddmmyyyy')

    year, dt = int(d[4:]), [int(i) for i in d]
    for i in get_range(year):
        n = map(int,list(str(pad(i))))
        k1 = 11 - ((3*dt[0] + 7*dt[1] + 6*dt[2] + 1*dt[3] + 8*dt[-2] + 9*dt[-1] + 4*n[0] + 5*n[1] + 2*n[2]) % 11)
        k2 = 11 - ((5*dt[0] + 4*dt[1] + 3*dt[2] + 2*dt[3] + 7*dt[-2] + 6*dt[-1] + 5*n[0] + 4*n[1] + 3*n[2] + 2*k1) % 11)
        if k1 < 10 and k2 < 10:
            print ''.join(map(str,dt[:4] + dt[6:] + n + [k1,k2]))

generate('31101990')


texts:
I wrote some Python code to solve the following problem.  I'm curious to see if someone else can find a better solution, or critique my solution.

How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element?  Push, pop and min should all operate in O(1) time.

class SmartStack:
    def __init__(self):
        self.stack= []
        self.min = []

    def stack_push(self,x):
        self.stack.append(x)
        if len(self.min) != 0:
            if x < self.stack_min():
                self.min.append(x)
        else:
            self.min.append(x)

    def stack_pop(self):
        x = self.stack.pop()
        if x == self.stack_min():
            self.min.pop()
        return x

    def stack_min(self):
        return self.min[-1]

def main():
    print "Push elements to the stack"
    list = range(10)
    stack = SmartStack()
    for i in list:
        stack.stack_push(i)
    print "Print stack and stack minimum"
    print stack.stack
    print stack.stack_min()
    print "Push -1 to stack, print stack and stack minimum"
    stack.stack_push(-1)
    print stack.stack
    print stack.stack_min()
    print "Pop from stack, print stack and stack minimum"
    print stack.stack_pop()
    print stack.stack
    print stack.stack_min()

if __name__ == "__main__":
    main()


texts: Concise way of creating a IntRange out of an Int

texts:
I want to create a collection (in this case a map due to the extended function 'groupBy') that maps an IntRange to a list of a data class, which members are determined whether an int inside the data class is within the IntRange.
The IntRanges are 0..9, 10..19, 20..29, etc.

Concrete example:

data class Trip(
    val (...)
    val distance: Double
)

[...]

val mappedTrips = trips.groupBy {
    ((it.duration-(it.duration)%10))..((it.duration-(it.duration)%10)+9) }

Explicitly the

((it.duration-(it.duration)%10))..((it.duration-(it.duration)%10)+9)

part seems to be not very concise, hard to read and therefore I was wondering if there is a way to make it more efficient, meaning more easy to read, concise.

Thank you in advance.

Edit:

TaxiPark Class

package taxipark

data class TaxiPark(
        val allDrivers: Set<Driver>,
        val allPassengers: Set<Passenger>,
        val trips: List<Trip>)

data class Driver(val name: String)
data class Passenger(val name: String)

data class Trip(
        val driver: Driver,
        val passengers: Set<Passenger>,
        // the trip duration in minutes
        val duration: Int,
        // the trip distance in km
        val distance: Double,
        // the percentage of discount (in 0.0..1.0 if not null)
        val discount: Double? = null
) {
    // the total cost of the trip
    val cost: Double
        get() = (1 - (discount ?: 0.0)) * (duration + distance)
}

Task

Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on.
Return any period if many are the most frequent, return null if there're no trips.

Test sample

class TestTask5TheMostFrequentTripDurationPeriod {

    private fun testDurationPeriod(expected: Set<IntRange?>, tp: TaxiPark) {
        val actual = tp.findTheMostFrequentTripDurationPeriod()
        val message = "Wrong result for 'findTheMostFrequentTripDurationPeriod()': $actual."
        if (expected.size <= 1) {
            Assert.assertEquals(
                    message + tp.display(),
                    expected.firstOrNull(), actual)
        } else {
            Assert.assertTrue(message +
                    tp.display() +
                    "\nPossible results: $expected" +
                    "\nActual: $actual\n",
                    actual?.let { it in expected } ?: expected.isEmpty())
        }
    }

    @Test
    fun test00() = testDurationPeriod(setOf(null), taxiPark(0..1, 0..10))

    @Test
    fun test01() {
        // The period 30..39 is the most frequent since there are two trips (duration 30 and 35)
        testDurationPeriod(setOf(30..39), taxiPark(1..3, 1..5,
                trip(1, 1, duration = 10),
                trip(3, 4, duration = 30),
                trip(1, 2, duration = 20),
                trip(2, 3, duration = 35)))
    }

    @Test
    fun test02() = testDurationPeriod(setOf(30..39), taxiPark(0..5, 0..9,
            trip(0, listOf(2, 9), duration = 14, distance = 25.0),
            trip(1, listOf(8), duration = 39, distance = 37.0, discount = 0.2),
            trip(5, listOf(0, 5), duration = 27, distance = 28.0, discount = 0.3),
            trip(4, listOf(0, 6), duration = 33, distance = 14.0),
            trip(2, listOf(5, 1, 4, 3), duration = 2, distance = 15.0),
            trip(4, listOf(7), duration = 27, distance = 2.0),
            trip(4, listOf(4, 6), duration = 31, distance = 31.0),
            trip(3, listOf(9, 0), duration = 34, distance = 7.0),
            trip(5, listOf(3), duration = 25, distance = 33.0),
            trip(1, listOf(0, 7, 2, 3), duration = 13, distance = 17.0))
    )
}


texts: Asking 2 values, feet and inches, and it converts them to centimeters

texts:
I was doing an exercise in PHP, and it works perfectly, no problems. But I think that maybe I coded it so long, and I think it can be shorter than it is now, but I don't know how to make it shorter and that works exactly the same way.

I will explain what this code is doing for you so it's faster if you are going to help (if you want a deeper explanation, you can translate the commented section because that's the wording of the exercise): first of all, I have a PHP file and a html file with a form. The form it's asking for 2 values (feet and inches), for converting them to centimeters. Feet value must be integer, greater than or equal 0. Inches must be integer or decimal, and greater than or equal 0.

<?php
    //Realice un formulario que introduzca dos valores (pies y pulgadas) y los convierta a
    //centímetros. Los pies deben ser un número entero mayor o igual que cero. Las pulgadas
    //son un número entero o decimal mayor o igual que cero. Un pie son doce pulgadas y una
    //pulgada son 2,54 cm.

    $converPC = 30.48;
    $converPlC = 2.54;
    $pies = trim(htmlspecialchars(strip_tags($_REQUEST["pies"]), ENT_QUOTES, "UTF-8"));
    $pulgadas = trim(htmlspecialchars(strip_tags($_REQUEST["pulgadas"]), ENT_QUOTES, "UTF-8"));
    if ( (!empty($pies)) && (!empty($pulgadas)) ) {
        if ( (is_numeric($pies)) && (is_numeric($pulgadas)) ) {
            //Apartado de los pies
            if ( (filter_var($pies, FILTER_VALIDATE_INT)) && ($pies >= 0) ) {
                $resultadoPI = $pies*$converPC;
                print "CONVERSIÓN PIES - CENTÍMETROS
";
                print "$pies pies son $resultadoPI centímetros

";
            } else {
                print "Error en pies
";
                print "Debe introducir un número entero mayor o igual que cero

";
            }
            //Apartado de las pulgadas
            if ($pulgadas >= 0) {
                $resultadoPU = $pulgadas*$converPlC;
                print "CONVERSIÓN PULGADAS - CENTÍMETROS
";
                print "$pulgadas pulgadas son $resultadoPU centímetros";
            } else {
                print "Error en pulgadas
";
                print "Debe introducir un número mayor o igual que cero";
            }
        } else {
            print "Error, ambos valores deben ser numéricos";
        }
    } else {
        print "Para que todo funcione, debe rellenar TODOS los campos del formulario";
    }

?>


texts: What is the security issue in this code?

texts:
I was asked how this code has a security risk.  Does anyone have any ideas what it is? I am new on the security topic and don't know what to look for.

String DBdriver = "com.ora.jdbc.Driver";
String DataURL = "jdbc:db://localhost:5112/users";
String loginName = "stackoverflow";
String passwd = "codeReview";
Class.forName(DBdriver);
Connection conn = DriverManager.getConnection(DataURL, loginName, passwd);
String Username = request.getParameter("USER");
String Password = request.getParameter("PASSWORD");
int iUserID = -1;
String loginUser = "";
String sel = "SELECT UserID, Username FROM USERS WHERE Username = '"
    +Username + "' AND Password = '" + Password + "'";
Statement selectStatement = conn.createStatement ();
ResultSet result = selectStatement.executeQuery(sel);
if (result.next()) {
       iUserID = result.getInt(1);
       loginUser = result.getString(2);
}
PrintWriter wr = response.getWriter ();
if (iUserID >= 0) {
       wr.println ("you logged in: " + loginUser);
} else {
       wr.println ("you cannot login in !Access Denied!")
}


texts:
Related to this question (and even this Stack Overflow's one) I have been trying to avoid blocking the code. So what I understood it's that is preferable to make all the methods that rely on an async one async themselve (thus not defeating the purpose of asynchronous). Therefore I have changed my code to do the following (I include here more "layers" than in the questions I linked as I had to change accordingly those).

My API, exposing a method:

[Route("api/postconfiguration")]
public async Task<IHttpActionResult> PostConfiguration(configurationData configurationData)
{
    try
    {
        await _configurationRequestHandler.HandlePostRequest(configurationData);
        return Ok();
    }
    catch (Exception e)
    {
        // Log error
        return InternalServerError(e);
    }
}

That uses this method:

public async Task HandlePostRequest(Data Data)
{
    var configuration = await _ConfigurationService.GetConfigurationAsync(Data.AgentId);

    // Use that configuration
}

And this would be the method calling the external api

public class ConfigurationApiClient : IConfigurationService
{
    private readonly HttpClient _client;
    private const string resourcePath = "configuration/{0}";

    public ConfigurationApiClient(IConfigurationManager configurationManager)
    {
        _client = new HttpClient();
        _client.BaseAddress = new Uri(configurationManager.GetAppSetting("ConfigurationApiUrl"));
        _client.DefaultRequestHeaders.Accept.Clear();
        _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<Configuration> GetConfigurationAsync(int agentId)
    {
        try
        {
            var response = await _client.GetAsync(String.Format(resourcePath, agentId));
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsAsync<Configuration>();
        }
        catch (HttpRequestException ex)
        {
            throw new Exception(string.Format("Exception when getting  configuration for agent: {0}", agentId), ex);
        }
    }

}

This is my understanding of what I should do for making it asynchronous, but would appreciate if someone points me any error.

I am using the API on one client myself, which does this:

public async Task DeployConfiguration(Package package, EFEnvironment environment)
{
    using (var client = new HttpClient())
    {
        // Prepare the configurationData

        var agentTasks = agents.Select(a =>
            {
                var configurationPostRequest = new ConfigurationData
                    {
                        // Create it
                    };

                return client.PostAsJsonAsync("api/postconfiguration", configurationPostRequest);
            });

        await Task.WhenAll(agentTasks);
    }
}

Which is just called inside a sync method:

_deployApiService.DeployConfiguration(package, environment);