texts: Excel VBA object with validated bounds for an interval

texts:
I'm working through a problem I have with Excel VBA. I have two object classes. Class clsLoadStep stores three copies of class clsLoad objects. Class clsLoad simply stores a value and a string stating where that value came from. One clsLoad stores a max value and another a min value. My problem comes to read/write access to the nested clsLoad objects in the clsLoadStep. Currently the properties of the clsLoad objects of clsLoadStep can be changed (via the Get property then the Let property of the clsLoad object) which can result in the Max object storing a value less than the Min object. Is there a way to restrict access to the clsLoad objects in the clsLoadStep object to read-only while still letting the definition of the clsLoad class have both read and write properties? I want to be able to read the properties of the clsLoad objects but not change them.

I have a function in the clsLoadStep object that checks if min > max and swaps the object references if that's the case. The clsLoadStep object still needs to be able to tell if the clsLoad object's values have changed. Is there a recommended way to accomplish this?

For a while I had a "Parent" property of the clsLoad object that pointed to the clsLoadStep object. This allowed the clsLoadStep object to know when the clsLoad object changed (by calling the UpdateMaxMin function of the parent). That was a problem though as mulitple objects could reference the clsLoad object and it would be restricted to one parent.

Class clsLoad

Option Explicit

Private pValue As Double
Private pSource As String

'*****************************************************************
'P R O P E R T I E S
'*****************************************************************

'''''''''''''''''''''''''
' Value property
'''''''''''''''''''''''''
Public Property Get Value() As Double
    Value = pValue
End Property
Public Property Let Value(ByVal Val As Double)
    pValue = Val
End Property

'''''''''''''''''''''''''
' Source property
'''''''''''''''''''''''''
Public Property Get Source() As String
    Source = pSource
End Property
Public Property Let Source(ByVal Val As String)
    pSource = Val
End Property

Class clsLoadStep

Option Explicit

Private pMax As clsLoad
Private pMin As clsLoad
Private pOcc As clsLoad
Private pSource As String

'*****************************************************************
'P R O P E R T I E S
'*****************************************************************

'''''''''''''''''''''''''
' Max property
'''''''''''''''''''''''''
Public Property Get Max() As clsLoad
    Set Max = pMax
    UpdateMaxMin
End Property
Public Property Set Max(ByVal newLoad As clsLoad)
    Set pMax = newLoad
    UpdateMaxMin
End Property

'''''''''''''''''''''''''
' Min property
'''''''''''''''''''''''''
Public Property Get Min() As clsLoad
    Set Min = pMin
    UpdateMaxMin
End Property
Public Property Set Min(ByVal newLoad As clsLoad)
    Set pMin = newLoad
    UpdateMaxMin
End Property

'''''''''''''''''''''''''
' Occur property
'''''''''''''''''''''''''
Public Property Get Occ() As clsLoad
    Set Occ = pOcc
End Property
Public Property Set Occ(ByVal newLoad As clsLoad)
    Set pOcc = newLoad
    UpdateMaxMin
End Property

'''''''''''''''''''''''''
' Source property
'''''''''''''''''''''''''
Public Property Get Source() As String
    Source = pSource
End Property
Public Property Let Source(ByVal Val As String)
    pSource = Val
End Property

'''''''''''''''''''''''''
' UpdateMaxMin sub - Swap max and min objects if max is less than min
'''''''''''''''''''''''''
Private Sub UpdateMaxMin()
    Dim tmpLoad As clsLoad
    If pMax.Value < pMin.Value Then
        Set tmpLoad = pMax
        Set pMax = pMin
        Set pMin = tmpLoad
        Debug.Print "Max less than min. Swapped max and min."
    End If
End Sub


texts:
Can this method be improved?:

public static Session getHibernateSession() throws SQLException{
    synchronized(dbSessionMutex){
        if(session == null || !session.isOpen()){
            session = HibernateUtil.getSessionFactory().openSession();
        }
        else{
            final SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session.getSessionFactory();
            final ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider();
            try{
                final Connection conn = connectionProvider.getConnection();
                if(conn.isClosed()){
                    session.close();
                    session = HibernateUtil.getSessionFactory().openSession();
                }
                else{
                    conn.close();
                }
            }
            catch(Exception e){
                LOGGER.error("Exception: ", e);
                session.close();
                session = HibernateUtil.getSessionFactory().openSession();
            }
        }
    }
    return session;
}


texts: Overriding Backbone.Collection.add to enforce uniqueness on non-id property

texts:
I've overridden Backbone.Collection.add for my Collection to ensure that the Collection never has two PlaylistItems who share a Song ID. My implementation seems incredibly verbose and I was curious if there's a better way to express my desires:

var PlaylistItems = MultiSelectCollection.extend(_.extend({}, SequencedCollectionMixin, {
    model: PlaylistItem,

    //  Don't allow duplicate PlaylistItems, determined by the PlaylistItem's Song's ID.
    add: function (items, options) {

        if (items instanceof Backbone.Collection) {
            items.each(function (item) {
                trySetDuplicateSongId.call(this, item);
            }.bind(this));
        }
        else if (_.isArray(items)) {
            _.each(items, function (item) {
                trySetDuplicateSongId.call(this, item);
            }.bind(this));
        } else {
            trySetDuplicateSongId.call(this, items);
        }

        return MultiSelectCollection.prototype.add.call(this, items, options);
    }

}));

function trySetDuplicateSongId(playlistItemToAdd) {
    var duplicatePlaylistItem = this.find(function (playlistItem) {
        return playlistItem.get('song').get('id') === playlistItemToAdd.get('song').get('id');
    });

    var duplicateFound = !_.isUndefined(duplicatePlaylistItem);

    if (duplicateFound) {

        //  Make their IDs match to prevent adding to the collection.
        if (duplicatePlaylistItem.has('id')) {
            playlistItemToAdd.set('id', duplicatePlaylistItem.get('id'));
        } else {
            playlistItemToAdd.cid = duplicatePlaylistItem.cid;
        }

    }
}


texts:
I want to improve this code with better logic and using STL.

#include <iostream>
#include <vector>

void addition(const std::vector<int>& A,
              const std::vector<int>& B,
                    std::vector<int>& C)
{
   int size_A = A.size();
   int size_B = B.size();
   int max_size;
   if (size_A >= size_B)
   {
      max_size = size_A;
   }
   else
   {
      max_size = size_B;
   }

   int carry = 0, sum = 0;

   int i = size_A - 1, j = size_B - 1, k = max_size;
   C.resize(k + 1);

   while ( i >= 0 && j >= 0 && k >= 0)
   {
      sum = A[i] + B[j] + carry;

      if (sum == 0)
      {
         carry = 0;
         C[k] = 0;
      }
      else if (sum == 1)
      {
         carry = 0;
         C[k] = 1;
      }
      else if (sum == 2)
      {
         carry = 1;
         C[k] = 0;
      }
      else if (sum == 3)
      {
         carry = 1;
         C[k] = 1;
      }
      i--;
      j--;
      k--;
   }
  //if size of first binary number is greter than first
  if (max_size == size_A)
  {
     while (i >= 0 && k >= 0)
     {
        sum = A[i] + carry;

        if (sum == 0)
        {
           carry = 0;
           C[k] = 0;
        }
        else if (sum == 1)
        {
           carry = 0;
           C[k] = 1;
        }
        else if (sum == 2)
        {
           carry = 1;
           C[k] = 0;
        }
        else if (sum == 3)
        {
           carry = 1;
           C[k] = 1;
        }
        i--;
        k--;
     }
  }
  //If size of second binary number is greater than first
  else if (max_size == size_B)
  {
     while (j >= 0 && k >= 0)
     {
       sum = B[j] + carry;

       if (sum == 0)
       {
          carry = 0;
          C[k] = 0;
       }
       else if (sum == 1)
       {
          carry = 0;
          C[k] = 1;
       }
       else if (sum == 2)
       {
          carry = 1;
          C[k] = 0;
       }
       else if (sum == 3)
       {
          carry = 1;
          C[k] = 1;
       }
       j--;
       k--;
     }
  }
  C[0] = carry;
}

int main()
{
   int n1, n2, val;
   std::cout << "Enter the  number of bits for first binary numbers \n";
   std::cin >> n1;
   std::cout << "Enter the  number of bits for second binary numbers \n";
   std::cin >> n2;

   std::vector<int> A;
   std::vector<int> B;
   std::vector<int> C;

   std::cout << "Enter bits for first binary number \n";
   for (int i = 0; i < n1; i++)
   {
      std::cin >> val;
      A.push_back(val);
   }

   std::cout << "Enter bits for second binary number \n";
   for (int i = 0; i < n2; i++)
   {
     std::cin >> val;
     B.push_back(val);
   }

   std::cout << "First number    : ";
   for (int i = 0; i < A.size(); i++)
   {
      std::cout << A[i];
   }

   std::cout << "\nSecond number   : ";
   for (int i = 0; i < B.size(); i++)
   {
      std::cout << B[i];
   }

   addition(A, B, C);

   std::cout << "\nResult          : ";
   for (int i = 0; i < C.size(); i++)
   {
     std::cout << C[i];
   }
   std::cout << "\n";
}


texts: Function for removing forbidden characters

texts:
void removeForbiddenChar(string* s)
{
    string::iterator it;

    for (it = s->begin() ; it < s->end() ; ++it){
        switch(*it){
        case '/':case '\\':case ':':case '?':case '"':case '<':case '>':case '|':
            *it = ' ';
        }
    }
}

I used this function to remove a string that has any of the following character: \, /, :, ?, ", <, >, |. This is for a file's name. This program runs fine. It simply change a character of the string to a blank when the respective character is the forbidden character. However, I have a feeling against this use of switch statement. I simply exploit the case syntax here, but this, somehow nags me. I just don't like it. Anybody else got a better suggestion of a better implementation in this case?


texts:
This code is intended to take input from a form and append it to a database table. The same data is sent to a separate function for subsequent mailing to the respondent. I'm self-taught and it works so overall I'm quite happy.

It just starts to seem a little flabby around the binding and creation of the $mail_params. I imagine there's no real performance cost here but are there more efficient ways of setting multiple variables?

As my first outing into MySQLi functions I would be grateful for a weather eye on the prepared statement and its suitability in preventing SQL injection.

function submit_form ($db_params) {

// connect
$mysqli = new mysqli($db_params['host'], $db_params['username'],
                     $db_params['password'], $db_params['dbname']);

// check
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    return false;
}

// prepare
if (!($stmt = $mysqli->prepare("INSERT INTO interface_response(issue,
                                                               comment,
                                                               email,
                                                               reporting_organisation,
                                                               reporting_dept_prac,
                                                               causing_organisation,
                                                               causing_dept_prac)
                                VALUES (?, ?, ?, ?, ?, ?, ?)"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
    return false;
}

// bind
if (!$stmt->bind_param("sssssss", $issue, $comment, $email,
                                  $reporting_organisation, $reporting_dept_prac,
                                  $causing_organisation, $causing_dept_prac)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
    return false;
}

$email = $_POST['email'];
$mail_params['email'] = $email;

$issue = $_POST['issue'];
$mail_params['issue'] = $issue;

$comment = $_POST['comment'];
$mail_params['comment'] = $comment;

$reporting_organisation = $_POST['reporting_organisation'];
$mail_params['reporting_organisation'] = $reporting_organisation;

$reporting_dept_prac = department_or_practice($_POST['reporting_department'],
                                              $_POST['reporting_practice']);
$mail_params['reporting_dept_prac'] = $reporting_dept_prac;

$causing_organisation = $_POST['causing_organisation'];
$mail_params['causing_organisation'] = $causing_organisation;

$causing_dept_prac = department_or_practice($_POST['causing_department'],
                                            $_POST['causing_practice']);
$mail_params['causing_dept_prac'] = $causing_dept_prac;

// execute
if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    return false;
} else {
    return send_mail($mail_params);
}

// close
$stmt->close();

$mysqli->close();

}


texts:
JavaScript has some inaccurate rounding behavior so I've been looking for a reliable solution without success. There are many answers in this SO post but none cover all the edge cases as far as I can tell. I wrote the following which handles all the edge cases presented. Will it be reliable with edge cases I haven't tested?

If this is a viable solution, any enhancements to make it more efficient would be appreciated. It's not fast (time to run function 1000000 times: 778ms) but doesn't seem to be  terrible either. If there is a better solution, please post.

The edge cases that seemed to give the most problem were the first two:

console.log(round(1.005, 2)); // 1.01
console.log(round(1234.00000254495, 10)); //1234.000002545
console.log(round(1835.665, 2)); // 1835.67))
console.log(round(-1835.665, 2)); // -1835.67))
console.log(round(10.8034, 2)); // 10.8
console.log(round(1.275, 2)); // 1.28
console.log(round(1.27499, 2)); // 1.27
console.log(round(1.2345678e+2, 2)); // 123.46
console.log(round(1234.5678, -1)); // 1230
console.log(round(1235.5678, -1)); // 1240
console.log(round(1234.5678, -2)); // 1200
console.log(round(1254.5678, -2)); // 1300
console.log(round(1254, 2)); // 1254
console.log(round("123.45")); // 123
console.log(round("123.55")); // 124

function round(number, precision) {
  precision = precision ? precision : 0;

  var sNumber = "" + number;
  var a = sNumber.split(".");
  if (a.length == 1 || precision < 0) {
    // from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
    var factor = Math.pow(10, precision);
    var tempNumber = number * factor;
    var roundedTempNumber = Math.round(tempNumber);
    return roundedTempNumber / factor;
  }
  // use one decimal place beyond the precision
  var factor = Math.pow(10, precision + 1);
  // separate out decimals and trim or pad as necessary
  var sDec = a[1].substr(0, precision + 1);
  if (sDec.length < precision + 1) {
    for (var i = 0; i < (precision - sDec.length); i++)
      sDec = sDec.concat("0");
  }
  // put the number back together
  var sNumber = a[0] + "." + sDec;
  var number = parseFloat(sNumber);
  // test the last digit
  var last = sDec.substr(sDec.length - 1);
  if (last >= 5) {
    // round up by correcting float error
    // UPDATED - for negative numbers will round away from 0
    // e.g. round(-2.5, 0) == -3
    number += 1/(factor) * (+number < 0 ? -1 : 1);
  }
  number = +number.toFixed(precision);
  return number;
};


texts:
I've been thinking about implementing events and wrote some abstract code:

#include <memory>
#include <vector>
#include <iostream>

template<typename Event>
class Dispatcher
{
public:
    class Listener
    {
    public:
        virtual void OnEvent(Event& event, Dispatcher& sender) {};
    };

private:
    typedef std::shared_ptr<Listener> ListenerPtr;
    typedef std::vector<ListenerPtr> Listeners;
    Listeners _listeners;

public:
    void Reg(ListenerPtr listener)
    {
        if( _listeners.end() != std::find(_listeners.begin(), _listeners.end(), listener) )
            return;

        _listeners.push_back(listener);
    }

    void Unreg(ListenerPtr listener)
    {
        Listeners::iterator iter = std::find(_listeners.begin(), _listeners.end(), listener);
        if( _listeners.end() == iter )
            return;

        _listeners.erase(iter);
    }

    void Dispatch(Event& event)
    {
        for( Listeners::iterator iter = _listeners.begin(); iter != _listeners.end(); ++iter )
            (*iter)->OnEvent(event, *this);
    }
};

struct SomeEvent
{
    int someParam;
    SomeEvent(int someParam) : someParam(someParam) {}
};

class SomeDispatcher : public Dispatcher<SomeEvent>
{
};

struct OtherEvent
{
    int otherParam;
    OtherEvent(int otherParam) : otherParam(otherParam) {}
};

class OtherDispatcher :
    public SomeDispatcher, public Dispatcher<OtherEvent>
{
};

class Consumer :
    public Dispatcher<SomeEvent>::Listener,
    public Dispatcher<OtherEvent>::Listener
{
    virtual void OnEvent(SomeEvent& event, Dispatcher<SomeEvent>& sender)
    {
        std::cout << "OnEvent SomeEvent " << event.someParam << std::endl;
    }

    virtual void OnEvent(OtherEvent& event, Dispatcher<OtherEvent>& sender)
    {
        std::cout << "OnEvent OtherEvent " << event.otherParam << std::endl;
    }
};

int main(int argc, char **argv)
{
    OtherDispatcher dispatcher;

    std::shared_ptr<Consumer> consumer(new Consumer());

    dispatcher.Dispatcher<SomeEvent>::Reg( consumer );
    dispatcher.Dispatcher<OtherEvent>::Reg( consumer );

    dispatcher.Dispatcher<SomeEvent>::Dispatch(SomeEvent(1));
    dispatcher.Dispatcher<OtherEvent>::Dispatch(OtherEvent(2));

    dispatcher.Dispatcher<SomeEvent>::Unreg( consumer );

    dispatcher.Dispatcher<SomeEvent>::Dispatch(SomeEvent(3));
    dispatcher.Dispatcher<OtherEvent>::Dispatch(OtherEvent(4));

    return 0;
}

It compiles and works as expected, but... I have to write more code to inherit from Dispatcher and Listener, to register listener and to define more exactly which dispatcher I'm registering to. And this method does not allow registering of custom class method, but only OnEvent().

Apart from this, are there any issues with this code? Is it compatible with different compilers and platforms? Any suggestions?


texts: PHP PDO Class with multiple Select Efficiency and speed

texts:
I am very new to classes, and not sure how efficient this class is, would appreciate improvement feedback and info on efficiency including speed.

The class includes a construct that creates a connection to the database and two other functions that get data from the database and return some values concated with some HTML.

This is made from code that I've found around the web mostly SO, so would be good if suggestions were easy to understand for a novice.

Can improvements be made to this so that it is efficient and best practices are incorporated?

<?php
class MyClass {
protected $PDO;

public function __construct(PDO $PDO) {
    $this->PDO = $PDO;
}

public function getCount($sq,$bkid,$bkname) {
    $sth = $this->PDO->prepare("SELECT COUNT(sentence) AS b FROM sentence, chapters, books WHERE MATCH(sentence) AGAINST (:q IN BOOLEAN MODE) AND chapters.book_Id = books.book_Id AND sentence.chapter_Id = chapters.chapter_Id AND books.book_Id = :bk");
    $sth->execute(array(':q' => $sq, ':bk' => $bkid));
    $row = $sth->fetch(PDO::FETCH_ASSOC);
    $total = $row['b'];
    if($total!=0)
    {
    $ensq = urlencode($sq);
    $count = "$bkname$total ";
    return $count;
    }
    else
    {
    return;
    }
}

public function getwriter($sqn) {
    $nsth = $this->PDO->prepare("SELECT COUNT(DISTINCT(writer)) AS n FROM sentence WHERE MATCH(writer) AGAINST (:q IN BOOLEAN MODE)");
    $nsth->execute(array(':q' => $sqn));
    $nrow = $nsth->fetch(PDO::FETCH_ASSOC);
    $ntotal = $nrow['n'];
    if($ntotal!=0)
    {
    $nensq = urlencode($sqn);
    $ncount = "writers$ntotal ";
    return $ncount;
    }
    else
    {
    return;
    }
}

public function getChapter($cqn) {
    $csth = $this->PDO->prepare("SELECT COUNT(chapter_Title) AS c FROM chapters WHERE MATCH (chapter_Title) AGAINST (:q IN BOOLEAN MODE)");
    $csth->execute(array(':q' => $cqn));
    $crow = $csth->fetch(PDO::FETCH_ASSOC);
    $ctotal = $crow['c'];
    if($ctotal!=0)
    {
    $censq = urlencode($cqn);
    $ccount = "Chapters$ctotal ";
    return $ccount;
    }
    else
    {
    return;
    }
}
}
$dbh = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'db', 'pass');
?>

And also is it ok to call the function multiple times next to each other like so:

$t = new MyClass($dbh);
echo $t->getCount($search,11,"Book 1");
echo $t->getCount($search,4,"Book 2");
echo $t->getCount($search,39,"Book 3");
echo $t->getCount($search,56,"Book 4");
echo $t->getWriter($search);
echo $t->getChapter($search);
$dbh = null;


texts:
What this code tries to do is find possible combinations of three numbers.  For example, let's say I have the following numbers:

1, 2, 3, 4, 5, 6, 7

Some possible combinations of three numbers would be:

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

I do get the desired outcome but my code looks ugly.  Are there any remarks or alternate ways to do this?

<?php

    $numbers = [2, 8, 16, 30, 44, 48];
    $number  = $numbers;
    $slice   = [];
    $threes  = [];
    $x       = 1;
    $stake   = 10;
    $odds    = 325;

    echo implode(" | ", $numbers)."
";

    foreach ($numbers as $key) {

        if (count($number) == 6) {
            // $slice = array_slice($number, 0,3);

            $threes[] = $key;
            $threes[] .= next($number);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            $threes[] .= next($number);

            $x++;

            //--------------------------------------------------------------//

            array_pop($threes);
            array_pop($threes);
            $threes[] .= prev($number);
            array_pop($threes);
            $threes[] .= prev($number);
            array_pop($threes);
            $threes[] .= prev($number);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            array_pop($threes);
            $threes[] = prev($number);
            array_pop($threes);
            $threes[] = prev($number);
            $threes[] = next($number);

            $x++;

            array_pop($threes);
            $threes[] = next($number);

            $x++;

            array_pop($threes);
            array_pop($threes);
            $threes[] = prev($number);
            $threes[] = next($number);

            $x++;

        } elseif (count($number) == 5) {
            $threes[] = $key;
            $threes[] .= next($number);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            array_pop($threes);
            $threes[] .= prev($number);
            array_pop($threes);
            $threes[] .= prev($number);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            array_pop($threes);
            $threes[] .= prev($number);
            $threes[] .= next($number);

            $x++;
        } elseif (count($number) == 4) {
            $threes[] = $key;
            $threes[] .= next($number);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            $threes[] .= next($number);

            $x++;

            array_pop($threes);
            array_pop($threes);
            $threes[] .= prev($number);
            $threes[] .= next($number);

            $x++;
        } elseif (count($number) == 3) {
            $threes[] = $key;
            $threes[] .= next($number);
            $threes[] .= next($number);

        }

        array_shift($number);
        $threes = [];
    }

    echo "
---------------------------------------------------------------------------
";
    echo "Total combinations of 3's: ".$x."
";

    ?>


texts:
I was playing around with ES6 arrow functions, currying and partial application and I decided to try a functional implementation of the FizzBuzz problem:

function* range(start, stop) {
  for (var i = start; i < stop; i++)
    yield i
}

var map = fn => res => x => fn(x) ? res : null
var isDividedBy = dividend => divisor => divisor % dividend === 0
var mapDividedBy = x => map(isDividedBy(x))
var mappers = [
  mapDividedBy(3)('Fizz'),
  mapDividedBy(5)('Buzz')
]
var applyMappers = mappers => x => mappers.map(fn => fn(x)).join('') || x

var result = Array.from(range(1, 100)).map(applyMappers(mappers))

console.log(result)

My main focus was to be able to easily add any other case like "print Zazz for numbers lower than 10" by simply adding map(x => x < 10)('Zazz') to the mappers array.

What do you think?


texts:
I am new to writing unit tests and i am facing some difficult writing unit tests for this class.
I am using Xunit and moq.
public class WriteFileOutput: IWriteFileOutput
{
    public string File { get; set; }
    public WriteFileOutput(string fileName)
    {
        File = fileName;
    }

    public void writeFile(List<CustomerDistanceRecord> invitees)
    {
        var result = JsonConvert.SerializeObject(invitees, Formatting.Indented);
        if (System.IO.File.Exists(File))
        {
            System.IO.File.Delete(File);
            using(var tw = new StreamWriter(File, true))
            {
                tw.WriteLine(result.ToString());
                tw.Close();
            }
        }
        else if (!System.IO.File.Exists(File))
        {
            using(var tw = new StreamWriter(File, true))
            {
                tw.WriteLine(result.ToString());
                tw.Close();
            }
        }
    }
}

The code below tests that the writefileoutput writes out a file. I am not sure if this is a good unit test and I was wondering if someone could show me a better way of testing it class. Also I am not sure it deleting the file in the constructor before it is called is a good idea either. Thanks for the help.
 private readonly string _path = "../../../TestOutput/CustomerRecords.json";

    public WriteFileTests()
    {
        if (File.Exists(_path))
        {
            File.Delete(_path);
        }
    }

    [Fact]
    public void WriteFileOuput_should_be_called()
    {
        var fileWriteFileOutput = new WriteFileOutput($"{_path}");
        fileWriteFileOutput.writeFile(It.IsAny<List<CustomerDistanceRecord>>());
        Assert.True(File.Exists($"{_path}"));
    }


texts: Error handling in an Android API (class or enum)

texts:
I am developing an Android Library which will be distributed to other developers.
The library itself is a wrapper of the industry specific one. This makes the API development a bit less flexible. The main goal is to provide an easy and understandable API to the external developers.

For now I've selected an asynchronous approach as a basis for the public API.
The simplified version of the public API look like this:

MyApi{
 public void login(String user, String password, LoginListener listener){...}
 public void doAction1(String actionParam, Action1Listener listener){...}
 public void doAction2(String actionParam1, String actionParam2, Action2Listener listener){...}
}

All the names are selected just for this question.
So the listener (interface) in each method may have arbitrary number of methods. I try to limit the number as much as possible. One method that each of the listeners have is onError(XXXError).

So there is a separate type of Error for each type of listener. Errors extend RuntimeException class an may have common traits. Such as "caused by network problem" error.

For example, this is how the LoginListener interface looks:

public interface LoginListener {
    void onLoginSuccess();
    void onLoginFailed(LoginError error);
}

As a result the user of my API may either display some default error message or do an additional check. Additional check may be required since the error may be caused by different communication problems (network connection, bad input params, internals server error, etc.) in case.

Here is the implementation:

LoginListener loginListener = new LoginListener(){
        @Override
        public void onLoginSuccess() {
            //proceed
        }

        @Override
        public void onLoginFailed(LoginError error) {
            if(error.isNetworkError()){
                //ask user to check network connection
            }else{
                //display default message
            }
        }
    };

For Action1 and Action2, the errors are more complicated and may involve even instanceof comparison to get the exact reason.

Isn't error typing an overhead? What are good examples of error handling/notification?

An option of implementing one MyApiError class with an enum of causes, sounds like a non-flexible and misleading one.


texts:
Just wondering if my

else {return false;}

statements are superfluous... do I just need one return true; here?

function has_access() {
    if ( is_user_logged_in() ) {
        $role = get_current_user_role();
        $admins = array(
            'Administrator',
            'Agent',
            'Contributor',
        );

        if (in_array($role, $admins)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}


texts: Counting number of pairs in an integer array

texts:
So, I wanted to have the count for number of pairs of same integer there are in an array for which I used a HashMap

Input contains two lines:

  Integer n:

  Signifies the size of input
  Input numbers separated by white space character:
  E.g 4 6 6 7 7 8 7 6 4

For the same input,

  Expected Output:

  3

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class SockMerchant {

    public int[] returnsockArr() {
        Scanner sc = new Scanner(System.in);
        int arraySize = sc.nextInt();
        int[] sockArr = new int[arraySize];
        for(int i = 0;i <= arraySize-1; i++) {
            sockArr[i] = sc.nextInt();
        }
        sc.close();
        return sockArr;
    }

    public int returnCount(Map<String, Object> mapCount) {
        int count = 0;
        for(String keyName : mapCount.keySet()) {
            int value = (int)mapCount.get(keyName);
            count = count+(value/2);
        }
        return count;
    }

    public int setMapAndReturnCount(int[] sockArr) {
        Map<String, Object> mapCount = new HashMap<String, Object>();
        for(int j = 0;j<= sockArr.length-1;j++) {
            if(mapCount.containsKey(Integer.toString(sockArr[j]))) {
                mapCount.put(Integer.toString(sockArr[j]), (int)mapCount.get(Integer.toString(sockArr[j]))+1);
            }
            else {
                mapCount.put(Integer.toString(sockArr[j]), 1);
            }
        }
        return returnCount(mapCount);
    }

    public static void main(String args[]) {
        SockMerchant sm = new SockMerchant();
        int[] sockArr = sm.returnsockArr();
        int finalCount = sm.setMapAndReturnCount(sockArr);
        System.out.println(finalCount);
    }
}

I think that I have complicated the solution a bit too much

Is there a better approach to do the same thing?


texts: Twisting words! (boustrophedon formatting)

texts:
I decided to implement properly the Code Golf challenge about twisting strings. I report the assignement verbatim for convenience:

  Twisting Words!

  Given a string and a positive integer. You must twist the string, back
  and forth.

  Example Input / Output

  Input

Programming Puzzles & Code Golf
4

  Output

Prog
mmar
ing
zzuP
les
oC &
de G
 flo

  Input

  The input can be taken in through STDIN, or function argument. The
  input will consist of a string and a positive integer, n. The
  integer will determine the length of each twisted line.

  The string is twisted back-and-forth. An input of HELLO, WORLD! and
  5 would look like:

  Output

  The output will be the twisted text. It may not any trailing
  whitespace. If the input string length is not divisible be the line
  length, add a space until the line is filled:

  An example of this:    Input

Hello, World!
5

  Output (Note the whitespace at the very end)

Hello
roW ,
ld!

My implementation

def twist(text, chunk_size)
   text
     .+(" " * ((text.length % chunk_size) - 1))
     .chars
     .each_slice(chunk_size)
     .each_with_index
     .map {|str, i| i.odd? ? str.reverse : str}
     .map(&:join)
     .join("\n")
end

puts twist("Hello, World!", 5)
puts
puts twist("foo bar baz", 7)


texts: Convert a string in time format to minutes

texts:
I am new to C#. I just created a method where I can convert a string with the format HH:MM AM/PM to minutes. I was wondering if there is a better or more effective way to achieve the same result.

static void Main(string[] args)
    {

        string time1 = "11:15 AM";
        string time2 = "11:15 PM";

        calculateTimeInMinutes(time1);
        calculateTimeInMinutes(time2);

        void calculateTimeInMinutes(string currentTime)
        {
            if (currentTime.Contains("PM"))
            {
                int hours = Convert.ToInt32(currentTime.Substring(0, 2));
                int HoursInminutes = (12 + (hours % 60)) * 60;
                string minutesInString = currentTime.Split(':')[1];
                int minutes = Convert.ToInt32(minutesInString.Remove(2));
                int totalMinutes = HoursInminutes + minutes;
                Console.WriteLine(totalMinutes);
            }
            else
            {
                int hours = Convert.ToInt32(currentTime.Substring(0, 2));
                int HoursInminutes = (hours % 60) * 60;
                string minutesInString = currentTime.Split(':')[1];
                int minutes = Convert.ToInt32(minutesInString.Remove(2));
                int totalMinutes = HoursInminutes + minutes;
                Console.WriteLine(totalMinutes);
            }
        }

        Console.ReadKey();
    }
}


texts:
It's a simple app that uses a public API to display data. It works as is, but I'm seeing a lot of spaghetti code that my limited experience can't fix on its own.

import React, { Component } from "react";
import Spinner from "./components/common/Spinner";
import "../src/App.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoading: false
    };
  }

  componentDidMount() {
    const urlParams = new URLSearchParams(window.location.search);
    const city = urlParams.get("city");
    fetch(`http://opentable.herokuapp.com/api/restaurants?city=${city}`)
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoading: true,
          items: json
        });
      });
  }
  render() {
    const { isLoading, items } = this.state;
    let content =
No Data
;
    if (!items.restaurants || items.restaurants === []) {
      content =
No Data
;
    } else if (items.restaurants.length !== 0) {
      console.log(items);
      let itemsToArray = Object.values(items.restaurants);
      content = (

              {itemsToArray.map(item => (

                    {item.name}
                  {" "}
                  | {item.address}{" "}
                  | Price rating:{" "}
                  {item.price}

              ))}

      );
    }
    return !isLoading ? (

        <Spinner />

    ) : (
      <React.Fragment>

{content}

      </React.Fragment>
    );
  }
}

export default App;


texts:
I made a small simple drawing app using HTML5 Canvas, learning how to use canvas.
You can right click to change color, scroll to change brush size, and click + drag to draw on the screen.
Any feedback is appreciated, but I am concerned about storing each move event circle that is created in an array may become quite messy eventually.

class Circle {
  constructor(x, y, radius = 2) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.persist = [];
    this.color = "lightblue";
  }
  draw() {
    this.persist.forEach(e => {
      c.beginPath();
      c.arc(e.x, e.y, e.radius, 0, Math.PI * 2, false);
      c.fillStyle = e.color;
      c.fill();
    });
    c.beginPath();
    c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
    c.fillStyle = this.color;
    c.fill();
  }
}

const colors = [
  "#ffadad",
  "#ffd6a5",
  "#fdffb6",
  "#caffbf",
  "#9bf6ff",
  "#a0c4ff",
  "#ffc6ff",
  "#bdb2ff"
]

var c = null;
var canvas = null;
const main = function () {
  canvas = document.querySelector("canvas");
  c = canvas.getContext("2d");
  sizeCanvas();
  window.addEventListener("resize", sizeCanvas);
  window.addEventListener("mousemove", function(e){
    myCursor.x = event.x;
    myCursor.y = event.y;
    if (e.buttons == 1) {
      myCursor.persist.push({x: myCursor.x, y: myCursor.y, radius: myCursor.radius, color: myCursor.color});
    }
  });
  window.addEventListener("wheel", function(e){
    e.preventDefault();
    const amountToChange = -1 * e.deltaY / 25;
    if (myCursor.radius + amountToChange < 1 || myCursor.radius + amountToChange > 50) return;
    myCursor.radius += amountToChange;
  }, {passive: false});
  window.addEventListener("contextmenu", function(e) {
    e.preventDefault();
    myCursor.color = colors[Math.floor(Math.random()*colors.length)]
  });
  putCursorOnCanvas();
  // makeCanvasDrawable();
}

function sizeCanvas() {
  canvas.height = innerHeight;
  canvas.width = innerWidth;
}

const myCursor = new Circle(0, 0, 10);
function putCursorOnCanvas() {
  requestAnimationFrame(putCursorOnCanvas);
  c.clearRect(0, 0, innerWidth, innerHeight);
  myCursor.draw();
}

function makeCanvasDrawable() {

}

window.onload = main;
body {
  background-color: lightblue;
  margin: 0;
  height: 100%;
  overflow: hidden;
}

canvas {
  background-color: black;
  cursor: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>draw a line :D</title>
    <link rel="stylesheet" href="main.css">
    <script src="main.js" charset="utf-8"></script>
    <meta content="width=device-width, initial-scale=1" name="viewport">
  </head>
  <body>
    <canvas></canvas>
  </body>
</html>


texts:
Inspired by the non-locking implementation proposed in this post, the following code is an attempt to (about) do the same using the azure cache. As I'm totally green on the Azure cache I'd appreciate input on best practices or pitfalls. I should add that this method is assumed to be the only interaction with the azure cache in the application.

public class AzureCacheWrapper
{
    private readonly DataCache cache;

    public AzureCacheWrapper(DataCacheFactory cacheFactory)
    {
        this.cache = cacheFactory.GetDefaultCache();
    }

    public T GetOrAdd<T>(string key, Func<T> factoryMethod)
    {
        var factoryMethodAsLazy = new Lazy<T>(factoryMethod);
        var cachedFactory = cache.Get(key) as Lazy<T>;
        if (cachedFactory == null)
        {
            try
            {
                cache.Add(key, factoryMethodAsLazy);
                cachedFactory = factoryMethodAsLazy;
            }
            catch (DataCacheException ex)
            {
                if (ex.ErrorCode != DataCacheErrorCode.KeyAlreadyExists)
                {
                    throw;
                }

                // We know for sure that the key exists at this point:
                // Two concurrent callers tried to get it, and this thread
                // happened to be deadlock victim.
                cachedFactory = (Lazy<T>)cache.Get(key);
            }
        }

        return cachedFactory.Value;
    }
}


texts: Retrieving the first occurrence of every unique value from a CSV column

texts:
A large .csv file I was given has a large table of flight data. A function I wrote to help parse it iterates over the column of Flight IDs, and then returns a dictionary containing the index and value of every unique Flight ID in order of first appearance.

Dictionary = { Index: FID, ... }

This comes as a quick adjustment to an older function that didn't require having to worry about FID repeats in the column (a few hundred thousand rows later...).

Example:

20110117559515, ...
20110117559515, ...
20110117559515, ...
20110117559572, ...
20110117559572, ...
20110117559572, ...
20110117559574, ...
20110117559587, ...
20110117559588, ...

and so on for 5.3 million some rows.

Right now, I have it iterating over and comparing each value in order. If a unique value appears, it only stores the first occurrence in the dictionary. I changed it to now also check if that value has already occurred before, and if so, to skip it.

def DiscoverEarliestIndex(self, number):
    result = {}
    columnvalues = self.column(number)
    column_enum = {}
    for a, b in enumerate(columnvalues):
        column_enum[a] = b
        i = 0
    while i < (len(columnvalues) - 1):
        next = column_enum[i+1]
        if columnvalues[i] == next:
            i += 1
        else:
            if next in result.values():
                i += 1
                continue
            else:
                result[i+1]= next
                i += 1
    else:
        return result

It's very inefficient, and slows down as the dictionary grows. The column has 5.2 million rows, so it's obviously not a good idea to handle this much with Python, but I'm stuck with it for now.

Is there a more efficient way to write this function?


texts: A simple log that tracks hours worked and and a python script that calculates wages

texts:
I wrote a simple Python script that will calculate income for a given month and hourly wage by parsing the contents of a log file. The instructions for how to use it is in my GitHub account here. The script is used in the command line with the following command

python calculate_hours.py MY_LOG.txt MONTH YEAR HOURLY_WAGE

MY_LOG.txt is the text file containing the date and the number of hours worked on that day
MONTH and YEAR are the full (not abbreviated) month and year for which you'd like the income calculated (e.g. December 2015)
HOURLY_WAGE is, well, your hourly wage (e.g. 25)

The log file must be formatted in a specific way. An entry in the log should look like the following

**Date**: 21 December 2015
**Time**: 5pm - 7pm, 12-1am
**Hours**: 2, 1

**Notes**:
+ Debugged script written yesterday
+ Checked data

The script depends on the information after **Date** and **Hours** to calculate income.

It's very simple and I was wondering if there was a way to improve it. The script looks for patterns in the log file to get the date and the hours worked.

import re
import argparse

def wage_calculator(log_txt_file, month, year, wage):

    date_pattern = "\*\*Date\*\*"  # pattern identifying the date in the file
    hours_full = []

    with log_txt_file as f:

        for line in log_txt_file:

            if re.search(r"{0}".format(date_pattern), line):  # go to the relevant line

                if re.search(month, line) and re.search(str(year), line):  # within line, go to desired month/year

                    # skips two lines to the line containing the number of hours worked
                    f.next()
                    hours_line = f.next()

                    hours_list_str = re.findall(r'[-+]?\d*\.*\d+', hours_line)  # put hours in a list
                    hours_list = [float(x) for x in hours_list_str]

                    hours_full += hours_list

                    sum_hours_date = sum(hours_list)

                    print line.rstrip()
                    print "Hours logged: " + str(hours_list)
                    print "Total hours for the day " + str(sum_hours_date) + "\n"

    hours_total = sum(hours_full)

    print "Total hours worked in {0} {1} is {2}".format(month, year,
                                                        hours_total)
    print "At ${0}/hr, your total wage for {1} {2} is ${3}".format(wage, month
                                                                   , year, hours_total * wage)

def main():

    parser = argparse.ArgumentParser()

    parser.add_argument("file",
                        help="Text file containing hours logged (e.g. ra_hours.txt)",
                        type=argparse.FileType('r')
                        )
    parser.add_argument("month",
                        help="The month for which we want the income",
                        type=str)
    parser.add_argument("year",
                        help="Enter year",
                        type=int)
    parser.add_argument("wage",
                        help="Enter hourly wage",
                        type=float)

    args = parser.parse_args()

    wage_calculator(args.file, args.month, args.year, args.wage)

if __name__ == '__main__':
    main()


texts:
I'm moving on to graphics, picking Pyglet and Cocos2D. This is my first program in Python with GUI.

Introducing:

Two distinct high definition button sprites
Satisfying high quality button pressing clicks
Conveniently positioned counter
Fully functional exit button
Detailed error logging techniques to support software users
Nice hand-picked background color

I would be very happy if you would correct my first steps to game programming.

Files

""" Button presses counter. """

import cocos
import pyglet

class App (cocos.layer.ColorLayer):
    """ A class holding an App layer, the only layer of the program. """
    is_event_handler = True

    def __init__(self):
        """ Initializes the App layer. """
        CENTER = 320, 240 # Center point constant. No >80 symbols and multilines.
        super(App, self).__init__(135, 206, 235, 255) # skyblue background color

        # Counter
        self.text = cocos.text.Label('0',
                                     anchor_x = 'center',
                                     anchor_y = 'center',
                                     position = CENTER)
        self.add(self.text, z = 1)

        # Button stuff
        self.b_released = True # Button state
        # Button sprites
        try:
            self.pressed = cocos.sprite.Sprite('pressed.png', position = CENTER)
            self.released = cocos.sprite.Sprite('released.png', position = CENTER)
            self.add(self.released) # When button state changes, sprites switch
        except Exception:
            with open('errlog.txt', 'a+') as f:
                f.write("Problems w/ 'pressed.png' & 'released.png'. ")
                f.write("Most likely do not exist or are corrupted.\n")
        # Sounds
        try:
            self.p_sound = pyglet.resource.media('press.wav',streaming=False)
            self.r_sound = pyglet.resource.media('release.wav',streaming=False)
        except Exception:
            with open('errlog.txt', 'a+') as f:
                f.write("Problems w/ 'press.wav' & 'release.wav'. ")
                f.write("Most likely do not exist or are corrupted.\n")

    def update_counter(self):
        """ Increases counter, positions it on center. """
        self.text.element.text = str ( int(self.text.element.text)+1 )
        self.text.element.position = 320, 240

    def on_mouse_press(self, x, y, buttons, modifiers):
        """ Changes state, sprite, plays sound when button is pressed. """
        if x > 241 and x < 399 and y > 161 and y < 319 \
        and self.b_released and buttons & pyglet.window.mouse.LEFT:
            self.b_released = False
            self.add(self.pressed)
            self.remove(self.released)
            self.p_sound.play()
            self.update_counter()

    def on_mouse_release(self, x, y, buttons, modifiers):
        """ Changes state, sprite, plays sound when button is released. """
        if not self.b_released:
            self.b_released = True
            self.add(self.released)
            self.remove(self.pressed)
            self.r_sound.play()

cocos.director.director.init()
cocos.director.director.run( cocos.scene.Scene( App() ) )


texts: Appropriate use of bind for elasticsearch callback

texts:
I'm starting a new project with Node. I'm learning the object model, and the code below is my first module. One of the things threw me was the behavior of this inside the callback for exists.  Is my usage of bind correct?  Is there a way to write this without needing the bind?  It feels like it may be a bit of a workaround for something I've structured incorrectly.

My project

var es = require('elasticsearch');

function NetFlowStorage() {
    this.host = 'localhost:9200';
    this.shards = '4';
    this.replicas = '0';
    this.index_name = 'flow_track2';
    this.client = null;

}

// setup our index
NetFlowStorage.prototype.createIndex = function createIndex() {

    this.connect();

    this.client.indices.exists({
        index: 'flow_track2'

    }, function(error, exists) {

        if (exists === true) {
            console.log('index already exists, not creating again');
        } else {
            console.log('creating index');

            this.client.indices.create({
                index: 'flow_track2',
                body: {
                    index: {
                        number_of_shards: this.shards,
                        number_of_replicas: this.replicas
                    }
                }
            }, function(error, response, status) {
                if (error) {
                    console.log(error + ' ' + status + ' ' + response);
                    process.exit(1);
                }

            });
        }
    }.bind(this));
};

// Store the actual flow
NetFlowStorage.prototype.storeFlow = function storeFlow(flow) {
    flow.timestamp = Date.now();

    this.connect();

    this.client.index({
        index: 'flow_track2',
        type: 'raw_flow',
        body: {
            ipv4_src_addr: flow.ipv4_src_addr,
            ipv4_dst_addr: flow.ipv4_dst_addr,
            ipv4_next_hop: flow.ipv4_next_hop,
            input_snmp: flow.input_snmp,
            output_snmp: flow.output_snmp,
            in_pkts: flow.in_pkts,
            in_bytes: flow.in_bytes,
            first_switched: flow.first_switched,
            last_switched: flow.last_switched,
            ipv4_src_port: flow.ipv4_src_port,
            ipv4_dst_port: flow.ipv4_dst_port,
            tcp_flags: flow.tcp_flags,
            protocol: flow.protocol,
            src_tos: flow.src_tos,
            in_as: flow.in_as,
            out_as: flow.out_as,
            src_mask: flow.src_mask,
            dst_mask: flow.dst_mask,
            timestamp: flow.timestamp
        }
    });
};

NetFlowStorage.prototype.connect = function connect() {

    if (this.client === null) {

        this.client = new es.Client({
            host: this.host
        });
    }
    return this.client;
};

module.exports = NetFlowStorage;


texts: Optimization of a basic Sieve of Eratosthenes algorithm

texts:
I have the following Sieve of Eratosthenes algorithm:

public static ArrayList<Integer> sieveOfEra(int limit) {
    int crosslimit = (int) Math.sqrt(limit);
    boolean[] sieve = new boolean[limit+1];
    ArrayList<Integer> primes = new ArrayList<Integer>(Arrays.asList(2));

    for (int n = 4; n <= limit; n += 2) {   // mark even mumbers > 2
        sieve[n] = true;
    }

    for (int n = 3; n <= crosslimit; n += 2) {
        if (!sieve[n]) {
            for (int m = n*n; m <= limit; m += 2*n) {
                sieve[m] = true;
            }
        }
    }

    for (int i = 3; i <= limit; i += 2) {
        if (!sieve[i]) {
            primes.add(i);
        }
    }

    return primes;
}

It returns an ArrayList of all the primes up to n. It first marks the composite numbers in a boolean array, then loops through the boolean array to add unmarked indexes as prime numbers in the primes ArrayList.

I'm looking for any feedback in general, but specially for ways to optimize the algorithm.

I understand that I can get rid of marking even numbers, and even including them in the sieve, but I don't understand how it would be implemented.


texts: Two maximal value in array. Sorted and Array.Sort()

texts:
Compare the two methods of sorting the array in ascending order, where can I optimize? How best to handle exception handling?

    class Inside {

    Random rand = new Random();

        // step 1.1: Fill array, output array

        public void SortedArray(int arrSize) {

            int[] arrOne = new int[arrSize];
            Console.Write("Array size: " + arrSize + "\n\t\t\t\t\t\tARRAY\n");

            for (int x = 0; x < arrOne.Length; x++) {

                arrOne[x] = rand.Next(-1000, 1000);
                Console.Write("{0, 8} | ", arrOne[x]);
                if (x % 8 == 0) Console.WriteLine();
            }

            // step 1.2: Sorted array and output on monitor two maximal value

            for (int i = 0; i < arrOne.Length; i++) {

                int minIndex = i;
                for (int j = i + 1; j < arrOne.Length; j++) if (arrOne[minIndex] > arrOne[j]) minIndex = j;
                int temp = arrOne[minIndex];
                arrOne[minIndex] = arrOne[i];
                arrOne[i] = temp;
            }

            Console.Write("\n\n\t\t\t\t\t\tARRAY SORTED\n\n");

            for (int x = 0; x < arrOne.Length; x++) {
                Console.Write("{0, 8} | ", arrOne[x]);
                if (x % 8 == 0) Console.WriteLine();
            }

            Console.WriteLine("\n\nMaximal value 1: " + arrOne[arrOne.Length - 1] + "\nMaximal value 2: " + arrOne[arrOne.Length - 2]);
        }

        // Step 2.1: Fill array and output

        public void SortedMethod(int arrSize) {

        int[] arrOne = new int[arrSize];
        Console.Write("Array size: " + arrSize + "\n\t\t\t\t\t\tARRAY\n");

        for (int x = 0; x < arrOne.Length; x++)  {

            arrOne[x] = rand.Next(-1000, 1000);
            Console.Write("{0, 8} | ", arrOne[x]);
            if (x % 8 == 0) Console.WriteLine();
        }

        // Step 2.2: Sorted array and output on monitor two maximal value

        Array.Sort(arrOne);
        Console.Write("\n\n\t\t\t\t\t\tARRAY SORTED\n\n");

        for (int x = 0; x < arrOne.Length; x++)  {
            Console.Write("{0, 8} | ", arrOne[x]);
            if (x % 8 == 0) Console.WriteLine();
        }
        Console.WriteLine("\n\nMaximal value 1: " + arrOne[arrOne.Length - 1] + "\nMaximal value 2: " + arrOne[arrOne.Length - 2]);
    }
}

// user class

class Data {

static void Main() {

        // Step 1: Call the sort method by selecting
        Inside obj = new Inside();
        Console.Write("Please, enter array size: ");
        int sizeArr = Convert.ToInt32(Console.ReadLine());
        var timeStart = Stopwatch.StartNew();
         obj.SortedArray(sizeArr);
         timeStart.Stop();

        // Step 2: Call method Array.sort()

        var timeStartTwo = Stopwatch.StartNew();
        obj.SortedMethod(sizeArr);
        timeStartTwo.Stop();

        // Step 3: Compare runtime

        Console.Write("SortedArray = {0}\nSortedMethod = {1}", timeStart.Elapsed, timeStartTwo.Elapsed + "\n");
    }
}


texts: Microsoft OA | Longest Substring Without 3 Contiguous Occurrences of Letter

texts:
For the following question, does my JS Solution seem correct?
I'm looking for some peer review.

Q: Given a string s containing only a and b, find longest substring of s such that s does not contain more than two contiguous occurrences of a and b.

Examples:
"aabbaaaaabb" => "aabbaa"
"aabbaabbaabbaa" => "aabbaabbaabbaa"
function maxLenSubStr(s) {
    let start = 0, end = 0;
    let numOfConsecutiveChars = 0;
    let res = "";
    while (end <= s.length) {
        numOfConsecutiveChars++;
        if (numOfConsecutiveChars > 2 || end == s.length) { // time to end our substring is these two cases
            if (end-start > res.length) res = s.substring(start,end); // if it is not longer, there is no need to store it
            start = end-1; // slide our window so we can look for a new valid substring
            numOfConsecutiveChars--; // now we have a valid substring with two contiguous occurrences instead of three
        }
        if (s[end] !== s[end+1]) numOfConsecutiveChars = 0;
        end++;
    }
    return res;
    // Time Complexity: O(n)
    // Space Complexity: O(1)
}


texts:
I have a Feather M0 basic paired with a OLED FeatherWing. I am making an instructions page but the code is quite repetitive. How can I make my code shorter?

import board
from busio import I2C
from adafruit_ssd1306 import SSD1306_I2C
from time import sleep
from digitalio import DigitalInOut, Direction, Pull

i2c = I2C(board.SCL, board.SDA)
oled = SSD1306_I2C(128, 32, i2c)

button_A = DigitalInOut(board.D9)
button_B = DigitalInOut(board.D6)
button_C = DigitalInOut(board.D5)

button_A.direction = Direction.INPUT
button_B.direction = Direction.INPUT
button_C.direction = Direction.INPUT

button_A.pull = Pull.UP
button_B.pull = Pull.UP
button_C.pull = Pull.UP

def check_buttons():
    if button_A.value is False:
        return 'A'
    elif button_B.value is False:
        return'B'
    elif button_C.value is False:
        return 'C'
    else:
        return None

def wait_for_A():
    sleep(0.5)
    while check_buttons() is not 'A':
        pass

oled.fill(0)
oled.text('Adafruit Feather', 0, 0, 1)
oled.text('Program selector', 0, 8, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()

wait_for_A()

oled.fill(0)
oled.text('Instructions:', 0, 0, 1)
oled.text('Use A and C to move', 0, 8, 1)
oled.text('up and down.', 0, 16, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()

wait_for_A()

oled.fill(0)
oled.text('Instructions (cont.):', 0, 0, 1)
oled.text('Press B to select a', 0, 8, 1)
oled.text('program.', 0, 16, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()

wait_for_A()

oled.fill(0)
oled.text('Instructions (cont.):', 0, 0, 1)
oled.text('At anytime you can', 0, 8, 1)
oled.text('press reset to go...', 0, 16, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()

wait_for_A()

oled.fill(0)
oled.text('Instructions (cont.):', 0, 0, 1)
oled.text('... back to the main', 0, 8, 1)
oled.text('screen.', 0, 16, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()

wait_for_A()

oled.fill(0)
oled.text('Instructions (cont.):', 0, 0, 1)
oled.text('The programs will', 0, 8, 1)
oled.text('have there own...', 0, 16, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()

wait_for_A()

oled.fill(0)
oled.text('Instructions (cont.):', 0, 0, 1)
oled.text('... instructions.', 0, 8, 1)
oled.text('Press A to continue', 0, 16, 1)
oled.text('to menu', 0, 24, 1)
oled.show()

wait_for_A()

oled.fill(0)
oled.show()


texts: Method to separate a list of ports to scan

texts:
I'm building a port scanner as an exercise. It contains a method to separate the ports that the user wants to have checked, which can include single ports and port ranges, ex: 22, 23, 80-120, 443-500, 1024, etc. It discards wrong ports such as negative ports, wrong range such as 120-80 instead of 80-120 which is the right form, and duplicate ports.

I'm wondering if there's a better way to do this, or to improve the code, make it shorter, using a more effective technique. The text box to enter the list of ports only accepts numbers, commas and dashes.

private List<int> extractPorts(string ports)                // the string argument contains a list of ports entered through a text box
    {

        string[] portList = ports.Split(',');                   // save everything between commas, including ranges like 80-120

        List<int> listOfPorts = new List<int>();                // creates a new list of integers to save the valid given ports

        for (int i = 0; i < portList.Length; i++ )              // iterates through port list including single ports and ranges
        {
            if (portList[i].Contains('-'))                      // if finds a range like 80-120...
            {
                try
                {
                    int[] range = Array.ConvertAll(portList[i].Split('-'), int.Parse);  // saves the edges of a range into an array ex: 80-120 as 80 and 120

                    for (int j = range[0]; j <= range[range.Length - 1]; j++)           // iterates through the range saved above ex: from 80 to 120 the get
                    {
                        listOfPorts.Add(j);                                             // every single port ex: in this case it gets 40 ports, from 80 to 120
                    }                                                                   // if finds an error like a negative port or a wrong range like 120-100
                }                                                                       // instead of 100-120 will discard it
                catch { }
            }
            else
                listOfPorts.Add(Convert.ToInt32(portList[i]));  // adds a single port to the list
        }

        List<int> intPortsList = listOfPorts.Distinct().ToList();   // eliminate duplicated ports

        listOfPorts.Clear();                                        // clear the previous list

        foreach (int item in intPortsList)
        {
            if (item <= 65536)                                      // discard ports out of range
              listOfPorts.Add(item);
        }

        listOfPorts.Sort();                                         // to sort the final list

        return listOfPorts;
    }


texts: Searching for selectors not using document.querySelector/document.querySelectorAll

texts:
I had a technical interview the other day and failed a certain question:

    Given a CSS selector (can just be a class name, id or an arbitrary
    number of selectors), return the parent DOM element in an array. The caveat is that you cannot use external libraries or use
    document.querySelector or document.querySelectorAll. Use
    the HTML code below:

For example, if given a CSS selector of img.ClassTwo it would return the img tag, where if the given CSS selector was div#idOne.classTwo it would return 1 div, whereas if the selector was just div, it would return 2 divs. Whereas if I was given img#One it would return an empty array.

My code below works, but I feel that it is too 'cheeky' as it doesn't use either document.querySelector or document.querySelectorAll directly, but uses a variation of document.querySelectorAll - as I can't think of an alternative method that can cater for an arbitrary number of CSS selectors unlike how document.querySelector or document.querySelectorAll can.

Is my code correct? Or can it be improved anyway?

var theFunction = function (input) {

    let arr = [];

    let body = document.getElementsByTagName("BODY")[0];

    let selectors = body.querySelectorAll(input);

    for (i = 0; i < selectors.length; ++i) {
        arr.push(selectors[i].nodeName);
    }

    console.log(arr);

}


texts: Converting an object to be used with a treegrid

texts:
I'm a bit novice/moderate at JS. To my surprise I managed to put this together and it does work for what I intended.

The objective is to convert an object into a format that is more conducive to being used with a treegrid. I'm using the underscore library to grab object keys at various points.

I just wanted to know if maybe there's a better or perhaps more performant way of looping through these deeply nested objects that I may be overlooking. Something that's capable of handling hundreds, or even a thousand, of these nodes without potentially locking up a browser?

I found a hint about storing the length variables separately in a similar question that displayed looping through things in this manner, I just wanted to know if there may be any other tips?

JSBin

var data_source = {"sprint":{"children":{"country":{"us":{"clicks":26}},"device":{"iphone":{"clicks":26}},"isp":{"comcast cable":{"clicks":26}},"os":{"ios":{"clicks":15},"android":{"clicks":10}},"referer":{"unknown":{"clicks":26}}},"clicks":26},"verizon":{"children":{"country":{"us":{"clicks":10,"conversions":5,"earned":0.5,"spent":0.2}},"device":{"galaxy s":{"clicks":1}},"isp":{"comcast cable":{"clicks":1}},"os":{"android":{"clicks":1}},"referer":{"unknown":{"clicks":1}}},"clicks":1,"conversions":1}};

var object = [];

function convert(data){
  var keys = _.keys(data);
  var keyslength = keys.length;
  for (var i = 0; i < keyslength; i++){
    var me = data[keys[i]];
    var rootleaf = buildLeaf(me);
    rootleaf.name = keys[i];
    rootleaf.children = [];

    var childkeys = _.keys(me.children);
    var childkeyslength = childkeys.length;
    for (var i2 = 0; i2 < childkeyslength; i2++){
      var childme = me.children[childkeys[i2]];
      var childleaf = {};
      childleaf.name = childkeys[i2];
      childleaf.children = [];

      var grandchildkeys = _.keys(childme);
      var grandchildkeyslength = grandchildkeys.length;
      for (var i3 = 0; i3 < grandchildkeyslength; i3++){
        var grandchildme = childme[grandchildkeys[i3]];
        var grandchildleaf = buildLeaf(grandchildme);
        grandchildleaf.name = grandchildkeys[i3];
        childleaf.children.push(grandchildleaf);
      }

      rootleaf.children.push(childleaf);
    }

    object.push(rootleaf);
  }
}

convert(data_source);
console.log(object);

function buildLeaf(node){
  var tempnode = {};
  var clicks = ((node.clicks) ? node.clicks : 0);
  var conversions = ((node.conversions) ? node.conversions : 0);
  var earned = ((node.earned) ? node.earned : 0);
  var spent = ((node.spent) ? node.spent : 0);
  tempnode.clicks = clicks;
  tempnode.conversions = conversions;
  tempnode.earned = '$' + earned.toFixed(2);
  tempnode.spent = '$' + spent.toFixed(2);
  tempnode.conversion_rate = conversionRate(conversions,clicks);
  tempnode.net_earned = netEarned(earned,spent);
  tempnode.epc = epc(clicks,earned,spent);
  tempnode.roi = roi(earned,spent);
  return tempnode;
}

// calculation functions

function conversionRate(cv, cl) {
    if (cl === 0) return '0%';
    return ((cv/cl)*100).toFixed(1) + '%';
}
function epc(cl, e, s) {
    if (cl === 0 || e === 0) return '$0.000';
    return '$' + ((e - (cl * s)) / cl).toFixed(3);
}
function netEarned(e, s) {
    if (e === 0) return '$0.00';
    return '$' + (e - s).toFixed(2);
}
function roi(e, s) {
    if (e === 0) return '0%';
    return (((e - s) / s) * 100).toFixed(0) + '%';
}


texts: Project Euler #10 in Swift - Summation of primes

texts:
I just finished Project Euler #10 in Swift, and since there is not any version yet on Code Review, I would like to have some comments on what I did to try to improve it.

I hope I learned some from the previous code reviews :).

  The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

  Find the sum of all the primes below two million.

import Foundation

func summationOfPrimesBelow(var n:Int) -> Int {

    assert(n > 0, "argument must be positive")

    var composite = [Bool](count: n, repeatedValue: false)

    var x = 2
    let maxPrime = Int(ceil(sqrt(Double(n))))

    while x <= maxPrime {
        if composite[x] == false {
            for y in stride(from: x * x, through: n - 1, by: x) {
                composite[y] = true
            }
        }
        x++
    }

    var result = 0
    for i in stride(from: 2, through: composite.count - 1, by: 1) {
        if composite[i] == false {
            result += i
        }
    }

    return result
}

func euler10() {
    let number = summationOfPrimesBelow(2_000_000)

    println(number)
}

func printTimeElapsedWhenRunningCode(operation:() -> ()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed : \(timeElapsed) s")
}

printTimeElapsedWhenRunningCode(euler10)

The code executes in 0.012s in Release mode.


texts: v2 - Adding a duplicate entry randomly into a list in haskell using random monad

texts:
Next version of Adding a duplicate entry randomly into a list in haskell using random monad

I wrote this trying to set up a Haskell testcase. The aim is to take a list and add a single duplicate from any place in the list to anywhere else in the list.  I'm trying to learn to use the Random Monad properly so the main aims should be clear, simple, idiomatic and pure code. However any recommendations for improvement are appreciated.

The code here has most of the improvements suggested by @Petr in the review of the previous version, however

I'm still using lists rather than sequences because the code I plan to test uses lists
I still have an infinite list function because I want to be able to use it easily from IO code where the number of strings to be generated isn't known in advance.  I believe that since the Random Monad uses incremental state based on the State Monad, it should be okay to generate infinite lists with it.

-- DataListDuplicator.hs by Michael De La Rue 2014
-- licensed to StackExchange codereview under cc by-sa 3.0
-- may be used under AGPLv3

module DataListDuplicator where

import Control.Monad.Random

infiniteDuplicateLists :: (MonadRandom m) => [a] -> m [[a]]
infiniteDuplicateLists = mapM addRandomDuplicate . repeat

addRandomDuplicate :: MonadRandom m => [a] -> m [a]
addRandomDuplicate genlist = do
     frompos <- getRandomR (0 ,llen - 1)
     topos   <- getRandomR (0 ,llen)
     let  newlist = listEntryDuplicate frompos topos genlist
     return newlist
   where
     llen = length genlist

listEntryDuplicate from to list =
      start ++ [repeat] ++ end
    where
      repeat = list !! from
      (start, end) = splitAt to list

Here's a little program which drives that:

-- duplicate-to-list-randmonad.hs by Michael De La Rue 2014
-- licensed to StackExchange codereview under cc by-sa 3.0
-- may also be used under AGPLv3
-- N.B. Trivial copying of code fragments does not normally require any license.

import Data.List
import Control.Monad.Random
import DataListDuplicator

main :: IO ()
main = do
    putStrLn $ "list comparison " ++ prettyList list
    g <- getStdGen
    let shuffled = evalRand (infiniteDuplicateLists list) g
    putStrLn $ "lists after \n" ++ intercalate "\n" ( map prettyList (take 5 shuffled))
    where
    list = ["a","b","c"]

prettyList :: (Show a) => [a] -> String
prettyList list = " [ " ++ intercalate "," (map show list) ++ " ] "


texts:
The purpose of this code is to centralize all error / status messages to present to the user. For example, registering an account and the user email address is already registered. A status code is set then sent off to get a friendly error message to present to the user. All services will have its own set of status code and status messages which is handled by a status handler for filtering. While this is only a basic class I want to make sure that I am going in the right direction before extending.

Status codes

namespace Services.RegistrationService
    {
        public enum StatusCodes
        {
            UserAlreadyExists,
            // more to come

        }
    }

List of statuses for registration

using Framework;
using System.Collections.Generic;

namespace Services.RegistrationService
{
    public class RegistrationStatusMessages : MessageStatusHandler
    {
        public void AddErrors(List<StatusCodes> codes)
        {
            foreach(var errorCodes in codes)

            switch (errorCodes)
            {
                case StatusCodes.UserAlreadyExists: { base.add("User already exists", "EmailAddress", true); break; }
            }
        }
    }
}

Message status handler

using System.Collections.Generic;
using System.Linq;

namespace Framework
{
    public class MessageStatusHandler
    {
        protected List<MessageStatusHandler> _errorList;

        private string _friendlyErrorMessage;
        private bool _isError;
        private string _propertyName;

        public MessageStatusHandler()
        {
            _errorList = new List<MessageStatusHandler>();

        }

        protected void add(string friendlyErrorMessage, string propertyName, bool isError)
        {
            _errorList.Add(new MessageStatusHandler { _friendlyErrorMessage = friendlyErrorMessage, _propertyName = propertyName, _isError = isError });
        }

        public bool HasErrors()
        {
            return _errorList.Any(x => x._isError == true);
        }
    }
}

Again, it is a simple class setup that centralizes status codes, error messages for each service. Is there any way to improve on this, or am I going in the right direction?


texts:
This code is a Parser that parses numbers according to R5RS.

#b1001 - binary
#o2127 - octal
#h02d  - hexadecimal
#d1231 - decimal
3923 - decimal

It is working at the moment, the only problem is the parseNumberBase. I am really new to haskell, but it does not look very good to me.

How could I improve it? (readability wise)
It would also be nice to see a more "idiomatic" approach

import Data.Char (digitToInt)
import Numeric (readInt, readOct, readHex)
import Data.Maybe (listToMaybe, fromJust)

parseNumber :: Parser LispVal
parseNumber = parseNumberBase 'd'
          <|> do char '#'
                 base <- oneOf "bdoh"
                 parseNumberBase base

-- | Parses a number at a specific base
parseNumberBase :: Char -> Parser LispVal
parseNumberBase 'b' =
    do digits <- many1 (oneOf "01")
       return $ (Number . fromJust . readBinary) digits
parseNumberBase 'o' =
    do digits <- many1 octDigit
       return $ Number (fst (readOct digits !! 0))
parseNumberBase 'd' =
    do digits <- many1 digit
       return $ (Number . read) digits
parseNumberBase 'h' =
    do digits <- many1 hexDigit
       return $ Number (fst (readHex digits !! 0))
parseNumberBase _ =
    error "Wrong number base"

readBinary :: String -> Maybe Integer
readBinary =
    fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt


texts: Shell script to calculate the total space consumed by a user by file-size

texts:
I'm working with a small bash code which is working fine but i'm just looking if there is better way to formulate this, In this code i'm looking for the Files between year 2002 and 2018 on the 7th column.

Below is the working code,

Script:

#!/bin/bash
# scriptName: Ftpcal.sh
FILE="/home/pygo/Cyberark/ftplogs_3"
AWK="/bin/awk"
GREP="/bin/grep"
USERS="`"$AWK" '$7 >= "2002" && $7 <= "2018"' $FILE | "$AWK" '{print $3}' | sort -u`"
for user in $USERS;
do
echo "User $user " | tr -d "\n";
"$AWK" '$7 >= "2002" && $7 <= "2018"' "$FILE" | "$GREP" "$user" | "$AWK" '{ total += $4}; END { print "Total Space consumed: "  total/1024/1024/1024 "GB"}';
done | column -t
echo ""
echo "=============================================================="
"$AWK" '$7 >= "2002" && $7 <= "2018"' "$FILE" | "$AWK" '{ total += $4}; END { print "Total Space consumed by All Users: "  total/1024/1024/1024 "GB"}';
echo ""

Actual data Result:

$ sh Ftpcal.sh

User  16871                   Total  Space  consumed:  0.0905161GB
User  253758                  Total  Space  consumed:  0.0750855GB
User  34130                   Total  Space  consumed:  3.52537GB
User  36640                   Total  Space  consumed:  0.55393GB
User  8490                    Total  Space  consumed:  3.70858GB
User  tx-am                   Total  Space  consumed:  0.18992GB
User  tx-ffv                  Total  Space  consumed:  0.183137GB
User  tx-ttv                  Total  Space  consumed:  17.2371GB
User  tx-st                   Total  Space  consumed:  0.201205GB
User  tx-ti                   Total  Space  consumed:  58.9704GB
User  tx-tts                 Total  Space  consumed:  0.0762068GB

------------ snipped output --------------
==============================================================
Total Space consumed by All Users: 255.368GB

Sample data:

-rw-r--r-- 1 34130 14063436 Aug 15  2002 /current/focus-del/files/from_fix.v.gz
-rw-r--r-- 1 34130 14060876 Jul 12  2007 /current/focus-del/files/from1_fix.v.gz
-rw-r--r-- 1 34130 58668461 Feb 23  2006 /current/focus-del/files/from_1.tar.gz
-rw-r--r-- 1 34130 14069343 Aug  7  20017 /current/focus-del/files/from_tm_fix.v.gz
-rw-r--r-- 1 34130 38179000 Dec  7  20016 /current/focus-del/files/from_tm.gds.gz
-rw-r--r-- 1 34130 15157902 Nov 22  20015 /current/focus-del/files/from_for.tar.gz
-rw-r--r-- 1 34130 97986560 Nov  4  20015 /current/focus-del/files/from_layout.tar

Sample Result:

$ sh Ftp_cal.sh
User  34130  Total  Space  consumed:  0.0808321GB

==============================================================
Total Space consumed by All Users: 0.0808321GB

I'm okay with any better approach as a review process to make it more robust.

Thanks.


texts:
I'm writing my own HTTP client, kinda like cURL. (I already know I'm reinventing the wheel, this is more or less getting an inside look of HTTP 1.x before 2 becomes a thing.)

So far pages download perfectly fine using OS provided socket libs. (Linux/Mac)
So what the problem/question is, how can I better my client? One of the main problems with it, is that it's slow. Like 1.00 - 1.30 seconds slow. I know this may not sounds like much, but the 1 second is mainly because of the timeout of the recv. Or maybe I cant do much more except do what other HTTP clients do and cache data.

char   buf[CHUNK_SIZE+1];
    //now it is time to receive the page
    memset(buf, 0, sizeof(buf));
    std::string htmlcontent;

    struct timeval tv;

    tv.tv_sec = 1;
    setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO,(struct timeval *)&tv,sizeof(struct timeval));

    while(true){
        tmpres = recv(socket, buf, CHUNK_SIZE, 0);

        if(tmpres < 1)
        {
            break;
        }

        htmlcontent += buf;
        memset(buf, 0, tmpres);
    }

So as you can see, the recv timeout is 1 second. I'm hoping to maybe manipulate this in someway so, it's instead 500 milliseconds for timeout or perhaps look at another method in general when dealing with chunk data from a HTTP server. And of course I googled some topics, but a lot of them had pretty basic examples. Mostly what I have already written.


texts:
I have made a simple pagination algorithm. It shows "next" and "previous" buttons when appropriate.

It also limits the amount of buttons if the page amount exceeds a certain amount, e.g. 1 2 ... 15 16 17 18 19 ... 99 100.

It works fine, but I feel it can be simplified.

function appendTruncateButtons(buttons, pageCount) {
  buttons.push("...");
  buttons.push(pageCount - 1);
  buttons.push(pageCount);
}

function prependTruncateButtons(buttons) {
  buttons.push(1);
  buttons.push(2);
  buttons.push("...");
}

function generateButtons(currentPage, pageCount, surroundingPageLinkSize) {
  var buttons = [];

  if (currentPage > 1) {
    buttons.push("<");
  }

  var truncate = pageCount > (7 + (surroundingPageLinkSize * 2));
  if (!truncate) {
    for (var i = 1; i <= pageCount; i++) {
      buttons.push(i);
    }
  }
  else {
    var truncateEnd = currentPage < (1 + (surroundingPageLinkSize * 2)),
        truncateBoth = (pageCount - (surroundingPageLinkSize * 2)) > currentPage && currentPage > (surroundingPageLinkSize * 2);

    if (truncateEnd) {
      for (var j = 1; j < (4 + (surroundingPageLinkSize * 2)); j++) {
        buttons.push(j);
      }
      appendTruncateButtons(buttons, pageCount);
    }
    else if (truncateBoth) {
      prependTruncateButtons(buttons);
      for (var k = (currentPage - surroundingPageLinkSize); k <= (currentPage + surroundingPageLinkSize); k++) {
        buttons.push(k);
      }
      appendTruncateButtons(buttons, pageCount);
    }
    else { // Truncate start
      prependTruncateButtons(buttons);
      for (var l = pageCount - (2 + (surroundingPageLinkSize * 2)); l <= pageCount; l++) {
        buttons.push(l);
      }
    }
  }

  if (currentPage < pageCount) {
    buttons.push(">");
  }

  return buttons;
}
// generateButtons(currentPage, pageCount, surroundingPageLinkSize)
console.log(generateButtons(1, 100, 3));
console.log(generateButtons(50, 100, 3));
console.log(generateButtons(99, 100, 3));


texts:
SELECT * FROM
  (SELECT a.*, ROWNUM rnum from
     (SELECT a.CUST_FULL_NAME,a.TAX_NET,
        (SELECT NEXT_INT_PAYMENT_AMOUNT_NET FROM
           (SELECT a.*, ROWNUM rnum from
              (SELECT NEXT_INT_PAYMENT_AMOUNT_NET,NEXT_INT_PAYMENT_DATE FROM SINAYA.T_XLS_DEPOSIT WHERE DEAL_TYPE IN
                 (SELECT CODE FROM SINAYA.R_CAS_CODE WHERE (CODE_PARENT='01' OR CODE ='01')) AND CIF LIKE '1690XD' ORDER BY NEXT_INT_PAYMENT_DATE DESC) a ) WHERE rnum=1) AS GIRO,

FROM SINAYA.T_XLS_DEPOSIT a JOIN SINAYA.R_BRANCH b ON a.BRANCH=b.BRANCH_CODE JOIN SINAYA.R_CAS_CODE c ON c.CODE=a.DEAL_TYPE WHERE CIF LIKE '1690XD' ORDER BY NEXT_INT_PAYMENT_DATE DESC) a) WHERE rnum=1

Here it is, i've fixed the query above :

SELECT
RATE_GIRO,GIRO,TAX_NET_GIRO,RATE_TABUNGAN,TABUNGAN,TAX_NET_TABUNGAN,RATE_DEPOSITO,DEPOSITO,TAX_NET_DEPOSITO
FROM
(SELECT a.*, ROWNUM rnum from (SELECT (TAX_RATE) AS RATE_GIRO,(NEXT_INT_PAYMENT_AMOUNT_NET) AS GIRO,(TAX_NET) AS TAX_NET_GIRO FROM SINAYA.T_XLS_DEPOSIT WHERE DEAL_TYPE IN (SELECT CODE FROM SINAYA.R_CAS_CODE WHERE (CODE_PARENT='01' OR CODE ='01')) AND CIF LIKE '1966P2' ORDER BY NEXT_INT_PAYMENT_DATE DESC)a) GIRO FULL JOIN
(SELECT b.*, ROWNUM rnum from (SELECT (TAX_RATE) AS RATE_TABUNGAN,(NEXT_INT_PAYMENT_AMOUNT_NET) AS TABUNGAN,(TAX_NET) AS TAX_NET_TABUNGAN FROM SINAYA.T_XLS_DEPOSIT WHERE DEAL_TYPE IN (SELECT CODE FROM SINAYA.R_CAS_CODE WHERE (CODE_PARENT='02' OR CODE ='02')) AND CIF LIKE '1966P2' ORDER BY NEXT_INT_PAYMENT_DATE DESC)b) TAB ON GIRO.rnum=TAB.rnum FULL JOIN
(SELECT c.*, ROWNUM rnum from (SELECT (TAX_RATE) AS RATE_DEPOSITO,(NEXT_INT_PAYMENT_AMOUNT_NET) AS DEPOSITO,(TAX_NET) AS TAX_NET_DEPOSITO FROM SINAYA.T_XLS_DEPOSIT WHERE DEAL_TYPE IN (SELECT CODE FROM SINAYA.R_CAS_CODE WHERE (CODE_PARENT='03' OR CODE ='03')) AND CIF LIKE '1966P2' ORDER BY NEXT_INT_PAYMENT_DATE DESC)c) DEPO ON DEPO.rnum = TAB.rnum
WHERE GIRO.rnum=1 OR TAB.rnum=1 OR DEPO.rnum=1

the new one three times better but still takes time around 45sec for the query to finish
(before takes 3 minutes because the size of data is very large)


texts: Parallelization of number factors using OpenMP

texts:
For a simple try at parallelization on my own outside of school, I've created a number factors calculator.  I hope to eventually come up with something more creative.

Since I don't have access to parallel computers at this time, I'm using OpenMP provided by my compiler (gcc 4.8.1) and running it on my laptop (Intel Core i3-2330M).  I'm using a maximum of four threads, which was determined from a call to omp_get_max_threads().

I've conducted four runs, each with four billion values and from one to four threads:

#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <omp.h>

void displayCompTime(std::clock_t start, std::clock_t end, std::int64_t integer, int threads)
{
    double elapsed = static_cast<double>(end - start) / CLOCKS_PER_SEC;

    std::cout << integer << " values and " << threads << " thread(s): "
              << std::setprecision(4) << std::fixed << elapsed << "s\n";
}

void calcFactors(std::int64_t integer, int threads)
{
    std::map<std::int64_t, std::int64_t> factors;
    std::int64_t i;

    #pragma omp parallel for num_threads(threads) default(none) \
        shared(factors, integer), private(i)
    for (i = 2; i <= integer; i++)
    {
        if (integer % i == 0)
        {
            factors[i] = integer / i;
        }
    }
}

int main()
{
    const std::int64_t integer = 4000000000;
    const int runs = 4;

    for (int i = 0; i < runs; i++)
    {
        std::clock_t start = std::clock();
        int threads = i + 1;
        calcFactors(integer, threads);
        std::clock_t end = std::clock();
        displayCompTime(start, end, integer, threads);
    }
}

Output:

4000000000 values and 1 thread(s): 67.7330s
4000000000 values and 2 thread(s): 40.7640s
4000000000 values and 3 thread(s): 32.5630s
4000000000 values and 4 thread(s): 29.7640s

Based on these results, this code doesn't appear to scale very well.  I don't know if using a non-default static schedule would give faster times, and anything else would just incur additional overhead.  Fortunately, I didn't need to include atomic or critical.

Would avoiding a lot of division help?  I didn't try for anything else yet as this is only a start.  I also wanted to see how well my laptop could handle parallelization.

Other than performance, I'm okay with any general OpenMP advice.  I was sure to use some good practices for that, such as default(none) for explicitly listing the variables.


texts: How can I make this C++ code to obtain passwords more efficient?

texts:
The comments in the code kind of explain it. Backspace characters only move cursor back and don't erase output so I need to overwrite them with ' ' to delete them.
#include <iostream>
#include <string>
using namespace std;

const string PASSWORD = "PASSWORD";
int main(int argc, char** argv) {
string userkey = "";
char c;
int keystrokes = 0;

cout<<"Enter passkey: ";
while(true){
    if(_kbhit()){
        c=_getche();
        if(c=='\r'){//check if user hit enter, _getche() records enter as \r
            cout<<'\n';
            break;
        }
        else if(c =='\b'){//check if user typed backslash, overwrite character there
            cout<<' ';
            if(keystrokes==1){ //makes sure userkey is cleared
                userkey = "";
                keystrokes--;
                cout<<'\b';
            }
            else if(keystrokes!=0){
                userkey = userkey.substr(0,userkey.length()-1);//cuts out last char of userkey
                keystrokes--;
                cout<<'\b';
            }
        }
        else if (c!='\b'){
            cout<<"\b*";//replaces enter char with'*'
            keystrokes++;
            userkey+=c;
        }
    }
}
//cout<<userkey;
if (userkey!=PASSWORD)
    return 0;


texts: Merge array of hashes, keeping duplicate values as arrays

texts:
I am working on a Ruby gem to pull data from the Wikidata API.  The data is deeply nested, as it contains a lot of repetition.

I have written a piece of Ruby (sans Rails) code that enables an array of hashes to be merged together, with any duplicate key-value pairs being stored as an array under the same key.

For example:

[{:a=>1, :b=>2}, {:b=>3, :c=>4}, {:d=>5, :a=>6}].merge_hashes

gives:

{:a=>[1, 6], :b=>[2, 3], :c=>4, :d=>5}

I began with the following:

class Array
  def merge_hashes
    raise StandardError.new "Array is not an Array of Hashes" unless self.all? {|e| e.is_a? Hash}
    self.each_with_object({}) do |el, h|
      el.each do |k, v|
        if h[k].nil?
          h[k] = v
        else
          h[k] = Array.new([h[k]]) << v
          h[k] = h[k].flatten
        end
      end
    end
  end
end

And refactored to:

class Array
def merge_hashes
    raise StandardError.new "Array is not an Array of Hashes" unless self.all? {|e| e.is_a? Hash}
    self.each_with_object({}) { |el, h| el.each { |k, v| h[k].nil? ? h[k] = v : h[k] = (Array.new([h[k]]) << v).flatten } }
  end
end

Are there any other improvements I could make?  Is that an acceptable exception to throw?


texts:
I have written the following code to export to data to a spreadsheet with this result:

Please let me know how to improve it.

import numpy as np
import xlwt #THIS MAY BE GOOD
#from pandas import DataFrame

amin =2
amax=10
da = 2
names = ['amin', 'amax', 'da']
values = [amin, amax, da]

fname='EXPORTexample.xls'; sheetname = 'sheet 1'

book = xlwt.Workbook()
sh = book.add_sheet(sheetname)

col=0;
# FIRST WRITE THE VARIABLES AND THEIR VALUES INTO XLSX.
for row, (name, value) in enumerate(zip(names, values)):
    sh.write(row, col, name);
    sh.write(row, col+1, value);

t2 = np.arange(0.0, 5.0, 1)
amat= np.arange(amin,amax,da)

fn=np.zeros((np.shape(t2)[0],1))

col=3;
#row_eps =0;
#row_Dt += row_eps;

for a in amat:
    fn = a*t2

    names = ['eps_dot', 'Delta_t']
    values=[a*1., a*1.]
    #write specific a conditions on every data curve/set
    for row, (name, value) in enumerate(zip(names, values)):
        sh.write(row, col, name);
        sh.write(row, col+1, value);

    #write names such as strain, stress, d11s, d_dot, d11
    occ_rows = len(names)#no.of occupied rows.
    names = ['strain', 'stress', 'd11s', 'd_dot', 'd11']
    for cols,name in enumerate(names):
        sh.write(occ_rows+1, col+cols, name)

    ## WRITE actual numbers
    for rows, (strain_i,stress_i, d11s_i, d_dot_i, d11_i) in enumerate(zip(fn, t2, fn, t2, fn)):

        sh.write(occ_rows+1+rows+1, col, strain_i)
        sh.write(occ_rows+1+rows+1, col+1, stress_i)
        sh.write(occ_rows+1+rows+1, col+2, d11s_i)
        sh.write(occ_rows+1+rows+1, col+3, d_dot_i)
        sh.write(occ_rows+1+rows+1, col+4, d11_i)

    col+=6 #incremening column value to avoid overwriting and related error

book.save(fname)


texts:
What's the fastest way of doing this?

int hextoint(char number) {
    if (number == '0') {
        return 0;
    }
    if (number == '1') {
        return 1;
    }
    if (number == '2') {
        return 2;
    }
    /*
     *  3 through 8
     */
    if (number == '9') {
        return 9;
    }
    if (number == 'a') {
        return 10;
    }
    if (number == 'b') {
        return 11;
    }
    if (number == 'c') {
        return 12;
    }
    if (number == 'd') {
        return 13;
    }
    if (number == 'e') {
        return 14;
    }
    if (number == 'f') {
        return 15;
    }
    return -1;
}


texts: Sum of all numbers whose remainder and quotient are the same

texts:
This prints out the sum of the numbers that have same remainder and quotient according to the input number. It's an online judge problem, and it currently throws a time-out since it's taking too long. Yes, the number being divided could be any positive integer.

Are there any suggestions on speeding up this code? And are there any small tips or good practice habits that makes Python code faster and more memory efficient?

import sys
n = input()
result = 0
for num in xrange(1, sys.maxint):
    if num % n == num / n:
        result += num

    if num / n > n:
        break
print result


texts: Reading CSV files pertaining to financial recorts

texts:
I have a number of text files (they are reports from a financial system) stored in a directory. Each report has a particular piece of text to search for (eg Report Total) and then a range of characters to extract for the value (e.g. position 78 for 10 characters).
There are a number of these reports - but no more than 200 so not a huge amount of processing or work required.

The premise of my solution is to maintain a simple CSV file with the report name, text to search for, start value for extract, length of characters to extract. Then, it is a simple case of updating this text file to add or remove the reports as necessary.

The script I have developed is below, and it works, but I would be interested in some critique as to how it may be made "better".

What needs changing/improving and why?

#!/usr/bin/perl -w
use strict;
use strict;
use Data::Dumper;
use Cwd;
use Text::CSV;

my $SrcDir="/data03/adudata/live/work/";
my $RepDir="/data03/adudata/live/archive/";
my $ReportList='pl_rec.list';
my $csv = Text::CSV->new();
my @FileToRead;
my @TextToFind;
my @RowsOffset;
my @DataStart;
my @DataEnd;
my %ReportData;

chdir $SrcDir;
open my $fh, '<', $ReportList or die "Could not open file";
while (my $row = $csv->getline( $fh )) {
  push (@FileToRead, $row->[0]);
  push (@TextToFind, $row->[1]);
  push (@RowsOffset, $row->[2]);
  push (@DataStart, $row->[3]);
  push (@DataEnd, $row->[4]);
}

close ($fh);

for my $i(0 .. $#FileToRead) {
  open $fh, "<", $RepDir.$FileToRead[$i]. ".prn" or
    die "Could not open $FileToRead[$i]";

  while (<$fh>) {

    if (grep /$TextToFind[$i]/, $_) {
      my $extractValue = substr($_,$DataStart[$i],$DataEnd[$i]);
      $extractValue =~s/(^\s+)|(s+$)//g;
      $extractValue =~ s/,//g;
      $ReportData{$TextToFind[$i]} = $extractValue+0;
    }
  }
close $fh;
}

while(my($code,$value)=each(%ReportData)){
  print "$code,$value\n";
}


texts:
I'm comparing two variables which I'd like to be printed to the console like so:

==Full Ex Vat==
true

Currently the code to do this is:

print '==Full Ex Vat=='
print case when
@aTotalExVat = @sTotalExVat
then 'true' else 'false' end

which I feel isn't as elegant as it could be.

Any tips?


texts: Retrieving data from files in the folder

texts:
I am to use VBA code to simply retrieve certain data from all Excel files in certain folder and paste it in working spreadsheet. I am not sure that this is the most efficient (which matters as I would like to learn how to write the most possible efficient codes).

I am using simple copy/paste actions but maybe there are more sophisticated methods (which could help me in the future if for example I would need to get data with certain words in contiguous column in the worksheets, or to order it by date of file creation), or maybe there is better way how to get to the files, or maybe a better to do this and how using forms and tables.

Option Explicit
Sub copydata()
Dim script As Object
Dim catalogue As Object
Dim textfile As Object
Dim loadedfile As Workbook
Dim actualfile As Workbook
Dim path As String
Dim column_index As Integer
path = InputBox("Please input path")
Application.ScreenUpdating = False
Set actualfile = ActiveWorkbook
Set script = CreateObject("Scripting.FileSystemObject")
Set catalogue = script.GetFolder(path)
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
   For Each textfile In catalogue.Files

      Workbooks.Open textfile
      Set loadedfile = ActiveWorkbook
      loadedfile.Worksheets(1).Range("D1:D15").Copy
      column_index = actualfile.Worksheets(1).Range("A5").CurrentRegion.Columns.Count
      actualfile.Worksheets(1).Range("A5").Offset(0, column_index).PasteSpecial
      loadedfile.Close Savechanges:=False

    Next textfile

Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True

End Sub


texts:
I would like to share my design of mvc via js.

What do you think about it? I tried to not use any mvc framework but i want to get clear structure and a decoupled organisation.

Next step for me is evaluating something like require.js to get rid of the ordering within the index file

The code:

XX.namespace.ContactListController = (function() {

var _initListener = function() {
    $(document).ready(function() {
        $("#addContact").click(function() {
            var contactName = $("#contactName").attr('value');
            var contact = new  XX.namespace.ContactModel(contactName);
            $.publish("add#contact", contact);
        });

        $("#removeContact").click(function() {
            var contactName = $("#contactName").attr('value');
            var contact = new  XX.namespace.ContactModel(contactName);
            $.publish("remove#contact", contact);
        });
    });
};

var interface = {
    init: function() {
        _initListener();
    }
};
return interface;

})(XX.namespace.ContactListModel, XX.namespace.ContactListView);

XX.namespace.ContactListModel = (function() {

var contactList = [];

/**
* @private
*/
var _addContact = function(channel, contact) {
    contactList.push(contact);
};

var _removeContact = function(channel, contact) {
    var index = contactList.indexOf(contact);
    contactList.splice(index, 1);
};

/**
* API
*/
$(document).ready(function() {
    $.subscribe("add#contact", _addContact);
    $.subscribe("remove#contact", _removeContact);
})
 })();

XX.namespace.ContactModel = function x(name) {
this.name = name;
};

   XX.namespace.ContactListView = (function(){

var uiComponents = {
    contactList:  "#contactList"
};

var _addContact = function(channel, contact) {
    $(uiComponents.contactList).append("
" + contact.name +"
");
};

var _removeContact = function(channel, contact) {
    $(uiComponents.contactList+" li[contact_name='" + contact.name+ "']").remove();
};

/**
* API
*/
$(document).ready(function() {
    $.subscribe("add#contact", _addContact);
    $.subscribe("remove#contact", _removeContact);
})
})();

     (function() {
      XX.namespace.ContactListController.init();
 })();

<!DOCTYPE html>

     <meta charset="utf-8">

ContactList1

Chat

            <input type="text" id="contactName"/>
            <input type="button" id="addContact" value="hinzufügen">
            <input type="button" id="removeContact" value="entfernen">

        Message: <input id="msg"  type="text" />
        <textarea id="msgContainer"></textarea>


texts: Using toString() as a hack to generate keys for react-select component

texts:
While trying to integrate react-select component on my codebase on documentation it's explained that you can pass an array of options with label and value attributes eg :

import Select from 'react-select';

let options = [
 {
  label: 'Color',
  value: 'Blue'
 }
]

<Select options={options} />

And it works fine, but in my case I need value to be an object as simply a String won't do the job how I want. I know I can keep an array of objects separately and do a find based on their ID on that array but this lacks on performance and increases chances for side effects.

So what I tried was using options with value as objects :

let options = [
  {
    label: 'Color',
    value: {
      r: 123,
      g: 78,
      b: 198
    }
  }
]

But this way I had errors on my console, telling me that you have to use unique keys for each child and this was because the component takes an option value and uses that for key and that key when converted to string became "[object Object]" so finally the key was always option-[object Object] .

To solve this out I overrode the value attribute toString() method and it worked :

let options = [
  {
    label: 'Color',
    value: {
      r: 123,
      g: 78,
      b: 198,
      toString: function(){
        return this.r + this.g + this.b;
      }
    }
  }
]

So what could be downsides of this, as obviously this is a hack.