texts: JavaScript code to add buttons and slowly remove them

texts:
My javascript code is working, however i am seeking suggestions on how I can go about improving my existing code for reusability and testability. The code is pretty straight forward, I have three buttons "add", "slow remove" and "clear". The add button adds 40 buttons to the DOM dynamically with id + index. The slow remove button, uses setTimeout and CSS transition opacity to slowly fade out the 40 buttons, and the clear button clears the 40 buttons immediately.

Buttons JS:

  (function () {

    /* button_add when clicked dynamically generates 40 buttons with indexes
       when clicked an alert is display with button's id */
    const CLS = ["thin", "button"];
    const BUTTON_NUM = 40;
    let buttons = [];
    let add_btns = document.querySelector('.button_add');
     add_btns.addEventListener("click", function () {
         let i = 0;
        while (i <= BUTTON_NUM) {
            let btn = document.createElement("BUTTON");
            buttons.push(container.appendChild(btn));
            i++;
            for (let button in buttons) {
                btn.setAttribute('id', "button " + button);
                btn.classList.add(...CLS);
                btn.innerHTML = "Button # " + button;
            }
            btn.addEventListener("click", function () {
                let id = this.id;
                alert("my id is: " + id);
            });
        }
     });

    /* button_slow_remove when clicked 40 buttons fade out slowly and buttons array is
       emptied */
    let slow_remove_btns = document.querySelector('.button_slow_remove');
    slow_remove_btns.addEventListener("click", function () {
            buttons.forEach(function (el) {
                el.classList.add('slow-fade');
            });
            buttons.length = 0;
    });

    /* button_clear when clicked 40 buttons are cleared immediately and buttons array is
           emptied */
    let clear_btns = document.querySelector('.button_clear');
    clear_btns.addEventListener("click", function () {
        buttons.forEach(function (el) {
            el.classList.add('clear');
        });
        buttons.length = 0;
    });
}) ();

Buttons.css:

html section button, body section button {
    align-self: center;
    background: transparent;
    padding: 1rem 1rem;
    margin: 0 1rem;
    transition: all .5s ease;
    color: #41403E;
    font-size: 2rem;
    letter-spacing: 1px;
    outline: none;
    box-shadow: 20px 38px 34px -26px rgba(0, 0, 0, 0.2);
    border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;
}

div#container button {
    display: inline-flex;
    align-self: center;
    background: transparent;
    padding: 1rem 1rem;
    margin:  .2rem 1rem;
    transition: all .5s ease;
    color: #41403E;
    font-size: .3rem;
    letter-spacing: 1px;
    outline: none;
    box-shadow: 20px 38px 34px -26px rgba(0, 0, 0, 0.2);
    border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;
}

html section button:hover, div#container button:hover, body section button:hover {
    box-shadow: 2px 8px 4px -6px rgba(0, 0, 0, 0.3);
}

section button.dotted, body section button.dotted.thick {
    border: dotted 5px #41403E;
}

div#container button.thin, body section button.lined.thin {
    border: solid 2px #41403E;
}

.button--main, button.button{
    cursor: pointer;
}

.clear {
    display: none!important;
}

.slow-fade {
    opacity: 0;
    -webkit-transition: opacity 7s linear;
    -moz-transition: opacity 7s linear;
    transition: opacity 7s linear;
}

@media (max-width: 620px) {
    body h1 {
        margin-top: 2rem;
    }
    body section, div#container {
        display: flex;
        flex-direction: column;
        justify-content: center;
        margin-bottom: 1rem;
    }
    body section button {
        align-self: center;
        margin-bottom: 2rem;
    }
}


texts: Simple JavaScript (sub) class [properties, getters, methods]

texts:
The more I consider object oriented JavaScript the more I am confused. There are so many different ways and concepts and I simply do not know any longer what fits best for my purposes.

I like the constructor pattern but I have the feeling that I've mixed different concepts:

Subclass.prototype = Object.create(Superclass.prototype);

function Subclass(name, value) {
    Superclass.call(this);

    this._name = name;
    this._value = value;

    this._init();
}

Object.defineProperties(Subclass.prototype, {
    'name': {
        get: function() { return this._name; }
    },
    'value': {
        get: function() { return this._value; },
        set: function(value) { this._value = value; }
    }
})

Subclass.prototype._init = function() {
    // some initialization
};

Subclass.prototype.compute = function() {
    var name = this.getName();
    var value = this.getName();
    // do something with name and value...
};

Is there a cleaner way?
Should one use getters and setters for "internal" access (like I would do it in other languages)?

Edit #1

Define properties of prototype (Object.defineProperties(Subclass, {} to Object.defineProperties(Subclass.prototype, {})


texts: Python right position for a Error message in a class

texts:
first of all sorry for this easy question. I have a class

class Grid(object):
    __slots__= ("xMin","yMax","nx","ny","xDist","yDist","ncell","IDtiles")
    def __init__(self,xMin,yMax,nx,ny,xDist,yDist):
        self.xMin = xMin
        self.yMax = yMax
        self.nx = nx
        self.ny = ny
        self.xDist = xDist
        self.yDist= yDist
        self.ncell = nx*ny
        self.IDtiles = [j for j in np.ndindex(ny, nx)]
        if not isinstance(nx, int) or not isinstance(ny, int):
            raise TypeError("an integer is required for nx and ny")

where

xMin = minimum x coordinate (left border)
yMax = maximum y coordinate (top border)
nx = number of columns
ny = number of rows
xDist and yDist = resolution (e.g., 1 by 1)

nx and ny need to be an integer. I wish to ask where is the most elegant position for  the TypeError. Before all self. or in the end?


texts: Find max element in increasing-decreasing array

texts:
Question:  Find the largest in a list that list is stored as two sections, one in ascending order and the other in descending order.  Elements are distinct.

E.g:  Input [2 3 4 5 6 7 10 9 8 7]

Output: 10

My solution is below.  Works on my unit-tests.  Want to know if there any improvements from the coding point of view (esp if it is asked in an interview).

long getMaxIndex(long *arr, size_t size)
{
    long left = 0;
    long right = size - 1;

    if (arr == nil) return 0;

    while (left < right)
    {
        long mid = left + ((right-left)/2);

        if(mid == size -1)
            return mid;

        if (arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1])
        {
            return mid;
        }

        if (arr[mid] > arr[mid-1])
        {
            left = mid;
        }
        else
        {
            right = mid-1;
        }

        if (arr[mid] > arr[mid+1])
        {
            right = mid;
        }
        else
        {
            left = mid+1;
        }
    }

    return left;
}


texts:
I'm looking to get some feedback on this program I wrote - ways I could make it simpler or best practices methods.
Chapter 7:

Let's write a program which asks us to type in as many words as we
want (one word per line, continuing until we just press Enter on an
empty line), and which then repeats the words back to us in
alphabetical order. OK?
...
Assignment: Write the program we talked about at the very beginning of
this chapter. Hint: There's a lovely array method which will give you
a sorted version of an array: sort. Use it!

Here's the program I wrote:
puts "This program will take your words and sort them alphabetically"
puts ""
puts "Type in a word and press enter. When you are done, press enter on an empty line to launch program."

inputArray = []
while (inputWord = gets.chomp) != ""
    inputArray.push inputWord
    puts "Current List is: " + inputArray.join(', ')
end
print "Your list in alphabetical order is: " + inputArray.sort.join(', ') + "."


texts:
I have the following PHP function, which is admittedly not quite as robust as it could be (I'm missing some sanity checks including a proper one for $sendTo for example; odd choices in text formatting, too) but I don't see why it shouldn't work. A version of it certainly worked the other day, though I made a few small changes (allegedly for the better!) today. When the function executes, my condition if (mail(etc)) indeed appends a success string to my content.

<?php
$FROM_EMAIL = "foo@bar.com";
$email = "foo@bar.com";
$content = "";
$emailMessage = "";
$sendTo = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  foreach ($_POST as $key => $value) {
    $value = (string) $value;
    if ($key === "DESCRIPTION_OF_ITEMS")
      $value = str_replace("\r", '
', $value);
    if ($value !== "" && $key !== "hiddenField" && $key !== "button2" && $key !== "cloneAdmin")
      $emailMessage .= "$key - $value
\n";
    if ($key === "EMAIL")
      $sendTo = $value;
  }

  if ($emailMessage !== "") {
    $content .= "
Thank you for submitting your registration form... we'll get back to you shortly.

You can expect to receive an email with the following registration information:
";
    $content .= $emailMessage;
    if (mail("foobar@bazbat.com,$sendTo", "Foobar Registration Form", $emailMessage, "MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\nFrom: $FROM_EMAIL\r\nReply-to: $email")) {
      $content .= "
Email successfully sent!
";
    } else {
      $content .= "
We encountered an error and the email was not successfully sent.
";
    }
  } else {
    $content .= "No Email message";
  }
  $content .= "
";
} else {
  $content .= "

A blank or invalid form was sent; your submission has not been successful.
";
}
?>

For the record, I tried the mail() function in its most basic form as well:

mail('foo@bar.com', 'My Subject', $emailMessage);

and it didn't make a difference. The successful trial earlier this week used the additional header parts.

Unfortunately I don't have access to the PHP logs; I only have FTP access. Also as you may have been able to guess from the coding style, I'm generally more of a JavaScript guy, so I'm not sure what my options are for capturing errors without the PHP log.

Is it possible that there's just a problem (or security measures?) with the mail server? That the PHP code is fine and the problem is elsewhere? Maybe my own mail server is flagging spam and not even passing it into my junk box?


texts:
I am trying to visualize a pointcloud centered around the origin. I also want to have a user controlled rotation for which I found the arcball.

rMat is the model matrix, passed into the shader.

inline QVector3D getArcballVector(const QPoint& pt, int width, int height)
{
    QVector3D P = QVector3D(1.0*pt.x ()/width * 2 - 1.0,
                            1.0*pt.y ()/height * 2 - 1.0,
                            0);
    P.setY (-P.y ());

    float OP_squared = P.lengthSquared ();
    if (OP_squared <= 1)
        P.setZ (std::sqrt(1 - OP_squared));  // Pythagore
    else
        P.normalize ();  // nearest point
    return P;
}

void PointCloud::mouseMoveEvent(QMouseEvent * e)
{
    if(e->buttons ()==Qt::LeftButton)
    {
        if(!rotPos.isNull () && rotPos!=e->pos ())
        {
            //rotate using an arcBall for freeform rotation
            QVector3D vec1 = getArcballVector (rotPos, width (), height ());
            QVector3D vec2 = getArcballVector (e->pos (), width (), height ());

            //use bisector to get half-angle cos and sin from dot and cross product
            // for quaternion initialisation
            QVector3D vec3 = vec1+vec2;
            vec3.normalize ();
            QVector3D rotaxis = QVector3D::crossProduct (vec1, vec3);
            double cos = QVector3D::dotProduct (vec1, vec3);

            QQuaternion quat (cos,rotaxis);
            quat.normalize ();
            //we want to left-multiply rMat with quat but that isn't available
            //so we'll have to do it the long way around
            QMatrix4x4 rot;
            rot.rotate (quat);
            rMat=rot*rMat;

            updateGL ();
        }
        rotPos=e->pos ();
    }
}

void PointCloud::mousePressEvent(QMouseEvent *e)
{
    if(e->buttons ()==Qt::LeftButton)
    {
        rotPos=e->pos ();
    }
}

One point to make is that most arcball examples use acos to get the rotation angle for the axis-angle representation and use that to create the matrix and only mention using quaternions in passing (and if they do use quaternions they still end up using axis-angle). I found that I can derive the quaternion values directly using the dot and cross products of the first vector with the bisector of the 2 vectors (vec3).

Are there any glaring inefficiencies? I could move the update code to a QTimer activated slot but the usage of the program has the user mostly ignoring the screen while concentrating on the road.


texts: What are the draw backs, if any, in using C and C++ together? Is doing so considered correct by the large?

texts:
I have written code exclusively in both C and C++. I see clear advantages in both and therefore have recently began using them together. I have also read, what I would consider,          outrageous comments claiming that to code in C is outright dumb, and it is the language of past generations. So, in terms of maintenance, acceptance, common practice and efficiency; is it something professionals on large scale projects see/do?

Here's an example snippet:
I obviously need to #include both <stdio.h> and <iostream>.

#define STRADD ", "
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include "Struct.h"
#include "Rates.h"
#include "Taxes.h"
using namespace std;

And later I utilize functions like...

void printHeading(FILE * fp)
{
    fprintf(fp, "Employee            Pay        Reg Hrs     Gross       Fed        SSI        Net\n");
    fprintf(fp, "Name                Rate       Ovt Hrs     Pay         State      Defr       Pay\n");
    fprintf(fp, "==================================================================================\n");
    return;
}

and..

void getEmpData(EmpRecord &e)
{
    cout << "\n Enter the employee's first name: ";
    getline(cin, e.firstname);
    cout << " Enter the employee's last name: ";
    getline(cin, e.lastname);
    e.fullname = e.lastname + STRADD + e.firstname; //Fullname string creation
    cout << " Enter the employee's hours worked: ";
    cin >> e.hours;
    while(e.hours < 0)
    {
        cout << "  You did enter a valid amount of hours!\n";
        cout << "  Please try again: ";
        cin >> e.hours;
    }
        cout << " Enter the employee's payrate: ";
        cin >> e.rate;

    while(e.rate < MINWAGE)
    {
        cout << "  You did enter a valid hourly rate!\n";
        cout << "  Please try again: ";
        cin >> e.rate;
    }
    cout << " Enter any amount to be tax deferred: ";
    cin >> e.deferred;
    while(e.deferred < 0)
    {
        cout << "  You did enter a valid deferred amount!\n";
        cout << "  Please try again: ";
        cin >> e.deferred;

    }
    cin.ignore(100, '\n');
    return;
}

Thanks in advance!


texts: Persist values for a known set of keys in Python

texts:
Use case: I sometimes write programs that want to store a little state between runs, e.g., "What was the last file selected last time this program ran?" I wanted a convenient way to track this state. Python's built-in shelve module is pretty good but I wanted a way to restrict the possible set of keys in the shelf so that I wouldn't (due to a bag) store something under some unexpected key that would never be read. While I was at it I made it so the you access values using foo.a instead of foo['a'], though I paid a price for this.

Questions I have about this code are:

Is there an easier way I could have accomplished this using built-in stuff or widely used libraries?
Did I choose the right design?

I could have tried to inherit from one of the existing shelf classes, though the shelve module decides at runtime what sort of shelf you should get back from shelve.open.
I could have tried to use descriptors to create my own pseudo-properties, sort of like what's done here, but I don't see a need to decide which fields to include at the class, rather than instance, level

Is there any less gross for me to use __getattr__ and __setattr__ (without having to store a list of fields to be handled as special)?
Did I handle the nested context managers (shelf within RestrictedShelf) correctly? Do I need a bunch of try/except logic in __exit__, as in the fourth example in this answer?
Should I be defining my own exception classes, identical with Exception beyond the class name, as I did?
Is making _check_special_keys a class method, rather than a static method, the correct approach?

import shelve
import os
import sys

class UnexpectedKeyError(Exception):
    pass
class BadSpecialKey(Exception):
    pass

class RestrictedShelf(object):
    _SPECIAL_KEYS = ["_filepath", "_keys", "_shelf"]

    @classmethod
    def _check_special_keys(cls):
        for key in cls._SPECIAL_KEYS:
            if not key.startswith("_"):
                raise BadSpecialKey("Special key does not start with underscore: '{}'".format(key))

    def __init__(self, filepath, keys):
        self._filepath = filepath
        self._keys = list(keys) # Make a copy in case someone modifies the original list

        for key in keys:
            if not isinstance(key, str):
                raise TypeError("String object expected for key, {} found".format(key.__class__.__name__))
            # The keys in _SPECIAL_KEYS can't be used, but let's just rule out all keys that start with underscore for good measure
            if key.startswith("_"):
                raise ValueError("Key illegally starts with underscore: '{}'".format(key))

    def __enter__(self):
        self._shelf = shelve.open(self._filepath)
        for key in self._shelf.keys():
            if key not in self._keys:
                # This is not quite the same thing as a regular KeyError
                raise UnexpectedKeyError(key, "Shelf at '{}' contains unexpected key '{}'".format(self._filepath, key))
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if sys.version_info[0] <= 2:
            self._shelf.close()
        else:
            self._shelf.__exit__(exc_type, exc_val, exc_tb)

    def __getattr__(self, key):
        self.check_key(key)
        return self._shelf.get(key)

    def __setattr__(self, key, value):
        if key in self._SPECIAL_KEYS:
            # https://stackoverflow.com/a/7042247/2829764
            super(RestrictedShelf, self).__setattr__(key, value)
        else:
            self.check_key(key)
            self._shelf[key] = value

    def check_key(self, key):
        if key not in self._keys:
            raise KeyError(key)

RestrictedShelf._check_special_keys()

if __name__ == "__main__":
    with RestrictedShelf(os.path.expanduser("~/tmp/test.shelf"), "a b c".split()) as rs:
        print(rs.a) # `None` the first time you run this; `10` thereafter
        rs.a = 10
        print(rs.a) # 10
        print(rs.b) # None


texts: Simplifying the array of objects with comma separated values

texts:
Looking a way to reduce the below code to get comma separated values from the list of arrays
By using ECMA or plain old vanilla JS. How should we achieve this?
Actual Array Data:
[{
    ansBook: "046H",
    ansPersonId: "2044000102",
    bookNbr: "046H",
    dns: "0",
    examCode: "20717010",
    examShortTitle: "QA-ATAG-Director of Applications",
    nar: "0",
    personId: "2044000102",
    pull: "0",
    wn: "0",
    corrCd: 1
  },
  {
    ansBook: "046I",
    ansPersonId: "2044000102",
    bookNbr: "046I",
    dns: "0",
    examCode: "20721010",
    examShortTitle: "QA-ATAG-Plans Examinier",
    nar: "0",
    personId: "2044000102",
    pull: "0",
    wn: "0",
    corrCd: 1
  }
];

Expected Result:
{
  "PersonIds": "2044000102, 2044000102",
  "BookLetCodes": "046H, 046I",
  "ExamNumbers": "20717010, 20721010",
  "ExamTitles": "QA-ATAG-Director of Applications, QA-ATAG-Plans Examinier"
}

As I am getting the expected result. But I need to reduce and improvise the performance performed on it..

let seriesDataSet = [{
    ansBook: "046H",
    ansPersonId: "2044000102",
    bookNbr: "046H",
    dns: "0",
    examCode: "20717010",
    examShortTitle: "QA-ATAG-Director of Applications",
    nar: "0",
    personId: "2044000102",
    pull: "0",
    wn: "0",
    corrCd: 1
  },
  {
    ansBook: "046I",
    ansPersonId: "2044000102",
    bookNbr: "046I",
    dns: "0",
    examCode: "20721010",
    examShortTitle: "QA-ATAG-Plans Examinier",
    nar: "0",
    personId: "2044000102",
    pull: "0",
    wn: "0",
    corrCd: 1
  }
];

let auditingInfo = {};
auditingInfo = (seriesDataSet).filter(w => (w.dns == '0' && w.pull == '0') && w.corrCd == 1)
  .map(e => ({
    PersonIds: e.personId,
    BookLetCodes: e.ansBook,
    ExamNumbers: e.examCode,
    ExamTitles: e.examShortTitle
  }))
console.log(auditingInfo)

let auditingDetails = {
  PersonIds: auditingInfo.map(x => x.PersonIds).join(', '),
  BookLetCodes: auditingInfo.map(x => x.BookLetCodes).join(', '),
  ExamNumbers: auditingInfo.map(x => x.ExamNumbers).join(', '),
  ExamTitles: auditingInfo.map(x => x.ExamTitles).join(', ')
}
console.log('______________________________________________')
console.log('Expected Result:')
console.log(auditingDetails)
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

OR
let ScoringApprove: Array<number> = [];
ScoringApprove = new List<SeriesReportsDataset>(this.tempSeriesDataSet)
                .Where(w => (w.dns == '0' && w.pull == '0') && w.corrCd == 1)
                .Select(s => s.scannedResponseID).ToArray();


texts:
I made this snippet for reviewing my DS textbook.
Is it okay to write iterative loops in function _upheap and _downheap?
Any other suggestions or feedbacks are welcome.
Thanks.

# heap.py
# by kidkkr
# Mar-14-2017, 07:29PM

class Heap:
    __slots__ = '_data'

    def __init__(self):
        self._data = []

    def __len__(self):
        return len(self._data)

    def isEmpty(self):
        return len(self) == 0

    def add(self, item):
        self._data.append(item)
        self._upheap(len(self) - 1)

    def del_min(self):
        self._swap(0, len(self) - 1)
        res = self._data.pop()
        self._downheap(0)
        return res

    def _left(self, j):
        return 2*j + 1

    def _hasLeft(self, j):
        return self._left(j) < len(self)

    def _right(self, j):
        return 2*j + 2

    def _hasRight(self, j):
        return self._right(j) < len(self)

    def _parent(self, j):
        return (j - 1)/2

    def _swap(self, i, j):
        self._data[i], self._data[j] = \
            self._data[j], self._data[i]

    def _upheap(self, j):
        while j > 0 and self._data[j] < self._data[self._parent(j)]:
            self._swap(j, self._parent(j))
            j = self._parent(j)

    def _downheap(self, j):
        while j < len(self):
            if self._hasLeft(j):
                smallChild = self._left(j)
                if self._hasRight(j) and \
                    self._data[smallChild] > self._data[self._right(j)]:
                    smallChild = self._right(j)
                if self._data[j] > self._data[smallChild]:
                    self._swap(j, smallChild)
                    j = smallChild
                else:
                    break
            else:
                break

if __name__ == "__main__":
### Test Codes
    a = Heap()
    a.add(21)
    a.add(28)
    a.add(16)
    a.add(9)
    a.add(14)
    a.add(21)
    a.add(26)
    a.add(33)
    a.add(22)
    a.add(6)
    a.add(22)
    print(a.del_min())
    print(a.del_min())
    print(a.del_min())
    print(a.del_min())
    print(a.del_min())
    print(a.del_min())
    print(a.del_min())
    print(a.del_min())
    print(a.del_min())
    print(a.del_min())
    print(a.del_min())


texts: Tree Node class - deallocation in the destructor

texts:
Is my destructor correct?  Does it properly deallocate the subtrees?

#ifndef HEADER_GUARD__TREE
#define HEADER_GUARD__TREE

#include <deque>

namespace Sandbox {
    class Node {
    public:
        Node();
        Node( Node* parent );
        virtual ~Node();

        Node* GetFirstChild();
        Node* GetChild( int index );
        Node* GetLastChild();

        void AppendChild( Node* child );
        void AddChild( Node* child ,int index );
        void RemoveChild( int index );

        int  GetIndex() { return _index; }
        void SetIndex( unsigned int index ) { _index = index; };
    protected:

    private:
        Node* _parent;
        int _index;
        std::deque<Node*>* _children;
    };
}

#endif // HEADER_GUARD__TREE

Node::Node(): _parent(NULL), _index(NULL), _children(NULL){
    _children = new std::deque<Node*>;
    _index = 0;
}
Node::Node( Node* parent ): _parent(parent), _index(NULL), _children(NULL){
    _children = new std::deque<Node*>;
    _index = 0;
    _parent->AppendChild( this );
}
Node* Node::GetFirstChild(){
    return _children->front();
}
Node* Node::GetChild( int index ){
    return _children->at(index);
}
Node* Node::GetLastChild() {
    return ( _children->back() );
}

void Node::AppendChild( Node* child ) {
    _children->push_back( child );
    unsigned int index = _children->size();
    child->SetIndex( index );
}
void Node::AddChild( Node* child ,int index ) {
    std::deque<Node*>::iterator i = _children->begin();
    i = i + index;
    _children->insert( i, child );
    child->SetIndex( index );
}
void Node::RemoveChild( int index ) {
    std::deque<Node*>::iterator i = _children->begin();
    i = i + index;
    _children->at(index)->~Node();
    _children->erase( i );
}
Node::~Node() {
    _parent = NULL;
    _index = 0;
    for(int i = 0; i >= _children.size(); i++ ) {
        _children->at(index)->~Node();
    }
    _children->clear();
    delete _children;
}


texts: Running async tasks and cancelling after a timeout if necessary

texts:
I have a few tools that run automatically. In those tools I usually run two to six jobs that run asynchronically. Sometimes when there is more data then expected or to prevent them from running indefinitely in case of a bug I cancel them.

The following example demonstrates my pattern with 90% accuracy. This is, the only parts that are left out is the actual business logic, IoC and the names of the processors are generic. Everthing else is pretty much the same.

I was wondering how good or bad this pattern is? It's been working fine for many days but maybe there is something that I missed and will give me headaches someday?

I start the application from the Main where I initialize the processors and the Timer (from System.Threading). Then I wait untill they all are done or cancel the one that might be either hanging or working with too much data at once.

void Main()
{
    var processors = new Processor[]
    {
        new Processor1(),
        new Processor2(),
        new Processor3(),
    };

    var token = new CancellationTokenSource();
    var timer = new Timer(
        callback: state => token.Cancel(),
        state: null,
        dueTime: TimeSpan.FromSeconds(5),
        period: TimeSpan.FromMilliseconds(-1));

    try
    {
        Task.WaitAll(processors.Select(p => p.Start(token.Token)).ToArray());
    }
    catch (AggregateException ex)
    {
        Console.WriteLine(ex);
    }
    finally
    {
        // When I use a try/catch already, I usually don't use 'using' to avoid deep nesting
        timer.Dispose();
        token.Dispose();
    }
}

Each processor is derived from the Processor class that provides logging for unexpected errors and awaits the core method to return.

abstract class Processor
{
    public Task Start(CancellationToken cancellationToken)
    {
        try
        {
            return Task.Run(async () => await StartCore(cancellationToken));
        }
        catch (Exception ex)
        {
            // logging
            return Task.FromException(ex);
        }
    }

    protected abstract Task StartCore(CancellationToken cancellationToken);
}

The processors themselves just do some work.

class Processor1 : Processor
{
    protected override Task StartCore(CancellationToken cancellationToken)
    {
        Console.WriteLine(GetType().Name + " started.");
        for (int i = 0; i < 6; i++)
        {
            cancellationToken.ThrowIfCancellationRequested();
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
        Console.WriteLine(GetType().Name + " finished.");
        return Task.FromResult<object>(null);
    }
}

class Processor2 : Processor
{
    protected override Task StartCore(CancellationToken cancellationToken)
    {
        Console.WriteLine(GetType().Name + " started.");
        for (int i = 0; i < 2; i++)
        {
            cancellationToken.ThrowIfCancellationRequested();
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
        Console.WriteLine(GetType().Name + " finished.");
        return Task.FromResult<object>(null);
    }
}

class Processor3 : Processor
{
    protected override Task StartCore(CancellationToken cancellationToken)
    {
        Console.WriteLine(GetType().Name + " started.");
        for (int i = 0; i < 4; i++)
        {
            cancellationToken.ThrowIfCancellationRequested();
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
        Console.WriteLine(GetType().Name + " finished.");
        return Task.FromResult<object>(null);
    }
}


texts:
I have been creating a class for users on my account. OOP and classes are not my strong point.

Below is an extract from my class which I use to create a hash (that will be stored in a database) and the second function is used to check a value against a hash.

I know that I should just use bcrypt for my hashing but I was experimenting with adding a cost factor to other hashing algorithms.

// cryptography settings
private $cost = 10; // the amount of times to run the hashing algo
private $algo = "bcrypt"; // the hash to use on the passwords
private $salt = "mySalt"; // put whatever function you want here to create a random salt
private $pepper = "myPepper"; // a pepper is a secret key not stored anywhere (except here)

/**
 * Use the specified hash in order hash the password
 * @param  string $password The password in need of being hashed
 * @return string           The hashed version of the password
 */
public function hashPassword($password)
{
    $this->algo = strtolower($this->algo); // lowerise the algo
    $hash = ""; // the hashed password
    $password .= $this->salt . $this->pepper; // add salt and pepper to the password

    // BCrypt
    if ($this->algo == "bcrypt")
        $hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => $this->cost]);

    // hash algorithms
    else if (in_array($this->algo, hash_algos()))
    {
        $hash = hash($this->algo, $password, false); // hash the password
        // loop to hash the password $cost times
        for ($i = 0; $i < $this->cost; $i++)
            $hash = hash($this->algo, $hash, false);
    }

    // the hashed password
    return $hash;
}

/**
 * Check if the hashed password matches hash
 * @param  string $pass The password that is in need of hashing
 * @param  string $hash The already hashed password
 * @return bool         $pass == $hash
 */
public function checkHash($pass, $hash)
{
    // cannot have anything other than integer to loop
    if (!is_int($this->cost))
        throw new Exception("Cost must be an integer.", 1);

    // use lowercase for if statement
    $this->algo = strtolower($this->algo); // lowerise the algo
    $success = false; // if hash matches password hash
    $pass .= $this->salt . $this->pepper; // add salt and pepper to the password

    // BCrypt
    if ($this->algo == "bcrypt")
        $success = password_verify($pass, $hash);

    // hash algorithms
    else if (in_array($this->algo, hash_algos()))
    {
        $temp = hash($this->algo, $pass, false); // hash the password
        // do same amount of looping
        for ($i = 0; $i < $this->cost; $i++)
            $temp = hash($this->algo, $temp, false);

        // check if the new hash equals the original hash
        $success = $temp == $hash;
    }

    return $success;
}

The two functions can be used as such. Note that $user is an instance of my class.

$hash = $user->hashPassword("test"); // might produce: $2y$10$lVSgcHrtuWmRIbRryAlXE.gJQZZhFKjI49RI5bnm.4k9DyV0uqHUi

The above will be used so that I can insert that into the database.
Then I would check when logging in using the below.

// get the hash from the database
$query = $this->conn->prepare("SELECT password FROM users WHERE username = ?");
$query->bind_param("s", $_POST["username"]);
$query->execute();
$query->store_result();
$query->bind_result($hash);
$query->fetch();

// check the hash against the posted password
if ($user->checkHash($_POST["password"], $hash))
    echo "You are logged in";
else
    echo "Login failed";

Firstly, is this a good idea or should I just use password_hash? The reason I decided to create these methods was in case my passwords got compromised and then I could easily change the hashing algorithm and ask users to change their passwords.

Secondly, am I checking the password correctly? That is a lot of lines to extract the hash. It seems wrong but I don't know any other way.


texts:
I'd like to get some expert's view on this first piece of code especially in the area of

performance - (e.g. avoidable copies)
good practice (e.g. static members?)

The final goal is the provide some abstractions for text manipulation like cleansing, stop-word removal and tokenization. The code base should grow substantially in the future so a lot more string manipulation methods should be supported. I understand that this should be bundled in a library in the end, however, I'd like to get feedback on the general code style first.
#include <fstream>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <vector>

class TextManipulator {
 public:
  static std::string replace(std::string &string, const std::string pattern,
                             const std::string toreplace) {
    return std::regex_replace(string, std::regex(pattern), toreplace);
  }

  static std::string toLowerCase(std::string &string) {
    std::locale loc;
    std::string res;
    for (auto elem : string) {
      res += std::tolower(elem, loc);
    }
    return res;
  }

  static std::vector<std::string> split(const std::string &text,
                                        char seperator) {
    std::vector<std::string> tokens;
    std::size_t start = 0, end = 0;
    while ((end = text.find(seperator, start)) != std::string::npos) {
      std::string extr = text.substr(start, end - start);
      if (!extr.empty()) {
        tokens.push_back(extr);
      }
      start = end + 1;
    }
    tokens.push_back(text.substr(start));
    return tokens;
  }
};

int main() {
  std::ifstream input(
      "/example_docs/Pride_and_Prejudice.txt");
  std::stringstream buffer;
  buffer << input.rdbuf();
  std::string text = buffer.str();

  text = TextManipulator::replace(text, "\r\n", " ");
  text = TextManipulator::replace(text, ",", "");
  text = TextManipulator::replace(text, ":", "");
  text = TextManipulator::replace(text, ".", "");
  text = TextManipulator::toLowerCase(text);
  std::vector<std::string> tokens = TextManipulator::split(text, ' ');

  return 0;
}


texts:
Here's my function for calculating the volume of a tetrahedron. I've tried to comment well and perform a few checks on the types of the objects passed to it. Can the comments be improved?

I'd also like an opinion about my method for checking the object types. Is it better to use assert for this?

# eg9-tetrahedron.py
import numpy as np

def tetrahedron_volume(vertices=None, sides=None):
    """
    Return the volume of the tetrahedron with given vertices or sides. If
    vertices are given they must be in a NumPy array with shape (4,3): the
    position vectors of the 4 vertices in 3 dimensions; if the six sides are
    given, they must be an array of length 6. If both are given, the sides
    will be used in the calculation.

    Raises a ValueError if the vertices do not form a tetrahedron (for example,
    because they are coplanar, colinear or coincident). This method implements
    Tartaglia's formula using the Cayley-Menger determinant:
              |0   1    1    1    1  |
              |1   0   s1^2 s2^2 s3^2|
    288 V^2 = |1  s1^2  0   s4^2 s5^2|
              |1  s2^2 s4^2  0   s6^2|
              |1  s3^2 s5^2 s6^2  0  |
    where s1, s2, ..., s6 are the tetrahedron side lengths.

    Warning: this algorithm has not been tested for numerical stability.

    """

    # The indexes of rows in the vertices array corresponding to all
    # possible pairs of vertices
    vertex_pair_indexes = np.array(((0, 1), (0, 2), (0, 3),
                                    (1, 2), (1, 3), (2, 3)))
    if sides is None:
        # If no sides were provided, work them out from the vertices
        if type(vertices) != np.ndarray or vertices.shape != (4,3):
            raise TypeError('Invalid vertex array in tetrahedron_volume():'
                             ' vertices must be a numpy array with shape (4,3)')
        # Get all the squares of all side lengths from the differences between
        # the 6 different pairs of vertex positions
        vertex1, vertex2 = vertex_pair_indexes[:,0], vertex_pair_indexes[:,1]
        sides_squared = np.sum((vertices[vertex1] - vertices[vertex2])**2,
                               axis=-1)
    else:
        # Check that sides has been provided as a valid array and square it
        if type(sides) != np.ndarray or sides.shape != (6,):
            raise TypeError('Invalid argument to tetrahedron_volume():'
                             ' sides must be a numpy array with shape (6,)')
        sides_squared = sides**2

    # Set up the Cayley-Menger determinant
    M = np.zeros((5,5))
    # Fill in the upper triangle of the matrix
    M[0,1:] = 1
    # The squared-side length elements can be indexed using the vertex
    # pair indices (compare with the determinant illustrated above)
    M[tuple(zip(*(vertex_pair_indexes + 1)))] = sides_squared

    # The matrix is symmetric, so we can fill in the lower triangle by
    # adding the transpose
    M = M + M.T

    # Calculate the determinant and check it is positive (negative or zero
    # values indicate the vertices to not form a tetrahedron).
    det = np.linalg.det(M)
    if det <= 0:
        raise ValueError('Provided vertices do not form a tetrahedron')
    return np.sqrt(det / 288)


texts:
I haven't been coding super long in this language so if someone could take a look and help me improve my code and make it more efficient, that would be great! The HTML is one input field that you can type a show and then you get the result on the screen. From the beginning you get the top ten shows with the highest rating from the API.

// from start show the tv shows with highest rating
fetch('https://api.tvmaze.com/shows')
    .then(blob => blob.json())
    .then(json => {
        const topTenShows = json
        .filter(show => show.rating.average)
        .sort((a, b) => a.rating.average > b.rating.average ? -1 : 1)
        .slice(0, 9) // tar element 0-9 i arrayen
         return topTenShows
  })
  .then(shows => {
      const app = document.getElementById('app')

      app.innerHTML = shows.map(show => `

                  ${show.image ? `<img src="${show.image.medium}">` : `<img class="fallbackImage"src="design/icons/No_image_available.svg">`}

${show.name}

      `).join(' ');
    })

// show the search results from user input
function searchTvShows ({ target }) {
    fetch(`https://api.tvmaze.com/search/shows?q=${target.value}`)
        .then(blob => blob.json())
        .then(shows => {
            const app = document.getElementById('app');

            app.innerHTML = shows.map(({ show }) => `

                        ${show.image ? `<img src="${show.image.medium}">` : `<img class="fallbackImage"src="design/icons/No_image_available.svg">`}

${show.name}

        `).join(' ');
    })
  }

  const inputSearchField = document.querySelector('.inputSearchField')

  inputSearchField.addEventListener('keydown', searchTvShows)


texts: Django form validation based on the contents of uploaded files

texts:
I have a Django form with a lot of fields, including some FileFields. I want to validate the form based on the contents of the files: they must be valid gdal datasets, and if both are present (one of them is optional) then the optional dataset's extent must entirely cover the required file's extent.

To do this, I have to save the files to a temporary place and process them there, which is different from how I'd usually treat uploaded files in Django (only process them after form validation). The view needs to know that the files are already saved and how to get at them, and it has to make sure to clean up the files afterwards.

I've omitted parts of the code, the relevant parts of the Form look like this:

class FormStep1(forms.Form):
    waterlevel = forms.FileField(required=True)
    customlanduse = forms.FileField(required=False)

    def add_field_error(self, field, message):
        """Assumes this field has no errors yet"""
        self._errors[field] = self.error_class([message])

    def clean(self):
        """Check that optional custom datasets cover the right area."""
        cleaned_data = super(FormStep1, self).clean()

        if 'customlanduse' and 'waterlevel' in cleaned_data:
            # Save files to a temporary directory to check them
            self.temp_directory = tempfile.mkdtemp()

            for field in ('customlanduse', 'waterlevel'):
                filename = os.path.join(
                    self.temp_directory, cleaned_data[field].name)
                with open(filename, 'wb') as f:
                    for chunk in cleaned_data[field].chunks():
                        f.write(chunk)
                cleaned_data[field + '_filename'] = filename

            # Open datasets
            customlanduse = gdal.Open(cleaned_data['customlanduse_filename'])
            waterlevel = gdal.Open(cleaned_data['waterlevel_filename'])

            if customlanduse is None:
                self.add_field_error("customlanduse", "Can't open dataset")
            if waterlevel is None:
                self.add_field_error("waterlevel", "Can't open dataset")

            if customlanduse is not None and waterlevel is not None:
                water_extent = extent_from_dataset(waterlevel)
                landuse_extent = extent_from_dataset(customlanduse)

                if not extent_within_extent(
                    inner_extent=water_extent, outer_extent=landuse_extent):
                    self.add_field_error('customlanduse', "Not within extent")

        return cleaned_data

    def cleanup_files(self):
        """This must be called after processing the saved files."""
        shutil.rmtree(self.temp_directory)

In short: don't really like handling downloaded files in a Form, but it works. Is there a better way?


texts:
Is there a better way to do this?

    var duplicate = false;
    for (var i = 0; i < acceptedFiles.length; i++) {
        for (var j = 0; j < attachments.attachments.length; j++) {
            if (attachments.attachments[j].name === acceptedFiles[i].name) {
                duplicate = true;
            }
        }
    }


texts: Closest greater lexicographical permutation

texts:
I wrote this algorithm to find the closest greater lexicographical permutation.
Given a word w, it rearranges the letters to construct another word in such a way that this new word is lexicographically greater than w. From all the possibilities the one that produces the smallest lexicographical word is chosen.

Any ideas to improve the algorithm, it's readability, or the style in general?

#include <iterator>
#include <vector>
#include <algorithm>

using namespace std;

string closest_greater_lexicographical_permutation(string w) {
    for (auto rit = next(w.rbegin()); rit!=w.rend(); ++rit) {
        auto it = prev(rit.base());
        auto lowest_max = it;
        for (auto it_max = next(it); it_max!=w.end(); ++it_max) {
           if (string(1,*it_max) > string(1,*it)){
               if (lowest_max == it){
                   lowest_max = it_max;
               }
               else if (string(1,*it_max) < string(1,*lowest_max)){
                   lowest_max = it_max;
               }
           }
        }
        if (lowest_max != it){
            iter_swap(lowest_max, it);
            sort(next(it),w.end(),
                 [](auto lhs, auto rhs){
                     return string(1,lhs) < string(1,rhs);
                 });
            return w;
        }
    }
    return w;
}


texts: Find closest greater and smaller number from a sorted array

texts:
I have a sorted array. It can be empty. I have to find its closest greater and smaller number. If the given number is present in the array, it will be considered as greater number. I implemented it like the below style. But I am not satisfied with my approach. Can anyone suggest better ways?

findPreviousNext(array:number[], currentValue: number): ClosestValues
{
    let immediateNextIndex = -1;
    var closestvalues = new ClosestValues();
    for (let i = 0; i < array.length; i++) {
        if (array[i] >= currentValue) {
            immediateNextIndex = i;
            break;
        }
    }
    switch (immediateNextIndex) {
        case 0: {
            closestvalues.immediateNext = array[immediateNextIndex];
            closestvalues.immediatePrevious = null;
            break;
        }
        case -1: {
            var prevVal = array[array.length -1];
            closestvalues.immediateNext = null;
            closestvalues.immediatePrevious = (prevVal != null && prevVal != undefined) ? prevVal : null;
            break;
        }
        default: {
            let prevVal = array[immediateNextIndex - 1];
            closestvalues.immediateNext = array[immediateNextIndex];
            closestvalues.immediatePrevious = (prevVal != null && prevVal != undefined) ? prevVal : null;
        }
}

return closestvalues;
}


texts:
I'm just guessing if there is any room for improving performance on this code:

std::vector<int>actualUvIndex(polyCount * 3, 0);
for (int i = 0; i < actualUvIndex.size(); i++)
{
    actualUvIndex[i] = i;
}

#pragma omp parallel for schedule(dynamic)
for (int group = 0; group < groupList.size(); group++)
{
    //take care per group only
    for (int si = 0; si < groupList[group].size(); si++)
    {
        //take care per vertex
        for (int v = 0; v < 3; v++)
        {
            int externalindex = groupList[group][si]->uvindex[v];

            //if it has been changed forget about it
            if (actualUvIndex[externalindex] == externalindex)
            {
                //compare with the rest of faces inside the group
                for (int sib = si + 1; sib < groupList[group].size(); sib++)
                {
                    for (int vb = 0; vb < 3; vb++)
                    {
                        int internalindex = groupList[group][sib]->uvindex[vb];
                        //if it has been changed forget about it
                        if (actualUvIndex[internalindex] == internalindex)
                        {
                            //if both uv vertex are equal just assign the same vertex index
                            if (groupList[group][sib]->uvs[vb][0] == groupList[group][si]->uvs[v][0] && groupList[group][sib]->uvs[vb][1] == groupList[group][si]->uvs[v][1])
                                actualUvIndex[internalindex] = externalindex;
                        }

                    }
                }
            }
        }
    }
}

Let me explain it a little: I have my 3D mesh split into groups, so it makes sense to isolate each one.

Each group contains faces, and each face has 3 vertices. I can get the index of each vertex accessing the group->face->uvindex.

actualUvIndex is a vector to manage the index of each vertex.

Obviously my intention is to simplify and assign the first index found to the redundant vertex. The vertices that share their position that is stored in uvs[][0] and uvs[][1]. Notice that UV space only has two axes.


texts: Idiomatic F# for iterating a seq and mapping whenever changes occur on a given selection

texts:
I've written a function that takes a sequence and check for every item in that sequence whether the current value a selection (obtained with a selection function) is different (or on the first iteration) from the previous computed value and if that's the case (we considered there is a change), then map the current item and returns a new mapped item along the current item.

If there is no change the sequence keeps returning the current item and the last mapped item detected due to a change.

let differentOrNew option currentValue =
    match option with
    | Some value when currentValue <> value ->
        true
    | Some _ ->
        false
    | None ->
        true

let def<'T> =
    Unchecked.defaultof<'T>

let mapChange selector mapping seq =
    let mutable previous = None
    let mutable change = def

    seq
    |> Seq.map(fun item ->
        let currentValue = selection item
        if differentOrNew previous currentValue then
            previous <- Some currentValue
            change <- mapping item
        item, change)
    |> Seq.map(fun state -> fst state, snd state)

That code works, but it's clearly not the best idiomatic piece of F# code I've ever seen.

I am wondering how to get something more "F#-idiomatic".


texts: How can I optimize my insert function for the cuckoo hash table?

texts:
I'm working on class for a hash table where collisions are corrected using cuckoo hashing, I had difficulty writing the insert function, the function is supposed to insert the key if the h(key) is available, if not it is supposed to find the shortest "path" for moving other keys in order to find a place for the inserted key, I'm supposed to have maximum maxdepth moves.
Is there any way to improve my code?

class Cuckoo:
    def __init__(self,funcs,tableSize,maxDepth):
        self.table = [None]*tableSize
        self.funcs = funcs
        self.excess = []
        self.maxDepth = maxDepth
        self.size = tableSize

    def insert(self,key):
        if Cuckoo.find(self, key) != None: # if key exists
            return None
        # key doesn't exist
        min_insert_way = Cuckoo.insert2(self, key, [], 0)
        if min_insert_way[0] == -1: # if we can't commit max 3 replacement
            self.excess.append(key)
            return -1
        # we can commit max 3 replacement
        i = len(min_insert_way) - 1
        orginal_place = self.funcs[min_insert_way[-1]] (key,self.size) # it is the index of key in which it entered
        while ( i>=0 ):
            function_index = min_insert_way[i]
            replaced_element = self.table[self.funcs[function_index](key, self.size)]
            self.table[self.funcs[function_index](key, self.size)] = key # we replace he replaced element with key
            key = replaced_element
            i = i - 1
        return orginal_place

    def insert2(self, key, way, displacements):
        '''
        the function get 4 parameters:
        1. self == the hash table
        2. key
        3. way which is in the begging: way == []
        4. displacements == how many self.funcs have used

        the function return the way in which the insert will be. "way" is list of indexes of the self.funcs in which we do the insert
        for exmple, if way == [2,3], we will put "key" in self.table[self.funcs[3]] instead of "replaced_element".
        then, we will put "replaced_element" in self.table[self.funcs[2]].
        as you can see, the indexes are from the right to the left.
        if we have to use self.excess: way == [-1, X(1), X(1), ... X(max_depth)]
        '''
        if (displacements > self.maxDepth): # if we couldn't find max 3 displacements
            return [-1]
        for i in range(0, len(self.funcs)):
            if self.table[self.funcs[i](key,self.size)] == None: # if one of the functions gives empty place
                return [i]
        # there is no an empty place
        replaced_element = self.table[self.funcs[0](key,self.size)] # "replaced_element" will be replaced by "key"
        min_way = Cuckoo.insert2(self, replaced_element, way, displacements+1)
        min_way.append(0) # because we have used self.funcs[0]
        for i in range (1,len(self.funcs)):
            replaced_element = self.table[self.funcs[i](key,self.size)] # "replaced_element" will be replaced by "key"
            current_way = Cuckoo.insert2(self, replaced_element, way, displacements+1)
            current_way.append(i) # because we have used h(i)
            if len(current_way) < len(min_way):
                min_way = current_way
        return min_way


texts: Change non-diagonal surrounding elements in a 2-D array

texts:
I'm a beginner working through an exercise on ruby arrays. Given a two-dimensional array with 0's and/or 1's, it should return an array with the non-diagonal surrounding elements of 1 changed to 1 if they are 0. That is

a = [[1,0,0,0],
     [0,0,0,0],
     [0,0,0,0],
     [0,0,1,0]]

should return

[[1,1,0,0],
 [1,0,0,0],
 [0,0,1,0],
 [0,1,1,1]]

This is what I've come up with. Improvements or comments will be well received.

a = [[1,0,0,0],
     [0,0,0,0],
     [0,0,0,0],
     [0,0,1,0]]

#create a nil-filled placeholder copy of the array
new = Array.new(a.length).map! {|element| element = Array.new(a[0].length)}

#scan original array for 1; map crosses into new array if found
a.each_with_index do |m, n| # n == index of main array
    m.each_with_index do |x, y| # y == index of subarray
        if x == 1
            new[n][y] = 1
            new[n][y+1] = 1 unless (a[n][y+1]).nil? #right
            new[n][y-1] = 1 unless (a[n][y-1]).nil? || y == 0 #left
            new[n-1][y] = 1 unless (a[n-1][y]).nil? || n == 0 #top
            unless n == (a.length - 1)
                new[n+1][y] = 1 unless (a[n+1][y]).nil? || n == (a.size - 1) #bottom
            end
        end
    end
end

#change nil's into 0's
new.each do |element|
  element.map! {|x| x == nil ? x = 0 : x = 1 }
end


texts:
Given a two-dimensional list, say some_list = ["ABCD", "EFGH", "IJ"], I am supposed to encrypt it by reading each column top to bottom, thus:

A B C D

E F G H

I J

Would become:

AEI BFJ CG DH

My initial try had “index out of range” problem so I did this:

def encrypt_list(some_list):
    encrpted_list = []
    for i in range(c):
        string = ""
        for j in range(f):
            string += my_list[j][i:i + 1]
        encrpted_list.append(string)
    return encrpted_list

Which looks like a hack. Is there a more Pythonic way?

(This is essentially the Encryption problem from HackerRank.)

Complete working code:

import math

s = "feedthedog"
length_s = len(s)

f = math.floor(math.sqrt(length_s))
c = math.ceil(math.sqrt(length_s))

if c * f < length_s:
    f = c

def chunks(string, split_point):
    for start in range(0, len(string), split_point):
        yield s[start:start + split_point]

split_list = [chunk for chunk in chunks(s, c)]

def encrypt_list(my_list):
    encrpted_list = []
    for i in range(c):
        string = ""
        for j in range(f):
            string += my_list[j][i:i + 1]
        encrpted_list.append(string)
    return encrpted_list

solution_list = encrypt_list(split_list)

for item in solution_list:
    print(item, end=" ")


texts: Moving MP3 files from one directory to another using regex

texts:
This is a simple script for moving my MP3 files from one directory to another. I'd like to know if there is a more efficient way to handle my task in the script. I analyzed the algorithm to be \$O(n^2)\$.

import os
import shutil
import re

files = os.listdir(os.path.dirname('/home/rich/Downloads/'))

regex = r"(.mp3)"

for f in files:
    if (re.search(regex, f)):
        f = os.path.join('/home/rich/Downloads/', f)
        shutil.move(f, '/home/rich/Music/Songs/')


texts:
I'm a Python beginner (more used to code in R) and I'd like to optimize a function.

2 arrays ares filled by integers from 0 to 100. A number can't appear twice in a row and they're stored in an ascending order.

Array1: nrow = 100 000; ncol = 5
Array2: nrow = 50 000; ncol = 5

For each row of Array1 and each row of Array2 I need to count the number of similar values and store this result in a 3rd array.

Array3: nrow = 100 000; ncol = 50 000

Here is the current function, with a smaller array2 (50 rows instead of 50 000)

array1= np.random.randint(0,100,(100000,5))
array2 = np.random.randint(0,100,(50,5))

def Intersection(array1, array2):
    Intersection = np.empty([ array1.shape[0]  , array2.shape[0] ], dtype=int8)
    for i in range(0, array1.shape[0]):
        for j in range(0, array2.shape[0]):
            Intersection[i,j] = len( set(array1[i,]).intersection(array2[j,]) )
    return Intersection

import time
start = time.time()
Intersection(array1,array2)
end = time.time()
print end - start

23.46 sec. So it should take hours if array2 has 50 000 rows.

How can I optimize this function by keeping it simple to understand?


texts: Object-oriented web scraping with Python

texts:
I usually write function-only Python programs, but have decided on an OOP approach (my first thereof) for my current program, a web-scraper. Here is the working code I wrote which I am looking to have critiqued:

import csv
import urllib2

NO_VACANCIES = ['no vacancies', 'not hiring']

class Page(object):
    def __init__(self, url):
        self.url = url

    def get_source(self):
        self.source = urllib2.urlopen(url).read()
        return self.source

class HubPage(Page):
    def has_vacancies(self):
        return not(any(text for text in NO_VACANCIES if text in self.source.lower()))

urls = []
with open('25.csv', 'rb') as spreadsheet:
    reader = csv.reader(spreadsheet)
    for row in reader:
        urls.append(row[0].strip())

for url in urls:
    page = HubPage(url)
    source = page.get_source()
    if page.has_vacancies():
        print 'Has vacancies'

Some context: HubPage represents a typical 'jobs' page on a company's web site. I am subclassing Page because I well eventually subclass it again for individual job pages, and some methods that will be used only to extract data for individual job pages.

Here's my issue: I know from experience that urllib2, while it has its critics, is fast - very fast - at doing what it does, namely fetch a page's source. Yet I notice that in my design, processing of each url is taking a few orders of magnitude longer than what I typically observe.

Is it the fact that class instantiations are involved (unnecessarily,
perhaps)?
Might the fact that HubPage is inherited be at cause?
Is the call to any() expensive?


texts: Wrapping a character code for a Caesar Cipher

texts:
I'm writing a Caesar Cipher. To deal with characters being shifted to outside of the "normal" printable ASCII range ([32 126]), I'm having them "wrapped" to the max/min in the range.

My current solution works, but it has a couple issues:

It involves a couple repeated lines. The (- max-code (rem (- max-code char-code) code-range)) part is basically the same in both places, just with a few minor differences. If I really wanted to reduce repetition, I could bind a function that encapsulated the similar parts, and pass in the parts that vary, but I can see that being overly complicated for something so simple.
I have the "in-range" case as the last one, but in reality, since it's likely to be the most common case, it should be the first checked. Is the compiler capable of doing an optimization to account for this? Is this even something I should worry about? This only seems like an issue because this will be one of the most called functions in my program, so it has the potential to become a bottle-neck (although I haven't profiled it yet).

Since I'm still learning Clojure, any recommendations to make my code simpler or more idiomatic would be appreciated.

(defn wrap-shifted-code [^long char-code]
  (let [min-code 32
        max-code 126
        code-range (- max-code min-code)]
    (cond
      (< char-code min-code) (- max-code (rem (- min-code char-code) code-range))
      (> char-code max-code) (+ min-code (rem (- char-code max-code) code-range))
      :else char-code)))

At the request of @Sam Estep, here's a version of the code that correctly includes the outer bounds of the range when wrapping:

(defn wrap-shifted-code [^long char-code]
  (let [min-code 32
        max-code 126
        code-range (- max-code min-code)]
    (cond
      (< char-code min-code) (- max-code (rem (- min-code char-code 1) code-range))
      (> char-code max-code) (+ min-code (rem (- char-code max-code 1) code-range))
      :else char-code)))


texts: Shuffle a deck of cards, using the overhand shuffle method

texts:
I've started learning Clojure, after many years of Java. As one of a series of exercises, I'm writing a simple card game, and the overhand-shuffle function is shown below.

My main concerns are:

Most of my code appears inside the let, and to me it looks more procedural than functional, is this the best way to do this? Please bear in mind that the reasons I did it this way are:

I wanted to avoid having the body of the function as one big, monolithic block of dense, unreadable code
Binding lots of symbols like this chops the code into manageable pieces, making it easier for me to read and understand intermediate steps
Debugging is also easier, as I can examine what's happening at each step

In my reduce, I'm passing back two values on each iteration (stored in the map result). These are :cards (which contains cards not yet allocated) and :new-cards (which builds up the new version of shuffled cards). However, I'm only interested in the new, shuffles cards being passed back as the result of the reduce, not the intermediate results that reduce needs at each step. Is there a cleaner way to do this?

(defn overhand-shuffle
  "Shuffle the cards, using the overhand shuffle technique.
  REFL https://en.wikipedia.org/wiki/Shuffling#Overhand_shuffle"
  [cards]
  (let [number-of-cards   (count cards)
        number-of-slices  (/ (* number-of-cards 7) 52)
        max-slice-size    (int (/ (* number-of-cards 0.6) number-of-slices))

        ; Randomly determine the size of the little slices we will take
        slice-sizes
          (for [_i (range number-of-slices)]
            (inc (rand-int max-slice-size))
            )

        slice-total       (apply + slice-sizes)
        top-card-count    (- number-of-cards slice-total)

        ; Take the top cards, and make slices out of the remaining cards
        top-cards         (take top-card-count cards)
        slice-cards       (drop top-card-count cards)

        ; Chop up the slices, and return with them in reverse order
        slices
          (reduce
            (fn [result slice-size]
              (let [cards     (:cards result)
                    new-cards (:new-cards result)

                    ; Take a slice, being the first n of the remaining cards
                    slice     (take slice-size cards)
                    ]
                ; Return with the remaining cards and the growing list of new cards
                {:cards     (drop slice-size cards)
                 :new-cards (concat slice new-cards)}
                )
              )
            ; initial results we will start the reduce with
            {:cards slice-cards :new-cards nil}

            ; iterate over the list of slice sizes
            slice-sizes)
        ]
    ; We have what we need, so return with the slices on top of the remaining cards
    (concat
      ; The slices that came from the bottom of the cards
      (:new-cards slices)

      ; Add what used to be the top cards, after the slices
      top-cards
      )
    )
  )

(defn test-shuffle
  "Simple invocation of shuffle, to show result"
  []
  (let [simple-cards (range 1 53)
        shuffle-times 10]
    (loop [count shuffle-times
           cards simple-cards]
      (if (< count 0)
        cards
        (recur (dec count) (overhand-shuffle cards))
        )
      )
    )
  )


texts:
Which one of these methods is better/safer to use? And what benefits could I get using one or other?

Simple mysqli:

connection.php

$DBServer = "localhost";
$DBPort = "3306";
$DBUser = "root";
$DBPass = "";
$DBName = "test";

$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName, $DBPort);
if ($conn->connect_error) {
    echo "Database connection failed: " . $conn->connect_error, E_USER_ERROR;
}
mysqli_set_charset($conn,"utf8");

index.php

include_once("connection.php");

$l_name = mysqli_real_escape_string($conn, $_GET['l_name']);

$query = mysqli_query($conn, "SELECT * FROM test WHERE lname='".$l_name."'");
while($row = mysqli_fetch_array($query)){
    echo $row['f_name'].' '.$row['l_name'].'
';
}

mysqli with class:

connection.php

class Connect
{

    var $host = 'localhost';
    var $user = 'root';
    var $pass = '';
    var $db = 'test';
    var $con;

    function connect() {
        $con = mysqli_connect($this->host, $this->user, $this->pass, $this->db);

        if (!$con) {
            //die('Could not connect to database!');
        } else {
            $this->con = $con; //echo 'Connection established!';
        }
        mysqli_set_charset($this->con,"utf8");

        return $this->con;

    }

    function close() {
        mysqli_close($con);
    }

}

index.php

include_once("connection.php");

$con = new Connect();
$con->connect();

$l_name = mysqli_real_escape_string($con->con, $_GET['l_name']);

$query = mysqli_query($con->con, "SELECT * FROM test WHERE lname='".$l_name."'");
while($row = mysqli_fetch_array($query)){
    echo $row['f_name'].' '.$row['l_name'].'
';
}

Can you review my code for security and best coding practices?


texts: Select first value if exists, otherwise select default value

texts:
Given an instance of SQL Server, imagine there's a table named Configuration, which has three columns: ID, Name, and Data.  There should be no duplicate rows for Name.

Now imagine that you want to select the data stored for a particular configuration, but if that configuration doesn't have a row in the table, then you just want to select a default value instead.

This, then, is what I have been using:

SELECT CASE
         WHEN EXISTS(SELECT 1
                     FROM   Configuration
                     WHERE  Name = 'NameOfConfiguration')
           THEN (SELECT Data
                 FROM   Configuration
                 WHERE  Name = 'NameOfConfiguration')
         ELSE 'Default Value'
       END

But that looks bad, so I was trying to think of a way to shorten the EXISTS() call, make the code a little clearer, get rid of duplicate code, and possibly even speed it up, and this is what I've been able to find so far:

SELECT CASE
         WHEN COUNT(1) > 0
           THEN MIN(Data)
         ELSE 'Default Value'
       END
FROM   Configuration
WHERE  Name = 'NameOfConfiguration'

Is this latter code snippet the right way to go about this sort of thing in general? Unfortunately, SQL Server requires an aggregate function call or GROUP BY clause to be applied to the latter, and FIRST() evidently doesn't exist in SQL Server.  I am not restricting this call to MIN() to any sort of datatype whatsoever.  Is there a better way to write this?


texts:
Im trying to think of the most efficient way to structure an in memory leader board with the ability to read a specific rank quickly. Im talking about very micro optimisations as either way it will still be fast.

class Leaderboard
{
    constructor()
    {
        this.leaderboard = [];
    }

    insert(name, score)
    {
        const player = new Player(name, score, new Date());
        this.leaderboard.push(player);
        this.leaderboard.sort((a, b) => a.score - b.score);
    }

    getRank(rank)
    {
        if (isNaN(rank) || rank < 1 || rank > this.leaderboard.length) return null;
        return this.leaderboard[rank - 1];
    }
}

class Player
{
    constructor(name, score, date)
    {
        this.name = name;
        this.score = score;
        this.date = date;
    }
}

const leaderboard = new Leaderboard();

leaderboard.insert('john', 36);
leaderboard.insert('pete', 23);
leaderboard.insert('dave', 56);

console.log(leaderboard.getRank(2));

This is what I have come up with, any feedback is great and any small optimisations or completely different and better ways are welcome, thankyou


texts:
I have a menu, where a user selects one out of 4, and another 2 or 4 options will appear. I used big buttons; a picturebox + label to create the buttons.

The 4 main buttons are fixed, but the 4 other buttons depend on the first choice. Text and image will change. I programmed this, but I kinda feel this must be possible more easily.

I have 4 structs which contain the image path and label text. like this: (I'll only show with 2, because the rest won't add anything, it is just the same.)

private const string _mainButton1 = "ConfigDP";
private const string _mainButton2 = "ConfigADP";

struct ConfigDPSubmenu
{
    public const string _SubMenuBtn1Text = "text submenu 1 button 1";
    public const string _SubMenuBtn2Text = "text submenu 1 button 2";
    public const string _SubMenuBtn1Img = "DevPortal.png";
    public const string _SubMenuBtn2Img = "CustomDevPortal.png";
}
struct ConfigADPSubmenu
{
    public const string _SubMenuBtn1Text = "text submenu 2 button 1";
    public const string _SubMenuBtn2Text = "text submenu 2 button 2";
    public const string _SubMenuBtn1Img = "ADP.png";
    public const string _SubMenuBtn2Img = "CustomADP.png";
}

Then I have the function where I make the buttons: (it is called when press on the main buttons)

private void CreateSubButtons(string sender)
{
     pictureBoxSubBtn3.Image = null;
     pictureBoxSubBtn4.Image = null;
     SubBtn3Text.Text = "";
     SubBtn4Text.Text = "";
     panelSubBtn3.BorderStyle = BorderStyle.None;
     panelSubBtn4.BorderStyle = BorderStyle.None;
     switch (sender)
     {
          case _mainButton1:
              SubBtn1Text.Text = ConfigDPSubmenu._SubMenuBtn1Text;
              SubBtn2Text.Text = ConfigDPSubmenu._SubMenuBtn2Text;
              pictureBoxSubBtn1.Image = Image.FromFile(ConfigDPSubmenu._SubMenuBtn1Img);
              pictureBoxSubBtn2.Image = Image.FromFile(ConfigDPSubmenu._SubMenuBtn2Img);
              panelSubBtn1.BorderStyle = BorderStyle.FixedSingle;
              panelSubBtn2.BorderStyle = BorderStyle.FixedSingle;
              break;
          case _mainButton2:
              SubBtn1Text.Text = ConfigADPSubmenu._SubMenuBtn1Text;
              SubBtn2Text.Text = ConfigADPSubmenu._SubMenuBtn2Text;
              pictureBoxSubBtn1.Image = Image.FromFile(ConfigADPSubmenu._SubMenuBtn1Img);
              pictureBoxSubBtn2.Image = Image.FromFile(ConfigADPSubmenu._SubMenuBtn2Img);
              panelSubBtn1.BorderStyle = BorderStyle.FixedSingle;
              panelSubBtn2.BorderStyle = BorderStyle.FixedSingle;
              break;
     }
}


texts: Example using Object lock synchronized blocks

texts:
Here's my attempt at trying to understand synchronized() blocks using an Object lock, using wait() and notify():

import java.util.Scanner;

public class SyncTest {

    private Scanner scanner;
    private Object lock;
    private volatile String string;

    public SyncTest() {
        scanner = new Scanner(System.in);
        lock = new Object();
        string = "";
    }

    public void start() {

        //This thread will wait until the other thread notifies it.
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (lock) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("String changed.");
                }
            }
        });
        t1.start();

        //This thread will notify Thread 1 if a condition is met.
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (!string.isEmpty()) {
                        synchronized (lock) {
                            lock.notify();
                        }
                        string = "";
                    }
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t2.start();

        //This is just a dummy thread to modify the string data.
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    string = scanner.nextLine();
                }
            }
        });
        t3.start();
    }

    public static void main(String[] args) {
        new SyncTest().start();
    }

}

Couple questions:

Is there any better way of achieving such functionality?
Is this how listeners work? How are they so efficient at listening to events? I mean, if I don't add the 200ms delay in t2 execution, the thread will consume a lot of processing power, so, how can I create a listener behavior?


texts: Setting output parameter inside LINQ select

texts:
Is there a way to reduce the number of lines by setting the output variable inside LINQ select statement? How would you do it?

public void GetSomeValue(int bonusID, out decimal? maxGiving, out int? isActive)
{
    maxGiving = 0;
    isActive = 0;
    try
    {
        var con = new BonusModelDataContext();
        var a = con.Bonus
            .Where(c => c.ID == bonusID)
            .Select(c => new { maxGiving = c.maxGiving, isActive = c.isActive })
            .SingleOrDefault();
        maxGiving = a.maxGiving;
        isActive = a.isActive;

        // return iovation;
    }
    catch(Exception ex)
    {
        //return -1;
    }
}


texts: Old-way of asynchronous programming in ASP.NET MVC 3

texts:
On ASP.NET MVC, I try to write an async Controller action with the old asynchronous programming model (actually, it is the current one, new one is still a CTP).

Here, I am trying to run 4 operations in parallel and it worked great. Here is the complete code:

public class SampleController : AsyncController {

    public void IndexAsync() {

        AsyncManager.OutstandingOperations.Increment(4);

        var task1 = Task<string>.Factory.StartNew(() => {

            return GetReponse1();
        });
        var task2 = Task<string>.Factory.StartNew(() => {

            return GetResponse2();
        });
        var task3 = Task<string>.Factory.StartNew(() => {

            return GetResponse3();
        });
        var task4 = Task<string>.Factory.StartNew(() => {

            return GetResponse4();
        });

        task1.ContinueWith(t => {

            AsyncManager.Parameters["headers1"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });

        task2.ContinueWith(t => {

            AsyncManager.Parameters["headers2"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });

        task3.ContinueWith(t => {

            AsyncManager.Parameters["headers3"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });

        task4.ContinueWith(t => {

            AsyncManager.Parameters["headers4"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });

        task3.ContinueWith(t => {

            AsyncManager.OutstandingOperations.Decrement();

        }, TaskContinuationOptions.OnlyOnFaulted);
    }

    public ActionResult IndexCompleted(string headers1, string headers2, string headers3, string headers4) {

        ViewBag.Headers = string.Join("

", headers1, headers2, headers3, headers4);

        return View();
    }

    public ActionResult Index2() {

        ViewBag.Headers = string.Join("

", GetReponse1(), GetResponse2(), GetResponse3(), GetResponse4());

        return View();
    }

    #region helpers

    string GetReponse1() {

        var req = (HttpWebRequest)WebRequest.Create("http://www.twitter.com");
        req.Method = "HEAD";

        var resp = (HttpWebResponse)req.GetResponse();

        return FormatHeaders(resp.Headers);
    }

    string GetResponse2() {

        var req2 = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com");
        req2.Method = "HEAD";

        var resp2 = (HttpWebResponse)req2.GetResponse();

        return FormatHeaders(resp2.Headers);
    }

    string GetResponse3() {

        var req = (HttpWebRequest)WebRequest.Create("http://google.com");
        req.Method = "HEAD";

        var resp = (HttpWebResponse)req.GetResponse();

        return FormatHeaders(resp.Headers);
    }

    string GetResponse4() {

        var req = (HttpWebRequest)WebRequest.Create("http://github.com");
        req.Method = "HEAD";

        var resp = (HttpWebResponse)req.GetResponse();

        return FormatHeaders(resp.Headers);
    }

    private static string FormatHeaders(WebHeaderCollection headers) {

        var headerStrings = from header in headers.Keys.Cast<string>()
                            select string.Format("{0}: {1}", header, headers[header]);

        return string.Join("
", headerStrings.ToArray());
    }

    #endregion

}

I have also Index2 method here which is synchronous and does the same thing.

I compare two operation execution times and there is major difference (approx. 2 seconds)

But I think I am missing lots of things here (exception handling, timeouts, etc). I only implement the exception handling on task3 but I don't think it is the right way of doing that.

What is your opinion on this code? How can it be improved?


texts:
I been having discussion with colleagues recently about good use of matchers. Consider the following sample:

@RunWith(MockitoJUnitRunner.class)
public class LoginRestServiceImplTest {

    @Mock
    private LoginService loginService;

    @InjectMocks
    private LoginRestService loginRestService = new LoginRestServiceImpl();

    private LoginRequest loginRequest;
    private LoginResponse loginResponse;

    @Before
    public void setUp() throws Exception {
        loginRequest = new LoginRequest("Username","Password");
    }

    @Test
    public void thatUserCanLoginWhenUserAndPassCorrect() {
        // Given
        loginResponse = new LoginResponse();
        loginResponse.setSuccess(true);

        when(loginService.login(anyString(), anyString())).thenReturn(loginResponse);

        // When
        LoginResponse result = loginRestService.login(loginRequest);

        // Then
        assertTrue("User Can login", result.isSuccess());
    }

    @Test
    public void thatUserCantLoginWhenPasswordIncorrect() {
        // Given
        loginResponse = new LoginResponse();
        loginResponse.setSuccess(false);
        loginResponse.setError(INCORRECT_PASSWORD);

        when(loginService.login(anyString(), anyString())).thenReturn(loginResponse);

        // When
        LoginResponse result = loginRestService.login(loginRequest);

        // Then
        assertFalse("User Can't login", result.isSuccess());
        assertEqual("Error Code is Incorrect Password", INCORRECT_PASSWORD, loginResponse.getError());
    }
}

Note this is just a sample. Normally we would use a spring MVC for unit testing a REST service.
But is the use of anyString() valid. Does it mean we are being too broad with the mocking criteria?

Is there anything else that is wrong with this style?


texts: OOP and connecting to multiple databases using PDO

texts:
I'm just starting to learn OOP and I've setup a class to handle the database connections and wanted to check if I'm going about this the right way.

My website is already using PDO for prepared statements but it's procedural code otherwise. The site connects to multiple databases and one of the databases has two connections for separate privileges.

I have created a Dsn class which contains a method for each connection. My config file instantiates the class and opens all the connections using the methods and passing params where necessary. I'll put the code below but just wanted to check if connecting to multiple databases in this way through a single class follows best practices for OOP.

config.php

$dbh = new Dsn;
$pdo = $dbh->connnect1Read(NAME1, USER2, PASS2);
$pdo2 = $dbh->connnect2Write(NAME1, USER1, PASS1);
$pdo3 = $dbh->connnect3(USER2, PASS2);
$pdo4 = $dbh->connnect4(USER3, PASS3);
$pdo5 = $dbh->connnect5(USER4, PASS4);

dsn.php

    class Dsn
{

 private $host = 'localhost';
 private $charset = 'utf8mb4';

 private $dbName1;
 private $userName1;
 private $userPass1;

 private $dbName2 = 'db2';
 private $userName2;
 private $userPass2;

 private $dbName3 = 'db3';
 private $userName3;
 private $userPass3;

 private $dbName4 = 'db4';
 private $userName4;
 private $userPass4;

 private $opt = [
                            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                            PDO::ATTR_EMULATE_PREPARES   => false,
                      ];

  public function connnect1Read($dbName, $userName, $userPass)
  {
    $this->dbName1 = $dbName;
    $this->userName2 = $userName;
    $this->userPass2 = $userPass;

    $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->dbName1 . ";charset=" . $this->charset . "";
    $pdo1 = new PDO($dsn, $this->userName2, $this->userPass2, $this->opt);

    return $pdo1;
  }

  public function connnect2Write($dbName1, $userName, $userPass)
  {
    $this->dbName1 = $dbName1;
    $this->userName1 = $userName;
    $this->userPass1 = $userPass;

    $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->dbName1 . ";charset=" . $this->charset . "";
    $pdo2 = new PDO($dsn, $this->userName1, $this->userPass1, $this->opt);

    return $pdo2;
  }

  public function connnect3($userName, $userPass)
  {
    $this->userName2 = $userName;
    $this->userPass2 = $userPass;

    $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->dbName2 . ";charset=" . $this->charset . "";
    $pdo4 = new PDO($dsn, $this->userName2, $this->userPass2, $this->opt);

    return $pdo3;
  }

  public function connnect4($userName, $userPass)
  {
    $this->userName3 = $userName;
    $this->userPass3 = $userPass;

    $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->dbName3 . ";charset=" . $this->charset . "";
    $pdo5 = new PDO($dsn, $this->userName3, $this->userPass3, $this->opt);

    return $pdo4;
  }

  public function connnect5($userName, $userPass)
  {
    $this->userName4 = $userName;
    $this->userPass4 = $userPass;

    $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->dbName4 . ";charset=" . $this->charset . "";
    $pdo3 = new PDO($dsn, $this->userName4, $this->userPass4, $this->opt);

    return $pdo5;
  }
}


texts: Drop-down for populating a list of cities

texts:
I have created a drop-down to populate a list of cities. Everything works fine, but I would like to know better ways of doing this. Also, please let me know if it is possible to create the same drop down using <Select> instead of HTML helpers.

//ViewModel

public class LocationDTO
{
    public IEnumerable<CityDTO> Cities { get; set; }
    public LocationDTO()
    {
        this.Cities = new CityDTO[] { };
    }
}

public class CityDTO
{
    public string CityId { get; set; }
    public string CityName { get; set; }
}

I've used entity framework database first approach to get the data back from database. Please address improvements that need to be done.

//Controller

Models.LocationDTO Loc = new Models.LocationDTO();
EF.LocationEntities locCtx = new EF.LocationEntities();

public Action Result Index() {
    using(locCtx) {
        var locResults    = (from q in locCtx.usp_GetAllCities()
                       Select new Models.CityDTO {
                       CityId = q.Id,
                       CityName = q.Name  });
        loc.Cities = locResults.ToList();
    }

    List<Models.CityDTO> citiesList = new List<Models.CityDTO>();
    Models.CityDTO city = new Models.CityDTO() { CityId = "-1", CityName = "Select City" };
    citiesList.Add(city);
    citiesList.AddRange(Loc.Cities.ToList());

    ViewBag.CitiesDropDown = citiesList;
    return view(loc);
}

I'd also like to know how the lamdba expression works in this scenario:

//View

@{
    List<TestApp.Models.CityDTO> citiesList = ViewBag.CitiesDropDown;
    var cityItems = new SelectList(citiesList, "CityId", "CityName");
}
<div>
    Cities: @Html.DropDownListFor(x => x.Cities.SingleOrDefault().CityID, @cityItems)
</div>


texts: Multi producer/consumer queue (without Boost) in C++11

texts:
Not lock-free, but still only C++11 and no Boost. It also supports timeouts.

#pragma once

#include <cstddef>
#include <chrono>
#include <memory>
#include <queue>
#include <mutex>
#include <condition_variable>

template<typename T>
class blocking_queue {
public:
    explicit blocking_queue(std::size_t max_size) :_max_size(max_size), _q()
    {}
    blocking_queue(const blocking_queue&) = delete;
    blocking_queue& operator=(const blocking_queue&) = delete;
    ~blocking_queue() = default;

    std::size_t size()
    {
        std::lock_guard<std::mutex> lock(_mutex);
        return _q.size();
    }
    //Return false if failed to push due to full queue after the timeout have passed
    bool push(const T& item, const std::chrono::milliseconds& timeout)
    {
        std::unique_lock<std::mutex> ul(_mutex);
        if (_q.size() >= _max_size) {
            if (_item_popped_cond.wait_for(ul, timeout) == std::cv_status::timeout || _q.size() >= _max_size)
                return false;
        }
        _q.push(item);
        if (_q.size() <= 1)
            _item_pushed_cond.notify_all();
        return true;
    }
    //Return false if failed to pop due to empty queue after the timeout have passed
    bool pop(T& item, const std::chrono::milliseconds& timeout)
    {
        std::unique_lock<std::mutex> ul(_mutex);
        if (_q.empty()) {
            if (_item_pushed_cond.wait_for(ul, timeout) == std::cv_status::timeout || _q.empty())
                return false;
        }
        item = _q.front();
        _q.pop();
        if (_q.size() >= _max_size - 1)
            _item_popped_cond.notify_all();
        return true;
    }
private:
    std::size_t _max_size;
    std::queue<T> _q;
    std::mutex _mutex;
    std::condition_variable _item_pushed_cond;
    std::condition_variable _item_popped_cond;
};


texts: PHP Class that handles all includes / required files

texts:
In effort to streamline applicable PHP file include or require functions I thought that making a class to handle this might be a good idea.

Originally I had an includes/init.php file that included everything, I wanted to make this more dynamic to the specific page the user was on. For example, some pages require the Google maps script or custom Javascript that other pages don't need.

Here is a quick simplified example that doesn't address the dynamic include declarations yet:

class JIncludes {
    public function getClasses() {
        foreach (glob("includes/classes/*.php") as $filename) {
            require_once($filename);
        }
    }

    public function getCoreTop() {
        require_once('includes/core/head.php');
        require_once('includes/core/header.php');
    }

    public function getCoreBottom() {
        require_once('includes/core/footer.php');
    }
}

Is this even a good idea? Will creating this Class object cause more overhead then the alternative?

I have tested this with the following in my index.php:

$include = new JIncludes();
$include->getClasses();
$include->getCoreTop();

$db = new DB('local');
$db->prepare('String');

The source shows the html from my head.php file fine and my PDO DB class works as well. Am I over-complicating things?


texts: Object-oriented implementation of a real-world scenario of using a bathroom

texts:
Is there any object oriented way or design pattern I can use to make this code better? How can I avoid casting in this code? What if I add new Object like WaterTank how will it interact with fitting?

Run.java

package main;

import fittings.Fitting;
import fittings.Tap;
import bathroom.Bathroom;
import user.User;

public class Run {

    public static void main(String[] args) {

        User rutvik = new User("rutvik");

        Bathroom bathroom = new Bathroom(rutvik);

        bathroom.getBathroomFitting(Fitting.TAP).use(rutvik);

        ((Tap)bathroom.getBathroomFitting(Fitting.TAP)).controlSpeed();

    }

}

User.java

package user;

import bathroom.BathroomUser;

public class User implements BathroomUser {

    String userName;

    public User(String userName){
        System.out.println("constructing user... "+userName);
        this.userName=userName;
    }

    @Override
    public String getUserName(){
        return userName;
    }

}

Bathroom.java

package bathroom;

import java.util.ArrayList;
import user.User;
import fittings.Fitting;
import fittings.Tap;

public class Bathroom {

    BathroomUser user;
    ArrayList<Fitting> fittings;

    public Bathroom(User user){
        System.out.println("constructing bathroom...");
        System.out.println("assigning user... " + user.getUserName()+" to bathroom");
        this.user=user;
        fittings=new ArrayList<Fitting>();
        fittings.add(new Tap());
    }

    public Fitting getBathroomFitting(int fittingType){
        for(Fitting fitting:fittings){
            if(fitting.getFittingType()==fittingType){
                return fitting;
            }
        }
        return null;
    }
}

BathroomUser.java

package bathroom;

public interface BathroomUser {

    public String getUserName();

}

Fittings.java

package fittings;

import bathroom.BathroomUser;

public abstract class Fitting {

    public static final int TAP=0;
    public static final int SHOWER=1;
    public static final int SINK=2;

    public abstract void use(BathroomUser user);

    public abstract int getFittingType();

}

Tap.java

package fittings;

import bathroom.BathroomUser;

public class Tap extends Fitting {

    public Tap() {
        System.out.println("constructing TAP fitting...");
    }

    @Override
    public int getFittingType() {
        return Fitting.TAP;
    }

    @Override
    public void use(BathroomUser user) {
        System.out.println("Tap is in use... by " + user.getUserName());
    }

    public void controlSpeed(){
        System.out.println("Tap Speed Changed");
    }
}


texts: Transcribe .docx files via python-docx to modify font and font size. Need to reconstruct paragraphs in target files

texts:
The intention is to transcribe .docx files to have modified font and font sizes while keeping the run attributes such as bold, underline, italic etc. I'll then add some headers and graphics to the newly created target.docx files

How to reconstruct paragraphs from runs? Each one, currently, gets it's own separate line!

from docx import Document
from docx.shared import Pt

def main(filename):
    try:
        src_doc = Document(filename)
        trg_doc = Document()

        style = trg_doc.styles['Normal']
        font = style.font
        font.name = 'Times'
        font.size = Pt(11)

        for p_cnt in range(len(src_doc.paragraphs)):
            for r_cnt in range(len(src_doc.paragraphs[p_cnt].runs)):
                curr_run = src_doc.paragraphs[p_cnt].runs[r_cnt]
                print('Run: ', curr_run.text)
                paragraph = trg_doc.add_paragraph()

                if curr_run.bold:
                    paragraph.add_run(curr_run.text).bold = True
                elif curr_run.italic:
                    paragraph.add_run(curr_run.text).italic = True
                elif curr_run.underline:
                    paragraph.add_run(curr_run.text).underline = True
                else:
                    paragraph.add_run(curr_run.text)

        trg_doc.save('../Output/the_target.docx')

    except IOError:
        print('There was an error opening the file')

if __name__ == '__main__':
    main("../Input/Current_File.docx")

nput:

1.0 PURPOSE The purpose of this procedure is to ensure all feedback is logged, documented and any resulting complaints are received, evaluated, and reviewed in accordance with 21 CFR Part 820 and ISO 13485

Output:

PURPOSE The purpose of this procedure is to ensure

all feedback is logged,

documented and any resulting complaints are received,

evaluated, and reviewed

in accordance with 21 CFR P art 820

and ISO 13485 .


texts: Grabbing resolution and offset from xrandr

texts:
(using GNU sed)
I want to grab some output from xrandr and leave out everything but the resolution and offset.
Input:
eDP1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 290mm x 160mm
   1366x768      60.02*+
   1280x720      59.74
   ...
   640x360       59.84    59.32    60.00
HDMI1 connected primary 2560x1440+1366+0 (normal left inverted right x axis y axis) 610mm x 350mm
   3840x2160     30.00 +  25.00    24.00    29.97    23.98
   2560x1440     59.95*
   ...
   720x400       70.08

Desired output:
1366x768+0+0
2560x1440+1366+0

This is my current command:
xrandr | sed -e '/^\ /d' -e 's/.*\(\<.*x[0-9]*+[0-9]*+[0-9]*\).*/\1/'

The first expression deletes all the lines that begin with spaces, leaving
eDP1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 290mm x 160mm
HDMI1 connected primary 2560x1440+1366+0 (normal left inverted right x axis y axis) 610mm x 350mm

Then the second expression find the resolution/offset and throws away everything else.
How could I make the regex cleaner?


texts: SFINAE with several condition [Refactoring]

texts:
How can I write this function shorter?

template<typename U, typename = typename std::enable_if<std::is_fundamental<U>::value>::type,
    typename = typename std::enable_if<!std::is_same<char, U>::value>::type,
    typename = typename std::enable_if<!std::is_same<void, U>::value>::type
>
void multiply(U&& u){};

I want exclude several type like void or char, which don't must be number. I wrote code like this, but I think, that is better solution. (code of course is correctly)


texts: My implementation of repository pattern in Laravel 5.6

texts:
<?php

namespace App\Repositories;

use App\Contracts\{
    CompanyInterface,
    ImageUploaderInterface
};
use App\Models\Company;
use Illuminate\Support\Facades\Auth;

class CompanyRepository implements CompanyInterface
{
    protected $imageUploaderRepository;

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

    public function myCompany(): Company
    {
        $companies = Auth::user()->companies;

        if ($companies && $companies->count() > 0) {
            return $companies->first();
        }

        return new Company();
    }

    public function upsert(Company $company, array $validated): Company
    {
        $company->name = $validated['name'];
        $company->address_number = $validated['address_number'];
        $company->address_street = $validated['address_street'];
        $company->address_city = $validated['address_city'];
        $company->address_region = $validated['address_region'];
        $company->address_postcode = $validated['address_postcode'];
        $company->address_country = $validated['address_country'];
        $company->address_geolocation = $validated['address_geolocation'];
        $company->contact_number = $validated['contact_number'];
        $company->contact_email = $validated['contact_email'];
        $company->fax_number = $validated['fax_number'];
        $company->opening_times = json_encode($validated['opening_times']);
        $company->timezone = $validated['timezone'];

        if (array_key_exists('logo', $validated)) {
            $this->imageUploaderRepository->deleteIfExists($company->logo);
            $company->logo = $this->imageUploaderRepository->uploadCompanyLogo($validated['logo']);
        }

        $company->save();

        if ($company->wasRecentlyCreated) {
            $company->user()->attach(Auth::user());
        }

        return $company;
    }
}

This works as expected, however I am not entirely sure if what I have done adheres to S.O.L.I.D principles and infact a good implementation of repository pattern.

Given the contexts:

I have two models (User and Company) and the relationship between the two is many-to-many
The relationship is enabled via a pivot table (user_company)
At the moment, a user can only have one company, later I will be making it possible for a user to own more than one company.
Company's logo can be replaced with a new one.

My issue / what I am unsure of is;

Is it okay that I use Auth::User in this repository? or should the logic of loading user's myCompany be put in UserRepository?
Is it okay for me to use another repository (e.g. imageUploaderRepository) in this repository?
Should controller be the one to orchestrate the logo uploading and not mix the operation in the company repo?
Is it okay that I do the many-to-many linking (via attach) in this repo? or should the controller do it?

P.S. this is how I use the repo in my controller:

public function save(SaveCompanyRequest $request)
{
    $company = $this->companyRepository->myCompany();
    $validated = $request->validated();

    $this->companyRepository->upsert($company, $validated);

    return redirect()
        ->back()
        ->with('status', 'Company details updated.');
}

And here are my interfaces:

Contracts\CompanyInterface - https://pastebin.com/sF1izT4D
Contracts\DateTimeInterface - https://pastebin.com/8BH9pUdQ
Contracts\ImageUploaderInterface - https://pastebin.com/WJFQy0SK

And the other two repositories i am using in CompanyInterface:

Repositories\DateTimeRepository - https://pastebin.com/8xCAX00p
Repositories\ImageUploaderRepository - https://pastebin.com/XXuECLSD

Lastly, the two related models:

Models\User - https://pastebin.com/YCw1rGZL
Models\Company - https://pastebin.com/cu54xknR