The good news is that your script doesn't look exploitable.  In particular, stripping out line break characters protects against header-splitting attacks.  Good job there.

The bad news is that it can mangle the text unnecessarily.  For example, if a user submits the form with the subject line

  Your <blink> tag is annoying

… it will come across as

  Subject: Your  tag is annoying

And for what gain?  strip_tags() is meant as a feeble defense against inappropriate HTML tags, but here you are sending plain text mail — a problem that has absolutely nothing to do with HTML.

It also probably does not make sense to strip all line termination characters from the message.

A more general concern I have is your use of the term sanitize, as it leads to confusion.  I recommend striking that word from your programming vocabulary (even if the PHP documentation uses it), to be replaced by three specific terms:

Canonicalization (or "Normalization"): transforming input from multiple representations of the same data into one preferred form.

For example, if your form accepts a credit card number, then you should strip out all whitespace, because they are not a meaningful part of the data.  Another example would be to lower-case an e-mail address.
Validation: rejecting input that violates your rules.  Validation failure should cause the user to have to resubmit after fixing the errors.

For example, if your form accepts a credit card number, then you should reject any submission that does not contain the right number of digits, the correct leading digits for the accepted card types, and a correct Luhn checksum.

For an e-mail form, your validation rules might require a name to be non-empty, a subject line that is one line of a reasonable length, and a plausible-looking e-mail address.
Escaping: transforming strings so that one kind of string can be safely embedded inside another kind of string without being misinterpreted.

Any time you compose a string that will be interpreted by another computer system, be it an e-mail message, HTML page, or SQL query, assume that you are vulnerable to some kind of injection attack. Every single one of these "human-friendly" languages (as opposed to binary formats such as JPEG images) will have delimiters of special significance. Header-splitting, HTML/JavaScript injection, and SQL injection attacks all have the same root cause: careless string concatenation or interpolation.

Therefore, before concatenating or interpolating strings, stop and think: "What is the appropriate escaping mechanism that I should be using?"  In the case of e-mail headers, RFC 2047 suggests that the relevant escaping mechanism is mb_encode_mimeheader().  Sometimes, the answer is that no escaping is required — the e-mail message body in this example is one of those rare occasions where that's true.

Canonicalization provides user-friendliness.  Validation enforces your business logic.  Escaping, not canonicalization or validation, upholds security.  The term "sanitize" conflates the three mechanisms, leading you do write improperly engineered code.

Suggested solution

function canonicalize(&$params) {
    $params['email'] = filter_var($params['email'], FILTER_SANITIZE_EMAIL);
    $params['phone'] = filter_var($params['phone'], FILTER_SANITIZE_NUMBER_INT);
}

function validate(&$params) {
    $errors = array();
    if (empty($params['name'])) {
        $errors['name'] = 'A name is required';
    }
    if (empty($params['email'])) {
        $errors['email'] = 'Invalid e-mail address';
    }
    if (empty($params['phone'])) {
        $errors['phone'] = 'A phone number is required';
    }
    return $errors;
}

function recipient(&$params) {
    return "email@example.com";
}

function subject(&$params) {
    return mb_encode_mimeheader("New contact from " . $params['name'], 'UTF-8', 'Q');
}

function body(&$params) {
    // Don't bother escaping e-mail body; it's for human consumption.
    return sprintf(
        "Name: %s\n" .
        "Email: %s\n" .
        "Phone: %s\n" .
        "Subject: %s\n" .
        "Message:\n%s\n",
        $params['name'], $params['email'], $params['phone'],
        $params['subject'], $params['message']);
}

function headers(&$params) {
    return sprintf(
        "From: %s <%s>",
        mb_encode_mimeheader($params['name'], 'UTF-8', 'Q'),
        $params['email']
    );
}

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] != "POST") {
    // Not a POST request, set a 405 (Method Not Allowed) response code.
    http_response_code(405);
    echo "There was a problem with your submission, please try again.";
} else {
    canonicalize($_POST);

    if (($errors = validate($_POST))) {
        display_form($errors);
    } elseif (!mail(recipient($_POST), subject($_POST), body($_POST), headers($_POST))) {
        // Set a 500 (Internal Server Error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    } else {
        // Set a 200 (Success) response code.
        http_response_code(200);
        echo 'Thank You! Your message has been sent.';
    }
}

In the rewrite above, I also proposed:

Breaking up the code into functions.
Rearranging the flow such that all of the error handlers come first.  (There are many ways to fail along the one true path to success.)
Changed the HTTP status code for non-POST requests to 405.
A stub (to be implemented) so that the user can get more informative feedback on validation failure.


SQL Stored Procedure to export specified data


it's clear and readable but i would like to point out some things :

Avoid using functions inside Render()

  A function in the render method will be created each render which is a
  slight performance hit. t's also messy if you put them in the render, which is a much  > bigger reason

Use the child.id instead of key as index when you map through an array in render() because Index as a key is an anti-pattern.

Keep your code as DRY as possible, the initialState can be an object outside the class instead of writing it twice or more, especially if it's a big object.

Optional : use Destructuring assignment to indicate which keys you will use in the function.

const initialState = {
  selected: '',
  nestSelect: '',
  children: [],
  active: '',
}

class NestedNav extends Component {
  constructor(props) {
    super(props)
    this.state = initialState
  }

  handleClick = title => {
    this.setState({ ...initialState })
  }

  mappedChildren = (child, selectedTitle) => {
    const { nestedParentClass } = this.props
    let childElement

    if (child) {
      childElement = child.map(({ id, title, children, url }) =>
<Link to={'/'}>{title}</Link>
        {children ?
          <FontAwesomeIcon
            onClick={() => this.mappedChildren(children, this.state.select)}
            className='i button'
            icon={faArrowCircleDown} /> : null}

)
      this.setState({
        selected: selectedTitle,
        children: childElement,
        active: 'true',
      })
    }
    return ''
  }

  navListItems = data => data.map(({ id, url, children, title, icon }) => {
    const { parentClass } = this.props
    return (
{icon}<Link to={'/'}>{title}</Link>
      {children ?
        <FontAwesomeIcon
          onClick={() => this.mappedChildren(children, title)}
          className='i button'
          icon={faArrowCircleRight} /> : null}

)
  });

  render() {
    const { data } = this.props
    const active = this.state.active === 'true' ? 'true' : ''

    return (

{this.state.selected}

          {this.state.children}

{this.navListItems(data)}

    )
  }
}
export default NestedNav


Concurrency and locking in a chat server

This is a nice project to learn concurrency on, and you've already identified a few issues that concern you, and you're right in some ways. Go documentation recommends using channels when possible, over mutexes. The documentation in the sync package says: "Other than the Once and WaitGroup types, most are intended for use by low-level library routines. Higher-level synchronization is better done via channels and communication."

Channels are your friend in Go, and you should use them liberally (well, more liberally than mutexes).

There are some special cases with channels, though, and your code has a good example of how they can be used in a broken way. Your concurrency is not nearly as significant as you think it is. I will focus on this code for the moment, and we'll simplify it down, and then get back to the concurrency problem in a bit...

Client handler

This code....

func (r *Server) handleConn(conn net.Conn) {
    reader := bufio.NewReader(conn)
    name, e := reader.ReadString('\n')
    name = strings.TrimSpace(name)
    if e != nil {
        conn.Close()
        return
    }

    c := &client{conn, reader, name}
    r.addClient(c)
    r.publishMessage(c.name + " has joined the server\n")
    r.handleClient(c)
}

func (r *Server) handleClient(c *client) {
    for {
        msg, e := c.reader.ReadString('\n')
        if e == io.EOF {
            c.conn.Close()
            r.deleteClient(c)
            r.publishMessage(c.name + " has left the server\n")
            return
        } else if e != nil {
            continue
        }
        r.messageChan <- message{c.name + ": " + msg, c}
    }
}

... takes a client network connection, pulls the name, and then establishes a loop for reading and distributing messages. It distributes the messages by pushing them on to the r.messageChan channel. Let's simplify that code a whole bunch, and point out some problems as we go.

First up, you need to learn the defer statement, and use it for closing the client connection. If you change the first line of the function to be:

func (r *Server) handleConn(conn net.Conn) {
    defer conn.Close()

now you don't need to worry about closing it in a number of other places. Just returning from the function is enough to close it.

Secondly, you should use a scanner... not a Reader. See: Scanner which has the documentation "Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text." Scanner defaults to using line-termination (which is what you have) so it's easy to set up. Your code:

    reader := bufio.NewReader(conn)

becomes:

     scanner := bufio.NewScanner(conn)

Note that Scanner never returns an EOF error, it just returns a false scan at EOF (or any other error). The advantage for you of a scanner is that it simplifies your loops, and error handling. This is not obvious immediately in your case as you scan the name, but will become apparent when processing messages. To get the name, you need:

// find the next end-of-line.. (or perhaps EOF)
if !scanner.Scan() {
    // could not scan anything on the first scan... odd... no name.
    // the scanner.Err() may have a value if there's a problem, but we don't care.
    return
}
name := strings.TrimSpace(scanner.Text())

OK, that's how you get the name.... and now we can create the client (using the scanner instead of reader) and we also use a defer function to remove the client instead of shifting that logic in to some other place (keeping the clean-up code in the same place as the mess-up code is important for maintainability). Also, we should relocate the "publish" methods in to the addClient and deleteClient methods (where they really should be anyway):

c := &client{conn, scanner, name}
r.addClient(c)
defer r.deleteClient(c)
r.handleClient(c)

OK, so now we have a client that can process incoming messages, let's look at that code, but using a scanner now instead of a reader, and it does not need to do the deleteClient or the related "publish" of the deletion. It also does not need to close the connection:

func (r *Server) handleClient(c *client) {
    for c.scanner.Scan() {
        msg := c.scanner.Text()
        r.messageChan <- message{c.name + ": " + msg, c}
    }
    // we could check scanner.Err() here, but we are ignoring all non-EOF errors anyway
}

Now, that looks neat... so small now that it's hardly worth having it's own function, let's pull it back in to the handleConn function (which we will rename to handleClient because I prefer client... and we'll remove the scanner from the client struct because no-one else uses it in any other place... our handleClient method is now:

func (r *Server) handleClient(conn net.Conn) {
    defer conn.Close()

    scanner := bufio.NewScanner(conn)

    // read off the first line as the "name"

    // find the next end-of-line.. (or perhaps EOF)
    if !scanner.Scan() {
        // could not scan anything on the first scan... odd... no name.
        // the scanner.Err() may have a value if there's a problem, but we don't care.
        return
    }
    name := strings.TrimSpace(scanner.Text())

    // register our client in to the control systems.
    c := &client{conn, name}
    r.addClient(c)
    defer r.deleteClient(c)

    // send messages in to the channel.
    for scanner.Scan() {
        r.messageChan <- message{name + ": " + scanner.Text(), c}
    }
}

Now, that's a bunch simpler, especially the reduced error handling, and the reduced content in the client.

There were a few things to hammer out here. We shifted the printing of messages like X has joined the server and X has left the server in to the addClient and deleteClient methods respectively. This reduces the mixed logic of handling a client and also reporting activity in this function, and shifts it to the more logical place where we are actually adding and deleting things. We used defer functions to handle cleanup of resources at the same time/place that the resources were created. We used a scanner instead of a reader.

messageChan

Let's cover that concurrency issue I mentioned earlier. It comes down to the messageChan. The problem is only one client is busy at a time. Let me explain... this code here:

r.messageChan <- message{name + ": " + scanner.Text(), c}

pushes messages on to the channel, and this code pulls them off:

for {
    m := <-r.messageChan
    .... distribute the messages to other clients
}

You would think that multiple clients could all be pushing messages, and the for-loop is pulling them and distributing them at the same time. Unfortunately, all the clients "block" at the point where they push the message, and they all wait there, until the for-loop starts, and it will pull just one message. That one message will be processed, and the client that happened to have its message pulled, will then go off and wait for another message - all the other clients are still blocked. Once the for loop has sent the message off, it will come back and read another from the channel, and one other client will be lucky enough to have its message delivered.

This is because you have created an unbuffered channel. The documentation has this to say: "If the capacity is zero or absent, the channel is unbuffered and communication succeeds only when both a sender and receiver are ready." Since the receiver is only ready once each loop, the receiver essentially serializes all the clients.

You need to declare your channel with some buffer size if you want to avoid this issue. Even a size of 1 would be beneficial. A larger buffer may result in caching of messages but that should not be a problem.

Communication instead of Mutexes

Communication in Go is an odd concept to explain. The purpose of mutexes is to allow safe access to resources from multiple go-routines. Communication is sort of the opposite - communication basically implies only one go-routine ever accesses a resource, so mutexes are not needed, but we can communicate the changes (normally via a channel) to that go-routine.

If only one routine accesses a resource, no mutex is needed. Let's see how we can apply that to your code. Your "server" code really has three things going on...

clients get added
messages get distributed
clients get removed.

You've already got a channel for the messages, so let's look at the other parts....

func (r *Server) addClient(c *client) {
    r.m.Lock()
    r.clients[c] = struct{}{}
    r.m.Unlock()
}

func (r *Server) deleteClient(c *client) {
    r.m.Lock()
    delete(r.clients, c)
    r.m.Unlock()
}

Let's turn those in to channels instead:

func (r *Server) addClient(c *client) {
    r.added <- c
}

func (r *Server) deleteClient(c *client) {
    r.deleted <- c
}

We will have to create those channels (with some buffering) on the Server... but, that's how we communicate the add/remove from the client.

How do we handle that on the server? Currently the server code looks like:

func (r *Server) sendMessages() {
    for {
        m := <-r.messageChan
        r.m.RLock()
        for k := range r.clients {
            if k != m.client {
                go k.conn.Write([]byte(m.message))
            }
        }
        r.m.RUnlock()
        fmt.Print(m.message)
    }
}

If we listen for communication from all channels, not just the messageChan, we can do it all in that routine (and no need for mutexes because we're the only ones to manipulate the client map.

func (r *Server) sendMessages() {
    for {
        select {
        case m := <-r.messageChan:
            for k := range r.clients {
                if k != m.client {
                    go k.conn.Write([]byte(m.message))
                }
            }
            fmt.Print(m.message)
        case c := <-r.added:
            r.publishMessage(c.name + " has joined the server\n")
            r.clients[c] = struct{}{}
        case c := <-r.deleted:
            r.publishMessage(c.name + " has left the server\n")
            delete(r.clients, c)
        }
    }
}

Now we can even remove the client map from the Server completely, and keep it local inside thesendMessages` go-routine.

Read up on the select statement which is how communication from multiple sources is handled: https://golang.org/ref/spec#Select_statements

Conclusion

This post has been long enough already... hopefully you'll get something out of it. I hope that you at least get how the unbuffered channels can impact things, and that communication with select-statements allows you to localize resources to just one routine, meaning mutexes are not needed.


Generate all permutations of a list in Python

Instead of calling a recursive function you could do it in place in an iterative way.

Like this:

l = [1, 2, 3, 4, 5]

def permute(l):
    n = len(l)
    result = []
    c = n * [0]

    result.append(l)

    i = 0;
    while i < n:
        if c[i] < i:
            if i % 2 == 0:
                tmp = l[0]
                l[0] = l[i]
                l[i] = tmp

            else:

                tmp = l[c[i]]
                l[c[i]] = l[i]
                l[i] = tmp

            result.append(l)
            c[i] += 1
            i = 0
        else:
            c[i] = 0
            i += 1

    return result

print(permute(l))

This is not my algorithm, it is called the Heap algorithm


Dispatching Brainfuck commands using if-else or dictionary

A few coding points:

I think you could simplify the arguments a lot by using kwargs, rather than passing a tuple of arguments.
Having your dict in the global namespace, rather than the function's local namespace, will slow it down considerably.
0 is False, so if args[2] != 0: can just be if args[2].
For unused variables, like step, I consider it better to mark it as such by using _ as the variable name.
Half of the functions are simple one-liners that can use lambdas.
Although half of the functions can be lambdas, some of them would work better by doing in-place operations on memo.
If you want to search until the end, you don't need to specify an end to find.
You add 1 to i in every case, so that can be moved out of the functions.

As for your questions:

There are three major situations where I would use the dict structure.

The functions can either be lambdas or external functions that are short and easy-to-read as dict values.  Usually this is better with only one or a few consistent arguments.
The functions are so long that putting them in an if chain makes it hard to keep track of the flow.  Again, usually this is better with only one or a few consistent arguments.
There are a huge number of possible inputs, which makes for an overly long if test chain, but where there are again only one or a few consistent arguments.

The problem with your case is that this is in-between, they are simple enough that you can follow the flow easily in an if test, but they are not all so simple that they can be put into lambdas without sacrificing clarity (it is possible to put all but one in lambdas, but half would be really hard to read).  Further, there are not so many situations that it becomes hard to read in an if chain (although it is getting close), and there are enough arguments (or enough inconsistency in the arguments) that it is getting to the point where I would not use the dict approach even if all the other criteria were satisfied (although again it is kind of borderline).

Ultimately, what it comes down to is whether the dict approach helps or hurts readability.  In your case, I think it hurts it.  If the criteria I described above hold, then it will probably help it (although you really need to look on a case-by-case basis, since there will be corner cases either way).


JMS configuration -- client exclusive messages

The code looks fine although I'm not familiar with JMS, so I can't say anything about it's correctness. Just three minor notes:

userMessage could be declared inside the try block:

try {
    byte[] in = new byte[(int) jmsMessage.getBodyLength()];
    jmsMessage.readBytes(in);
    ObjectInputStream inStream = new ObjectInputStream(new ByteArrayInputStream(in));
    MyObject userMessage = (MyObject) inStream.readObject();
...

(Effective Java, Second Edition, Item 45: Minimize the scope of local variables)

protected Logger log = LoggerFactory.getLogger(getClass());

The logger could be private.

(Item 13 of Effective Java 2nd Edition: Minimize the accessibility of classes and members.)
The logger also could be static. There is a good template for Eclipse for generating getLogger calls with MyType.class classes instead of getClass():

private static final Logger log = LoggerFactory.getLogger(QueueMessengerMessageListener.class);


Encapsulate implementation details and any ugliness in a function. Readability is paramount.

For example, a more elegant solution,

package main

import (
    "math/rand"
    "time"
)

// delay returns a random delay, in nanoseconds,
// between min and max seconds.
func delay(min, max float64) time.Duration {
    // time doesn't go backwards
    if min < 0 || min > max {
        return 0
    }
    // delay in seconds
    d := min + rand.Float64()*(max-min)
    // delay in nanoseconds
    return time.Duration(d * float64(time.Second))
}

func main() {
    dMin, dMax := 1.2, 2.7

    time.Sleep(delay(dMin, dMax))
}

By design, Go is type safe. Conversions between diffent types must be explicit.

Unless you have a very large number of occurrences of a floating-point variable and you can tolerate the loss of precision, use type float64, not float32.

  behemoth : something of monstrous size. Merriam-Webster

  a behemoth of type conversions. uli

I only found a few type conversions in the code you posted.


Cleaning up an utterance using multiple regex substitutions

If you use a regular expression once, you don't get any performance improvement from compiling it. You could just use re.sub directly.
If a string doesn't contain any special characters, there's no point in using a raw literal.
r' ' could be just ' '.
Using the same variable to represent different things is a bad practice. It confuses the people who read your code. It's not a good idea to do things like:

message_ascii = re.compile(r'[^\x00-\x7F]+')
message_ascii = message_ascii.sub(r' ', utterance)

because the same variable holds a compiled regex in the first line and it's reassigned to a string later on.

If you call this function multiple times and want to benefit from pre-compiled regular expressions, you could create a new class that compiles the expressions in its constructor and reuses them:

class TextProcessor:

    def __init__(self):
        # Initializes regular expressions here
        self.ascii_regex = re.compile(...)
        # Other expressions go here

    def process_text(self, text):
        ascii_text = self.ascii_regex.sub(' ', text)
        # The rest of the substitions go here


Ensuring file handle is closed in case of an exception

Your situation
Use closes the resource at the end of the block (lambda).
This means that the stream is closed before returning it.
The problem with reading lines
The file needs to be closed once you have read the needed lines.
The stream could close the file once the stream last item is reached.
The problem with this approach is that functions like limit, take, splititerator etc. are making it possible that the last item is never reached.
Therefor, you can do two things.
The first option is to let the caller close the file or sequence/stream/whatever you return.
The second option is to close inside your function, but then you need to do all the reading inside the function, so before you return from the function.
Options
You can read everything immediately by storing everything in a list using readlines.
(This means you read the whole file into memory, which means you should not do this for huge, huge, huge files, you almost always can ignore this warning).
fun readLines(path: String): List<String> = try{
    Paths.get(path).toFile().readLines()
} catch(ex: Exception) {
    ex.printStackTrace()
    emptyList<String>()
}

The other approaches work by moving the code you would normally do outside the function inside the function.
For example the forEachLine:
fun forEachLine(path: String, action: (String)->Unit){
    try{
        Paths.get(path).toFile().forEachLine(action)
    } catch(ex: Exception) {
        ex.printStackTrace()
    }
}

With that function you could rewrite
val t = readLines("somePath")
    .filter{ it.startsWith("ok:") }
t.forEach{ println(it) }
t.close()

with
forEachLine("somePath"){
    if(it.startsWith("ok:")
        println(it)
}

If you have functions that operates on a sequence of strings, or want more than a simple forEach, you can access the sequence itself by using  useLines, but again move the reading inside the function:
fun useLines(path: String, action: (Sequence<String>)->Unit){
    try{
        Paths.get(path).toFile().useLines(action)
    } catch(ex: Exception) {
        ex.printStackTrace()
    }
}

Can replace the former example with:
useLines("somePath"){ lines->
    lines.filter{ it.startsWith("ok") }
       .forEach{ println("it") }
}

NOTE: this function is not for extracting or returning the sequence.
all the functions needs to be done in the lambda,until you come across a terminal operation, an operation that no longer returns a sequence.
NOTE: sequence is the Kotlin-version of streams with lots of benefits.
Is closing required
from the javadoc

"...Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing ..."

so yes.
huge files
You should not use readlines on huge files.
What is a huge file?
The bible has around 31,000 lines which can have 20 bytes reference, so 620,000 bytes or roughly 0,5 mb.
The bible has 3,000,000 characters which is roughly 12 mb.
Acording to this post, Android has a memory limit from around 15mb (in the worst case).
This means that reading the bible in it entirely would theoretically be OK.
So, untill you run into problems, this is nothing to worry about.
Edit:
I don't completely know how flatmap in Java excactly works at the moment.
There was a bug that flatmap was not lazy.
This means that calling fileNames.flatMap(::readLines) with the readLines from your code was calculating the complete list before moving on: link.
This bug is fixed, so I don't know what it does at the moment.
If it still works the same way, it always closes the file for you, but it does so because it always parses the complete file.
In every case, if you are returning the Java-stream, calling close on the returning Stream is enough to close the file.
With sequences, this is not possible, as sequences are not closeable (They also don't know about AutoCloseable/Closeable).


Wrap conditions to be visible

The first order of business when having long if conditions is to wrap lines at each and every && or ||, and in general to wrap the lines
so that you are able to see the conditions without scrolling. If you have to scroll, you'll loose context straight away. This will render your code into the following:

if ($exceptionmodel->getValue() === ExceptionModel::VALOIR
    && (  ($mood->getValue() === Mood::Indicatif
           && $tense->getValue() === Tense::Present
           && in_array($person->getValue(),
                     [ Person::FirstPersonSingular,
                       Person::SecondPersonSingular,
                       Person::ThirdPersonSingular
                     ]))
        || $tense->getValue() === Tense::Futur
        || ($mood->getValue() === Mood::Conditionnel
            && $tense->getValue() === Tense::Present)
        || ($mood->getValue() === Mood::Imperatif
            && $tense->getValue() === Tense::Present
            && $person->getValue() === Person::SecondPersonSingular
           )
       )
   )
{
    $word_stem = word_stem_length($infinitiveVerb, 4) . 'u';
}

if ($exceptionmodel->getValue() === ExceptionModel::VALOIR
   && ($mood->getValue() === Mood::Subjonctif
       && $tense->getValue() === Tense::Present
       && in_array($person->getValue(),
                   [
                     Person::FirstPersonSingular,
                     Person::SecondPersonSingular,
                     Person::ThirdPersonSingular,
                     Person::ThirdPersonPlural
                   ])
      )
   )
{
    $word_stem = word_stem_length($infinitiveVerb, 4) . 'ill';
}

In addition to making them all visible, I've indented the different blocks as best I can. Possible bug: Do you have an parenthesis issue in the first if block after the in_array() where there seem to be missing an parenthesis? I've changed it here, but you need to reiterate it, to verify its correctness. In general if you wrap and get alternating && vs || you need to take care and verify correctness regarding ordering and grouping of conditionals.

Also note how I moved the starting brace, {, to the next line to keep it aligned with both the if and the ending brace, }. This also gives a much needed vertical space to break between conditions and the statement to be executed.

I've put the ending parenthesis, ), on a separate line as well, this comes somewhat down to personal taste, so do that if that pleases you. Or pack them together on the previous line. Just be consistent, and when dealing with long lines like in this block, try avoid having more than one condition on any line.

Precompute condition parts

Another good option can be to precompute the parts used in the condition. This has at least the following advantages:

Shorten the condition statement in general
Make it read more easily, as you clearly indicate the test condition
Avoid computing values more than once, i.e. $tense->getValue()
Simplify grouping and ordering of multiple conditions
Reuse of condition part in following if statements

Doing this you can end up with the following:

// Precompute condition parts
$exceptionIsValoir = $exceptionmodel->getValue() === ExceptionModel::VALOIR;

$moodVal =  $mood->getValue();
$moodIsIndicatif = $moodVal == Mood::Indicatif;
$moodIsConditionnel = $moodVal === Mood::Conditionnel;
$moodIsSubjonctif =  $moodVal === Mood::Subjonctif;

$tenseVal = $tense->getValue();
$tenseIsPresent = $tenseVal=== Tense::Present;
$tenseIsFutur = $tenseVal === Tense::Futur;

$personVal = $person->getValue();
$personIs_2S = $personVal == Person::SecondPersonSingular;
$personIs_1S_2S_3S = in_array($personVal, [
    Person::FirstPersonSingular,
    Person::SecondPersonSingular,
    Person::ThirdPersonSingular
  ]);
$personIs_1S_2S_3S_3P = in_array($personVal, [
    Person::FirstPersonSingular,
    Person::SecondPersonSingular,
    Person::ThirdPersonSingular,
    Person::ThirdPersonPlural
  ]);

// The actual validations
if ($exceptionIsValoir
    && (   ($moodIsIndicatif && $tenseIsPresent && $personIs_1S_2S_3S)
        || $tenseIsFutur
        || ($moodIsConditionnel && $tenseIsPresent)
        || ($moodIsImperatif && $tenseIsPresent && $personIs_2S)))
{
    $word_stem = word_stem_length($infinitiveVerb, 4) . 'u';
}

if ($exceptionIsValoir
    && ($moodIsSubjonctif && $tenseIsPresent && $personIs_1S_2S_3S_3P))
{
    $word_stem = word_stem_length($infinitiveVerb, 4) . 'ill';
}

Early returns to reduce nesting levels

The concept of early returns to reduce nesting levels, is that if you have a structure like the following with no else block on the first few levels:

function something() {
    if first_level_condition {
        if second_level_condition {
            if third_level_condition and something {
                do something useful
            } else {
                do something else
            }
        }  // Note missing else block on second level
     }  // Note missing else block on first level
}

Then you can simplify this to:

function something() {
    if not first_level_condition
       or not second_level_condition {
        return
    }

    if third_level_condition and something {
        do something useful
    } else {
        do something else
    }
}

Now you've moved your code of interest, that is level three, out two indentation levels, which gives you some more room to write code in.

At first glance of your example, it seemed like you could do this in your code as the two original cases both had the common element of $exceptionmodel->getValue() === ExceptionModel::VALOIR, which could have been negated, and caused an early return. However in your added excerpt, and in the original code many more variants exists making this not so useful in your context.

It is still a useful pattern to be aware of, when doing multiple if statements and nesting of these.

(Optionally) Build condition groups

Another option which I've used sparingly is to actually precompute the entire groups of condition statements, using constructions like the following:

// Precompute condition parts
... as before ...

// Build condition group
$c = ($moodIsIndicatif && $tenseIsPresent && $personIs_1P_2P_3P)
$c = $c || $tenseIsFutur
$c = $c || ($moodIsConditionnel && $tenseIsPresent)
$c = $c || ($moodIsImperatif && $tenseIsPresent && $personIs_2S)

if ($exceptionIsValoir && $c)
{
   $word_stem = word_stem_length($infinitiveVerb, 4) . 'u';
}
...

This construct can be useful in some circumstances, but in your case I believe I would stop at precomputing the condition part using good condensed variable names, and do an early return if possible.

Addendum 1: Automating generation of condition variables

You ask if one can automate stuff like $exceptionIsValoir or $tenseIsPresent, and as I'm a bit rusty I php I posted my version as a question here: Dynamic variables in Php from enum. But it is possible to make dynamic variables in PHP, and one way of doing it is:

$exceptionVal = $exceptionmodel->getValue();
foreach(ExceptionModel::getConstants() as $constName => $constValue) {
    ${'exceptionIs' . $constName} = $exceptionVal === $constValue;
}

$tenseVal = $tense->getValue();
foreach (Tense::getConstants() as $constName => $constValue) {
    ${'tenseIs' . $constName} = $tenseVal === $constValue;
}

This would allow you to use $exceptionIsALLOIR or $tenseIsPresent. You could optionally change the first one to use $exception_is_ALLOIR by changing the constant string prefix.

With regards to the use of in_array() within the if conditions, I'm no personal fan of it. This is partly because it is lengthy and kind of confusing as you prefix the enums with full class name. I would rather precompute these manually, like in $personIs_1S_2S_3S, as this can shorten the text compared to the rather lengthy version of $personIsFirstPersonSingular || $personIsSecondPersonSingular || $personIsThirdPersonSingular.

Regarding precomputing combinations of ExceptionModel, I would do it on a case by case basis. Possibly I there would use the or'ed combination as I don't see a neat way of shortening the names as is easily done for the Person enum.

Addendum 2: Reconsider general concept of word_stem()

When following your links to the original code I see that word_stem() is a rather long function consisting of above 40 disconnected if statements similar to the two above (or four in modified post), spanning over 300 lines. That is a heavy function, and raise some concerns:

Can it be simplified by using other functions?
Can it be simplified by connecting together the if's, so that you don't need to execute all of them each and every time?
How do you test such a massive beast if it is correct at all?
If you match on one of the if's, does that exclude all others? In other words, can you do return $word_stem directly instead of at end?

Without looking into the functions too much, I would consider if you should make functions like word_stem_Exer_Exe and word_stem_xER and word_stem_ENVOYER, and let the code in word_stem() be:

if ($exceptionIs_ELER_ELE_or_ETER_ETE) {
    $word_stem =  word_stem_Exer_Exe($person, $tense, $mood);
}
if ($exceptionIsCER or $exceptionIsGER or $exceptionIsE_Akut_CER
    or $exceptionIsE_Akut_GER)
{
    $word_stem =  word_stem_xER($person, $tense, $mood);
}
if ($exceptionIsENVOYER) {
    $word_stem = word_stem_ENVOYER($person, $tense, $mood);
}

Or possibly use if ... else if ... else if which would stop evaluating the if sequences at first hit. In other words, this would require that only one of the 40++ if's matches. Using return directly would also eliminate evaluating further if's effectively.

Using functions like word_stem_xxxx() would also ease the testing some, as you could specific test that exception group. With these functions you would then move the person, tense and mood tests inside of the function, and then they could possibly be clearer in general even without that much shortening. You could then possibly only use the first tip of $tenseVal = $tense->getValue() to shorten them sufficiently.

Disclaimer: I don't know the entire context, and haven't thoroughly read the accompanying code, so consider this carefully before reimplementing into sub-functions or else-if's as that might have side effects not known to me. Then again, you might have a lot of side effects already in the massive beast that word_stem() is.

Addendum 3: Automagical is<ENUM_VALUE>() methods

An alternative approach to creating the temporary variables, is to use reflection and automatically define test function for equality to any given enum value.

If extending the base Enum class, or the ExtensionModel class with the following function:

function __call($func, $param) {
    $func_prefix = substr($func, 0, 2);
    $func_const = substr($func, 2);
    if ($func_prefix == "is") {
        $reflection = new ReflectionClass(get_class($this));
        return $this->getValue() === $reflection->getConstant($func_const);
    }
}

Then it is legal to do stuff like in the following test function:

function myFunction(ExceptionModel $exceptionModel, Tense $tense) {

    if ($exceptionModel->isALLER()
        && $tense->isPresent() ) {
        ... do something ...
    }

given that both ExceptionModel and Tense inherits from the Enum class. In other words, now you can do $enumobject->is<ENUM_VALUE>() for any enum value inheriting from Enum.

  PS: After posting my original answer you added two more excerpts. I've not included those in my analysis, but the concept will be the same only with a few more lines added.


Your parser will of course only be able to handle very specific input. For example leading whitespace in front of # or passing garbage values as numbers in your config file.

If you want to improve this, I would first start by not ignoring the return value of sscanf.It will return the number of items it could successfully parse. This could also be used to generate useful error messages.

The file that you are opening should be closed with

fclose(fp).

Your read_*_from_config_line methods have a potential buffer overflow issue when the variable length is longer than MAX_CONFIG_VARIABLE_LEN. In this case you can just increase the buffer size, as you know that the strings are not longer than CONFIG_LINE_BUFFER_SIZE but generally you should try to avoid using sscanf and the likes.


Comparing a list of known animals to a master list of animals

This is the sort of thing that Python is really good at.  Your code seems like it functions, but it will be very inefficient for large data sets. For each input value you have to check every line in the the master list -- and the way you have it set up here you're going to read the master list off disk for each input value as well, so it will be really slow.

The first step obvious fix is to load the master list into memory and keep it around for the duration of a session.  This is a fairly simple change to your existing code.  First, change your pull_lines so it returns a dictionary instead of a list:

def pullLines(file_input):
    '''returns a dictionary of the entries in <file_input> keyed by the first item in each line'''
    master_dict = {}
    with open(file_input,'rU') as info:
        for eachline in info.readlines():
            tokens = eachline.split()
            master_dict[tokens[0]] = tokens[1:]

Then, you move pull lines out of the inner loop:

lookup = pull_lines(path_to_file)
with open(results_list,"w+") as output:
    output.write(getHeader(master_list))
    for item in pullIDs(known_stars):
        if item in lookup:
            output.write(lookup[item])

This has a couple of advantages

1) not hitting the disk for every query will be much faster

2) the dictionary lookup faction is much faster than straight for loop comparison, since the dictionary uses hashed values instead of more expensive string compares.

As an aside, you should look into readlines, which the usual pythonic way of reading text files with info on lines.

For the longer term this is a great application for Python's built in database functionality (with the sqllite module). You could convert your existing text files into a sqllite database and then your lookups can be much more flexible and precise ('find spectrum and power for stars with id > X and < Y' sort of thing).  You probably also want to set this file up so you could call it from the command line, which would involve using the argparse module to grab command line arguments and out them into known_stars, master_list and output_file


As you have already mentioned, DbContext is a UoW, and DbSet is a repository -- there is no need to reimplement those patterns, unless you're into ridiculously useless complexity.

Entity Framework wraps all pending changes in a transaction for you already, so each DbContext in an application contains DbSets that are somehow related. Blogs and Posts are definitely related, so they belong under the same context.

If your app had a blog module and a completely distinct chat module, you could use separate contexts, as your app would never be using both in the same controller.

I have an app with dozens of absolutely unrelated modules; either I defined a single context with 650 entity types (and only used a fraction of it every time), or I broke it down into much smaller and sanely manageable modules... I went for the second option. (the app is an ERP extension)


How to optimize bitwise get/set/clear of ranges of bits on 8-bit integers in JavaScript?

For any of the following suggestions, please do profile them to test the performance difference. Performance is likely to vary across multiple browser implementations of the JavaScript interpretation engine.
Rather than a loop for getNumBits, try Math.floor(Math.log(n)/LN_2) - or maybe trunc instead of floor - where LN_2 is precomputed as Math.log(2).
Try to avoid single-letter variables. Your functions are very impenetrable and will be neither legible nor maintainable by anyone else, or by you in a few weeks. In other words, you should not be a human minifier.
Rewrite your code to assume that the index is zero-based starting from the least-significant bit and going left. This will greatly simplify your code and will obviate calls to getNumBits.

Example implementations:
const LN_2 = Math.log(2);

function getNumBits(n) {
    return Math.trunc(Math.log(n) / LN_2) + 1;
}

function getBitRange(n, startIndex, size) {
    return (n >> startIndex) & ((1 << size) - 1);
}

function setBitRange(n, startIndex, size, value) {
    const mask = (1 << size) - 1;
    return (
        n & ~(mask << startIndex)
    ) | ((value & mask) << startIndex);
}

function clearBitRange(n, startIndex, size) {
    const mask = (1 << size) - 1;
    return n & ~(mask << startIndex);
}

A comment about getNumBits and the alternate implementation offered by @potato. That one is indeed faster than calls to log; a local test of mine using Node and 10,000,000 iterations indicates by a factor of about 16. But that needs to be taken with a grain of salt.
If you're (for some reason) doing a massive amount of client-side data processing and needing to call this function many thousands of times, it might be justified (with HEAVY commenting) to use the bit-twiddle method. In all other cases, I don't recommend using something that's so obscure and difficult-to-understand.


First impressions - this code is very clear.  I like the variable names - that makes lines like if straight and flush read very naturally.

I don't think there's a need to treat a Royal Flush separately - this is the same rank as Straight Flush, just with the largest possible high-card.  The "should not occur" comment is irrelevant - no matter how rare, we must correctly score Straight Flush (and we would expect a thorough test set to include some).

Instead of needing a separate tiebreaker function to evaluate the kickers, we could return a tuple from eval_hand, with the kickers following the rank+value.  We're already doing something like that for Full House; it's easy to extend that throughout.  I'd collect values in descending order:

values = sorted([c[0] for c in hand], reverse=True)
straight = (values == range(max(values), min(values)-1, -1)) # but see below

Then we can return as much as is necessary for the rank:

if straight and flush:
    return 8, values[0]

if three_of_a_kind and pair_present: return 6, three_value, pairs[0], values
if flush: return 5, values
if straight: return 4, values[0]
if three_of_a_kind: return 3, three_value, values
if len(pairs) == 2: return 2, pairs, values
if len(pairs) == 1: return 1, pairs[0], values

Counting pairs/trips/quads can be simplified, given that we have the values in sorted order.  We can use itertools.groupby() to get the count of identical values, rather than needing to search with values.count():

trips = []
pairs = []
for v, group in itertools.groupby(values):
    count = sum(1 for _ in group)
    if count == 4:
        return 7, v, values
    if count == 3:
        trips.append(v)
    elif count == 2:
        pairs.append(v)

Some additional test cases indicated a few problems:

The test for a straight doesn't work when I compare a list against a range (Python 3.6.5).  I needed to materialise it as a list first:

straight = values == list(range(values[0], values[-1]-1, -1))

We don't test for an ace-low straight:

straight = (values == list(range(values[0], values[0]-5, -1))
            or values == [14, 5, 4, 3, 2])

Flushes should be comparable - highest differing card still tie-breaks between flushes of different suits.

And some simplifications:

Straights and flushes can both be returned before checking for pairs/trips/quads
We don't need boolean flags to say that three_value or pairs is populated - we can directly test those variables are truthy or not.
For ranks 0, 1, 2, the rank is exactly the number of pairs found.
Instead of try/except, we can populate value_dict with the digits 2 to 9.
We're not required to find anything other than the number of Player 1 wins, so remove the code that was useful while debugging.

Applying the above, I get the following modified code:

import itertools

value_dict = {'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}
value_dict.update((str(x), x) for x in range(2,10))

def eval_hand(hand):
    # Return ranking followed by tie-break information.
    # 8. Straight Flush
    # 7. Four of a Kind
    # 6. Full House
    # 5. Flush
    # 4. Straight
    # 3. Three of a Kind
    # 2. Two pair
    # 1. One pair
    # 0. High card

    values = sorted([c[0] for c in hand], reverse=True)
    suits = [c[1] for c in hand]
    straight = (values == list(range(values[0], values[0]-5, -1))
                or values == [14, 5, 4, 3, 2])
    flush = all(s == suits[0] for s in suits)

    if straight and flush: return 8, values[1]
    if flush: return 5, values
    if straight: return 4, values[1]

    trips = []
    pairs = []
    for v, group in itertools.groupby(values):
        count = sum(1 for _ in group)
        if count == 4: return 7, v, values
        elif count == 3: trips.append(v)
        elif count == 2: pairs.append(v)

    if trips: return (6 if pairs else 3), trips, pairs, values
    return len(pairs), pairs, values

player1_wins = 0
with open("p054_poker.txt") as f:
    for line in f:
        cards = [(value_dict[x[0]], x[1]) for x in line.split(' ')]
        player1_wins += eval_hand(cards[:5]) > eval_hand(cards[5:])

print(player1_wins)


Simple wrapper for member function pointers with known signature

Sorry for the brief answer, typing on phone.

Your NetworkPublisher should have Register(int signal, std::function<void()> callback)

And then simply do:

publisher.Register(WHATEVER_SIGNAL, std::bind(&MyClass::MySignalCallback, this));

This way you dont need the PacketCallback class and your subscriber interface is more generally usable as you can now pass lamdas and free functions as well. Further more your NotifySubscribers will simplify a bit.

Side note: You might want to consider using smart pointers instead of raw pointers. Or references if null is not an allowed argument.

Edit: In reply to comments, this is one way I would consider of doing it:

enum class SignalType{
   NewConnection,
   ConnectionLost
};

const std::array<SignalType,2> AllSignalTypes = {
    SignalType::NewConnection,
    SignalType::ConnectionLost};

class ISubscriber{
public:
    virtual bool supportsSignal(SignalType signalType) const = 0;
    virtual void signal(SignalType signalType, const RakNet::Packet& packet) = 0;
}

class Publisher{
public:
    void registerSubscriber(const std::shared_ptr<ISubscriber>& subscriber){
        for(auto& type : AllSignalTypes){
            if(subscriber->supportsSignal(type)){
                // TODO: Check for duplicates or change to std::unordered_set<weak_ptr>
                subscribers[type].emplace_back(subscriber);
            }
        }
    }

    void signal(SignalType signalType, const RakNet::Packet& packet){
        forEachLiveSubscriber(signalType, [&packet](const std::shared_ptr<ISubscriber>& subscriber){
            subscriber->signal(signalType, packet);
            return true;
        });
    }

    void unregisterAll(const ISubscriber& subscriber){
        // Technically not necessary but for good measure
        for(auto& type : AllSignalTypes){
            forEachLiveSubscriber(signalType, [&packet](const std::shared_ptr<ISubscriber>& sharedSubscriber){
                return sharedSubscriber.get() != &subscriber;
            });
        }
    }

private:
    std::unordered_map<SignalType, std::vector<std::weak_ptr<ISubscriber>>> subscribers;

    template<typename Callable>
    void forEachLiveSubscriber(SignalType signalType, Callable&& callback){
        auto& signalSubscribers = subscribers[signalType];

        auto it = signalSubscribers.begin();
        while(it != signalSubscribers.end()){
            auto& strongPtr = it->lock();
            if(strongPtr && callback(strongPtr)){
                it++;
            }
            else{
                // The subscriber has destructed without unregistering,
                // Or the callback requested us to remove it.
                it = signalSubscribers.erase(it);
            }
        }
    }
}

class MySubscriber : public ISubscriber{
    bool supportsSignal(SignalType signalType) const override{
        return signalType == NewConnection || signalType == ConnectionLost;
    }

    void signal(SignalType signalType, const RakNet::Packet& packet) override{
        switch(signalType){
            case NewConnection:
                std::cout<<"Someone connected"<<std::endl;
                break;
            case ConnectionLost:
                std::cout<<"Someone lost connection"<<std::endl;
                break;
        }
    }
}

Note that by using shared_ptr we get access to weak_ptr which in turn allows lazy garbage collection of the subscribers. In turn this means that a subscriber doesn't have to unregister if all shared pointers to it just simply die.

The above code is untested pseudocode. Some assembly may be required :)


Truncating long strings when saving inventory items to database

Making duplicate testing just to avoid a method call doesn't make much sense. Method calls are not that expensive. On the contrary, they can help make the code cleaner.

You can make a method that helps you clean up the strings, just pass in how long each string may be. I think that maked the code as DRY as possible:

private string TruncateString(string value, int maxLen) {
  value = value.Trim();
  if (value.Length > maxLen) {
    value = value.Substring(0, maxLen);
  }
  return value;
}

private InventoryItem TruncateVerboseStringMembers(InventoryItem invItem) {
  invItem.Description = TruncateString(invItem.Description, 35);
  invItem.vendor_id = TruncateString(invItem.vendor_id, 10);
  invItem.vendor_item = TruncateString(invItem.vendor_item, 12);
  return invItem;
}

This will give you the overhead of always calling the method for each string and always assigning the reference back, but those are very cheap operations. Compared to any database call, it's negligible.

If there is nothing in the string to trim, and nothing to truncate, you will actually be putting back the original string reference in the property, so there are no extra strings created in the usual case.


You may want your properties to be private set so that they can't be changed from the outside:

public class Office
{
    public Int32 SyncID { get; private set; }
    public string OfficeName { get; private set; }
}

To do that you can make GetOffice a member of Office instead of OfficeRepository.

Or you can define a constructor ...

// Logically immutable
public class Office
{
    public Office(Int32 SyncID, string OfficeName)
    {
        this.SyncID = SyncID;
        this.OfficeName = OfficeName;
    }
    public Int32 SyncID { get; private set; }
    public string OfficeName { get; private set; }
}

... and change your GetOffice method to invoke the constructor instead of invoking the set properties.

Similarly, OfficeMgrViewModel needn't have a public set property if it had a constructor.

See also this answer which mentions how to simplify your GetOffice method to not use a List, if you expect that your join where will never produce more than one record.


What is Model in MVC?

  Now I know that a model shouldn't need anything specific - everything has to be generalized so it's accessible from multiple controllers which do something different.

A model is not a generalized concrete class, but a virtual layer that contains all business logic which in a good architecture would also contain it's own layers (application, domain and infrastructure) for more abstraction.

How to do specific things with a generalized model concrete class?

  My main issue, though is: How the hell do I tell the model to save something the way I want it to? If it's generalized, it should have no information about any save table, any output message or any saving pattern to begin with.

Because it's not generalized (as I just explained above) this problem should now be solved.

Controller

The following diagram might give you a better visual picture of the (one of the possible)  data flow in a MVC structure.

Do note that with the orthodox MVC pattern the Controller is not supposed to call or instantiate any views, but solely control the Model layer, nothing else. However, over the years this has changed due to I don't know what. But nowadays what you'll mostly see and hear is that a Controller's job is to control the model layer and call / return the appropriate view.

Your Case

I see you have a private sendMail() method in your Controller. Well, that doesn't belong there. In your model layer (specifically the application layer) I would have a class like EmailService that would contain this sendMail() method.

In your Controller you can now just get the needed parameters from a http request object and call $this->emailService->sendMail($data); or something of sorts. And finally call the appropriate view, if any (if you follow the contemporary MVC pattern that is).


Your get_pair_of_socks seems to be initializing a pile of socks, so you have the wrong name.

If I understand things correctly, you initialize a pile of "left" socks, then initialize a pile of "right" socks (socks don't have left and right, but the labels make it easier to keep track of what's going on), and then put the pile of "left" socks on top of the "right" pile. So each half of the final pile has only one copy of each sock pair. This is an odd situation to be simulating. I recommend initializing the pile in one go with random.sample(list(range(number_of_socks_to_consider))*2,2*number_of_socks_to_consider).

I think you could just take the sock on the top of the pile without affecting the results, rather than the complicated pop statement you're currently using. (A random element from a random permuted set isn't any more random than the first element from a randomly permuted set).

first_pair seems to be the first sock in the attempted pair, while second_pair is the  second sock, which, again, is poor naming (perhaps you are confusing "pair" with "partner").

I don't think you're following the algorithm describes in that link: that involves taking a sock, then taking the rest of the socks in order, while you are taking a sock, then checking the remaining socks with replacement, which again is making it take longer.

You don't need a separate case to handle the first sock you try to pair with the sock you picked. You can just do this:

    first_pair = socks.pop(index_to_pull_sock_from(socks))
    attempt_count = 0
    while True:
        attempt_count = attempt_count + 1
        random_pick = index_to_pull_sock_from(socks)
        second_pair = socks[random_pick]
        if second_pair == first_pair:
                break


database connection, fetching rows and handling error in csharp

using (SqlConnection sqlConnection = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;pooling=true"))
  {
      ...
      }
      finally
      {
          sqlConnection.Close();
      }
  }

You're correctly using a using statement for the connection, which will both close and dispose the connection when its scope finishes. So no need to explicit call Close().

Almost (if not) every database related object implements IDisposable - including SqlCommand, so you should encapsulate that in a using as well.

All in all, your method should look like something like this:

public List<Department> FindAllDepartment()
{
  using (SqlConnection sqlConnection = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=sa;Password=P@ssw0rd;pooling=true"))
  {
    sqlConnection.Open();

    using (SqlCommand command = new SqlCommand("SELECT * FROM Employees.dbo.Department", sqlConnection))
    using (SqlDataReader sqlDataReader = command.ExecuteReader())
    {
      List<Department> rows = new List<Department>();
      while (sqlDataReader.Read())
      {
        rows.Add(new Department(sqlDataReader.GetInt32(0), sqlDataReader.GetString(1)));
      }

      return rows;
    }
  }
}

where the using statements handle the clean up - even if an exception is thrown.


All combinations of a string with special characters

Well, you can simply find out where the * can be, e.g.:

___, __*, _**, _*_, **_, ***,*__

and then replace:

fin, fi*, f**, f*n, **n, ***,*in

Code:

public static String[] possibleCombinations(String s) {
    int length = s.length();
    char[][] strings = new char[length * (length + 1) / 2][length];
    for (int i = 0; i < strings.length; i++) {
        strings[i] = s.toCharArray();
    }
    strings[0][0] = '*';
    for (int i = 0, j = 0, counter = 0; i < length; i++, counter += length - i + 1, j = i) {
        for (; j < length; j++) {
            for (int k = j; k < length; k++) {
                strings[counter + k - i][j] = '*';
            }
        }
    }
    String[] result = new String[strings.length + 1];
    result[0] = s;
    for (int i = 0; i < strings.length; i++) {
        result[i + 1] = new String(strings[i]);
    }
    return result;
}

It's fairly fast:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
**aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
***aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
...
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa***
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*a
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa**
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*
length: 50
Time taken: 1064956 nanoseconds

Length: 500
Time taken: 733033361 nanoseconds


Schedule matches for a season or round robin tournament

Use readable variable names. I can guess at the meaning of sch (schedule?) and  rr (round robin), but I'm at a loss for w (week?) and p. There's no reason to shorten the names, it does not affect the execution of the code; it does affect the readability. Everything might make sense to you today, but not to other people, or you in the future.
Using arrays versus lists is (at least partially) subjective), but I do think that you should be using lists here. It keeps the syntax cleaner and doesn't require readers to keep track of the array indexes.

The for loops are adding so much to the complexity. w < TeamCount - 1 and p < TeamCount / 2 are not easy to understand the intention. If you stick to using lists, that guides you towards using a more readable foreach statement, e.g. foreach(week in weeks)

bool awayHome = false is a very confusing name. A better name would be generateReverseMatch (or whatever designated name you prefer)
Personally, I like to keep the constructor focused on property/field assignment. I would abstract the match generation into a private method, which can still be called from the constructor: Matches = GenerateMatches(teamCount);
While not wrong per se, be on the lookout of overzealously using ToString() instead of a nicer  PrintMatches() method. Most of the time, you want a custom layout, especially if you want to have different ways of showing the same season.

Switching the code over to using lists instead of arrays is going to have a strong impact on the posted code, so I'm not sure if further code review is going to be relevant here.


std::shared_ptr has a contextual conversion to bool, just like raw pointers.  So instead of comparing to nullptr, you can simply write

if (!myObject)

The raw string seems to be unnecessary:

std::string query =
    "INSERT INTO myObject (EquipmentId, ExerciseId ) VALUES (?1, ?2)";

I don't think you need the ; statement terminator in SQL queries that are already bounded by C++ API calls - they are needed in an interactive SQL shell but not here.

When we exit early (via throw of an exception), is there some mechanism to abort the transaction for us?  And to finalize the statement?

Prefer to declare your variables nearer to where they are used - specifically, lastInsertedId is a long way from where you use it:

  int lastInsertedId = -1;
  if(returnCode == SQLITE_ROW)
  {
    lastInsertedId = sqlite3_column_int(sqlStatement, 0);
  }

Or even

  const int lastInsertedId = returnCode == SQLITE_ROW
                             ? sqlite3_column_int(sqlStatement, 0)
                             : -1;


Identifying array elements, rearranging them, and replacing them

It's extraordinarily confusing to have if (fast == nums.length - 1) as a conditional within a loop that continues while fast < nums.count returns true.  This is the last part of the loop, and it only executes on the last iteration of the loop... so why is it even in the loop at all?

A couple of comments in our code can help us out.  We have two distinct parts:

Shuffling the non-tens to the front.
Zero-ing out the tens.

So let's use comments to mark these in distinct blocks.  And, let's move the second part to its own loop.

And while we're at it, let's make the method more generic to replace any number with another given number.

public int[] replaceNum(int[] nums, int eliminationNum, int replaceNum) {
    int nextMoveIndex = 0;

    // shuffle non-elims to the front
    for (int i = 0; i < nums.length; ++i) {
        if (nums[i] != eliminationNum) {
            nums[nextMoveIndex++] = nums[i];
        }
    }

    // zero out the elimination number
    while (nextMoveIndex < nums.length) {
        nums[nextMoveIndex++] = replaceNum;
    }

    return nums;
}


Filtering ASP.NET membership roles without the default attributes

public abstract class BaseController : Controller
{
    public MasterDbContext Context { get; } = new MasterDbContext();
}

I really don't like this. Every single controller class derived from BaseController has a public IDisposable dependency. That's taking encapsulation for a little "talk", outside, in a dark alley.

I can't think of a single reason Context would need to be public for. It should be protected.

But that's not the biggest issue. From the outside, say, from a derived class' point of view, inheriting from BaseController seems like a casual thing to do: the name suggests it, strongly.

Every derived controller inherits an IDisposable dependency that it didn't ask for - and since the base class creates it and doesn't take its responsibilities (he who creates an IDisposable instance, should be the one to call Dispose), if every derived type fails to override the controller's Dispose method, every single controller is leaking resources.

So you could implement IDisposable.Dispose in the BaseController.

Or, you could simply get rid of BaseController altogether. Disposable resources are important, they shouldn't be implicit. There's a very solidly (yet far from SOLID) tightly-coupled relationship between every controller and MasterDbContext - and that relationship is toxic.

There has to be a better way. This is more explicit:

[Authorize]
[RequiredRole(Roles = Constants.Roles.Moderator)]
public class AdminController : Controller
{
    private MasterDbContext Context { get; } = new MasterDbContext();

    // controller methods...

    protected override void Dispose(bool disposing)
    {
        if (disposing && Context != null)
        {
            Context.Dispose();
            Context = null;
        }

        base.Dispose(disposing);
    }
}

Now now, I hear you - "but what about DRY? I have to repeat that code in every controller?". No you don't.

What you can do, is make it someone else's job to create (and therefore to dispose) the context: you tell that "someone else" that you need a MasterDbContext, and let them deal with its lifetime.

[Authorize]
[RequiredRole(Roles = Constants.Roles.Moderator)]
public class AdminController : Controller
{
    private readonly MasterDbContext _context

    public AdminController(MasterDbContext context)
    {
        _context = context;
    }

    // controller methods...
}

Now anyone can look at that class and know that it requires a Constants.Roles.Moderator role, and that it has a MasterDbContext dependency. It's still coupled with a concrete type, but at least it's explicit about it. And we don't need to worry about disposing the context anymore - a controller that receives its DbContext through the constructor can happily assume that whoever put it there is going to dispose it when it destroys it.. and exactly when that happens is not its job either: the controller had nothing to do with creating the context.

This poses a problem though: the default controller factory requires a default constructor. And if you add one, then your context is always going to be null... which defeats the purpose of telling your caller that you have a dependency on MasterDbContext.

The solution is nothing less than implementing your own controller factory! Kidding. You can simply take an existing one - ninject, for example, will substitute the default controller factory for one that uses the Ninject IoC container to create an instance per request and inject it into the controllers' constructors.

All that's left to do is to tell Ninject that whenever a controller requests a MasterDbContext, you give it a MasterDbContext instance. The registration code might look like this:

Kernel.Bind<MasterDbContext>().To<MasterDbContext>().InRequestScope();

And from there, you're an inch away from being able to do this instead:

Kernel.Bind<IUnitOfWork>().To<MasterDbContext>().InRequestScope();

Which means your controllers can look like this:

[Authorize]
[RequiredRole(Roles = Constants.Roles.Moderator)]
public class AdminController : Controller
{
    private readonly IUnitOfWork _context

    public AdminController(IUnitOfWork context)
    {
        _context = context;
    }

    // controller methods...
}

And here goes the "D" of SOLID:

  Depend on abstractions, not on concrete types.

The IUnitOfWork interface can be a simple, minimal wrapper for DbContext:

public interface IUnitOfWork : IDisposable
{
    IDbSet<T> Set<T>();
    void Commit();
}

And now you can instantiate an AdminController in a unit test, mock the IUnitOfWork dependency, and write unit tests for every controller method!


You say cache I say memory leak.

You haven't given much thought to your eviction policy yet and that's 95% of the work in writing a decent cache. Your expired entries are only removed when someone tries to access them.

Consider the case when the cache is used poorly - i.e. you end up caching a huge number of things that are only accessed once. Without a subsequent access after they are expired, they aren't removed and you have a whole bunch of wasted memory.

Your cache also lacks thread safety - that's also a really, really bad thing for a general cache that you intend on using everywhere. A cache doesn't need to be thread safe if you intend on using it in a single threaded application. However, I'd argue that isn't how most caches are used.

Why don't you use something like MemoryCache to do all the hard work?


Classes are first-class objects in Python.

amap = {
  'zip': zipfile.ZipFile,
  'rar': rarfile.RarFile
}

 ...

with amap[archive_type](encode(f)) as archive:
   ...

or

with amap.get(archive_type, rarfile.RarFile)(encode(f)) as archive:
   ...


Expectation Setting
Your algorithm is an incrementing index, which you then convert in to the radix of your charset.
Your charset is what, 95 characters?
So, there are the following possible permutations for passwords:
1 char -> 95
2 char -> 9025
3 char -> 857375
4 char -> 81450625
5 char -> 7737809375
6 char -> 735091890625
7 char -> 69833729609375
8 char -> 6634204312890625

OK, so, let's assume the person chooses an 8 char password you need to crack, and that it starts about half-way through your alphabet with a 'K'.
That means you will have to calculate about... 3,000,000,000,000,000 passwords before you get to the right one....
Now, let's assume your browser is super fast (like in the scale of a super-computer), and can compute 1 billion passwords each second....
It will need 3,000,000 seconds to get to the right one.... which is.... about 5 weeks (not 2.5 years as originally stated).
Now, your browser, if it is on an amazing PC, will be 1000 times slower.... so, the right way to crack this password this millennium, is to actually wait about 20 years, and then crack it then when computers are a few hundred times faster ;-)
Note, I would not expect even the fastest PC to be able to get to 5char passwords using a single-threaded execution model, in the most optimal way, to check more than 1,000,000 passwords a second, which makes 5 char passwords more than 2 minutes away....
This is one of the joys about brute-force tactics, by the way, is that, in general, the fastest way to crack a brute-force password of reasonable length, is to do nothing.... and wait for technology to get faster... and then start later, and finish sooner.
Alternate algorithm
Using recursion would be a natural way to solve the general problem of checking all solutions, but it has the problem that it checks all solutions in the wrong order (typically it solves the longest passwords first.... which would be counter-intuitive to check a bunch of 8-char passwords before you check all 7 char passwords.
So, you are left with just making the current system faster... and, that's a somewhat fruitless problem, because even halving the time would not be meaningful in most cases.
This leads on to multi-threading, which is the fastest way to accelerate the problem, but I am not sure this is available on your browser.


Read CSV files and find the same values on the specific columns

Pointers to chan

Channel variables are references to an underlying data structure.
As such, in terms of resources, I don't think you gain anything at all by passing a *chan instead of the chan itself.
I re-read the section on channels in Effective Go,
and there's no mention about saving resources by passing around pointers,
and it's not logical.
So I think you can safely stop using a pointer for this and simplify the code.

Likely bug

This can be simplified:

isExistAll := false
for _, data := range datas {
    if data[value] {
        isExistAll = true
    } else {
        isExistAll = false
    }
}

You can use the value of data[value] directly:

isExistAll := false
for _, data := range datas {
    isExistAll = data[value]
}

But I don't think this code does what you intended.
The value of isExistAll will be the value of the last data[value].
I think you want it to be true only of all values are true:

isExistAll := true
for _, data := range datas {
    isExistAll = isExistAll && data[value]
}

Constructing paths

Instead of concatenating strings like dir + file.Name() to create paths,
it's better to use path.Join(dir, file.Name()).


Your code is really hard to follow. It reads and modifies a lot of local fields/properties that are somewhere hidden. I tried to refactor it but it's still buggy I believe as some parameters are unclear. Nevertheless it should give you an idea how to improve it.

Using Tuple is a quick and dirty way to test something because you almost instantly forget what the properties are for as they are simply named ItemX. If you plan to use this code longer then just for experiments I'd use a real class.

You should pass all the parameters that the function needs instead reading them from the some fields or properties... unless it's a part of some class which we don't know.

In particular you could create filter criteria for passing the parameters and return a cheese filter as a result.

You don't need to check the date string for null/empty, the TryParse won't throw on null, that's what it is for.

Work on your variable names. tmp, tmp2 are not good at all. Give them real names, like dateStart or dateEnd or even tmpDateStart but just tmp isn't good enough.

Here's an example that I managed to piece together:

public class FilterCriteria
{
    public CheeseFilter? filter { get; set; }
    public string DateStart { get; set; }
    public string DateEnd { get; set; }
    public String Country { get; set; }
}

class CheeseFilter
{
    public FilterCriteria Criteria { get; set; }
    public string SPName { get; set; }
    public List<SqlParameter> SqlParameters { get; set; }
}

public CheeseFilter CreateCheeseFilter(FilterCriteria filterCriteria)
{
    var isValidDateFormat = false;
    var sqlParameters = new List<SqlParameter>();
    var SPName = "ERROR";

    var dateStart = new DateTime(); // ForChecking GoodFormating of datetimes
    var dateEnd = new DateTime();

    switch (GetMode().Value)
    {
        case CheeseFilter.DateFrom:
            isValidDateFormat = DateTime.TryParseExact(filterCriteria.DateStart, TMP_DATEFORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp);;
            if (!isValidDateFormat) retrun null;

            sqlParameters.Add(new SqlParameter() { Name =  "@DateStart", Value = tmp.ToString("yyyyMMdd")});
            SPName = "Cheese_FromDate";
            break;

        case CheeseFilter.DateStart:
            isValidDateFormat = DateTime.TryParseExact(filterCriteria.DateStart, TMP_DATEFORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp);
            if (!isValidDateFormat) retrun null;

            sqlParameters.Add(new SqlParameter() { Name = "@DateEnd", Value = tmp.ToString("yyyyMMdd") });
            SPName = "Cheese_To_Date";
            break;

        case CheeseFilter.BetweenDates:
            isValidDateFormat =
                DateTime.TryParse(filterCriteria.DateStart, out dateStart) &&
                DateTime.TryParse(filterCriteria.DateEnd, out dateEnd);
            if (!isValidDateFormat) retrun null;

            sqlParameters.Add( new SqlParameter() { Name = "@DateStart",Value =  tmp.ToString("yyyyMMdd")}); //Converting for sqlServer
            sqlParameters.Add( new SqlParameter() { Name = "@DateEnd", Value = tmp2.ToString("yyyyMMdd")});
            SPName = "Cheese_Between_Date";
            break;

    }

    return new CheeseFilter
    {
        Criteria = GetMode().Value
        SPName = SPName
        SqlParameters = options
    };
}


Well, first of all your range only has to store the start date, as the weeks are always the same length:

struct Range {

  public DateTime Start { get; private set; }

  public DateTime End { get { return Start.AddDays(6); } }

  public Range(DateTime start) {
     Start = start;
  }

}

Getting the weeks can simply be done by looking for sundays starting six days into the previous month:

public static IEnumerable<Range> GetRange(int year, int month) {
  DateTime start = new DateTime(year, month, 1).AddDays(-6);
  DateTime end = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
  for (DateTime date = start; date <= end; date = date.AddDays(1)) {
    if (date.DayOfWeek == DayOfWeek.Sunday) {
      yield return new Range(date);
    }
  }
}

To clarify: This returns the whole weeks that have days in the month, not partial weeks created from the days in the month by grouping them by what week they belong to.


Don't pre-generate exceptions

On the exception in your original code: It's usually not a good idea to pre-generate exception instances. The stack trace is filled in by the constructor of Throwable, not by the throw statement, as the following code snippet demonstrates:

public class StackTrace {
    private static final Throwable t = new Throwable();
    public static void main(final String... args) throws Throwable {
        throw t;
    }
}

When you pre-generate exceptions, you will not be able to tell from the stack trace which call-tree caused the exception. In your case, you would instead see the call-tree that loaded the class:

$ java StackTrace
Exception in thread "main" java.lang.Throwable
        at StackTrace.<clinit>(StackTrace.java:2)

In Java, pre-generated exceptions are usually only found in environments where the stack trace is unavailable by nature, like Java Card Classic.

Consider converting your String to int[] first.

Normally I'd stick to Strings.
However, the case of an EAN13 is special.
The nature of an EAN13 is to be a 13 digit code.
Converting your 13 character String to an int[13] first makes this aspect of the semantics of an EAN13 more obvious and simpler.

You could then use constants like private static final int CHECK_DIGIT_INDEX = 12 to make it more obvious how an EAN13 is parsed. Consequently int pretendVd = Integer.valueOf(code.substring(12, 13)); would become int pretendVd = ean13digits[CHECK_DIGIT_INDEX];

Use names which are easy to understand, i.e. communicate intent

I could not find the term "pretend" resp. pretendVd in whatever documentation about EAN13 is available to me. I would rather call it checkDigitFromCode. The variable name dv is totally surprising, as I would at least have expected it to be vd. But I think calculatedCheckDigit or checkDigitFromCalculation would be better names. Even if variables have local scope, if there are multiple variables of the same type with different semantics, I'd rather be explicit about the intent of a variable and thus give it a name which communicates the intent well.
The worst name of all is me: The code multiplies odds and then the name is me.

Method length

The method validate(String) is quite long, and it can be split into two methods as it performs validation on two levels. First it validates whether the code actually really is 13 digits. Second it validates whether the checksum digit of the 13 EAN13 digits is correct. So, two more methods could be extracted from validate(String).

Validation Framework

This is definitely far from mandatory, it's just food for thought and showing possibilities. If you use a persistency framework like a JPA implementation, or a dependency injection framework like Spring, or even both, or something similar, you might want to consider the usage of declarative validation via annotations using the javax.validation API.

Some people favor separating model and validation always. I wouldn't go that far, and I'll try to explain that with an exaggeration: Tomorrow they'll make 6 classes, one for the instance fields, one for the constants, one for the construction (factory), one for the validation, one for the instance methods and one for the static methods. Where should this stop? The SRP doesn't say that "Every software entity should do just one thing". It comes with a clause, and this clause is important: "Every software entity should do just one thing on its level of abstraction". But it also means something else: Ideally, every software entity should have just one reason to change, and a change should ideally affect only one software entity.

If the validation only changes together with the model, it might be more prudent to keep validation and model together. If the validation is to a large extent independent of the model, it might be wiser to keep them separate.

Thinking about coupling, cohesion and interfaces also helps. If the validation is so loosely coupled, i.e. decoupled from the model that it checks not a specific model but an abstract model, resp. could be reused for different similar models, it certainly should be separate. If the validation is very tightly coupled to the model, it should be more cohesive with the model. And if you insert methods in the model to interface with the validation which are only for the validation and no other user in the system, you have strong arguments for keeping the validation inside the model class.

Welcome to engineering, there's no perfect solution, it always depends... ;)

Properly declare static methods.

Your methods getEanVd(int), sumEven(String), sumOdd(String) and isEven(int) never access any instance fields and thus could all be declared static.

Because they are private methods, it could actually make you wonder why you have a parameter String code and an instance field String code with identical content, which leads to:

Consider swapping validation sequence in the constructor

I think I guess your intention of first validating, then constructing the object with the sequence validate(code); this.code = code; in the constructor. You do not want the object to be constructed before it's validated.

However, consider a few things.

The construction is not really completed until the constructor returns. Whether you throw an exception soon or late in the constructor doesn't matter from a black box perspective. It also doesn't matter from a performance perspective, as an exception is a bad case path, not a happy path. Usually the performance of bad case paths doesn't matter.

However, it matters from a whitebox correctness perspective. Someone might look at the methods sumEven(String code) and sumOdd(String code) and realize that they're checking the very same code which would eventually be stored in the field, and thus turn the signatures into sumEven() and sumOdd(). Compiles still fine, but breaks with NullPointerException because of accessing still null field code before it was assigned to a (potentially) non-null value in the constructor.

Therefore, given a choice, i.e. when the field initialization is as trivial as simply assigning parameters to fields, I'd initialize fields first, as that leads to more robust code: It will allow subsequent private instance methods to access the fields even when they are called from the constructor.

Throwing the correct exceptions

The code part if (code == null) { throw NOT_VALID_EAN_EXCEPTION; } will be very difficult for developers to debug when it happens. Developers will assume that code was a String which was not an EAN13, but they will not expect that code was null, because the generally accepted behavior and practice is that if you pass null and null is not allowed you get nothing else but a NullPointerException. Getting a different exception than NullPointerException in case of a not-allowed null is very unexpected and can make developers waste a lot of debugging time staring at their code mislead into totally false assumptions.

In general, when null is not allowed, I'd not check, I'd simply let the code crash wherever it crashes. Whether the first check in validate(String) throws NullPointerException or whether some later part like code.substring() throws NullPointerException doesn't matter, the stack trace will always show the essential part which is that it was thrown somewhere in validate() called from Ean13().


Personally I think your going the wrong way about things, you can easily pass in a query string into the select method and set the 2nd param to true to bypass backticks.
So the output would place the sub query string within the main query select.
I would do something along the lines of:
class MyModel extends Model
{
    public function getRows()
    {
        //Create a subquery and render it to a stirng
        $sub = $this->db->select('number')->from('numbers')->where('numberID', 2)->_compile_select();

        //Clear the data from the CI Arrays
        $this->db->_reset_select();

        //Build the main query passing in the sub-query and disabling backticks
        $this->db->select("word,(" . $sub . ")", false)->where('wordID', 3);

        //Get the results
        $result = $this->get("words");
    }
}

Sources:

@ _compile_select()
@ _reset_select()

Firstly let me just state that the code above may not be fully working as i have not test machine a.t.m, but I do know that this is possible and you do not need all the extra logic specified.
It seems pretty simple to me without creating new $db's.
I also would recommend you encapsulate the logic above into a class so you can pass the object's around and make life simpler as the above is a POC

Concept:
class InnerQuery extends CI_DB_active_record
{
    public function __construct()
    {
    }

    public function __call($method,$params = array())
    {
        //Remove methods that modify the database
        switch(strtolower($method))
        {
             case 'get':
             case 'count_all_results':
             case 'get_where':
                 trigger_error("Cannot use {$method} in InnerQuery");
             break;
        }
        return $this;
    }

    public function compile()
    {
        return "(" . $this->_compile_select() . ")";
    }

    public function __tostring()
    {
        return $this->compile();
    }
}

Ok so the above class extends the same object as $this->db in your controller, so you can use all the methods to build a query such as
$this->InnerQuery->select("item as item_key")->from("inner_table")->where("foo","zed");

You should disable the parent methods that change the database or run any queries as this is only used to build a select string.
so you should in thoery be able to do:
$this->db->select("word")->where('wordID', 3);
$this->db->select($this->InnerQuery,false);

which would use the DB class to build your query and can just be passed into the outer select and the __tostring will return the (SELECT ...) with braces and pass it into the main query.


Here are some comments on your code and design.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit.

Use the required #includes

The code uses std::string which means that it should #include <string>.  It also needs #include <iostream>.

Don't #include headers that aren't needed

The inverse of the advice above is to not include header files that are not needed.  In this case, "bits/stdc++.h" should be removed.  It's not standard and will only increase compilation times, so you should probably avoid it in favor of using the standard #includes as actually needed.

Don't leak memory

Each time your code in main creates a new pizza, it loses any pointer to the old one, making it a certainty that memory is leaked.  There are two ways to deal with that.  One is to use delete to match each new.  Another alternative is to use smart pointers instead.

C++ isn't Java

Code like this looks more like Java than idiomatic C++:

std::string getdescription(){
    return description;
}
int getcost(){
    return cost;
}

Instead of writing generic getters and setters in the Java style, write idiomatic C++ instead:

std::string desc() const {
    return m_description;
}
int cost() const {
    return m_cost;
}

Here I've used a relatively common idiom of prefixing class variables with m_ and omitting the word get.  Additionally, both functions are declared const because they do not alter the underlying object.

Reread the decorator pattern description

I don't think your code actually faithfully implements the decorator pattern. Consider instead a revision to your pizza model in which a new pizza retains a reference to the underlying basic pizza model passed to the constructor.  That would be a better potential illustration for the use of a decorator pattern.  See https://en.wikipedia.org/wiki/Decorator_pattern for more details.


Compare same filenames with different extensions

If your directory is only containing two types of files, I would do the following way, using splitext function and Counter:

import os
from os.path import splitext
from collections import Counter

def compare_text_docx_pdf(path):
    #List containing all file names + their extension in path directory
    myDir = os.listdir(path)
    #List containing all file names without their extension (see splitext doc)
    l = [splitext(filename)[0] for filename in myDir]
    #Count occurences
    a = dict(Counter(l))
    #Print files name that have same name and different extension
    for k,v in a.items():
        if v > 1:
            print(k)


Iterating through specific elements of an array with filter()

This is kinda pointless:

var list = generators;

The generators argument is already a local variable. I get you might want to call it by a different name, but in that case the parameter should be called generatorIndices or something more descriptive.
The allGenerators variable isn't necessary. It could be, but you're not reusing it. You could just write $(".generatorContainer").hide();.

And yes, you can use jQuery's filter. You've already found all .generatorContainer elements once, so that's the collection you want to filter.

I'd probably just do:

var selectEnabledGenerators = function (generatorIndices) {
    var containers = $(".generatorContainer").hide();
    generatorIndices.forEach(i => containers.filter(`[data-generator=${i}]`).show() );
};


There are no docstrings.
I would suggest reconsidering the mutability of the vectors. The advantages of mutability are:

a. You get to reuse the original storage for the original vector when you make a change, avoiding a couple of memory management operations.

b. You save a couple of characters when writing some update operations, for example you can write v.normalize() instead of, say, v = v.normalized().

But the disadvantage of mutability is that it is harder to reason about operations. If you see a function that takes some vectors, let's say

def collide(p: VectorType, q: VectorType, r: Real) -> Bool:
    "Return True if p and q are separated by no more than r."

is it safe to pass p=sprite.position, or do you need to make a copy? With mutability, then for all you know, the function is implemented like this:

p -= q
return p.magnitude <= r

So in a world where vectors are mutable, you have to worry about this possibility, and perhaps document for each function which arguments get mutated and which don't. If vectors are immutable, then all this is unnecessary and reasoning about the behaviour of code is easier.

Immutability would avoid the need to implement the __iadd__ and __isub__ methods. Also, you could inherit from tuple and save some memory. See this vector class on github for some implementation ideas.
The __truediv__ method has different behaviour based on the type of the argument. This is inconsistent with the behaviour of __mul__ and __rmul__ and __rtruediv__, none of which have this behaviour. Also, dispatching based on the type makes it harder to read and reason about code. If you know that v is a vector and then you read the expression v / a, you can't immediately deduce that a must be a scalar as you could in the case of v * a.

I guess that you added the variant operation because of some use case. But nonetheless I would recommend giving the variant operation a different method name, for example scaled.
In __radd__ the operations should be reversed, with the other values on the left (just in case they have unusual implementations of __add__ method):

def __radd__(self, other):
    return Vector(other[0] + self.x, other[1] + self.y)

Similarly for __rmul__.
There's no checking that the other vector has the right length. There's nothing stopping me from writing:

Vector(1, 2) + [3, 4, 5]

which ought to be an error.
In __repr__ I suggest writing type(self) rather than self.__class__, just as you would write len(s) rather than s.__len__().
In from_polar you should call cls rather than Vector, to support subclasses.
normalize has the operations the wrong way round: you need to divide by the magnitude, not multiply. But it would be simpler to write self.magnitude = 1.
In magnitude it would be clearer to call the argument length or magnitude rather than value.
In magnitude, consider writing math.hypot(self.x, self.y).
In rotation it would be clearer to call the argument theta or angle rather than value.