shared_ptr implementation I've written a linked-list version of something like shared_ptr, which gets destroyed when the last copy of a pointer is destroyed.

Aside from the thread-unsafety, is it a fine implementation? Anything I could improve?

Also, what's the best way to extend it to make it work with HANDLEs, etc., without repeating (or limiting) myself unnecessarily, while avoiding excess verbosity (e.g. auto_<HANDLE, custom_deallocator<HANDLE> > is considered too verbose)?

template<typename T>
class auto_
{
    T *pValue;
    mutable const auto_<T> *pPrev, *pNext;

public:
    auto_()           : pValue(new T()),  pPrev(NULL), pNext(NULL) { }
    auto_(T *pValue)  : pValue(pValue),   pPrev(NULL), pNext(NULL) { }
    auto_(const T &v) : pValue(new T(v)), pPrev(NULL), pNext(NULL) { }
    auto_(const auto_<T> &o) : pValue(o.pValue), pPrev(&o), pNext(NULL) { o.pNext = this; }

    virtual ~auto_()
    {
        const auto_<T> *const pPrev = this->pPrev, *const pNext = this->pNext;
        if (pPrev != NULL) { pPrev->pNext = pNext; }
        if (pNext != NULL) { pNext->pPrev = pPrev; }
        if (pPrev == NULL && pNext == NULL) { delete this->pValue; }
        this->pPrev = this->pNext = NULL;
        this->pValue = NULL;
    }

    auto_<T>& operator=(const auto_<T>& other)
    {
        if (this != &other)
        {
            this->~auto_();
            this->pValue = other.pValue;
            this->pPrev = &other;
            this->pNext = other.pNext;
            if (other.pNext != NULL) { other.pNext->pPrev = this; }
            other.pNext = this;
        }
        return *this;
    }

    operator   T&() /*also const version*/ { return *this->pValue; }
    operator   T*() /*also const version*/ { return  this->pValue; }
    T* operator->() /*also const version*/ { return  this->pValue; }
    T& operator *() /*also const version*/ { return *this->pValue; }
};

Sample usage:

template<typename T>
T recurse(T value, int depth)
{
    if (depth > 0) { T result = recurse(value, depth - 1); return result; }
    else { return value; }
}

auto_<int> test()
{
    printf("Value: %d\n", *recurse(auto_<int>(10), 3));
    auto_<int> p1 = recurse<auto_<int> >(5, 3);
    printf("Value: %d\n", *p1);
    auto_<int> p2 = 3;
    p1 = p2;
    p2 = p1;
    return p2;
}

Implementing your own smart pointer is very hard please don't try.

If it is just to try and learn then fine you may learn something but after practicing go back to one that has been tested and is know to work.

20 seconds into looking Bug 1:

int main()
{
    auto_<int>   x;
    auto_<int>   y(x);
    auto_<int>   z(x);
}

Problem caused by this line:

auto_(const auto_<T> &o)
   : pValue(o.pValue)
   , pPrev(&o)
   , pNext(NULL)
{
    o.pNext = this;   // Here you are overwriting x.pNext when building z
}                     // It may or may not cause a bug but it was definitely
                      // not what you intended to do.

You now have

pNext List
[X] -> [Z] -> |    Y/Z point at nothing
       [Y] -> |    X   points at Z

pPrev List
[Y] -> [X] -> |    Y/Z point at X
[Z] ----^          X   points at nothing.

                   One assumes you are trying to create a circular list!

Don't use hungarian notation

pValue

Do you really want to bind your object to always using pointers?
Just use logical names for the members try not to encode type information into the name of the member it already has that information in its type.

Style Tip

Don;t do this:

    const auto_<T> *const pPrev = this->pPrev, *const pNext = this->pNext;

It really hard to read. You are doing complex enough stuff try and make it easy to read

    auto_<T> const* const pPrev = this->pPrev
    auto_<T> const* const pNext = this->pNext;

Don't do pointless work

    this->pPrev = this->pNext = NULL;
    this->pValue = NULL;

This does nothing. This object is going to be destroyed. Therefore these variables do not exist after the destructor exists. So little point in playing with their values just before destruction.

Don't manually call the destructor

        this->~auto_();

Nobody expects people to do this. Its just confusing. Move the code in the destructor into another method and call that.

Broken link

If sombody inserts a NULL pointer into your smart pointer you are asking for trouble when they de-reference it.

auto_<int>  x(NULL); // valid constructor

This is going to blow up

operator   T&() /*also const version*/ { return  *this->pValue; }

You either need to check the ptr on construction (to make sure it is never NULL) or if you allow NULL pointers then you need to check when the object is used.

Specialization

To avoid repeating yourself allow your code to be specialized by a second template parameter that understands how to reclaim the resources of different types. The default version just calls delete but this allows you to use specialize it for handles etc.

Circular lists are easier with no NULL pointers.

template<typename T>
struct Deleter
{
    void operator()(T* ptr) const { delete ptr;}
};

template<typename T, typename D = Deleter<T> >
class my_auto
{
    T *value;
    mutable const my_auto<T>* prev;
    mutable const my_auto<T>* next;

    public:
    // set up the chain to be circular pointing at just itself.
    // This way next/prev will never be NULL and we don't need to test
    my_auto()           : value(new T()),  prev(this), next(this) { }
    my_auto(T *value)   : value(value),    prev(this), next(this) { if (value == 0) throw int(1);}
    my_auto(const T &v) : value(new T(v)), prev(this), next(this) { }

    // insertInto() will do that appropriate set up.
    // We are currently not in a chain and have no value to release.
    my_auto(const my_auto<T> &o)
    {
        insertInto(o);
    }

    my_auto<T>& operator=(const my_auto<T>& other)
    {
        // Check for assignment to self
        if (this != &other)
        {
            testAndDestroy();
            removeFromChain();
            insertInto(other);
        }
        return *this;
    }

    ~my_auto()
    {
        testAndDestroy();
        removeFromChain();
    }

    private:
        // If next == this then this is the only node in the chain
        // So we destroy the data portion.
        void testAndDestroy()
        {
            if (next == this)
            {
                D     deleter;
                deleter(value);
            }
        }
        // Unlink this node from the chain.
        // If we are the only link in the chain it still works
        // we just remain linked to ourselves.
        void removeFromChain()
        {
            // Remove this node from the chain
            prev->next  = next;
            next->prev  = prev;
        }
        // Insert into another chain.
        // Assumes that we are not part of another chain
        // and that our data has already been released as required.
        void insertInto(const my_auto<T>& other)
        {
            value           = other.value;

            next            = other.next;
            other.next.prev = this;

            prev            = other;
            other.next      = this;
        }
};

If you want to use a non circular list (then you need to fix the constructor)

auto_(const auto_<T> &o)
    : pValue(o.pValue)
    , pPrev(&o)
    , pNext(o.pNext)                      // Fix this line
{
    if (o.pNext) { o.pNext.prev = this;}  // Add this line
    o.pNext = this;
}
// Your code assumes the node is always added to the end of the list
// You can not guarantee this. So you need to take account of being
// inserted into the middle.


Linear Regression on random data Wrote a simple script to implement Linear regression and practice numpy/pandas. Uses random data, so obviously weights (thetas) have no significant meaning. Looking for feedback on

Performance
Python code style
Machine Learning code style

# Performs Linear Regression (from scratch) using randomized data
# Optimizes weights by using Gradient Descent Algorithm

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

np.random.seed(0)

features = 3
trainingSize = 10 ** 1
trainingSteps = 10 ** 3
learningRate = 10 ** -2

randData = np.random.rand(trainingSize, features + 1)
colNames = [f'feature{i}' for i in range(1, features + 1)]
colNames.append('labels')

dummy_column = pd.Series(np.ones(trainingSize), name='f0')
df = pd.DataFrame(randData, columns=colNames)

X = pd.concat([dummy_column, df.drop(columns='labels')], axis=1)
y = df['labels']
thetas = np.random.rand(features + 1)

cost = lambda thetas: np.mean((np.matmul(X, thetas) - y) ** 2) / 2
dJdtheta = lambda thetas, k: np.mean((np.matmul(X, thetas) - y) * X.iloc[:, k])
gradient = lambda thetas: np.array([dJdtheta(thetas, k) for k in range(X.shape[1])])

# J(theta) before gradient descent
print(cost(thetas))

# Perform gradient descent
errors = np.zeros(trainingSteps)
for step in range(trainingSteps):
    thetas -= learningRate * gradient(thetas)
    errors[step] = cost(thetas)

# J(theta) after gradient descent
print(cost(thetas))

# Plots Cost function as gradient descent runs
plt.plot(errors)
plt.xlabel('Training Steps')
plt.ylabel('Cost Function')
plt.show()

Welcome!

Your first two lines are nice comments. Consider putting them in a module docstring:

"""Performs Linear Regression (from scratch) using randomized data.

Optimizes weights by using Gradient Descent Algorithm.
"""

Consider adding random noise to something linear (or to some "wrong model" sine or polynomial), rather than to a constant.

np.random.seed(0)

Nice - reproducibility is Good.

trainingSize = 10 ** 1
trainingSteps = 10 ** 3
learningRate = 10 ** -2

These expressions are correct and clear. But why evaluate a FP expression when you could just write it as a literal? 1e1, 1e3, 1e-2. (This answer would apply in many languages, including Python. And yes, I actually prefer seeing the two integers written as floating point, even if that forces me to call int() on them.)

PEP8 asks that you spell it training_size, and so on. Please run flake8, and follow its advice.

Your column names expression is fine. Consider handling the one-origin within the format expression:

col_names = [f'feature{i + 1}' for i in range(features)] + ['labels']

Specifying axis=1 is correct. I have a (weak) preference for explicitly spelling out: axis='columns'.

Consider hoisting the expression np.matmul(X, thetas) - y, so it is only evaluated once.

The three lambda expressions are fine, but they don't seem to buy you anything. Probably better to use def three times.

Ship it! But do consider noising a linear function, to make it easier to evaluate your results.


HTML CSS Field Layout I've had some help designing my field boxes and I was hoping to get feedback on the code. The fields will increase in complexity which is why I thought to structure it this way (image upload fields, textbox with WYSIWYG controls etc.

CSS

.error { height: 27px; background-color: red; margin-bottom: 4px;}
.lft { float: left; }
ul, li { list-style-type: none; vertical-align:middle; }
.ts3 { font-size: 15px; }
.dc3 { background-color: #808080; }
.tc5 { color: #333333;}
.p4 { padding: 4px; }
.r2 { border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; }
.r6 { border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; }
.field { line-height:27px; font-family:arial, sans-serif; border-color: #d9d9d9; border-top:solid 1px #c0c0c0; }
input.field{width:100%}
.fieldwrapper{ padding: 0 5px 0 0; overflow: hidden;}
label{width:200px; display:inline-block; float:left}

HTML

Error!

Sender email address

<input class="field r2" placeholder="Email" type="text" value="">

This is just me explaining how to use this particular field. It is very interesting, don't you know...

JSfiddle link
LNIK

If the input with the placeholder="Email" is actually an email address, then the type attribute should be set to email, not text.  (Reference: http://www.w3.org/TR/html-markup/input.email.html)
Declare an id attribute and a name attribute on the email field.  This will be necessary if you want to access the elements or their posted values explicitly. (Reference: http://reference.sitepoint.com/html/input/name , http://reference.sitepoint.com/html/core-attributes/id)
Once you have declared an id on the input, set the for attribute on the label equal to that id.  This will enable a behavior such that clicking on the label will focus on the input for the corresponding field.  (Reference: http://reference.sitepoint.com/html/label)
Use descriptive, semantic class names.  Good class names should indicate the nature of the content, not the format of the layout.  Instead of fieldwrapper try sender-email. (Reference : http://www.w3.org/QA/Tips/goodclassnames )
This depends on what HTML version you are using, but the HTML5 spec says that form elements should be wrapped in p tags, not divs.  (Reference: http://dev.w3.org/html5/spec/forms.html#writing-a-form's-user-interface)

The code that would correspond to my comments might look like :

    Sender email address:
    <input id="sender" name="sender" type="email" placeholder="Email" class="r2">

This is just me explaining how to use this particular field. It is very interesting, don't you know...

One thing you'll notice is that there are less CSS classes.  I have replaced the field-wrapper with email-input and completely removed the field class.  You can migrate the .field-wrapper CSS to the .email-input selector, and the field CSS to the .email-input > input selector.


WIFEXITED combined with WIFSIGNALED I am testing the WIFEXITED to see if a child process exited abnormally or normally. According to documentation, it should return a non-zero status for a child process that terminated normally.

#include <wait.h>
#include <unistd.h>
#include <iostream>
#include <sys/types.h>

int main(int argc, const char* const* argv) {
    int *pointer=NULL;
    int status;
    pid_t pid=fork();
    if (pid==0) {
        std::cout << "Child is: " << getpid() << std::endl;
        if (argc>1) {
            std::cout << getpid() << "Going to crash myself" << std::endl;
            *pointer=1; //Segmentation fault as of null pointer dereference
        }
        else
            pointer=NULL; //Safe code
    }
    else {
        std::cout << "Parent is: " << getpid() << std::endl;
        pid_t terminated=waitpid(-1, &status, 0);
        std::cout << "Child " << terminated << " exited ";
        if (WIFEXITED(status)) std::cout << "GOOD";
        else {
             std::cout << "BAD";
             // Is it worth here to also check for WIFSIGNALED or is it redundant?
        }
        std::cout << std::endl;
    }
    std::cout << getpid() << " exiting normally" << std::endl;
    return 0;
}

To test a normal exit, call it without arguments, and an abnormal exit with segmentation fault, call it with some parameters.

Furthermore, if I use WIFSIGNALED it detects correctly the bad status, then, what's the use for WIFEXITED?

Is it advisable to use only WIFEXITED, or do you advise also to use WIFSIGNALED for further checks? Is this combination useful or redundant?

WIFSIGNALED / WIFSTOPPED
If you get into the "BAD" case, you may want to check whether WIFSIGNALED is true or WIFSTOPPED is true.  WIFSIGNALED tells you if the program terminated with a signal (such as segv).  WIFSTOPPED tells you if the program is currently stopped (but not terminated).
If your child process can never be stopped, then you can assume that it terminated abnormally and not bother checking those macros.  In your particular example, your child will either segfault or exit right away, so it's unlikely that someone would be able to kill -STOP your process before it crashed.


Longest Substring without Repeating Characters Problem - Kotlin Recursion I am practicing coding questions on leetcode. I have been an OOP my whole career, and I am trying to wade into the dark abyss that is functional programming. So I am trying to do things purely functional, e.g. using recursion to try to get to the answer. The problem statement is this: Given a string, find the length of the longest substring without repeating characters.

Sorry for asking literally this leetcode question that everybody else is asking :D

I have coded up this solution -

class Solution {
    fun lengthOfLongestSubstring(str: String): Int {
        return when {
            str.length == 1 -> 1
            str.isEmpty() -> 0
            else -> helper(str, 0, 1, 0)
        }
    }

    private tailrec fun helper(str: String, leftIndex: Int, rightIndex: Int, max: Int): Int {
        return when {
            rightIndex >= str.length+1 -> max
            rightIndex >= str.length && isDistinct(str.substring(leftIndex)) ->
                helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))
            isDistinct(str.substring(leftIndex, rightIndex)) ->
                helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))
            else -> helper(str, leftIndex + 1, leftIndex + max + 1, max)
        }
    }

    private fun isDistinct(substring: String): Boolean {
        return substring.toList().distinct().size == substring.length
    }
}

I have a couple specific questions -
I am using the sliding window approach, is that appropriate in a functional setting? If not, what is a better approach functionally, speaking.

Is there redundancy in my recursion function that I can get rid of?

What things can I do to improve the legibility of the function? Clean code is always best!

What further steps can I take to optimize the solution? Currently this solution is only faster than 10% of other solutions (though those are likely imperative solutions)

Any other tips you can provide outside of the bounds of my question that can help would be awesome. I am also brand new to kotlin programming.

I don't necessarily hate this solution, but I'm sure it can be better. Please advise.

Note, I don't think about performance, only about kotlin.
Iluminate branch
in your when, you check if the rightIndex >= string.length+1.
this means in the next branches the size is maximal string.length.
Substring is exclusive, so it allows str.length.
this means the second and third branches are identical.
Use Set
It would make more sense to me to use toSet instead of toList.distinct, because sets are meant to hold distinct versions.
personal Choices:
Single-expression function
A single-expression-function is a function with one expression .
In kotlin, you can write this in an easier way.
Instead of writing
fun lengthOfLongestSubstring(str: String): Int {
    return when {
        ...
    }
}

you can write
fun lengthOfLongestSubstring2(str: String): Int = when {
    ...
}

or even without return-type:
fun lengthOfLongestSubstring2(str: String) = when {
    ...
}

I personally like to write these like:
fun helper(
    str: String,
    leftIndex : Int,
    rightIndex : Int,
    max: Int
) = when {
    ...
}

function with receiver
If I'm right functional means:

The function knows about the type and the type doesn't know about the function
If a function receives the same input, it should return the same output

(or only the later)
The first way is often expressed by having a function that only takes parameters, but is not called on an object: b(a) instead of a.b()
Kotlin allows to let a function like b(a) look like a.b(), if you define it that way.   This is called a function with receiver.
Note, inside de function-body, you refer to the receiver using this.
isDistinct("hi")
private fun isDistinct(
    substring: String
): Boolean = substring.toSet().size == substring.length

can be rewritten to
"hi".isDistinct()
private fun String.isDistinct() : Boolean = this.toSet().size == this.length

And as you don't have to call this inside a scope:
"hi".isDistinct()
private fun String.isDistinct() : Boolean = toSet().size == length

Or just:
"hi".isDistinct()
private fun String.isDistinct() = toSet().size == length

Under the scenes it's still the same function.
Inside kotlin, you can't call it the old way anymore
New code
class Solution {
    fun lengthOfLongestSubstring(
        str: String
    ) = when {
        str.length == 1 -> 1
        str.isEmpty() -> 0
        else -> helper(str, 0, 1, 0)
    }

    private tailrec fun helper(
        str: String,
        leftIndex: Int,
        rightIndex: Int,
        max: Int
    ): Int = when {
        rightIndex >= str.length + 1 -> max
        str.substring(leftIndex, rightIndex).isDistinct() ->
            helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))
        else -> helper(str, leftIndex + 1, leftIndex + max + 1, max)
    }

    private fun String.isDistinct() = toSet().size == length
}


WSGI static file handler I put up a simple WSGI static file handler, but I'm skeptical about its efficiency, also because I got a handful of errors while benchmarking it with Apache Benchmark.

The errors are:

IOError: [Errno 24] Too many open files: 'test.png'
Client 101 hit errno 32
Client 601 hit errno 32
Client 408 hit errno 32
Client 225 hit errno 32
Client 668 hit errno 32
Client 415 hit errno 32
Client 237 hit errno 32
Client 316 hit errno 104
...

This is what brought me to think it's inefficient.

The following is the Wsgi static file handler:

import bjoern
import os

# Get file size
size = os.path.getsize("test.png")

def app(environ, start_response):
    status = "200 OK"
    # Open image file
    the_file = open("test.png", "rb")
    response_headers = [ ('Content-Type', 'image/png'), ('Content-length', str(size)) ]

    start_response( status, response_headers )

    # return the entire file
    if 'wsgi.file_wrapper' in environ:
        # Return env[wsgi.fw](file, block size)
        return environ['wsgi.file_wrapper'](the_file , 1024)
    else:
        return iter(lambda: the_file.read(1024), '')

bjoern.run(app, "localhost", 8000)

Any advice/tips/suggestions?

In total, a process in Unix systems can have a limited number of open filehandles. By default this is only say 1024 per process in Linux; all of the open sockets also consume file descriptors. Even if you optimize the system, then reading the file for each request will be costly.

In this case, if you are really concerned about the performance, read the image into memory (as bytes/str), and send it from there instead:

with open('test.png', 'rb') as f:
    image_data = f.read()

...

    return ( image_data, )

However if you have a veery big file, then you could mmap it into memory in the beginning of the process (this consumes just 1 file descriptor) globally and send it from there in each client:

im_file = open('verybigfile.iso', 'rb')
mm = mmap.mmap(im_file, 0)

    ...
    return ( mm, )

Both of these would save you 1 file descriptor per a client requesting the file.

However, if you need to serve lots of files like this, then you might want to increase the limit of open file descriptors per a process, use a front-side cache such as Varnish and/or scale up into multiple processes, or hosts, or even use a CDN to deliver your files.


use regex to separate a list of serial numbers into multiple lists with matched prefix The question comes from How to separate a list of serial numbers into multiple lists with matched prefix? on Stack Overflow.
Input:

sn = ['bike-001', 'bike-002', 'car/001', 'bus/for/001', 'car/002', 'bus/for/002']

Intended output:

# string with same prefix will be in the same list, e.g.:

sn1 = ['bike-001', 'bike-002']
sn2 = ['car/001', 'car/002']
sn3 = ['bus/for/001', 'bus/for/002']

The original thread already had a brilliant answer using .startswith(<sub_str>), however I still want to use regex to solve the question.
Here's what I've tried: I use re.sub() to get the prefix and re.search() to get the 3-digits serial number. I'd like to know if there is a better way (like using one-time regex function) to get the solution.
import re

sn = ['bike-001', 'bike-002', 'car/001', 'bus/for/001', 'car/002', 'bus/for/002']
sn_dict = {}
for item in sn:
    category = re.sub(r'\d{3}', "", item)
    number = re.search(r'\d{3}', item).group()
    if category not in sn_dict.keys():
        sn_dict[category] = []
    sn_dict[category].append(category + number)

After running the script we will have the following sn_dict:
{
    'bike-': ['bike-001', 'bike-002'],
    'car/': ['car/001', 'car/002'],
    'bus/for/': ['bus/for/001', 'bus/for/002']
}

You can do this with re.findall. Instead of iterating over each string, you can combine all the serial numbers into one string and use regex to find all the matches (this implementation assumes there are no spaces in the serial number).
import re

string_list = ['bike-001', 'bike-002', 'car/001', 'bus/for/001', 'car/002', 'bus/for/002']
string = ' '.join(string_list)
matches = re.findall(r"([^0-9])", string)
numbers = re.findall(r"([0-9]{3})", string)
prefixes = ''.join(c for c in matches).split()
result_dict = {}
for prefix, number in zip(prefixes, numbers):
    if prefix not in result_dict.keys():
        result_dict[prefix] = []
    result_dict[prefix].append(prefix + number)

The first re.findall searches for any string that is not a number. The second finds any succession of three numbers. The next line combines the characters in matches, and since we denoted that we separated each serial number by ' ', we can split using the same value. Then, we use the same code present in your question to populate the result dictionary.


Linked list with removal function in Rust I know there are other structures which are better than the linked list, but I want to implement a singly linked list which has a remove function for study.

After struggling for a few hours, I wrote this code.

use std::rc::Rc;
use std::cell::RefCell;

type Link<T> = Option<Rc<RefCell<Node<T>>>>;

struct Node<T> {
    elem: T,
    next: Link<T>,
}

impl<T> Node<T> {
    fn new(elem: T) -> Rc<RefCell<Self>> {
        Rc::new(RefCell::new(Node {
            elem: elem,
            next: None,
        }))
    }
}

pub struct List<T> {
    head: Link<T>,
}

impl<T: Eq> List<T> {
    pub fn new() -> Self {
        List { head: None }
    }

    pub fn push(&mut self, elem: T) {
        let new_head = Node::new(elem);
        match self.head.take() {
            Some(old_head) => {
                new_head.borrow_mut().next = Some(old_head);
                self.head = Some(new_head);
            }
            None => {
                self.head = Some(new_head);
            }
        }
    }

    pub fn remove(&mut self, elem: T) {
        let mut head = self.head.clone().unwrap();
        if head.borrow().elem == elem {
            self.head = head.borrow().next.clone();
            return;
        }

        loop {
            let next = head.borrow().next.clone();
            match next {
                None => return,
                Some(ref node) => {
                    if node.borrow().elem == elem {
                        head.borrow_mut().next = node.borrow().next.clone();
                    }
                    head = node.clone();
                }
            }
        }
    }
}

fn main() {
    let mut list = List::new();
    list.push(3);
    list.push(2);
    list.push(1);
    list.remove(2);
    let head = list.head.unwrap().clone();
    assert_eq!(head.borrow().elem, 1);
    let next = head.borrow().next.clone().unwrap();
    assert_eq!(next.borrow().elem, 3);
}

To iterate this list, I implemented a iterator.

pub struct Iter<T> {
    next: Link<T>
}

impl<T> Iterator for Iter<T> {
    type Item = Rc<RefCell<Node<T>>>;

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.next.clone();
        let next_next = next.clone();
        self.next = match next_next {
            Some(node) => {
                node.borrow().next.clone()
            }
            None => {
                None
            }
        };
        next
    }
}

impl<T: Eq> List<T> {
    pub fn iter(&self) -> Iter<T> {
        Iter { next: self.head.clone() }
    }
}

fn main() {
    let mut list = List::new();
    list.push(3);
    list.push(2);
    list.push(1);
    list.remove(2);

    let mut it = list.iter();
    let next_node = it.next().unwrap();
    assert_eq!(next_node.borrow().elem, 1);
    let next_node = it.next().unwrap();
    assert_eq!(next_node.borrow().elem, 3);
    let next_node = it.next();
    assert_eq!(next_node.is_none(), true);
}

I'm not sure this code is good, because I think

there are too many clone() or borrow() calls.
code is long and not simple. (is using Rc and RefCell good?)

Are there easier or simpler ways?

Even if this code is not so bad, are there weak or dangerous points?

Read Learning Rust With Entirely Too Many Linked Lists.
Your code has compilation errors with Rust 1.18.0.

error[E0446]: private type `Node<T>` in public interface
  --> src/main.rs:82:5
   |
82 |     type Item = Rc<RefCell<Node<T>>>;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't leak private type

I derive Debug on almost every struct.
push can have all conditionals removed from it because doing
nothing is the same as setting None as the next value.
remove panics when called on a newly-created list.
pushing 1, 1, 1, 1, 2 and then removing 1 results in the list 2->1->1 which doesn't seem any flavor of correct. I assume you wanted to remove the first match.
It's way easier to get the code right when it operates on the same level of abstraction. I've created a method that removes on a &mut Link<T> because that's the shared type between List and Link.
Honestly, it's also easier to get this right with recursive code as well.
Doesn't make sense to return the Rc<RefCell<...>> as the iterator type - people care about the values, not the collection.
Can simplify the iterator by just taking the value out of the iterator state and putting a new value in sometimes.

use std::rc::Rc;
use std::cell::RefCell;

type Link<T> = Option<Rc<RefCell<Node<T>>>>;

#[derive(Debug)]
pub struct Node<T> {
    elem: T,
    next: Link<T>,
}

impl<T> Node<T> {
    fn new(elem: T) -> Rc<RefCell<Self>> {
        Rc::new(RefCell::new(Node {
            elem: elem,
            next: None,
        }))
    }
}

#[derive(Debug)]
pub struct List<T> {
    head: Link<T>,
}

impl<T: Eq> List<T> {
    pub fn new() -> Self {
        List { head: None }
    }

    pub fn push(&mut self, elem: T) {
        let new_head = Node::new(elem);
        new_head.borrow_mut().next = self.head.take();
        self.head = Some(new_head);
    }

    pub fn remove(&mut self, elem: T) {
        fn remove_inner<T: Eq>(node: &mut Link<T>, elem: T) {
            if let Some(ref mut n) = node.clone() {
                if elem == n.borrow().elem {
                    *node = n.borrow_mut().next.take();
                    return
                }

                remove_inner(&mut n.borrow_mut().next, elem);
            }
        }

        remove_inner(&mut self.head, elem)
    }
}

fn main1() {
    let mut list = List::new();
    list.push(3);
    list.push(2);
    list.push(1);
    list.remove(2);
    let head = list.head.unwrap().clone();
    assert_eq!(head.borrow().elem, 1);
    let next = head.borrow().next.clone().unwrap();
    assert_eq!(next.borrow().elem, 3);

    let mut list = List::new();
    list.remove(2);

    let mut list = List::new();
    list.push(1);
    list.push(1);
    list.push(1);
    list.push(1);
    list.push(2);
    list.remove(1);
    println!("{:?}", list);
}

pub struct Iter<T> {
    next: Link<T>,
}

impl<T> Iterator for Iter<T> {
    type Item = Rc<RefCell<Node<T>>>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.next.take() {
            Some(next) => {
                self.next = next.borrow().next.clone();
                Some(next)
            }
            None => None,
        }
    }
}

impl<T: Eq> List<T> {
    pub fn iter(&self) -> Iter<T> {
        Iter { next: self.head.clone() }
    }
}

fn main2() {
    let mut list = List::new();
    list.push(3);
    list.push(2);
    list.push(1);
    list.remove(2);

    let mut it = list.iter();
    let next_node = it.next().unwrap();
    assert_eq!(next_node.borrow().elem, 1);
    let next_node = it.next().unwrap();
    assert_eq!(next_node.borrow().elem, 3);
    let next_node = it.next();
    assert_eq!(next_node.is_none(), true);
}

fn main() {
    main1();
    main2();
}

Frankly, I don't know why you used Rc and RefCell — they aren't needed to implement a singly linked list. There's no need for complicated shared ownership (no need for Rc) and there's no need for interior mutability (no need for RefCell).


Which name should I choose for private abstract functionality with a public proxy? I have an abstract class implementing some concrete functionality for its child classes:

abstract class Function {
  def eval: Double = some_concrete_functionality_which_calls_fEval
  def simplify: Funcion = more_concrete_calling_fSimplify

  protected def fEval: Double
  protected def fSimplify: Funcion
}

The child classes should implement fEval and fSimplify themselves, while eval and simplify act like a public proxy between them to provide common functionality before calling the actual implementation.

f stands for function but, although I feel fName is not very expressive, I can't think of any good alternatives (besides concreteEval which seems very bloated.)

Any suggestions? Should I stick to concreteEval? Maybe keep it like it is?

I think that it's more a matter of taste. If I were to come along behind you, I wouldn't have any particular problem with fEval and fSimplify.

I'm not sure that I would like concreteEval.

In my own code I tend to use doEval, but I could also imagine using evalImpl or myEval, depending on what it is exactly that is being done by these functions.


Select a quote from a list randomly I'm working on a Random Quote Generator Project, and as part of the project, the second instruction is to create a getRandomQuote Function which

should take in one parameter that will later get passed into this function when it is invoked will be the array of quotes.
The body of the function should select and return a random quote object from the quotesarray.

I'm kinda confused with my code, I want a review on my code as to whether its fits the instruction.
Below is my code, thanks!!

// An array of Objects with the quote and source as properties
var quotes = [
    {
        quote: "In the end, it’s not the years in your life that count. It’s the life in your years",
        source: "Abraham Lincoln",

    },
    {
        quote: "Don’t gain the world and lose your soul, wisdom is better than silver or gold",
        source: "Bob Marley",

    },
    {
        quote: "Lighten up, just enjoy life, smile more, laugh more, and don’t get so worked up about things",
        source: "Kenneth Branagh",

    },
    {
        quote: "Don’t cry because it’s over, smile because it happened",
        source: "Ludwig Jacobowski",

    },
    {
        quote: "Do stuff. Be clenched, curious. Not waiting for inspiration’s shove or society’s kiss on your forehead. Pay attention. It’s all about paying attention. Attention is vitality. It connects you with others. It makes you eager. Stay eager",
        source: "Susan Sontag",

    }
];

// getRandomQuote function selects and returns a random quote object
function getRandomQuote(array) {
    for (var i = 0; i < quotes.length; i++) {
        var quoteIndex = Math.floor(Math.random() * quotes.length);
        var randomQuote = quoteIndex;
    }
    return randomQuote;
}

Random item from array

You don't need the for loop to select a random item from an array.

Just get an index using Math.floor(Math.random() * array.length)

function getRandomQuote(array) {
    return array[Math.floor(Math.random() * array.length)];
}

Or as an arrow function, and you don't need the get part of the function name that is implied.

const randomQuote = array => array[Math.floor(Math.random() * array.length)];

You can also use bitwise or zero | 0 in place of the Math.floor function

const randomQuote = array => array[Math.random() * array.length | 0];

Random pick from array

If you wish to ensure each quote is randomly selected and not repeating until all have been randomly selected you can create a copy of the array, and pick items from that using Array.splice until empty, then copy the source array again.

For example the function encapsulates array and source You must first call the function with an array, then any other calls will return a random item that does not repeat until all items have been picked.

const randomQuote = (() => {
    const picked = []; // to hold picked items
    var source;   // array of items to pick from
    return srcArray => {
        if (srcArray) {
            source = srcArray;
            picked.length = 0;
        } else {
            if (!picked.length) { picked.push(...source) }
            return picked.splice(Math.random() * picked.length | 0, 1)[0];
        }
    }
})();

randomQuote(["a","b","c","d","e","f"]); // set up the source array
console.log(randomQuote()); // display random quote in console.

At any time you can reset the source array by calling the function with an array.

Random and the array, common functions

Here is a set of common functions that use random to access arrays. Rather than have functions rely on each other, each function is written to be entirely stand alone. If you use many of them it will pay to encapsulate them all in an object.

const randItem = arr => arr[Math.random() * arr.length | 0];
const randPick = arr => arr.splice(Math.random() * arr.length | 0, 1)[0];
const randPut = (arr, item) => arr.splice(Math.random() * (arr.length + 1) | 0, 0, item);
const randShuffle = arr => {
    var len = arr.length
    while (len) {
        arr.push(arr.splice(Math.random() * (len--) | 0, 1)[0]);
    }
    return arr;
}
const randPlay = (arr, repeat) {
    var item;
    repeat = repeat > arr.length ? arr.length : repeat
    arr.push(item = arr.splice(Math.random() * repeat | 0, 1)[0]);
    return item;
}

What they do.

randItem(array)  return a random item but does not remove it
randPick(array)  returns a random item removing it from the array
randPut(array, item) randomly inserts the item into the array
randShuffle(array) Shuffles the array in place (does not make a copy)
randPlay(array, number) A variation on the no repeat, selects random items from the bottom number items. Good for play lists when you dont want to repeat the same track. Use with randShuffle on the array before you call randPlay. The same item will not play again until another array.length - number items have played.


Javascript Minesweeper (with Stack Snippets!) As Stack Snippets are live on Code Review now, I wanted to do something quick in it as part of rolfl's challenge on meta. And when you make things quick, they probably get dirty. And when things get dirty, you refactor. And when you don't know how to refactor, you post it up for review.

So, as many of my previous questions has been about Minesweeper probabilities, what better thing to make than a Minesweeper game?

This minesweeper game does not have any probability-calculations or other cool stuff though, that will have to wait until version 2.0 :) It's not the multiplayer variant Minesweeper Flags either. Just plain old Minesweeper. I decided to go with the 'Intermediate' setting, i.e. 16 x 16 with 40 mines.

It has been a while since I did any real JS coding, but I don't consider myself a beginner in it.

By the way, don't be afraid if it says 'Kaboom' on your first click. It's a bug feature, not a feature bug.

Stack-Snippet with JS + HTML: (a slightly modified version can be found on github)

var elements = [];
var fields = [];
var allFields = [];

function showField(thisButton) {
  var thisX = Number(thisButton.attr('data-x'));
  var thisY = Number(thisButton.attr('data-y'));
  var button = fields[thisY][thisX];
  var number = Number(button.attr('data-value'));
  thisButton.attr('data-visible', true);
  if (button.attr('data-mine') === 'true') {
    button.text('X');
    alert('KABOOM!');
    allFields.forEach(function(entry) {
      entry.attr('disabled', true);
    });
  }
  else if (number === 0) {
    button.text(number);
    for (var xx = thisX - 1; xx <= thisX + 1; xx++) {
      for (var yy = thisY - 1; yy <= thisY + 1; yy++) {
        if (fields[yy] !== undefined && fields[yy][xx] !== undefined) {
          var innerButton = fields[yy][xx];
          if (innerButton.attr('data-visible') === 'false') {
            showField(innerButton);
          }
        }
      }
    }
  }
  else {
    button.text(number);
  }
}

var table = $('#board').find('tbody');
for (var y = 0; y < 16; y++) {
  var tr = $('
');
  var row = [];
  for (var x = 0; x < 16; x++) {
    var td = $('');
    var button = $('<button>').text('_').attr('data-value', 0)
     .attr('data-x', x).attr('data-y', y).attr('data-visible', false)
     .attr('data-mine', false)
     .on('click', function() {
       showField($(this));
    });
    td.append(button);
    tr.append(td);
    row.push(button);
    elements.push(button);
    allFields.push(button);
  }
  fields.push(row);
  table.append(tr);
}

// Generate mines
for (var mines = 0; mines < 40; mines++) {
  var random = Math.floor(Math.random() * elements.length);
  var field = elements[random];
  var thisX = Number(field.attr('data-x'));
  var thisY = Number(field.attr('data-y'));
  field.attr('data-mine', true);
  for (var xx = thisX - 1; xx <= thisX + 1; xx++) {
    for (var yy = thisY - 1; yy <= thisY + 1; yy++) {
      if (fields[yy] !== undefined && fields[yy][xx] !== undefined) {
        var innerButton = fields[yy][xx];
        var previous = Number(innerButton.attr('data-value'));
        innerButton.attr('data-value', previous + 1);
      }
    }
  }
  elements.splice(random, 1);
}

Primary concerns:

Is it a good idea to use data-* attributes to store the data? It kinda makes it quite easy to cheat...
Am I using the features of JQuery in a good way?
Any other comments welcome! Don't be afraid to hurt my feelings, I'm more of a Java guy anyway...

thisButton.attr('data-x')

You can use jQuery's .data(). It uses an internal cache for storing key-value pairs, but if it doesn't find it there, it looks up the data-* attributes of the associated element. This means you can do thisButton.data('x'). Note that dash-space becomes camelCase.

Number(thisButton.attr('data-x'))

If you use jQuery's .data(), it automatically converts the type for you. If it finds "2", then it converts it to a number.

Also, you can use the unary + to convert strings to numbers. It's close to parseFloat(). Something like:

+"2" === 2

  Is it a good idea to use data-* attributes to store the data?

For a regular audience, maybe. For advanced users, you might want to do something else (unless they're just bored and want to play :P)

Use jQuery .data(). The data is stored in an internal cache rather than written as a data-* attribute. However, if you have reference to the element and call .data() against it, it could reveal the value. Also, afaik, the cache is accessible via jQuery._cache.
Use an internal mapping, and have the buttons only carry an index/coordinates. You can create a 2x2 array inside a closure which only your code can access. On click, you can announce the coordinates freely.

Also, any determined dev/skid can peek through using dev tools, so the best you can do is just make it harder to pick on.

  Am I using the features of JQuery in a good way?

Nothing wrong with it :D


Flexible presentation of a user's name based on a combination of available properties The goal is to add a new displayValue property to each object depending on what it has available out of Firstname, Lastname, Nickname and Name.

I'd like this cleaned up.

var data = [
    {
        Id: 132,
        Name: null,
        Firstname: "Sam",
        Lastname: null,
        Nickname: "Dim",

    },
    {
        Id: 162,
        Name: null,
        Firstname: "Junior",
        Lastname: "Dimmer",
        Nickname: null,
    },
    {
        Id: 132,
        Firstname: null,
        Lastname: null,
        Nickname: "Dimmest",
    },
    {
        Name: "No Light",
        Id: 132,
        Firstname: null,
        Lastname: null,
        Nickname: null
    }
]

function formatPeople(data) {

    var yesProp = function (prop) {
        return data[i].hasOwnProperty(prop) && data[i][prop] !== null;
    }

    var noProp = function (prop) {
        return data[i].hasOwnProperty(prop) && data[i][prop] === null;
    }

    for (var i = 0, len = data.length; i < len; i += 1) {
        // if it has the property Name
        if (yesProp('Name')) {
            data[i].displayValue = data[i].Name;
        }
        if (yesProp('Lastname')) {
            if (yesProp('Firstname')) {
                // if it has the property Lastname and Firstname
                data[i].displayValue = data[i].Lastname + ', ' + data[i].Firstname;
            } else {
                if (yesProp('Nickname')) {
                    // if it has the property Lastname and Nickname but not Firstname
                    data[i].displayValue = data[i].Lastname + ', ' + data[i].Nickname;
                } else {
                    // if it has the property Lastname but not Firstname or Nickname
                    data[i].displayValue = data[i].Lastname;
                }
            }
        } else {
            if (yesProp('Firstname')) {
                if (yesProp('Nickname')) {
                    // if it does not have the property Lastname but does have Firstname and Nickname
                    data[i].displayValue = data[i].Firstname + ', ' + data[i].Nickname;
                } else {
                    // if it does not have the property Lastname or Nickname but does have Firstname
                    data[i].displayValue = data[i].Firstname;
                }
            } else {
                if (yesProp('Nickname')) {
                    // if it does not have the property Lastname or Firstname but does have Nickname
                    data[i].displayValue = data[i].Nickname;
                }
            }
        }
    }

    return data;
};

First
Idiomatic javascript is to camelCase property names. consider the following:
{
    name: "No Light",
    id: 132,
    firstname: null,
    lastname: null,
    nickname: null
}

Your yesProp and noProp variables are very bad design. Hoisting allows the i variable to be in scope through es3 (to my recollection), but you should never try to take advantage of that. These functions should be rewritten to take the object they are operating on as a parameter.
Additionally, unless there should be some third undefined state, the opposite of yesProp should be !yesProp, not a different detection method.
yesProp is a poor description for the method as well. Consider something describing what it does like hasProperty.
Consider the following:
function hasNotNullProperty(target, property) {
    return target.hasOwnProperty(property) && target[property] !== null;
}

Second
Javascript is a truthy language, undefined and null are considered false. Your yesProp and my hasNotNullProperty method can go away entirely with a simple if (target[property]) { /* do stuff */ }. If the property is undefined or evaluates to a falsy value, then it will not execute the block.
Again in this section, data is a poor description of what we are expecting. Consider using a more descriptive value such as people.
There is no need to return data; at the end of the function -- You've modified the objects that were passed in.
Consider the following:
function formatPeople(people) {
    for (var i = 0, len = people.length; i < len; i += 1) {
        var displayName;

        // Lastname was defined and not null
        if (people[i].lastname) {
            displayName = people[i].lastname;
            // Firstname was defined and not null
            if (people[i].firstname) {
                displayName+= ', ' + people[i].firstname;
            }
            // Firstname was not defined or was null, but Nickname is defined and not null
            else if (data[i].nickname) {
                displayName += ', ' + people[i].nickname;
            }
        }
        // Lastname was undefined or null, but Firstname is defined and not null
        else if (people[i].firstname) {
            displayName = people[i].firstname;
            if (people[i].Nickname) {
                displayName += ', ' + people[i].nickname;
            }
        }
        // Lastname and Firstname were undefined or null, Nickname is defined and not null
        else if (people[i].nickname) {
            displayName = people[i].nickname;
        }

        if (displayName) {
            people[i].displayValue = displayName
        }
    }
}

That still leaves a lot of duplicate code. We will want to clean that up.
Finally
The truthy nature of javascript allows us to do this as well:
var falsy = null;
var truthy = {}; // an anonymous object
var isDefinedAndNotNull = undefined || falsy || truthy; // assigns truthy to isDefinedAndNotNull

This allows us to short-circuit the assignment of a value such as a name.
Let's remove some of that duplicate code, and make a few more names clearer.
function setDisplayNamesForPeople(people) {
    var lastname, firstname, nickname, defaultName, displayName;

    for (var i = 0, length = people.length; i < length; i++) {
        lastname = people[i].lastname;
        firstname = people[i].firstname;
        nickname = people[i].nickname;
        defaultname = people[i].name;
        displayName = formatName(lastname, firstname, nickname, defaultname);

        if (displayName) {
            people[i].displayValue = displayName;
        }
    }
}

//formatName format is (lastname [', ' (firstname | nickname)] | (firstname [', ' nickname]) | nickname | defaultname)
function formatName(lastname, firstname, nickname, defaultname) {
    var formattedName = "";
    if (lastname && (firstname || nickname)) {
        formattedName = ', ' + (firstname || nickname);
    }
    else if (firstname && nickname) {
        formattedName = ', ' + nickname;
    }

    formattedName = (lastname || firstname || nickname || defaultname) + formattedName;

    return formattedName;
}


Ruby function to surround a word with dashes I am new to Ruby on Rails. Can some one please help me with this question?

How would you modify the following to be consistent with Ruby's style?

class Add_dash
def dashesHere(word)
    attachTheDashes = "--" + word + "--"
        return attachTheDashes
   end
end

Well first your indention is a bit strange, it'd be better like this:

class Add_dash
  def dashesHere(word)
    attachTheDashes = "--" + word + "--"
    return attachTheDashes
  end
end

And you typically don't need return in Ruby, it'll return the last value evaluated in your function. So having that in mind you could write it like this:

class Add_dash
  def dashesHere(word)
    "--" + word + "--"
  end
end

But Ruby also offers a way to easily put any value into a string, without adding a bunch of strings together. It really allows you to put any Ruby code in a string, and whatever it returns, will be put into your string. That looks like this: "math: #{1 + 1}" which would be "math: 2", or "Hello #{name}" would greet who ever was in name.

So you could write your whole thing like this:

class Add_dash
  def dashesHere(word)
    "--#{word}--"
  end
end

And in Ruby class names (Add_dash in your case) are supposed to be written in CamelCase starting with a capital letter. Method names and everything else are written in snake_case.

This would be my final version:

class AddDash
  def dashes_here(word)
    "--#{word}--"
  end
end

I hope this helps!


Get remaining days in date range I wonder if there are some possible ways to simplify my code.

startDate = '04/02/2014'
endDate = '04/06/2014'

mondayTag = 0
tuesdayTag = 0
wednesdayTag = 1
thursdayTag = 0
fridayTag = 1
saturdayTag = 0
sundayTag = 0

public int GetRemainingDays(DateTime startDate, DateTime endDate, bool mondayTag, bool tuesdayTag, bool wednesdayTag, bool thursdayTag, bool fridayTag, bool saturdayTag, bool sundayTag)
{
    int i = 0;
    for (DateTime day = startDate.AddDays(1); day.Date <= endDate.Date; day = day.AddDays(1))
    {
        if (day.DayOfWeek == DayOfWeek.Monday && mondayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Tuesday && tuesdayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Wednesday && wednesdayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Thursday && thursdayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Friday && fridayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Saturday && saturdayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Sunday && sundayTag == true)
        {
            i = i + 1;
        }
    }
    return i > 0 ? i : 0;
}

Using System.Linq library the method can be rewritten like this:

public static int GetRemainingDays(DateTime startDate, DateTime endDate, ISet<DayOfWeek> includedDays)
{
    return Enumerable.Range(0, Int32.MaxValue)
        .Select(n => startDate.AddDays(n+1))
        .TakeWhile(date => date <= endDate)
        .Count(date => includedDays.Contains(date.DayOfWeek));
}

Which can then be more easily called like this:

GetRemainingDays(startDate, endDate,
    new HashSet<DayOfWeek>{DayOfWeek.Wednesday, DayOfWeek.Friday});

Note: You should test this (and the original version) against off-by-one errors.


Using encryption/hashing to create a secure login I am creating a login for an encrypted chat application which retrieves login information from a MySQL database. I have got to the point where I feel pretty confident that (to the best of my knowledge) it is relatively secure. I am trying to learn so feel free to criticize!

import hashlib
import mysql.connector
from tkinter import *
from tkinter import messagebox
from cryptography.fernet import Fernet

chat = Tk() #Api I am using to create the GUI for the application

#Connect to MySQL database
try:
    loginFRetrieve = open("LK.bin", "rb") #Retrieving Encryption key from file
    retrivedKey =  loginFRetrieve.read()
    loginFRetrieve.close()

    loginFRetrieve = open("LC.bin", "rb") #Retrieving MySQL server login credentials
    retrivedLC = loginFRetrieve.read()
    loginFRetrieve.close()

    cipher = Fernet(retrivedKey)
    retrivedLC = cipher.decrypt(retrivedLC) #Decrypting server login data from file
    retrivedLC = retrivedLC.decode('utf-8')
    lC = retrivedLC.split()

    mydb = mysql.connector.connect(host=lC[0],user=lC[1],passwd=lC[2],database=lC[3])
    del(lC)
except mysql.connector.Error as err:
    chat.withdraw()
    messagebox.showerror("Database Error", "Failed to connect to database")
    exit()

mycursor = mydb.cursor()

#hashPass hashes and returns a string of characters using SHA-256 algorithm
def hashPass(hP):
    shaSignature = \
        hashlib.sha256(hP.encode()).hexdigest()
    return shaSignature

#userExists checks a database too see if username exists in the database
def userExists(userName):
    mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % userName)
    userResult = mycursor.fetchall()
    if userResult:
        return True
    return False

#Creates a new user in the connected SQL database.
def newUser(nU, nP):
    if userExists(nU) == False:
        mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % nU)
        mycursor.fetchall()
        r = hashPass(nP)
        sql = "INSERT INTO logins(username, passwordhash) VALUES(%s,%s)"
        val = (nU, r)
        mycursor.execute(sql, val)
        mydb.commit()
        chat.title(string="User created")
    else:
        messagebox.showwarning("User Creation Error", "User already exists")

#Checks the connected SQL database for an existing user.
def existingUser(uN, pW):
    if userN.get() != "":
        if userExists(uN) == True:
            encryptedPass = hashPass(pW)
            mycursor.execute("SELECT * FROM logins")
            passResult = mycursor.fetchall()
            for row in passResult:
                if row[1] == uN and row[2] == encryptedPass:
                    chat.title(string="Login Successful!")
                elif row[1] == uN and row[2] != encryptedPass:
                    messagebox.showerror("Login Error", "Password does not match our records")
        else:
            messagebox.showerror("Login Error", "User does not exist")
    else:
        messagebox.showwarning("Login Error", "Please enter a username")

Encryption isn't Hashing
encryptedPass = hashPass(pW)

You're not encrypting the password, you're hashing it.
For passwords you should not be hashing them with the SHA2 family. Instead, use bcrypt.
Sanitize input
From my limited knowledge of Python, it doesn't appear you're sanitizing your input on some functions, for example userExists() and the first query in newUser(). Instead, you're using simple string formatting to substitute values directly.
You should be passing the variables as arguments to execute() every time.


PHP function to check whether a user is logged in So, I have a function which checks if a user is logged in, but it's a long chain of if/else statements.

public static function isLoggedIn(){
    Session::openSession();

    if(isset($_SESSION['userId'])){
        return true;
    }

    if(isset($_COOKIE['authToken'])){
        list($selector, $token) = explode(':', $_COOKIE['authToken']);
        $result = Database::query('SELECT * FROM logins WHERE login_selector = ?', array($selector))[0];

        if($result){
            if(!hash_equals($result['login_token'], hash('sha256', base64_decode($token)))){
                return self::notLogged();
            }else{
                self::relogUser($result['login_userId']);
                return true;
            }
        }else{
            return self::notLogged();
        }
    }else{
        return self::notLogged();
    }
}

I'm looking for advice on how to refactor it to make it more clean and easy to read.

EDIT: I tried using a series of returns but it didn't work because one failed and blocked the rest (obviously).

One of the problems you're facing is the pyramid of doom - deeply nested control structures that make for hard to read code.

You can simplify your code by inverting the conditions in your if-statements. For example, instead of

if(isset($_COOKIE['authToken'])) {
    // do something with authToken
    // ...
    // (potentially) lots of code
    // ...
} else {
    // throw an error / return
}

you could write

if(!isset($_COOKIE['authToken'])) {
    return;
}

// do something with authToken
// ...

By applying this to your the isLoggedIn function, you get a flatter, more easily readable equivalent:

public static function isLoggedIn(){
    Session::openSession();

    if(isset($_SESSION['userId'])){
        return true;
    }

    if(!isset($_COOKIE['authToken'])){
      return self::notLogged();
    }

    list($selector, $token) = explode(':', $_COOKIE['authToken']);
    $result = Database::query('SELECT * FROM logins WHERE login_selector = ?', array($selector))[0];

    if(!$result) {
      return self::notLogged();
    }

    if(hash_equals($result['login_token'], hash('sha256', base64_decode($token)))){
      self::relogUser($result['login_userId']);
      return true;
    }

    return self::notLogged();
}

Also, the method naming seems a little off. The name isLoggedIn implies that the function just checks if a user is logged in or not and nothing else. What the method actually does is to check if a user logged in and if not, try to log them in. If that fails, it calls the method self::notLogged.

The next step might be to tear apart the function into smaller functions that actually tell you what they do from their name alone - this will avoid confusion. See Single responsibility principle - this applies to functions as well - a function should ideally not do more than one thing.

In particular, the part of your code that performs the authentication and/or login-checking should not be concerned with what happens when authentication has succeeded/failed. Instead, they should signal their respective results to the calling function, either by returning a value or by throwing an Exception.

Exceptions have the added benefit of explicitly signaling to developers working with the code that a function has somehow failed to do what it was meant to. Better yet, they give you the freedom to express what exactly went wrong and how.

All in all, you might end up with something like this:

public static function authenticate() {
    if (self::isLoggedIn()) {
        // user is logged in already - all done!
        return;
    }

    // try to login user using authToken
    if(!isset($_COOKIE['authToken'])){
        throw new \Exception('Authentication failed! No authToken provided');
    }

    list($selector, $token) = explode(':', $_COOKIE['authToken']);
    $result = Database::query('SELECT * FROM logins WHERE login_selector = ?', array($selector))[0];

    if(!$result) {
        throw new \Exception('Authentication failed! Invalid authToken: login not found');
    }

    if(!hash_equals($result['login_token'], hash('sha256', base64_decode($token)))) {
        throw new \Exception('Authentication failed! Invalid authToken: key mismatch');
    }

    self::relogUser($result['login_userId']);
}

public static function isLoggedIn(){
    Session::openSession();
    return isset($_SESSION['userId']);
}

public static function handleAuthentication() {
    try {
        self::authenticate();
    } catch (\Exception $e) {
        self::notLogged();
    }
}


Load title from database based on member country As tim suggested, some changes to the database was necessary. I have posed an improved version of this question at Get title from database based on member country.

I have the following database:

Each member may have multiple countries (1:n) mapped in table country2memb. It's even possible that one member gets the same country multiple times (for example, Bernd got US twice).
Further, each member may have  multiple titles (1:n) mapped in table title2memb. Each entry idRank has a name which can be found in title.
I want to get the first N members that have at least once the country "US" in table country2memb and I want to display all their titles.
Here is working code, using two JOINS and two where statements for N=2:
<?php

$db= new mysqli("localhost","root","","example");

$sql      ="SELECT DISTINCT m.name, m.id FROM member m
INNER JOIN country2memb c ON m.id = c.idMember AND c.country='US' LIMIT 2";

$result   = $db->query($sql);

while($zeile = $result->fetch_assoc()){
  $id = $zeile['id'];
  echo $zeile['name'].": ";

  $sub_sql = "SELECT t.name FROM title t INNER JOIN title2memb tm ON
  t.id = tm.idRank AND tm.idMember='$id'";
  $sub_result   = $db->query($sub_sql);
  while($rank = $sub_result->fetch_assoc())
  {
    echo $rank['name']." ";
  }

  echo "<br>";
}

?>

And as a result I get (I had to use the DISTINCT keyword, otherwise I would get Bernd twice):

Bernd: Bee
Tom: Bear Dog

Is it really necessary to have 2 nested while clauses here?

Formatting

Your code has some formatting issues, reducing the readability of it:

spacing: your spacing around = seems arbitrary and you are missing spaces around ..
indentation: 2 spaces aren't really enough, use at least 4.
you should also indent the queries after a linebreak a bit more to increase readability.
your curly brackets are not consistent.

Security

Depending on who can add members and ranks, you may be vulnerable to XSS as the name is echoed unencoded. Even if this isn't a problem now because only you can add them, your requirements may change. Encoding input is always a good idea.

Also, depending on the type and changability of id you may be vulnerable to SQL injection. Always use prepared statements.

Structure

You should add functions to increase the maintainability - readability, reusability, changability, etc - of your code.

For example, selectMembersByCountry($country) or selectMemberRanksByID($id), which would then return an array of members and/or ranks.

Naming

zeile isn't a good name. First of all, your variable names shouldn't switch languages, and ideally they should all be in English.

But row wouldn't be much better. What is it really? Well, $result contains a list of members, right? So its name could reflect that, and then zeile could be member, which would give you: $member = $membersResult->fetch_assoc().

Simplify SQL

You could put all the logic directly into the query, but I don't think that that is necessary, so I'll leave that to someone else (although you may want to change your table structure first, see below).

I would say that it's fine the way it is. Especially when you extract the queries to functions, you would have well-defined and reusable functions.

Putting all the logic directly in the query is likely to be less readable and harder to maintain, and I doubt that it will give you a noticeable performance benefit (definitely not if you limit by 2).

Table Structure

Why do your mapping tables have their own id? This doesn't seem necessary.
For a 1:n relationship, you don't actually need a mapping table.
member-country doesn't actually seem to be a 1:n relationship, but n:m; A member can have multiple countries, and a country can have multiple members.
Because of the last point, you actually have duplications in your country2memb table (multiple entries of US for example). What you should do is have  a member table, a country table, and a memberCountry table to map between them.


Simple event manager in Java I have created a simple event manager and I want it to work properly in a multithreaded environment:

public enum EventType {
    EVENT_TYPE_A,
    EVENT_TYPE_B,
    EVENT_TYPE_C;
}

public interface Observer {
    void onEvent(EventType eventType);
}

public class ObserverManager {
    private Set<Observer> m_weakReferencedObservers;

    public ObserverManager() {
        m_weakReferencedObservers = Collections.newSetFromMap(new WeakHashMap<Observer,Boolean>()); // allows a set of weak references
    }

    public void add(Observer observer){
        if (observer != null) {
            m_weakReferencedObservers.add(observer);
        }
    }

    public void remove(Observer observer){
        m_weakReferencedObservers.remove(observer);
    }

    public void callEvent(EventType eventType){
        m_weakReferencedObservers.stream()
                .filter(Objects::nonNull)
                .forEach(observer -> observer.onEvent(eventType));

        m_weakReferencedObservers.remove(null);
    }
}

public class EventManager {
    private Map<EventType,ObserverManager> m_observerManagers = new HashMap<>();

    public void registerObserver(EventType eventType,Observer observer){
        synchronized (m_observerManagers){
            if (!m_observerManagers.containsKey(eventType)){
                m_observerManagers.put(eventType,new ObserverManager());
            }

            ObserverManager observerManager = m_observerManagers.get(eventType);
            observerManager.add(observer);
        }
    }

    public void unregisterObserver(EventType eventType,Observer observer){
        synchronized (m_observerManagers) {
            if (!m_observerManagers.containsKey(eventType)) {
                return;
            }

            ObserverManager observerManager = m_observerManagers.get(eventType);
            observerManager.remove(observer);
        }
    }

    public void callEvent(EventType eventType){
        if (!m_observerManagers.containsKey(eventType)){
            return;
        }

        ObserverManager observerManager = m_observerManagers.get(eventType);
        observerManager.callEvent(eventType);
    }
}

A few points:

Is my use of weak references appropriate here?
Is my use of the synchronized keyword appropriate here?
In general, is there a better way to implement this?
If I want my event manager to be able to send many more different onEvent methods (with different prototypes), what's the best way to do it? So, instead of only having onEvent(EventType eventType), I could also easily use onEvent(EventType eventType, MyClass myClass). I mean, in general, how can I let the user of this class create his own onEvent() prototype?

Answers to Your Questions

Yes, this usage is acceptable if your intention was to have a Set of Observer objects that can be removed by the garbage collector if they are not referenced from elsewhere.
Instead of using the old-school synchronized keyword, I'd recommend to add a ReentrantReadWriteLock field in EventManager and use it in the three methods.
I think that your implementation is already quite simple, readable and usable. Making it better would depend on the goal you are looking for. But there are still a few remarks after these answers.
If you add another method like onEvent(EventType, Class), it will have drawbacks such as pollution of the APIs of the objects that do not need the second method, ambiguities in the choice of the method to use for the caller, etc. If you want to grant your user a possibility to define custom events, the simplest way that I see here is to replace the EventType argument with String: the API will not be coupled with the rigid enum (which needs to be modified in order to introduce a new event type) and the user will be able to define his own event types easily.

Other Remarks

Style: the m_ prefix for the private fields violates standard Java naming conventions.
There is no need to call observerManagers.containsKey() to check if the item is already in the map. For Maps, there is the putIfAbsent method that does exactly the same in one line.
I'm not sure that .filter(Objects::nonNull) and weakReferencedObservers.remove(null) are necessary in ObserverManager.callEvent. How do you expect null values to be present in the collection, if add method checks the object to be not null?


Night Mode using CSS and JavaScript I just added a new feature to my portfolio: Night Mode. I created it with CSS and session storage in JavaScript. I want you to review my CSS of night files, I feel it's filled with !important and I'm sure this is a bad practice. Can anyone help me make them better?

My second question, the default mode (white mode) runs in the first milliseconds when moving from page to another. I think it's not a good practice. Can anyone help me make it better?

Live: just set the session to night using this JavaScript line sessionStorage.setItem("mode", "night"); and refresh.

Alll files.

CSS files:

body{
    background-color: black;
    color: white;
}
.indx-contnt p {
    color: white !important;
}
.signature span, a {
    color: white;
}
h1{
    color:#f90 !important;
}
.latest li span{
    color: black !important;
}
.latest li a{
    color:white !important;
}

.contentlist li:nth-child(2) a{
    color:#2CAAE1 !important;
}

.contentlist li:nth-child(3) a{
    color:#0177B5 !important;
}

.contentlist li:nth-child(1) a{
    color:#717171 !important;
}

#rss{
    background-color: black;
}

.signature span, a{
    color: white !important;
}
.latest li a:hover {
    color: #f90 !important;
}

p, h1, h2,h4,span{
    color: white;
}

body{
    background-color: black;
    color: white;
}
.signature span, a{
    color: white !important;
}
p, h1, h2, h4, span {
    color: white !important;
}
.project span {
    color: black !important;
}
.card{
    background-color: #ffffff0f !important;
}
.card:hover {
    box-shadow: 10px 7px 10px 0px rgb(255, 153, 0) !important;
}
.card a{
    background-color: black !important;
}

#rss{
    background-color: black !important;
}

.card-title{
    color: #f90 !important;
}

.posts a {
    color: white !important;
}

I like the idea you have here and the implementation looks good.  You are right though that it is not best practice to use !important frequently.
I'd think you could avoid using !importants simply with either of the following:

Order: having night mode CSS come later/below day mode CSS
Specificity: as in div.nightmode or .nightmode div would override just div.

Below I used specificity as the order was more to keep it organized.  Sorry I didn't revise your code but I wanted to test this out for myself and see if my simple idea would work.
Code
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Night Mode Test</title>

Some Sample Stuff

Sample Text...

    <button id="toggleNightMode" type="button" name="button">Toggle</button>

So I'd recommend doing the following:

Combine some of your CSS that uses the same color and/or background
Use specificity to override CSS instead of !importants.  I'd recommend using a class or two (dayMode, nightMode).  My small example only needed one: if it lacked the nightMode class then I knew it was day mode.

CodePen Example


Object parser in C++ Consider the following contrived data type:

Building: int age, char* location, float quality

The location is in the format "XXX-XXX" (exactly 7 characters).

Goal: Serialize the object into a binary format and then deserialize the object to display (on console) the exact same building info as inputed by the user.

For example, suppose the user imputed the building object: age = 45, location = "345-789", quality = "2.3829.

Then the program should display on the console:

age = 45, location = 345-789, quality = 2.3829

Attempt: Although my application works exactly as specified by the goal, I believe there are major inefficiencies in my code. I am asking for feedback directly related to efficiency. Does there exist a more efficient method to accomplish the same goal? This project is for educational purposes and I cannot use any serialization libraries.

#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>

class Building
{
private:
    int m_age; // the age of the building
    char m_locationCode[7]; // location is the format:: example "357-278" (exactly 7 characters)
    float m_buildingQuality; // the quality of the building (scale from 0 - 1000)
    int m_buildingQualityDecimals; // the number of digits after the decimal for building quality
public:
    Building(int age, const std::string& loc, const std::string& quality)
    {
        m_age = age;
        for(unsigned i = 0; i < loc.size(); i++)
            m_locationCode[i] = loc[i];
        char qualityBuffer[10];
        int count = 0;
        bool hitDecimal = false;
        for(int i = 0; i < quality.size(); i++)
        {
            qualityBuffer[i] = quality[i];
            if(quality[i] == '.')
            {
                hitDecimal = true;
            }
            if(hitDecimal == true)
                count++;
        }
        m_buildingQuality = atof(qualityBuffer);
        m_buildingQualityDecimals = count;

    }
    int getAge() {return m_age;}
    std::string getLoc()
    {
        std::string toReturn(m_locationCode, 7);
        return toReturn;

    };
    int getDecimals()
    {
        return m_buildingQualityDecimals;
    }
    float getQuality()
    {
        return m_buildingQuality;
    }
};

int main()
{
    Building b(345, "123-456", "3.23654");

    // Serializing
    std::ofstream file;
    file.open("BinaryBuilding.bin", std::ios::out | std::ios::binary | std::ios::trunc);
    file.write((char*) &b, sizeof(b)); // writing file to binary by casting to a char*
    file.close();

    // Deserialzing
    std::ifstream file2;
    file2.open("BinaryBuilding.bin", std::ios::in | std::ios::binary);
    Building* b2 = new Building(0, "000-000", "0.0");
    file2.read((char *) b2, sizeof(*b2));
    file2.close();

    // Testing process
    std::cout << "Age: " << b2->getAge() << "; Loc: " << b2->getLoc() <<
                "; Building Quality:" <<  std::setprecision(b2->getDecimals()) << b2->getQuality() <<std::endl;

    delete b2;
    return 0;
}

Console Output: Age: 345; Loc: 123-456; Building Quality: 3.23654

Remarks: Notice that I parse the number of characters after the decimal point as inputted by the user. I think this is inefficient since I must store another int inside the class. This is slower and increases the size of the binary file. I want to be able to serialize and deserialize this object as fast as possible. I will eventually extend this to parse millions of objects. My professor told me that the location (i.e. XXX-XXX) should not be written as ASCII. How could the task be accomplished without writing the location to ASCII?

Binary Serialization
Is a bit more complex that what you have implemented.
You have serialized the content of the memory that is occupied by an object of type Building. Which is not quite the same as binary serialization of an object.
Problem 1: Integers are not represented the same on all platforms.
Problem 2: Floats are not represented the same on all platforms.
Those are the obvious two. The not so obvious ones are packing added by the compiler to the object. Changing the compiler or even just the compiler flags can change both the packing (and thus alignment) and the size of the object.
Assuming all the above is handled and does not change. The above code is very fragile to any change. It assumes all the data is in the object. This is usually not the case (think of a string, most of the data is at the other end of a pointer). So just because you serialize the memory occupied by an object does not always mean you get all the data that belongs to an object.
To use an optimal binary serialization. I would serialize each member individually. That way at least you avoid the issues with packing introduced by the compiler.
Design
Not sure what m_buildingQualityDecimals is used for or why it is useful. If you are worried about the exactness of floating point then you should retain the data as a string or integer (depending on the situation).
Never make assumptions about a class
    file.write((char*) &b, sizeof(b)); // writing file to binary by casting to a char*

Here the external user is serializing the class. But has no idea what is inside the class. This makes this code impossibly brittle to change. It will almost certainly break over time.
What you should do is ask the object to serialize itself to the stream. The object understands itself and its members. So it can optimally serialize itself to the stream.
       b.write(file); // b can serialize itself to the stream.

  class Building
  {
     // Stuff
     void write(std::ostream& out)
     {
         char version = 1;
         out.write(&version, 1);
         out.write(&m_age, sizeof(m_age));
         out.write(m_locationCode, 7);
         out.write(&m_buildingQuality, sizeof(m_buildingQuality));
      }

The same applies to the read.
  file2.read((char *) b2, sizeof(*b2));
  // I would write...
  b2->read(file);

Normal serialization
// Testing process
std::cout << "Age: " << b2->getAge() << "; Loc: " << b2->getLoc() <<
            "; Building Quality:" <<  std::setprecision(b2->getDecimals()) << b2->getQuality() <<std::endl;

Again you are providing geter methods to access the member and retrieve values that you then use to perform an action. Geter methods break encapsulation and expose the internal types of the object. You should never use them like this. What you should do is ask the class to serialize itself to the stream. There is even a standard idiom for this in C++ and it is called the output operator.
  class Building
  {
       friend std::ostream& operator<<(std::ostream& out, Building const& value)
       {
           return out << "Age: " << value.m_age
                      << "; Loc: " << value.m_locationCode
                      << "; Building Quality:" << value.m_buildingQuality
                      << "\n";
        }

Prefer "\n" over std::endl
The only difference between the two is that std::endl also flushes the stream. The stream will flush itself automatically when it needs to and thus forcing a flush is only going to make it less efficient. Humans are notoriously bad at making this decision; the code is actually very good at. So let the code decide when to flush.
Don't use pointers in C++
    Building* b2 = new Building(0, "000-000", "0.0");

    // what happens if an exception happens between these two points?

    delete b2;

Using pointers is very C like and its not done much in modern C++ (unless you are implementing a container class or smart pointer or trying to do some tricky low level optimization).
In normal code you very rarely see them. The problem is that they do not show ownership semantics (the owner of a pointer is responsible for calling delete on it). So it is not clear who should delete them. So in most cases normal variables are a preferred and if you must dynamically create an object then you should be using a smart pointer so that the ownership semantics are specified.
In this case a normal object is best.


A VBA Product Dictionary with a Collection of Product Services I need to extract unique Product Group names along with its corresponding services from a table in a worksheet. The table is generated by a bot and is not filtered, I have sorted it by alphabetical order. The data is not fixed and can contain anywhere from 5 - 100 rows of data, depending on the month which the report from the bot is generated.
I decided to use a Dictionary to store the the Product Group Name as they Key, while using a Collection to store services. The Collection only stores unique services by using On Error Resume Next
What changes could I make to my code?
Snippet of my Table

Code
Public Sub BuildTMProductDictionary()

Dim tmData As Variant
tmData = Sheet1.ListObjects("Table1").DataBodyRange.Value

Dim i As Long
For i = LBound(tmData, 1) To UBound(tmData, 1)
    Dim product As String
    product = tmData(i, 1)

    'store unique services in a collection, On Error Resume Next used to avoid duplicates
    On Error Resume Next
    Dim services As New Collection
    services.Add (tmData(i, 2)), (tmData(i, 2))

    'get the product name of the next row
    Dim nextProduct As String
    nextProduct = tmData(i + 1, 2)

    'compare the current product against the next product create New Dictionary if <>
    If product <> nextProduct Then
        Dim productGroup As New Dictionary
        productGroup.Add product, services
        Set services = New Collection
    End If
Next
End Sub

Edit
My Collection of services needs to be unique. As an example "Positive Pay" which belong to the "ARP" product group should only appear once in the collection.

You seem to be misunderstanding how to use a Scripting.Dictionary.
There is no need to sort the data before processing into a dictionary.
There is also no need to construct a collection before you add to the dictionary.
Its also slightly more sensible to write the sub as a function.
As a final tweak I'd pass the array in as a parameter rather than hardwiring it into the function, but I'll leave that as an exercise for the reader (smile)
Public Function BuildTMProductDictionary() As Scripting.Dictionary

    Dim tmData As Variant
    tmData = Sheet1.ListObjects("Table1").DataBodyRange.Value

    Dim myDict As Scripting.Dictionary
    Set myDict = New Scripting.Dictionary

    Dim i As Long
    For i = LBound(tmData, 1) To UBound(tmData, 1)

        Dim myProduct As String
        myProduct = tmData(i, 1)

        Dim myService As String
        myService = tmData(i, 2)

        If Not myDict.exists(myProduct) Then

            myDict.Add myProduct, New Collection

        End If

        myDict.Item(myProduct).Add myService

    Next

    Set BuildTMProductDictionary = myDict

End Function

Replace
   If Not myDict.exists(myProduct) Then

        myDict.Add myProduct, New Collection

    End If

    myDict.Item(myProduct).Add myService

with
    If Not myDict.exists(myProduct) Then

        myDict.Add myProduct, New Scripting.Dictionary

    End If

    If Not myDict.Item(myProduct).exists(myService) Then

        myDict.Item(myProduct).Add myService,myService

    End If


Check if a type is of any from a list of types? I need to check whether a generic type parameter is in a set of valid types and have created extension methods to do a run time check:

public static bool Is(this Type type, params Type[] types) {
  return types.Any(t => t == type);
}

public static bool Is<T1>(this Type type) {
  return type.Is(typeof (T1));
}

public static bool Is<T1, T2>(this Type type) {
  return type.Is(typeof (T1), typeof (T2));
}

With additional methods for T3 - T#...

Usage (in constructor for the generic class):

if(!typeof(T).Is<Int32, String, Boolean, CustomClass, Whatever>())
    throw new ArgumentException("T must be a type.");

But I would prefer a compile time check (which I don't believe is possible). Failing that, any suggestions on improvements are appreciated.

Here is a run-time and a compile-time approach. For the compile-time approach I only show how it works for 3 type parameters and for 20 type parameters to show the concept. You can easily add more methods/classes for the number of type parameters you need.

Scroll down to the bottom to see some usage examples.

public static class RuntimeTypeCheckExtensions
{
    public static bool IsAssignableToAnyOf(this Type typeOperand, IEnumerable<Type> types)
    {
        return types.Any(type => type.IsAssignableFrom(typeOperand));
    }

    public static bool IsAssignableToAnyOf(this Type typeOperand, params Type[] types)
    {
        return IsAssignableToAnyOf(typeOperand, types.AsEnumerable());
    }

    public static bool IsAssignableToAnyOf<T1, T2, T3>(this Type typeOperand)
    {
        return typeOperand.IsAssignableToAnyOf(typeof(T1), typeof(T2), typeof(T3));
    }

    public static bool IsAssignableToAnyOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(this Type typeOperand)
    {
        return typeOperand.IsAssignableToAnyOf(typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10), typeof(T11), typeof(T12), typeof(T13), typeof(T14), typeof(T15), typeof(T16), typeof(T17), typeof(T18), typeof(T19), typeof(T20));
    }
}

public static class CompileTimeTypeCheckUtils
{
    public static IsAssignableToAnyOfWrapper<T1, T2, T3> IsAssignableToAnyOf<T1, T2, T3>()
    {
        return new IsAssignableToAnyOfWrapper<T1, T2, T3>();
    }

    public static IsAssignableToAnyOfWrapper<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> IsAssignableToAnyOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>()
    {
        return new IsAssignableToAnyOfWrapper<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>();
    }
}

public class IsAssignableToAnyOfWrapper<T1, T2, T3>
{
    public void OperandToCheck(T1 operand) { }
    public void OperandToCheck(T2 operand) { }
    public void OperandToCheck(T3 operand) { }
}

public class IsAssignableToAnyOfWrapper<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>
{

    public void OperandToCheck(T1 operand) { }
    public void OperandToCheck(T2 operand) { }
    public void OperandToCheck(T3 operand) { }
    public void OperandToCheck(T4 operand) { }
    public void OperandToCheck(T5 operand) { }
    public void OperandToCheck(T6 operand) { }
    public void OperandToCheck(T7 operand) { }
    public void OperandToCheck(T8 operand) { }
    public void OperandToCheck(T9 operand) { }
    public void OperandToCheck(T10 operand) { }
    public void OperandToCheck(T11 operand) { }
    public void OperandToCheck(T12 operand) { }
    public void OperandToCheck(T13 operand) { }
    public void OperandToCheck(T14 operand) { }
    public void OperandToCheck(T15 operand) { }
    public void OperandToCheck(T16 operand) { }
    public void OperandToCheck(T17 operand) { }
    public void OperandToCheck(T18 operand) { }
    public void OperandToCheck(T19 operand) { }
    public void OperandToCheck(T20 operand) { }
}

Usages:

Type someType = ...

// Three example usages of run-time check (using generic types, params and IEnumerable):
if (someType.IsAssignableToAnyOf<string, int, double>())
{
}

if (someType.IsAssignableToAnyOf(typeof(string), typeof(int), typeof(double)))
{
}

IEnumerable<Type> enumerableOfAcceptedTypes = new Type[]
{
    typeof (string),
    typeof (int),
    typeof (double)
};

if (someType.IsAssignableToAnyOf(enumerableOfAcceptedTypes))
{
}

// Two example usages of compile-time check:
CompileTimeTypeCheckUtils.IsAssignableToAnyOf<string, int, long>().OperandToCheck(5); // <-- No compile-time error

CompileTimeTypeCheckUtils.IsAssignableToAnyOf<string, int, long>().OperandToCheck(5F); // <-- Compile-time error


Handling Null Result with class object My BLL's function is like:

 public Categorymaster GetByPrimaryKey(CategorymasterKeys keys)
        {
            return _dataObject.SelectByPrimaryKey(keys);
        }

// above funciton is calling function written below

 public Categorymaster SelectByPrimaryKey(CategorymasterKeys keys)
        {
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.CommandText = "dbo.[categorymaster_SelectByPrimaryKey]";
            sqlCommand.CommandType = CommandType.StoredProcedure;

            // Use connection object of base class
            sqlCommand.Connection = MainConnection;

            try
            {

                sqlCommand.Parameters.Add(new SqlParameter("@category_id", SqlDbType.Int, 4, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, keys.Category_id));

                if (MainConnection.State == ConnectionState.Closed)
                {
                    MainConnection.Open();
                }

                IDataReader dataReader = sqlCommand.ExecuteReader();

                if (dataReader.Read())
                {
                    Categorymaster businessObject = new Categorymaster();

                    PopulateBusinessObjectFromReader(businessObject, dataReader);

                    return businessObject;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Categorymaster::SelectByPrimaryKey::Error occured.", ex);
            }
            finally
            {
                MainConnection.Close();
                sqlCommand.Dispose();
            }

        }

In my web page i have written below code:

BusinessLayer.Product_category_transFactory pctf = new Product_category_transFactory();

        Categorymaster cm = cmf.GetByPrimaryKey(new CategorymasterKeys(catid));//throws exception when it returns null

Now the issue i am facing is that when there is no result for the query then it returns null and throw exception.

The same model is used in whole application.
Please tell me what all minimum and optimum changes should i do handle null (when no result).

NOTE: i am using .net framework 4.0

Thanks

What is the exception you are getting?  What do you mean returns null and throws Exception?

From putting this code into a class and executing a test on it, I get back an object or null when the record exists or does not respectively.

If you're getting an exception from the above call with cmf.GetByPrimaryKey, is the exception in the call to the constructor of CategorymasterKeys?

Here is the test I used:

[TestMethod()]
public void TestWhenPassingAnIdNotInTheResultSetToSelectByPrimaryKey_ThenNullIsTheResult()
{
    var target = new Class2();
    CategorymasterKeys keys = new CategorymasterKeys { Category_id = 0 };
    Categorymaster actual = target.SelectByPrimaryKey(keys);
    Assert.IsNull(actual);
}


Interfacing between workbooks (Exporting data Table and key properties) So I recently rebuilt a worksheet we have for tracking our clients who take income from their portfolios (here). I intend to be pulling this data into other workbooks for various reporting functions.

To facilitate this, I decided to write methods in the "workbook" module to return:

The codenames of the sheets holding data tables
The headers used in the data tables
The data table from a specific sheet (specified by codename)

Is this an effective way of achieving my goal (reducing potential problems interfacing between workbooks)?

Module "A1_Public_Variables"

Option Explicit

Public Const TOP_LEFT_CELL_STRING As String = "Client Name"

Public Const CLIENT_NAME_HEADER As String = "Client Name"
Public Const INCOME_AMOUNT_HEADER As String = "Income"
Public Const PAYMENT_FREQUENCY_HEADER As String = "Frequency"
Public Const PAYMENT_DAY_HEADER As String = "Date Paid"
Public Const BASE_MONTH_HEADER As String = "Base Month"
Public Const ASCENTRIC_WRAPPER_HEADER As String = "Wrapper"
Public Const ASCENTRIC_ACCOUNT_NUMBER_HEADER As String = "Ascentric Acc #"
Public Const ACCOUNT_TO_PAY_FROM_HEADER As String = "Account to pay from?"

Public Const WS_2015_CODENAME As String = "ws_2015"
Public Const WS_2016_CODENAME As String = "ws_2016"

"Workbook" Module

Option Explicit

Public Sub GetDataTableHeaders(Optional ByRef topLeftCellString As String, Optional ByRef clientNameHeader As String, Optional ByRef incomeAmountHeader As String _
                                , Optional ByRef paymentFrequencyHeader As String, Optional ByRef paymentDayHeader As String, Optional ByRef baseMonthHeader As String _
                                , Optional ByRef ascentricWrapperHeader As String, Optional ByRef ascentricAccountNumberHeader As String, Optional ByRef accountToPayFromHeader As String)

    topLeftCellString = CLIENT_NAME_HEADER

    clientNameHeader = CLIENT_NAME_HEADER
    incomeAmountHeader = INCOME_AMOUNT_HEADER
    paymentFrequencyHeader = PAYMENT_FREQUENCY_HEADER
    paymentDayHeader = PAYMENT_DAY_HEADER
    baseMonthHeader = BASE_MONTH_HEADER
    ascentricWrapperHeader = ASCENTRIC_WRAPPER_HEADER
    ascentricAccountNumberHeader = ASCENTRIC_ACCOUNT_NUMBER_HEADER
    accountToPayFromHeader = ACCOUNT_TO_PAY_FROM_HEADER

End Sub

Public Sub GetWorksheetCodenames(Optional ByRef ws2015 As String, Optional ByRef ws2016 As String)

    ws2015 = WS_2015_CODENAME
    ws2016 = WS_2016_CODENAME

End Sub

Public Function GetDataArrayFromSheetByCodename(ByVal strCodeName As String) As Variant
    '/ returns the datatable, or an error if could not find worksheet

    Dim dataTable As Variant
        dataTable = Array()

    Dim wsWasFound As Boolean
    Dim ws_target As Worksheet, ws As Worksheet

    wsWasFound = False
    For Each ws In ThisWorkbook.Worksheets
        If ws.codeName = strCodeName Then
            Set ws_target = ws
            wsWasFound = True
        End If
    Next ws

    If wsWasFound Then

        Dim tableRange As Range
        Set tableRange = GetTableRange(ws_target)

            dataTable = tableRange

            GetDataArrayFromSheetByCodename = dataTable

        Else

            GetDataArrayFromSheetByCodename = CVErr(2042) '/ #N/A error
    End If

End Function

Just looking at your function there 2 ways to improve it:

Public Function GetDataArrayFromSheetByCodename(ByVal strCodeName As String) As Variant
  Dim ws As Worksheet
  For Each ws In ThisWorkbook.Worksheets
    If ws.CodeName = strCodeName Then
      Set GetDataArrayFromSheetByCodename = GetTableRange(ws)
      Exit Function
    End If
  Next ws
  GetDataArrayFromSheetByCodename = CVErr(2042) '/ #N/A error
End Function

When having LOTS of sheets, this may be faster, but uses an error:

Public Function GetDataArrayFromSheetByCodename(ByVal strCodeName As String) As Variant
  On Error Resume Next
  If Len(ThisWorkbook.VBProject.VBComponents(strCodeName).Name) = 0 Then
    GetDataArrayFromSheetByCodename = CVErr(2042)
  Else
    Set GetDataArrayFromSheetByCodename = GetTableRange(ThisWorkbook.VBProject.VBComponents(strCodeName))
  End If
End Function

Also as a quick-inprove just add Exit For after your wsWasFound = True to not loop all sheets that are left after you found a match.

For the second version of the function: I use the fact that errors inside of conditions inside of If-statements are always true when using On Error Resume Next. Len(....Name) = 0 Then normally NEVER can be true when there is a need of a name. But having an error inside will act like the whole statement is true. So it simply tries to catch the item. If it exists, it also has a name this way Len will be >0 and be false (now your calculation will be done), else (it doesn't exist) it will act like If is true and the = CVErr(2042) will be set.
For the Subs: they doesn't make sense to me. What do they do? As it looks to me, they do simply nothing.

Last hint: You may change the function to As Range. When set a variable to it, you later could simply check by If Variable Is Nothing then. So there would be no need for = CVErr(2042).

EDIT
just to show the way i would hand over the values (while im pretty sure you will not use it)

Public Function GetDataTableHeaders() As Variant
GetDataTableHeaders = Array("Client Name", "Client Name", "Income", "Frequency", _
  "Date Paid", "Base Month", "Wrapper", "Ascentric Acc #", "Account to pay from?")
End Function

then simply set a variable to it or directly use GetDataTableHeaders(2) to get "Income"... as it looks, you may want to output the values to a sheet as headers and this way it would be much easier. However, you want to make it "not understandable" in some way, and for that it will be better to stay as it is right now :)