Reading lines of a file into a vector of strings

General Comment

  Instead of putting a try catch for each of those std function calls, I have put a try catch-all block to collect all the possible errors. Is this a bad practice?

No that is completely fine. The general principle is that if you are not going to handle the error then you should not catch it. Logging is an exception to the rule; where you catch log and then re-throw.

BUT: Most C++ io functions do not throw exception on error (you can make them do so, but it is not normal). Instead a an error causes the flags on the stream to be set to indicate one of the failure states. Now the stream object itself can be used in a boolean context to check the state of these flags (stream will convert to true if it is in a good usable state and false if any of the error flags are set).

Code Review

Avoid output parameters

I hate return parameters. They are non logical and make the flow of the code hard to read. I prefer to return all the results (even if there is more than one).

void readData( std::vector<std::vector<std::string> >&,
                    const std::string& );

Now you are probably thinking that this is inefficient as this requires a copy of the object out of the function. Which is technically true. But the compiler writers put a lot of work into making sure that this copy does not actually happen. RVO and NRVO (optimizations) basically make sure that the object is built in place at the destination (no copy required).

Also in C++11 we introduced move semantics to the language. So on the rare occasion that RVO and NRVO fail a return value will be moved (not copied) from a function. moving a vector simply involves swapping three pointers (or something very close to this) so it is not very expensive.

Prefer "\n" over std::endl

The difference is that std::endl flushes the stream.

        std::cout << "Done" << std::endl;

The stream already flush themselves at the most appropriate time to make themselves efficient; manually forcing a flush is more likely to cause inefficiencies.

Return a non zero value to indicate failure

The OS uses the return value of main to detect if the program ran correctly.

    catch( const char* error)
    {
        std::cout << error << std::cout;
        return 0;
    }

Return a non zero value to indicate failure.

Catch all exceptions in main.

If you throw an exception and it is not caught the program will exit. BUT it is implementation defined if this will force the stack to unwind. If you catch in main() this will force the stack to unwind all the way to the top (thus making sure that all the appropriate destructors are called).

Note: You should re-throw the exception potentially after logging. This is because most OS detect applications that exit via an exception and provide further facilities to the user when this occurs.

int main()
{
    try
    {
         // STUFF
    }
    catch(...)
    {
         std::cout << "Exception Reached main()\n";
         throw;
    }
}

Use an exception derived from a std::exception

When you throw an exception you should throw an exception derived from std::exception. If you don't throw a specialized exception your default should probably be std::runtime_error.

    if (  !ifs )
        // this throws an object of type `char const*`
        throw "Error opening file.";
    // Try this
    if (  !ifs )
    {
        throw std::runtime_error("Error opening file.");
    }

STandard pattern for reading a file.

Your code actually works correctly

        while ( true ){
            std::string line;
            std::getline(ifs, line);

            if(!ifs)    // Most people forget this check.
                break;

            // STUFF
        }

But can be made more succinct. If you do the read as part of the test you can do the read and test as a single line.

        // This is more the standard pattern for reading a file.
        std::string line;
        while ( std::getline(ifs, line) )
        {
            // STUFF
        }

Note: std::getline() returns a reference to the input stream. Which is used in the boolean context checks the state of the error flags. So the loop is only entered if the read succeedes.

Vector can be constructed with iterators.

            std::istringstream iss(line);
            std::vector<std::string> row;
            std::copy(std::istream_iterator<std::string>(iss),
                 std::istream_iterator<std::string>(),
                 std::back_inserter(row));

Very good. But this can be simplified to:

            std::istringstream iss(line);
            std::vector<std::string> row{std::istream_iterator<std::string>(iss),
                                         std::istream_iterator<std::string>()};

Don't generalize an exception

Here you are catching a specific exception that could contain lots of information and replacing it with a string.

    catch(...)
    {
        throw "Error reading the content of the file";
    }

This looses all the relevant information about the original exception and replaces it with a string. Loosing information is never good.

Answer to Comments

I would refactor like this:

#include <iostream>
#include <fstream>
#include <sstream>
#include <iterator>
#include <stdexcept>
#include <vector>
#include <string>

using StringTable = std::vector<std::vector<std::string>>;

StringTable readData(std::string const& path)
{
    std::ifstream ifs(path);
    if (  !ifs )
    {
        throw std::runtime_error("Error opening file.");
    }

    StringTable table;
    std::string line;
    while (std::getline(ifs, line))
    {
        std::istringstream iss(line);
        table.emplace_back(std::istream_iterator<std::string>(iss),
                           std::istream_iterator<std::string>());
    }
    return table;
}

void doMain()
{
    std::string path  = "myDataFile";
    StringTable table = readData(path);
    std::cout << "Done" << "\n";

    // do something with the data ...
}

int main()
{
    try
    {
         doMain();
    }
    catch(std::exception const& e)
    {
        std::cout << "Exception: " << e.what() << "\n";
        throw;
    }
    catch(...)
    {
        std::cout << "Exception: Unknown\n";
        throw;
    }
    return 0;
}


First, don't use using namespace std;, or any other namespace, for that matter. This can cause you have load functions with the same name, which can cause problems. This is discussed in more detail here.

Second, you have a ton of variables you never use, including:

int turn3;
int turn4;
string decision3;
string decision4;
string decision5;
int random2;
int random3;

Third, you should use move functions.  One candidate for a function is asking whether to restart the game.

Fourth, I would use bools for dead and restart.  You will need to convert the input for restart, but it better represents what is happening.

Fifth, you should consistently indent your code at 4 spaces per level.  You do this for the most part, but you do not do this in main().


malloc

I start with one of the most common ones. Instead of char *board = malloc(sizeof(char) * BOARD_SIZE) write char *board = malloc(sizeof(*board) * BOARD_SIZE). If you decide to change the type in the future, you don't have to change at more than one place. And besides, sizeof(char) is ALWAYS 1.

But the biggest problem is that you're not checking the return value. It should look like this:

void *init_board()
{
    char *board = malloc(sizeof(char) * BOARD_SIZE);
    if(!board) {
        /* Handle error */
    } else {
        for(int i = 0; i < BOARD_SIZE; i++) {
            board[i] = ' ';
        }
    }
    return board;
}

Or like this:

void *init_board()
{
    char *board = malloc(sizeof(char) * BOARD_SIZE);
    if(board) {
        for(int i = 0; i < BOARD_SIZE; i++) {
            board[i] = ' ';
        }
    }
    return board;
}

But if you choose the latter one, then you need to check the return value of init_board().

Another thing about the board variable. Why not make it into a 3x3 array instead? It's overkill to call malloc for a 9 byte array. I would do like this instead:

const int dim=3;

void init_board(char board[dim][dim])
{
    for(int i=0; i<dim; i++)
        for(int j=0; j<dim, j++)
            board[i][j]=' ';
}

And then in main()

char board[3][3];
init_board(board);

scanf

You're also not checking the return value of scanf. That should also always be done.

scanf(" %d %d", &x, &y);

should be

if(scanf(" %d %d", &x, &y) != 2) {
    /* Handle error */
} else {

But if you ask me, the best method, even though it takes a few more lines, is this:

const size_t buffer_size = 100;
char buffer[buffer_size];
if(!fgets(buffer, buffer_size, stdin)) {
    /* Handle error */
} else {
    if(sscanf(buffer, "%d %d", &x, &y) != 2) {
        /* Handle error */
    }
}

bool

No reason to define bool, true and false on your own. Just include stdbool.h.

const

A minor thing is that you should declare playerOneChar and playerTwoChar as const.

style

This is my personal preference, but I think you waste a lot of space with unnecessary braces. I would at least move the opening brace to then end of previous line, except for functions. Like this:

bool is_draw(char *board)
{
    for(int i = 0; i < BOARD_SIZE; i++) {
        if(board[i] == ' ') {
            return false;
        }
    }
    return true;
}

or even

bool is_draw(char *board)
{
    for(int i = 0; i < BOARD_SIZE; i++)
        if(board[i] == ' ')
            return false;
    return true;
}

Remember that readability also includes not having to scroll more than necessary. Putting the opening brace on the line before or sometimes even removing them completely barely makes it harder to read at all. If you ask me it's even easier. But it can save you a ton of lines, making more code visible at the same time. In the above example I would probably remove the braces for the if statement, but keep the braces for the for loop.

I usually go by the coding style guide for the Linux kernel, except that I prefer a tab size of 4 instead of 8.

Apart from these things, I think it looks pretty good. Nice work.


Exception handling and general check in Java

Must I put in System.out.println(); so I can know which one it is?

That would be one approach, and it would certainly be better than your current approach, which is silently failing. In case something goes wrong, this will make it very difficult to find out the problem.

If you get an exception, you should first try to think of recovering from it right then and there.

If that is not possible, I would just trow it upwards, and let the calling method handle it. In your case for example by playing a default song, or skipping to the next song, etc.

If all else fails, you should report a helpful and detailed error message to the end user. For debugging purposes, you should also print the exact exception - including stacktrace - to the console.

Just swallowing the exception is pretty much never the correct approach.

Misc

// play the sound clip isn't really a helpful comment, it's pretty obvious from the code already
If you handle all exceptions the same way anyways (in your case ignoring them), you can just catch the generic Exception.
as barq said, your indentation is partly off.
music is a little generic as a method name. maybe playSong, or playClip


SQL Injection-wise, this is completely safe. You don't run any risk of SQL Injection.

However, some parts of your code is not optimal:

mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $user['username']);
mysqli_stmt_execute($stmt);

Why are you executing the statement twice?

Now, imagine that you hade your if-else switched so that you wanted to check for non-existing user first:

if (!mysqli_stmt_fetch($stmt)) {
    echo $username, ' doesn\'t exists';
}
elseif (mysqli_stmt_fetch($stmt)) {
    if ($user['username'] === $username) {
        echo $username, ' exists';
    }
}

This code would not work, and you might not be aware of why exactly. You might be just lucky that you did not code it this way from the start.

The issue is that you are calling mysqli_stmt_fetch twice. You should not do that, there can only be a maximum of one result, which means that the second if will always be false.

Your original code should look like this:

if (mysqli_stmt_fetch($stmt)) {
    if ($user['username'] === $username){
        echo $username, ' exists';
    }
}
else {
    echo $username, ' doesn\'t exists';
}

In fact though, if the first if-statement is true, then the inner if will also be true because of your SQL WHERE condition. So your code could be just this:

if (mysqli_stmt_fetch($stmt)) {
    echo $username, ' exists';
}
else {
    echo $username, ' doesn\'t exists';
}


First use of std::map in factors and prime factorization program

Looks generally ok. You can actually shorten iteration even more if your compiler supports range-based for loops:

for (auto iter = factors.begin(); iter != factors.end(); ++iter)
{
    std::cout << "      " << iter->first << " x " << iter->second << "\n";
}

Can be written as:

for(const auto& pair : factors) {
    std::cout << "      " << pair.first << " x " << pair.second << "\n";
}

Further, prefer to return by value than pass by non-const reference:

void findFactors(uint64_t positiveInt, std::map<uint64_t, uint64_t> &factors)

Should be

std::map<uint64_t, uint64_t> findFactors(uint64_t positiveInt)

This will be exactly the same speed in about 98% of situations thanks to (Named) Return Value Optimization.

One final thing to be aware of with map: insertion (or lookup) using [] vs insert.  [] performs a lookup; if the value is not found, it is default-constructed and then the copy-assignment operator (operator=) is called to give the object its value. Thus, [] performs a lookup, construction and copy assignment. It also requires a default constructor to be available. insert, on the other hand does not require a default constructor, and will (from memory) call only the copy constructor. It is thus often (slightly) faster (although for plain old data, the difference will be non-existent). The big difference is not requiring a default constructor, which may not exist.

Finally, a really small thing: it should (technically) be std::uint64_t. Importing <cstdint> (as opposed to stdint.h), based on the C++ spec, will guarantee that this (and uint32_t, etc) will live in the std namespace. It may also put them in the global namespace. Most headers seem to put them in both, but to be 100% portable (according to the standard, anyway), it should be prefixed with a std (or brought into scope with a using std::uint64_t).


Your use of executor.awaitTermination() seems odd to me. I would instead have used a CountdownLatch to trigger success in a blocked thread. But I also agree with @Craig P. Motlin that a Future makes sense.

Besides that specific comment, you might consider some asynchronous notification technique for the dependency to declare that it's alive. That might be overkill for your scenario, but it's worked for me. Jini service registry, JMS messages, Hazelcast, plain UDP multicast, etc.


"What is the maximum that Player 1 can win?"

Usability

I have a remark about defining recursive functions.
You don't want consumers of your API to think about the intermediate variables and their initial value. The consumer does not care you are using recursion internally.

Make your recursive function private.

private static int maxPlayer1(int[] a, int currSum, int sum, int start, int len)

And create a public API entrypoint.

public static int maxPlayer1(int[] a) {
     final int sum = IntStream.of(a).sum();
     return maxPlayer1(a, 0, sum, 0, a.length);
}

The consumer can now call your API without getting a headache:

public static void main(String[] args) {
     final int a[] = {1,2,3,7,4,8,1,8,1,9,10,2,5,2,3};
     System.out.println(maxPlayer1(a));
}

As compared to the original code the consumer had to write.

public static void main(String[] args) {
    int a[] = {1,2,3,7,4,8,1,8,1,9,10,2,5,2,3};
    int sum = 0;
    for (int i=0;i<a.length; i++) {
      sum += a[i];
    }
    System.out.println(maxPlayer1(a, 0, sum, 0, a.length));
  }


find_an() looks like an internal function, used by arithmetic_partial_sum().  If it is not for external use, it should be named with a leading underscore, to suggest it is private.

arithmetic_partial_sum() appears to handle only integer values, yet it return a floating-point value (1275.0 in the built-in example).  It should return an integer, since it is adding up integers.  Use the Python3.x integer-division operator: //.

    n = 1 + (an - a1) // d
    S = n * (a1 + an) // 2

Or, not assume the terms are integer, and use float(...) instead.

geometric_partial_sum() fails if the first 2 values are not  int values:

>>> geometric_partial_sum(f"1+{1/3}+{1/9}+{1/27}+{1/81}")
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    geometric_partial_sum(f"1+{1/3}+{1/9}+{1/27}+{1/81}")
  File "...\partial_sum.py", line 63, in geometric_partial_sum
    r = int(series[1]) / a1
ValueError: invalid literal for int() with base 10: '0.3333333333333333'

You should convert the terms to floating-point values, not integers:

    a1 = float(series[0])
    r = float(series[1]) / a1

find_an() assumes \$a_n\$ is immediately after the '.' term, so will fail with:

arithmetic_partial_sum("3+7+11+15+.+95+99")
arithmetic_partial_sum("3+7+11+15+19")

Why not just retrieve the last term?

def find_an(parsed_series):
    return int(parsed_series[-1])

Now the following all succeed and return the correct values

arithmetic_partial_sum("3+7+11+15+.+95+99")
arithmetic_partial_sum("3+7+11+15+...+95+99")
arithmetic_partial_sum("3+7+11+15+19")

The """docstrings""" for arithmetic_partial_sum() and geometric_partial_sum() appear unhelpful.  For example:

>>> help(arithmetic_partial_sum)
Help on function arithmetic_partial_sum in module __main__:

arithmetic_partial_sum(series)
    Returns the partial sum of an arithmetic series

    Formula:
        S = n( (a1 + an) / 2 )

    Find an:
        an = a1 + (n - 1)d

    Find n:
        n = 1 + ( (an - a1) / d )

    :param series: Arithmetic series to solve

The function is not returning an or n.  Even the formula is not particularly helpful.  """docstrings""" should tell a user how to use the function.  For example (adding Python 3.6 type hints as well):

def arithmetic_partial_sum(series:str) -> int:
    """
    Returns the sum of an arithmetic series

    Example:
        s = arithmetic_partial_sum("1+3+5+.+99")  # returns 2500

    :param series: A string representing the arithmetic series to solve
    """

Now type help(arithmetic_partial_sum):

>>> help(arithmetic_partial_sum)
Help on function arithmetic_partial_sum in module __main__:

arithmetic_partial_sum(series: str) -> int
    Returns the sum of an arithmetic series

    Example:
        s = arithmetic_partial_sum("1+3+5+.+99")  # returns 2500

    :param series: A string representing the arithmetic series to solve

The user is told the function takes a string and returns an integer.  The format of the string should be clear from the example.


If the arguments are that simple, what's wrong with a locally defined array?

Test t;
const Test args[] = { {"sizex", 12}, {"sizey", 24} };
t.get(1, args, sizeof(args)/sizeof(*args));


Find the smallest number Q whose product of digits is N

An efficient solution would be to express n as its prime
  factorization \$2^a3^b5^c7^d\$. Then, try to regroup those factors into the
  fewest number of 2, 3, 4, 5, 6, 7, 8 digits possible, in increasing
  order. If n has a prime factor larger than 7, then there is no
  solution.

The right way to group the \$2^a3^b\$ factors in 2,3,6,8,9 digits is first to minimize the number of digits, giving priority to \$2^3\$. You then end up with \$3^b\$ or \$2^13^b\$ or \$2^23^b\$. For \$b>2\$ you group by \$3^2\$. I then solved all the solutions for \$2^a3^b\$ with \$a,b\leq2\$ and figured out that the following precedence works : (9,8,7,6,5,4,3,2). So there must be a more elegant proof!

Note that the solution will have at most one 2 or one 3 or one 4.

int numberOfFactor(int * n, int factor)
{
    int number_of_factor = 0;
    while (*n % factor == 0)
    {
        *n /= factor;
        number_of_factor++;
    }
    return number_of_factor;
}

int appendDigits(int digit, int n_digit, int initial_shift)
{
    int i;
    int ret = 0;

    for (i=0; i<n_digit; i++)
        ret = ret + digit * pow (10, i + initial_shift);

    return ret;
}

int main()
{
    int n;
    int q;
    int n9, n8, n7, n6, n5;
    scanf("%d", &n);

    if (n <= 9)
    {
        printf("%d", n);
        return 0;
    }

    n9 = numberOfFactor(&n, 9);
    n8 = numberOfFactor(&n, 8);
    n7 = numberOfFactor(&n, 7);
    n6 = numberOfFactor(&n, 6);
    n5 = numberOfFactor(&n, 5);

    if (n>4)
    {
        printf("-1");
        return 1;
    }

    q = appendDigits(9,n9,0)
      + appendDigits(8,n8,n9)
      + appendDigits(7,n7,n9+n8)
      + appendDigits(6,n6,n9+n8+n7)
      + appendDigits(5,n5,n9+n8+n7+n6)
      + ((n!=1)?appendDigits(n,1,n9+n8+n7+n6+n5):0);

    printf("%d", q);
    return 0;
}

My first post, please be indulgent.


verbose vs readable

Why choose?

Just encapsulate all the explicit code and error checkings into functions (if possible) or macros (only when functions can't do it), and have a clean high level function.

Safe usage of malloc()

Malloc is easily misused.  Problems using malloc are the following:

sizeof(type) vs sizeof(*foo):

foo = malloc(sizeof(*foo) * nmemb); is better because if you ever change the type of foo, this call will still be valid, while if not, you would have to change every line where malloc is called with foo.  If you forget any of those lines, good luck!

overflow:

If (sizeof(*foo) * nmemb) > SIZE_MAX, it will silently wrap around, and allocate a very small amount of memory, and you will most likely end up accessing memory that you shouldn't.

Solution:

Use this enclosure around malloc

sizeof(type) vs sizeof(*foo)

As I said above, use the second.  Apart from malloc you also have this problem in memcpy.

fprintf(stderr, ...) + exit()

You could combine those two in just one function call:

error(): GNU extension

err(): BSD extension

I would advise to use the first one: first, GNU extensions are more commonly available (even Clang has most (if not all) of them); second, because err is a common name used in temporary variables or labels used in case of an error.

C99 types

If you don't have a reason to use old C89 (yes, 1989) types, don't use them. What is long long, and why would you use it?

int64_t is clearer, shorter, and better in every way, unless you need to interface a library that hasn't been updated in the last 30 years, which ironically is most of them.

Also instead of int, use int32_t, although if you want factorials that fit into an int64_t, I don't think you need more than int8_t.


Good Unit Tests when ReSharper bugs for null checks

Asserting

if (viewModel != null) Assert.IsInstanceOfType(viewModel.GetType(), typeof(DraftViewModel));

You should use another assert and not an if
Assert.IsNotNull(viewModel);

Resharper even suggests this option:

Test name

Create_DraftFacade_ViewResultWithDraftViewModel

You might also want to reconsider the naming of your tests. Usually we use this pattern

TestedMethod/Property_TestData/Case_ExpectedResult


Wrapping PDO: General Approach

Generally, wrapping PDO without actually adding any functionality is not recommended. See for example here, or pretty much any answer on basic PDO wrapper classes.

Because what happens is that you take a class with a pretty nice (and well known) interface, and then reduce the power of that interface (you can only perform FETCH_ASSOC, if you ever need a different fetch type, you would probably add a parameter/method to your script, if you follow my advice below, you will throw exceptions, etc; at some point, your script will be very close in use to PDO, just with different function names, and slightly limited functionality).

Wrapping PDO: Swallowing Exceptions

The biggest drawback of your solution is that you take perfectly fine exception and turn them into null returns. This has two downsides: It makes your calling code ugly (too many != null checks), and it makes it really hard to debug your code, as you just swallowed all the information, eg on why the database connection could not be established, or why the query returned nothing (is there nothing in the database, or is the query completely wrong? nobody knows now).

Wrapping PDO: Error Reporting

Another thing that's a real problem is that you are setting error reporting in this script. This is really something that needs to be controllable (for PDO as well as for PHP), because you want all the error reporting possible in development mode, but none of it in production. If you just set these values in various scripts, it will be really hard to control.

Your Questions

So I would definitely not recommend this approach, but if you want to go forward in this direction:

  Will this method of operation work?

Yes.

  Is this safe against SQL injection?

Yes. (assuming it is used correctly, which means no variable input in the querystring ever; and also assuming that this isn't an issue)

  Can this support multiple/no parameters?

Multiple queries definitely, and I would assume that execute(emtpyArray) is valid, but haven't tested it.

  Overall, is this an efficient way of querying a database?

Performance wise? Sure. Code wise? You don't actually save all that much typing. The PDO instantiation only happens once (and having a method for that seems fine to me), so lets look at the queries:

try {
    $query = $connection->prepare($queryString);
    $query->execute($parameters);
    if($sth->rowCount()) {
        // echo json_encode($sth->fetchAll(PDO::FETCH_ASSOC));
    } else {
        // print false
    }
} catch(PDOException $e) {
    // print error message
}

vs

if($connection != null) {
    $response = preformQuery($connection, 'SELECT * FROM users WHERE username = ?', 'test');
    if($response != null) {
        // echo json_encode($response);
    } else {
        // print false
    }
} else {
    // print error message
}

So with your approach, you basically saved one line.


Check user changed his password recently or not in specific period

Your query doesn't returns a result when there's no id matching 'some_id'.

Well, there's a trick to force a row, use an aggregate function.

I think this is your logic rewritten to a single CASE (of course COALESCE is just a shortcut for a CASE :-)

SELECT COALESCE(MIN(CASE WHEN Greatest(COALESCE(last_login_date, to_date('20160401','yyyymmdd'))
                                      ,to_date('20160401','yyyymmdd')
                             + COALESCE(not_change_day, 90) > sysdate
                         THEN 'true'
                     END)
                    ,'false')
FROM FT_PWD_CHANGE
WHERE id='foo'

Btw, for a hard-coded date I would prefer DATE '2016-04-01' over to_date('20160401','yyyymmdd'), it's shorter and Standard SQL.


DRY multiple if statements used to show/hide elements based on slider value

I am guessing that the '.volume' elements are like volume indicators, the louder the sound, the more you show.

You can iterate over the '.volume' elements, compare the index / elementCount to ui.value and decide to hide or show per that comparison.

So, something like :

$('.volumeSlider').slider({
    value: 1,
    orientation: "vertical",
    range: "min",
    max: 1,
    step: 0.05,
    animate: true,
    slide: function (e, ui) {
        $('p').text(ui.value);
        var v = $('.volume1');
        for( var i = 0 ; i < v.length ; i++ ){
            ( 1-ui.value > 1 / v.length * (i + 1)) ? v.slice(i).hide() : v.slice(i).show()
        }
    }
});

should work. This approach will work with any number of volume1 elements.
I did not test this, but once you see/get this I am sure you can make this work.

Further optimizations can be caching v.length and 1 / v.length, you could probably also use eq instead of slice()

EDIT : I fixed the code to work with your HTML, the original was

( ui.value < 1 / v.length * (i + 1)) ? v.slice(i).hide() : v.slice(i).show()
which would work if the HTML elements were created in what I see as the correct order.


Passing input parameters correctly to a method

Like most times, it is best to validate your data before you use it. In your case, since the input data needs to be validated by the Database infrastructure, I recommend adding it to the IDBClient interface.

I also assume that the paramMap is the query you want to run, and not part of the user/login information.

I suspect the logical thing to do is to extend your interface to look like:

public interface IDBClient {

    public interface SessionHandle extends AutoCloseable, Closeable {
        public boolean isAlive();
    }

    public SessionHandle createSession(Long userid, Long clientid,
              Long timeout_ms, boolean debug) throws InvalidLoginException;

    public String read(SessionHandle session, Map<String, String> parameterMap)
              throws ReadNotPossibleException, SessionExpiredException;
}

Now you are forced to create a SessionHandle instance that is pre-verified, and immutable. The content of that SessionHandle is whatever it needs to be for your actual IDBClient implementaton. The IDBClient implementation will know which handles are valid, and can do other things with the handle as needed.

Because times are good, and Java7 is better, you should also ensure that your SessionHandle is AutoCloseable so you can use try-with-resources.

Your Exceptions (which you should create custom versions of) for your interface should all extend a single Exception class, for example:

public DBClientException extends Exception { ..... }
public ReadNotPossibleException extends DBClientException {....}
public SessionExpiredException extends DBClientException {...}

by doing this, you can allow the user to catch just the database exception, or more-specific database exception sub-types if needed....

The 'user experience' will look like:

IDBClient client = DatabaseClientFactory.getInstance();
try (IDBClient.SessionHandle session =
          client.createSession( 109739281L, 20L, 1000L, true) ) {

    String result = client.read(session, paramMap);

} catch (DBClientException e) {
    .....
}


MySQL PDO query to search by name and role

There's different things about your code, the most important one is to start using PDO tools to facilitate our work. Use named parameters, and dissociate your query construct from setting correct values:

if the only thing you're going to catch is echo the error message, there's absolutely no reason to do it. setting $this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); will react in the exact same way.
for the LIKE portion of the code: named parameters must contain a full litteral string (or integer, or whatever) but you have to put wildcards % IN the string for the LIKE to work. exemple: $values[':character_match'] = '%value%'

$sql = 'SELECT users.id, users.users_id, username, firstname, lastname, password, position
            FROM users
            INNER JOIN users_role ON users.id=users_role.users_id
            INNER JOIN role ON users_role.users_role=role.id ';
if ($category != 'view_all') {
    $sql .= 'WHERE position=:position ';
}
if ($character_match != '') {
    $sql .= ($category == 'view_all' ? ' WHERE ' : ' AND ');
    $sql .= '(username LIKE :character_match OR firstname LIKE :character_match OR lastname LIKE :character_match)';
    $values[':character_match'] = $character_match;
}
$sql .= ' ORDER BY position';

switch ($category) {
    case 'admin':
        $values[':position'] = 'admin';
        break;
    case 'instructor':
        $values[':position'] = 'Instructor';
        break;
    case 'student':
        $values[':position'] = 'student';
        break;
    case 'Unverified':
        $values[':position'] = 'Unverified';
        break;
}

$q = $this->db->prepare($sql);
$q->execute($placeholders);

$rows = array();
while ($row = $q->fetch(PDO:: FETCH_ASSOC)) {
    $rows[] = $row;
}


Program slows down significantly based on input

This should help a little bit:

        List<string> CandidatesRet = new List<string>();

        var splitChars = new[] { ' ' };

        for (var indexCi = 0; indexCi < Ci.Count - 1; indexCi++)
        {
            // generate all sub itemset with length-1
            var allItems = Ci[indexCi].Split(splitChars);

            subItemset
                .AddRange(allItems.Select((s, i) => allItems.Where((t, j) => i != j)
                .Aggregate(string.Empty, (current, t) => current + (t + " ")))
                .Select(tempStr => tempStr.Trim()));

            // THE PROBLEM BEGINS HERE
            foreach (var subitem in subItemset)
            {
                for (var indexCommon = indexCi + 1; indexCommon < Ci.Count; indexCommon++)
                {
                    if (Ci[indexCommon].IndexOf(subitem, StringComparison.Ordinal) < 0)
                    {
                        continue;
                    }

                    var listTempCi = Ci[indexCommon].Split(splitChars);

                    commonItem.AddRange(listTempCi.Where(itemCi => !subitem.Contains(itemCi)));
                }

                allCommonItems.Add(commonItem);
            }

            // generate condidate from common item
            CandidatesRet.AddRange(oldItemsetCi
                .Select(item => new { item, flagCi = allCommonItems.All(listCommItem => listCommItem.Contains(item)) })
                .Where(t => t.flagCi)
                .Select(t => (Ci[indexCi] + " " + t.item).Trim()));
        }
    }

However, the big problem is the still the double loop, which will grow as a power-of-two rather than linearly with your data size.


The game "Rock Paper Scissors" can be specified in terms of states.
Specification
The game is played by two players, playerA and playerB. Each player selects from among a set of three options {null, rock, paper, scissors}. null is used to represent the state before a player has chosen. Using an ordered pair (playerA_choice, playerB_choice) creates the possible game states:
 (null,    rock)
 (null,    paper)
 (null,    scissors)
 (rock,    null)
 (rock,    rock)
 (rock,    paper)
 (rock,    scissors)
 (paper,   null)
 (paper,   rock)
 (paper,   paper)
 (paper,   scissors)
 (scissors, null)
 (scissors, rock)
 (scissors, paper)
 (scissors, scissors)

There are three final states and three transition functions to them:
playerA_wins = (rock, scissors) | (paper, rock) | (scissors, paper)
playerB_wins = (rock, paper) | (paper, scissors) | (scissors, rock)
draw = (rock, rock) | (paper, paper) | (scissors, scissors)

The start state is:
 (null, null)

The states:
 (null,    rock)
 (null,    paper)
 (null,    scissors)
 (rock,    null)
 (paper,   null)
 (scissors, null)

are blocking and require further input from one of the players.
Implementing The Specification
This is a sketch of the game:
# Some Useful Names
null = "null"
rock = "rock"
paper = "paper"
scissors = "scissors"

# A Thesaurus (implemented as a dictionary)
synonyms = {"rock": rock,
            "paper": paper,
            "scissors": scissors,
            "stone": rock,
            "vellum": paper,
            "shears": scissors}

# Final States
game_is_draw = "Game is a Draw"

playerA_wins = "Player A Wins"

playerB_wins =  "Player B Wins"

# Initial State
both_players_must_choose = "Both Players Must Choose"

# Transition States
playerA_must_choose = "Player A Must Choose"

playerB_must_choose = "Player B Must Choose"

# Transition Table (implemented as a dictionary)
transitions = {(null,    null): both_players_must_choose,
               (null,    rock): playerA_must_choose,
               (null,    paper): playerA_must_choose,
               (null,    scissors): playerA_must_choose,
               (rock,    null): playerB_must_choose,
               (rock,    rock): game_is_draw,
               (rock,    paper): playerB_wins,
               (rock,    scissors): playerA_wins,
               (paper,   null): playerB_must_choose,
               (paper,   rock): playerA_wins,
               (paper,   paper): game_is_draw,
               (paper,   scissors): playerB_wins,
               (scissors, null): playerB_must_choose,
               (scissors, rock): playerB_wins,
               (scissors, paper): playerA_wins,
               (scissors, scissors): game_is_draw}

# Simulate Initialization
playerA_choice = null
playerB_choice = null

# Simulate Players Choosing
playerA_choice = synonyms["stone"]
playerB_choice = synonyms["shears"]

# Main Logic
state = (playerA_choice, playerB_choice)
print(outcomes[state])

Details to handle input output should be at a higher layer of abstraction. It shouldn't matter to the game engine if the game is between a human and a computer, two humans, or two computers. It shouldn't matter if it is being played using a laptop or over the internet.
Data Structures
A good rule of thumb is to replace complex logic with a data structure, and
if choice == 'r' or choice == 'R' or choice == 'Rock' or choice == 'rock' or choice == '1':

is the sort of code that is hard to understand and hard to maintain. Perhaps to the point where it is better to forgo the user friendly approach?  Nay! A thesaurus is a good place to look for synonyms. Although, Python lacks Thesauri, a dictionary will probably do. Now the game can be sold at Ye Local Renaissance Faire as Stone, Vellum, Shears!
Indeed, a dictionary is a good way to map each possible game state to the next state. The code does in lieu of directly implementing the logic the specification uses to describe the final states.
The reason is maintainability. The mobile version of the game will offer an upgrade to Rock, Paper, Scissors, Spock, Lizard currently in development. Once we get around to updating the dictionaries synonyms and transitions the game will be done, profits will role in, and we will never have to work again unless sleeping on a stack of money counts as work.
But Really, Why All the Ceremony?
One of the real values that comes from using dictionaries is that a dictionary can be used to dispatch functions.
# Abbreviated Rock Paper Scissors

# Some Useful Names
rock = "rock"
paper = "paper"

def playerA_wins():
    print("Player A Wins")

def playerB_wins():
    print("Player B Wins")

transitions = {(paper, rock): playerA_wins,
               (rock, paper): playerB_wins}

transitions[(paper, rock)]()
transitions[(rock, paper)]()

Getting user input can be dispatched similarly by the dictionary. However, the initial (null, null) state, threading might be justified so that playerA_choice() doesn't block playerB_choice() or vice versa...that's IO for 'ya.
Recommendations

Better variable names. Write about rocks and paper and scissors: rock = 1 makes the code more readable. Readability particularly helps the person writing the code.
Make the code more modular. Put all the initialization together. Put all the user interface someplace else. Separate out the string matching. Only put high level abstractions in the main loop.
Consider specifying the problem before writing code for a solution. At the core Rock, Paper, Scissors does not deal with synonyms. Writing a specification makes it clear that synonyms are a feature and encourages keeping their logic outside the main loop. This makes the code more readable.


Here's a quick and dirty example to illustrate the benefit of the dictionary setup:

- (NSDictionary *)webServiceIDsAndURLs{
    NSDictionary *sillyExampleDictionary = @{ @1 : [NSURL URLWithString:@"http://www.noreagle.com"],
                                              @2 : [NSURL URLWithString:@"http://www.stackOverflow.com"],
                                              @3 : [NSURL URLWithString:@"http://www.etc.com"]};
    return sillyExampleDictionary;
}

...

- (BOOL) webServicesExecution:(NSNumber *) webServiceID webServiceParameters: (NSDictionary*) parameters{
    NSURL *URL = [[self webServiceIDsAndURLs] objectForKey:webServiceID];
    ClassWebService *webService = [[ClassWebService alloc] initWithID:webServiceID URL:URL];

    // see, no lengty switch, yay!

    return YES; // Not sure what you are planning here...
}


Here are some of the improvements i can suggest:

move your counter variable , from the inside the if statements , as increasing the count is independent of the if condition.
Use srand(time(NULL)); , below the declarations , or else , your compiler may throw this warning , when compiled using C90 standard.

warning: ISO C90 forbids mixed declarations and code [-pedantic]

So to ensure portability , avoid statements between declarations.
In the long run , more meaningful and formal names , can be used instead of names like r and guess.

In my personal opinion , these two changes would be better:

Using a break; , when the correct number is guessed , can eliminate the need for using an extra variable correct.
I would prefer to use just a  while() instead of do{}while();, if the program logic permits it.

Here is the program , modified with the changes , i listed above:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{

int random_num = 0;
int guessed_num = 0;
int counter = 0;

srand(time(NULL));
random_num = rand() % 10 + 1;

printf("Guess my number! ");

    while(1)
    {
        counter++;

        scanf("%d", &guessed_num);

        if (guessed_num == random_num)
        {
            printf("You guessed correctly in %d tries! Congratulations!\n", counter);
            break;
        }

        if (guessed_num < random_num)
            printf("Your guess is too low. Guess again. ");

        if (guessed_num > random_num)
            printf("Your guess is too high. Guess again. ");

    }

return 0;
}


Eager Loading Deeply into a Model with a Collection Property Whose Type is Inherited

The problem here is that you'd actually want to include subtypes. If Job had a collection of Pdfs, you could have done

Job job = await db.Jobs
                  .Include(j => j.Pdfs.Select(pdf => pdf.PdfPages))
                  .SingleOrDefaultAsync(j => j.Id == id);

But Pdf is a subtype, and EF doesn't support a syntax like

Job job = await db.Jobs
                  .Include(j => j.Files.OfType<Pdf>().Select(pdf => pdf.PdfPages))
                  .SingleOrDefaultAsync(j => j.Id == id);

So what you do is the only way to get the Job with Pdfs and PdfPages.

There are some improvements to be made though:

You can just load the child objects into the context without assigning them to job.Files yourself. EF will knit the entities together by relationship fixup.
You can first check if the Job is found and then load the Pdfs.

Turning it into this:

Job job = await db.Jobs.FindAsync(id);
if (job == null)
{
    return NotFound();
}
else
{
    // Load the PDFs for this job and include their PdfPages
    await db.Pdfs.Include(pdf => pdf.PdfPages).Where(pdf => pdf.Job_ID == id)
        .LoadAsync();
}

return Ok(job);


Pascal triangle algorithm is good but fails

The code appears to be correct, though the explanatory formula you posted is wrong.

Your factorial function is more complex than it needs to be.  Furthermore, adder is a poor variable name, since the result is multiplicative rather than additive.  The traditional recursive definition is:

def factorial(n: Int): Int = {
    if (n == 0) 1
    else n * factorial(n - 1)
}

The main problem with your approach is that you work with large numbers in both the numerator and the denominator.  If your program is generally working, then your problem is probably arithmetic overflow.  An Int would only handle values up to 231 - 1 correctly.

Therefore, your best bet is to use an entirely different way to construct Pascal's Triangle, as suggested by @janos.


I must say it was interesting running your code with some sample images-

You have so many variables declared especially the slides - You should try using a Create Factory method for your Images. Example from Creating an array of Image Objects

// Image factory
var createImage = function(src, title) {
  var img   = new Image();
  img.src   = src;
  img.alt   = title;
  img.title = title;
  return img;
};

// array of images
var images = [];

// push two images to the array
images.push(createImage("http://www.lostarkgames.com/images/pokemonlogo.jpg", "foo title"));
images.push(createImage("http://4.bp.blogspot.com/-Jv6VFqBbTIM/VNUbs8ZehLI/AAAAAAAATD8/Dwipe_uNxTQ/s1600/Pok%C3%A9mon_Gotta_Catch_'Em_All_1.png", "bar title"));

// output
console.log(images);

When you use fade out, it's best to fade out slowly before making the image transparent e.g 1-> 0.2->0 . It's just for the user experience. the animation lacks consistency based on the timing, some images stayed longer than 20 seconds


Placement of success code in a conditional

Some notes:

Imperative programming has its use cases (or so I've heard :-)) but implementing logic is definitely not one of them. Some thoughts on the matter. Use always expressions, not statements, to describe logic; that's it, don't begin with a x = 1 and then modify x somewhere else in the code. Write expression branches instead (conditionals are in expressions in Ruby). Don't think in terms of "how" but in terms of "what".
if !x.nil? -> if x.
obj.save may fail but you are not checking it.
Don't write explicit return (more on idiomatic Ruby).
As you say the order of checks is important. I usually check for "problems" first, and keep the "ok" scenario for the last branch.
You are using a value (a hash) instead of an exception to signal errors. It's slightly not idiomatical in Ruby (in the sense that people tend not to do it, not that there's anything wrong with it), but personally I like it (and use it).

You could write:

def redeem(pin)
  success, message = if date_claimed
    [false, 'Reward already claimed']
    ...
  end
  {:success => success, :message => message}
end

However, returning {success: ..., message: ...} on each branch, yet slightly more verbose, looks pretty nice and declarative:

def redeem(pin)
  if date_claimed
    {success: false, message: "Reward already claimed"}
  elsif reward.redemption_pin != pin
    {success: false, message: "Wrong pin"}
  else
    update_attribute(:date_claimed, Time.zone.now)
    {success: true}
  end
end


Gratulation! For  a beginner you made a good and clear game.

A first modified version:

class Board
    attr_reader :board

    def initialize(player1, player2)
        @board = (1..9).to_a    #You can use also a range to initialize the array
        puts "Player 1 is %s, Player 2 is %s." % [player1.mark, player2.mark]
        @player_1 = player1
        @player_2 = player2
        show_board
    end

    def play

      until end_game?
          puts "Player 1 turn"
          put_marker(@player_1.mark)
          if ! end_game?
              puts "Player 2 turn"
              put_marker(@player_2.mark)
          end
        end
    end

    def show_board
        puts '-'*9          #I prefer some lines in the board
        @board.each_slice(3) { |x| #Good! You use slice.
            puts x.join(' | ')
            puts '-'*9
          }
    end

    def get_place
      while
          place = gets.to_i - 1 #Use a return parameter
        #Check also if you get only values between 1 and 9 (no letters, no 0)
          if ! place.between?(0,9)
              puts "Invalid move, use 1..9. Please choose again!"
              next
          end
          if ! free_space?(place)
              puts "Invalid move, Pos. %i is occupied. Please choose again!"
              next
            end
            break #stop loop, Value is ok
        end
      return place
    end

    def free_space?(place)
        @board[place].is_a? Integer
    end

    def put_marker(mark)
        @board[get_place] = mark
        show_board
    end

    def win?(player)
        ary = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
        ary.any? do |array|
            array.all? { |num| @board[num - 1] == player.mark }
        end
    end

    def draw_condition
        @board.all? { |num| num.is_a? String }
    end

    def end_game?
        if win?(@player_1)  #use other check. The comparison wit == true is not necessary.
            puts "Player 1 wins!"
            show_board  #Show end situation
            exit
        elsif win?(@player_2)
            puts "Player 2 wins!"
            show_board  #Show end situation
            exit
        elsif draw_condition == true && player1_win_condition == false && player2_win_condition == false
            puts "It's a draw!"
            exit
        end
    end
end

class Player
    attr_accessor :mark

    def initialize(mark)
        @mark = mark
    end
end

new_board = Board.new(Player.new("X"), Player.new("O"))
new_board.play

I removed the reader place and the variable @place.
There is no reason why you need it.
It is only a temporary used variable, there is no need to store it in the class.
I replaced it with local variables and method return parameters.

The use of the return command is not necessary. I used it here to show explicit when I want to return a value.

I integrated the checks into get_place.
There is also a check for wrong values (like letters) and different messages.

I replaced player1_win_condition with a generic test with parameter.

I integrated the game in a method play. So it would be easier to start multiple games.

Most important: You used the fix constant 'X' and 'O' in your Game. But this data are also defined a parameter in the class Player. This can make problems if you replace X by x or something else.

What is missing:
* There is no check for similar Player.marks

What could be checked/Modified:

I don't like the end_game? in the actual version.
You could integrate it to play (player 1 can only win after his move, same for player 2. Then end_game? needs only to check for draw.
The board could be a simple array without initialization. nil would indicate free fields. This could make some checks easier. But with the initialization the board gets its initial values to be shown in show_board.

Another version!

The first version had some code repetition. For each player the code was written again.

The new version avoids this repetion:

class Board
        attr_reader :board

    def initialize(player1, player2)
        @board = (1..9).to_a    #You can use also a range to initialize the array
        @player_1 = player1
        @player_2 = player2
        puts "Player 1 is %s, Player 2 is %s." % [player1.mark, player2.mark]
        show_board
    end

    def play
      sequence = [@player_1,@player_2]
      until draw?
          puts "Player %s turn" % sequence.first.name
          put_marker(sequence.first.mark)
          if win?(sequence.first)
            puts "Player %s wins!" % sequence.first.name
            show_board  #Show end situation
            return
          end
          sequence.rotate! #switch to next player
        end
        puts "It's a draw!" #end message if not left before, becaus eone player wins
    end

    def show_board
        puts '-'*9          #I prefer some lines in the board
        @board.each_slice(3) { |x| #Good! You use slice.
            puts x.join(' | ')
            puts '-'*9
          }
    end

    def get_place
      while
          place = gets.to_i - 1 #Use a return parameter
        #Check also if you get only values between 1 and 9 (no letters, no 0)
          if ! place.between?(0,9)
              puts "Invalid move, use 1..9. Please choose again!"
              next
          end
          if ! free_space?(place)
              puts "Invalid move, Pos. %i is occupied. Please choose again!"
              next
            end
            break #stop loop, Value is ok
        end
      return place
    end

    def free_space?(place)
        @board[place].is_a? Integer
    end

    def put_marker(mark)
        @board[get_place] = mark
        show_board
    end

    def win?(player)
      ary = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
      ary.any? do |array|
          array.all? { |num| @board[num - 1] == player.mark }
      end
    end

    def draw?
        @board.all? { |num| num.is_a? String }
    end

end

class Player
    attr_accessor :mark
    attr_accessor :name

    def initialize(name, mark)
        @name = name
        @mark = mark
    end
end

new_board = Board.new(Player.new('Fred', "X"), Player.new('Joe', "O"))
new_board.play

To identify the players I need also a name. Before you had the fix 'Player one'. You could also remove the text Player in the output (replace Player X turn with X turn).


Use portable constructs

Variable-length arrays are not standard C++.  Using such non-standard extensions hampers your code because you can't easily use different compilers (this can possibly even exclude entire target platforms).

Avoid importing all of std into the global namespace

Namespaces provide us with an important service, separating the large and growing set of identifiers in std from those of our own code.  It's actively harmful to reverse that benefit with using namespace std.

Always test for errors when reading

Formatted input such as std::cin >> n >> k should always test the state of the stream before using the read values.

Use clearer names

We don't have to use names like t just because that's what the question uses to describe the number of test cases.  Similarly, hrs took me much longer to comprehend than would horse - and that's not going to push your line lengths.

Know your standard library

What we have is a priority queue of horses, ordered by the time they next return, with the horse's number as tie-breaker.  We have std::priority_queue with insertion/removal times that scale as O(log n), so iterating over the k previous riders to find which horse we get will scale as O(k log n).

The algorithm is pretty simple - for each member of the queue in front of us, take the next horse from the stable (a std::priority_queue), add its running time to its next-available time, and insert it back into the stable.  The horse at the front of the stable after k-1 iterations will be ours.


Musical graph algorithm, with an inlined lookup helper function

... I would like to understand how to properly get the most out of low
  level operations. ... Is this the correct way? ...

Up to a point.

There's little or nothing wrong with your get-tonnetz-connected and
tonnetz-connected? functions. I've tidied up the latter a bit.
Your tuned tonnetz-connected?-2 is a bit faster, but not much.
Pre-calculating the tonnetz-connected? values into a data
structure roughly doubles its speed.
Finally, we take a look at a way to derive the tonnetz graph from
first principles.

Functionality

Given a chord (set of notes/pitch-classes):

the get-tonnetz-connected function returns the fattest chord you
can reach from it in the tonnetz graph;
the tonnetz-connected? function tells you whether all its notes are
connected in the tonnetz graph.

Here's my revised tonnetz-connected?, which is essentially the same as yours:

(defn tonnetz-connected?
  "is the subgraph of the chord in the tonnetz graph connected?"
  [^long chord]
  (let [chord (int chord)]
    (loop [found (Integer/lowestOneBit chord)
           unmatched chord]
      (or (zero? unmatched)
          (let [newly-found (bit-and found unmatched)]
            (and (not (zero? newly-found))
              (recur (bit-or found (get-tonnetz-connected newly-found))
                     (bit-and-not unmatched newly-found))))))))

What is it doing?

It conducts a breadth-first search of the chord's subgraph of the tonnetz
graph, starting at an arbitrary note (in fact, the lowest one) of the
chord.
It keeps track of the found notes and of the unmatched ones:
those yet to be found.
It terminates

when there are no unmatched notes , returning true; otherwise
when there are no newly-found notes, returning false.

I've improved the algorithm a little, by

simplifying the setup of the loop;
abbreviating the logic by using the and and or macros, which you
can often bring into play when if forms return true or false
values; and
returning false as soon as there are no newly-found notes, saving
a  breadth-first-search step.

I've also changed a bit-xor to a bit-and-not. This makes no difference for this bit-field representation of the graph, but would be a lot faster if the equivalent adjacency-list representation were in play.

But the main thing is that the working of the algorithm is clearer (to me, at least), because the names tell me what's going on.

The only functional advantage this version possesses over yours is that it can handle the empty chord (denoted by 0), whereas yours blows up.

Performance

I used Criterium to measure performance:

(bench (tonnetz-connected? (rand-int 4096)))
Evaluation count : 684489240 in 60 samples of 11408154 calls.
             Execution time mean : 89.362030 ns
    Execution time std-deviation : 5.205238 ns

And for the tuned version;

(bench (tonnetz-connected?-2 (inc (rand-int 4095))))
Evaluation count : 666279660 in 60 samples of 11104661 calls.
             Execution time mean : 88.302147 ns
    Execution time std-deviation : 1.055889 ns

The untuned version is now just as fast as the tuned one. The tuned one's previous advantage of about 15% could probably be restored by changing its algorithm in the same way. I haven't troubled to do this, since there's a better way to speed things up:

Pre-calculating the tonnetz-connected? function.

We can pre-load the values of tonnetz-connected? into an array of booleans:

(def tonnetz-connected?-array
  (let [ans (->> 4096
                 range
                 (map tonnetz-connected?)
                 boolean-array)]
    (fn [^long chord] (aget ans chord))))

Measuring its performance ...

(bench (tonnetz-connected?-array (rand-int 4096)))
Evaluation count : 1202760240 in 60 samples of 20046004 calls.
             Execution time mean : 48.140865 ns
    Execution time std-deviation : 0.349284 ns

It's 45% faster than the tuned version.

Appendix: Deriving the Tonnetz graph

(This is not something you asked about, but I think it's worth doing.)

The Tonnetz graph just drops out of the sky as a series of magic numbers:

(def ^:private ^ints tonnetz-array
  (int-array [952 1904 3808 3521 2947 1799 3598 3101 2107 119 238 476]))

I've reverse-engineered the construction of this graph.

We start from the relative intervals that make up the tonnetz relation, which are the same for every note/pitch-class:

[3 4 5 7 8 9]

To turn these into a bit-mask, we use

(defn bits [bitlist]
  (reduce
    (fn [a i] (bit-or a (bit-shift-left 1 i)))
    0
    bitlist))

And, indeed

(bits [3 4 5 7 8 9])
=> 952

the mask for note 0.

For every semitone increment, we have to rotate the twelve-bit mask one bit to the left. A function that yields a function to rotate an n bit bit-field one to the left is

(defn rotate-bits-left-fn [n]
  (fn [bit-field]
    (if (bit-test bit-field (dec n))
      (-> bit-field (bit-shift-left 1) (bit-clear n) (bit-or 1))
      (-> bit-field (bit-shift-left 1)))))

If we apply this twelve times to 952 we get

(->> 952
     (iterate (rotate-bits-left-fn 12))
     (take 12))
=> (952 1904 3808 3521 2947 1799 3598 3101 2107 119 238 476)

... the tonnetz mapping we've seen already.

Putting it all together, we can derive your tonnetz-array thus:

(def ^:private ^ints tonnetz-array
  (->> [3 4 5 7 8 9]
       bits
       (iterate (rotate-bits-left-fn 12))
       (take 12)
       int-array))


I am also new to F#, so I have just 2 small annotations:

The function that parses the string to Int32 can be simplified:

match System.Int32.TryParse(str) with
    | (true, x) when x >= 0 && x <= 20 -> Some x
    | _ -> None

The last case of the function parseTopLevel should be _ -> instead of x -> because the value is not used ('_' expresses exactly that)


break is not a bad thing. Labels and goto are normally avoided. You are just breaking out of one loop, so you can just delete the outerloop: label and break; normally.

Comments at a method level are normally given with /** ... */ (JavaDoc syntax) above the method.

The trend is to avoid updating arrays in place (mutating), and instead just prefer returning new copies of the array (think of things as immutable), because when you mutate things it can sometimes be harder to keep track of state and easier to write incorrect code.
That's not to say it's wrong to do it with mutation. However, it might be better to keep mutation under control in the private parts of your code, so that if somebody re-uses your code, they don't have to worry about sequencing the method calls in the right order.

Presumably In is something provided by your course? Since I didn't have that, I just did the Scanner implementation to test with.

Here's your own code again, just with small changes as per the above comments, and formatted with 4 spaces (which seems to be more common these days).
import java.util.Scanner;

public class Main {

    public static void process(String s) {
        char[] sequence = s.toCharArray();
        removeParenthesisPairs(sequence);

        /*
         * I'm required by the assignment to have the boolean correct, int additional
         * and int removed like this. So I can't just do "Out.println("removed = " +
         * subtract(sequence)+ " und additional = " + add(sequence));"
         */
        boolean correct = checkIfCorrect(sequence);
        int additional = add(sequence);
        int removed = subtract(sequence);
        System.out.println(correct);
        System.out.println("removed = " + removed + " und additional = " + additional);
    }

    /**
     * I remove all the correct pairs from the sequence. I look for a ( and turn it
     * into an F [to signal it's removed] and search the rest of the sequence for a
     * ) and turn that into an F too. If there is no ) I turn the F back into (.
     * This part I really don't like, it looks super clunky.
     */
    private static char[] removeParenthesisPairs(char[] a) {
        for (int i = 0; i < a.length; i++) {
            if (a[i] == '(') {
                a[i] = 'F';
                for (int j = i + 1; j < a.length; j++) {
                    if (a[j] == ')') {
                        a[j] = 'F';
                        break;
                    }
                    if (j == a.length - 1) {
                        a[i] = '(';
                    }
                }
            }
        }
        return a;
    }

    /**
     * I check if the sequence is correct. If there are only F left in the array,
     * that means all entries were able to form pairs of () and the original
     * sequence was correctly parenthesised.
     */
    private static boolean checkIfCorrect(char[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            if (a[i] != 'F') {
                return false;
            }
        }
        return true;
    }

    /**
     * Check how many ) have to be subtracted at the beginning of the sequence.
     */
    private static int subtract(char[] a) {
        int count = 0;
        for (int i = 0; i < a.length; i++) {
            if (a[i] == ')') {
                count += 1;
            }
        }
        return count;
    }

    /**
     * Check how many ( are still left in the sequence and need a ) added to form a
     * pair. I am kinda repeating myself here in the subtract() and add() methods,
     * they are essentially doing the same thing. The only way I have figured out
     * for a method to return two values is by making a class. But it seems even
     * more convoluted to add new classes or is it preferable to this solution?
     */
    private static int add(char[] a) {
        int count = 0;
        for (int i = 0; i < a.length; i++) {
            if (a[i] == '(') {
                count += 1;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            process(scanner.next());
        }
    }

}

Before I looked at your code, I attempted the problem myself. Here's what I came up with - take from it what you will or leave it. I think our two versions produce different outputs for some inputs - that could be different interpretations of the problem, or one of us has got bugs! (Edit: Actually, they do seem to be the same after all).
import java.util.Scanner;

public class Parens {

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Input: ");
            Parens.displayBalancing(scanner.next());
            System.out.println();
        }

        System.out.println("Extra tests cases");
        for (String test : new String[] { "(()())E", ")(()((E", "())(E" }) {
            Parens.displayBalancing(test);
        }
    }

    public static void displayBalancing(String s) {
        Parens.Changes changes = balance(s);
        System.out.format("removed: %-2d  additional:  %-2d correct: %-5b  input: %s\n",
                changes.removed, changes.additional, changes.isNoChanges(), s);
    }

    public static class Changes {
        int removed;
        int additional;

        Changes(int remove, int add) {
            this.removed = remove;
            this.additional = add;
        }

        public boolean isNoChanges() {
            return removed == 0 && additional == 0;
        }
    }

    public static Changes balance(String s) throws IllegalArgumentException {
        return balance(s.toCharArray(), 0, 0);
    }

    private static Changes balance(char[] characters, final int remove, final int add)
            throws IllegalArgumentException {
        int open = 0;
        for (char c : characters) {
            switch (c) {
            case '(':
                open++;
                break;
            case ')':
                if (open == -remove) {
                    // got close paren but none are open
                    return balance(characters, remove + 1, add);
                }
                open--;
                break;
            case 'E':
                if (open != add - remove) {
                    // got E but some parens are still open
                    return balance(characters, remove, add + 1);
                }
                // balanced
                return new Changes(remove, add);
            default:
                throw (new IllegalArgumentException(
                        String.format("Unexpected character '%c'", c)));
            }
        }
        throw (new IllegalArgumentException("String didn't contain an E"));
    }

}

Then I realised your approach was actually pretty good. This should work too:
    public static Changes balance2(String s) {
        while (s.contains("()")) {
            s = s.replace("()", "");
        }
        int remove = 0;
        int add = 0;
        for (char c: s.toCharArray()) {
            if (c == 'E') {
                break;
            } else if (c == '(') {
                add++;
            } else if (c == ')') {
                remove++;
            }
        }
        return new Changes(remove, add);
    }


POSIX shell script using a string to store command arguments

First thing, you could turn the check if the checkbashisms tool is installed into a guard clause, shaving off one level of indentation:

if ! command -v checkbashisms >/dev/null 2>&1; then
    echo "‘checkbashisms’ is not available; it can be installed from the ‘devscripts’ package."
    exit 1
fi

The remaining logic can be simplified a lot with the xargs tool.

if git diff --cached --name-only | grep "\\.sh$" | xargs checkbashisms; then
    printf "(No Bashisms found)"
else
    exit 1
fi

I understand that the code you showed it only part of a bigger script and you still want to use the generated list of files. However, calling git diff repeatedly will have negligible overhead and you can wrap the code in a shell function like this:

staged_scripts() {
    git diff --cached --name-only | grep "\\.sh$"
}

staged_scripts | xargs checkbashisms

Or even

check_staged_scripts() {
    git diff --cached --name-only | grep "\\.sh$" | xargs $1
}

check_staged_scripts "checkbashisms"


Effectively convert little endian byte slice to int32

encoding/binary package may have what you need. Check this: http://golang.org/pkg/encoding/binary/#example_Read

Your code with modified read_int32 function could be:

package main
import (
    "bytes"
    "encoding/binary"
    "fmt"
)

func read_int32(data []byte) (ret int32) {
    buf := bytes.NewBuffer(data)
    binary.Read(buf, binary.LittleEndian, &ret)
    return
}

func main() {
    fmt.Println(read_int32([]byte{0xFE, 0xFF, 0xFF, 0xFF})) // -2
    fmt.Println(read_int32([]byte{0xFF, 0x00, 0x00, 0x00})) // 255
}

Also you can interpret big endian by replacing binary.LittleEndian with binary.BigEndian


Hash and check passwords in node.js using the native pbkdf2

Is it ok if I save the combined from the hashPassword as text in
  the DB? (column type text)

Yes, that's OK, if you use this to store password hashes. If you use it as a (encryption) key then you should avoid text, as it can be hard to destroy the result.

  I have to convert from text back in Buffer in the verifyPassword
  -- hash = Buffer.from(hash, 'hex'); part (timingSafeEqual only accepts buffer). Is this ok? Does it take a lot of time?

That's OK. Compared to PBKDF2 almost nothing takes a lot of time.

  Is using text ok, or should I use and save buffer for this?

No text is OK, see question #1.

With regards to the code, some notes:

Calling split multiple times is not a good idea, call it once and store the intermediate result.
As there are no checks on the results after the split, the hash string representation could be altered without notice (impact depends on how the code is used).
You could use just a counter to retrieve the various parts after split, and at least create the variables in order (e.g. salt before hash) - storing the hash last makes most sense to me.

I was afraid that you were implementing PBKDF2 yourself, but you seem to be correctly using the proper crypto calls.

A different idea of handling this (for you to ponder over).

Define your protocol somewhere and store a protocol version in your hash string. You could even use that to replace the salt size, iterations, hash type etc.. Then if you choose a higher iteration count you could just update your protocol version.


Good observation

Many new C programmers do not realize that n = strlen(s) when called in a loop can take code from linear performance O(n) to worse O(n*n) performance when  s may change or with weak compilers.

// I'd like to avoid repeated strlen() calls
int string_length = strlen(str);  // Good!!

Good use of const

Nice. string_contains_integer(const char *str)

Nicely formatted code

I hope you are using an auto formatter.  Life is too short for manual formatting.

"whatever its length is"

Strings can have a length that exceeds INT_MAX.  Note that strlen() returns type size_t.  That is the right-sized type for array indexing and sizing.  Note: size_t is some unsigned type.

// int string_length = strlen(str);
// for (int i = 0; i < string_length; i++)

size_t string_length = strlen(str);
for (size_t i = 0; i < string_length; i++)

Expensive sign compare

Rather than call strncmp(), just compare characters.

// char chr = str[i];
// if (strncmp("-", &chr, 1) == 0)
if (str[i] == '-')

OP's code is tricky here.  strncmp() can handle non-strings (which is what &chr points to) as long as they do not exceed n.  With n==1, code is effectively doing a char compare.

Sign at the beginning

Conversion of strings to numeric values allow a leading sign, either '-', '+' or none.  This code errantly allows a '-' someplace.  @Martin R.

Just start with

bool string_contains_integer(const char *str) {
  if (*str == '-' || *str == '+') {
    str++;
  }
  ....

  // Other sign code not needed

strlen() not needed.

Rather than i < string_length, just test str[i] != '\0'.  This speeds up detection of non-numeric strings as the entire string does not need to be read.

is...(int ch) quirk

is...() functions are specified for int values in the unsigned char range and EOF.  On common platforms where char is signed, isdigit(chr) risks undefined behavior (UB) when chr < 0.  Best to cast here.

// isdigit(chr)
isdigit((unsigned char) chr)

{ block }

Of coding style, I recommend to always use {} after if,else, even if one line.

//if (string_length == 0)
//    return false;

if (string_length == 0) {
    return false;
}

Minor: Simplification

To simply prints a line, code could use puts().  But what you did is OK.  Note puts() appends a '\n'.

// printf("%s\n", "PASS: Input is a number.");
puts("PASS: Input is a number.");

Alternative

This does not use array indexing.  Just increment the pointer as needed.

bool string_contains_integer_alt(const char *str) {
  if (*str == '-' || *str == '+') {
    str++;
  }

  if (*str == '\0') {
    return false;
  }

  while (isdigit((unsigned char)*str)) {
    str++;
  }

  return *str == '\0';
}


Build a generator over the file to return just ints, then transpose the enumeration to get your X and Y, eg:

with open('testing.txt') as fin:
    lines = (int(line) for line in fin)
    total = next(lines)
    X, Y = zip(*enumerate(lines, 1))

Note X and Y will be tuples instead of lists, but you can convert them after if you wish.


I attempted to reduce redundancy by simulating a do-while loop so that the first condition initializes the sequence and then the code can be factored out.

Instead of having a temporary list, it returns a generator which can be appended to the list.

I couldn't test this so I don't know if it works:

def get_object_list_for_user(user_service_token):
    endpoint = f"{HOSTNAME}/me/library/objects/"
    params = {"limit": 100}
    offset = 0

    lists_of_objects_to_append = []

    while True:
      json_resp = _call_service_api(endpoint, params=params).json()
      lists_of_objects_to_append.extend(extract_items(json_resp))

      offset += 100
      params.update({"offset": offset})

      if not json_resp.get("next"):
          return lists_of_objects_to_append

def extract_items(json_resp):
    for item in json_resp.get("data"):
        yield({"library_id": item["id"], "name": item["attributes"]["name"]})


Thanks for your question. IMHO, converting procedural code to OO code is an excellent thing to practice. Congratulations on your epiphany!

In general, the problem of persisting your game's data is a serialization problem. I would invite you to explore whether .NET's native "settings" functionality might be able to meet your needs. And beyond that, standard serialization to JSON or XML might be worth a look.

If you insist on "rolling your own" serialization, you can certainly do so in an object-oriented way. My take on getting started is below.

If you have complex data like game level definitions, you might be serializing quite a bit of data, which would be all the more reason to use a standard format like JSON or XML.

For serializing and deserializing a relatively simple config file, you can probably skip the factory pattern. But, if the config spans multiple files, including image blobs, etc., then a "Config Factory" might be worth considering.

I would recommend building one (or more) classes to properly model the actual config properties, and serializing/deserializing that instead of processing everything as strings.

For example:

public class Config
{
    public string PlayerName {get; set;}
    public DateTime LastPlayed {get; set;}
    public int HighScore {get; set;}
}

The below example takes a "hybrid" approach. It goes further than processing raw strings by using KeyValuePair, but stops short of a fully-typed Config class (as shown above).

Another quick tip: Instead of RawLineCollection, I'd call it RawLines, or even better, Lines.

Welcome to the wide world of OOP. In some of my other code review answers I go deeper into the principles that guide my OOP practice.

Here's the sample (this code compiles, but I didn't test it):

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

public class App_ConfigFile
{
    /*  Config file example

        player1Name:Jane
        player2Name:Joe
        difficulty:medium
        lastPlayed:04/20/2020
        lastLevel:5
        highScore:31000
     */

    public void Run()
    {
        var file = new ConfigFile(@"c:\myGame\config.txt");
        var config = file.ToConfigData();
        var player1name = config.GetByName("player1Name");
        var lastPlayed = DateTime.Parse(config.GetByName("lastPlayed"));
        var highScore = int.Parse(config.GetByName("highScore"));
    }
}

public class ConfigFile
{
    private string path;
    private List<Line> lines;
    public List<Line> Lines => lines ?? (lines = getLines());
    public bool HasContent => Lines.Count > 0;

    public ConfigFile(string path) => this.path = path;

    public ConfigData ToConfigData(char separator = ':') => new ConfigData(Lines.Select(l => l.ToKvp(separator)).ToList());

    private List<Line> getLines() => File.ReadAllLines(path).Select(l => new Line(l)).ToList();
}

public class Line
{
    public string Raw { get; private set; }
    public Line(string line) => Raw = line;

    public KeyValuePair<string, string> ToKvp(char separator)
    {
        var tokens = Raw.Split(separator);
        return new KeyValuePair<string, string>(tokens.First(), tokens.Last());
    }
}

public class ConfigData
{
    private List<KeyValuePair<string, string>> data;
    private Dictionary<string, string> _dictionary;
    private Dictionary<string, string> dictionary => _dictionary ?? (_dictionary = data.ToDictionary(d => d.Key, d => d.Value, StringComparer.OrdinalIgnoreCase));

    public ConfigData(List<KeyValuePair<string, string>> data) => this.data = data;

    public string GetByName(string key) => dictionary[key];
    public bool TryGetByName(string key, out string value) => dictionary.TryGetValue(key, out value);
}

}


Add functionality to object then remove those functions on export

Mild issue with assigning functions

It's possible that you could overwrite properties of a question if they have the same name as one of your validation functions. For example:

let question = {
  foo: "bar"
};

let validationOptions = {
    foo,
    cleanUp
};

When you execute Object.assign the later object's properties override earlier ones in the arguments array.

Alternative to deleting the functions

I think a better way to "delete" the added functions would be to just keep track of the original question object, and then return it from cleanUp:

export class Validator {
    validate(question) {
        let q = Object.assign(
            {},
            question,
            validationOptions
        );

        q.cleanUp = () => question;

        return q;
    }
}

let validationOptions = {
    validateString
};

function validateString() {
    // validate
    return this;
}

That way the initial object is unchanged, and you don't have to concern yourself with deleting the validation functions from the question when your done.

Wrapper Class

I think you also ought to consider making the validator a wrapper class for your question. That way your validation functions stay out of your data, you can still chain your methods, and you don't have to assign the validation functions for each object:

export class Validator {
    constructor(question) {
      this.data = question;
    }
    validateString() {
      return this;
    }
    cleanUp() {
      return this.data;
    }
}

If you want the validation functions to be free from an object, classes have prototypes that you can assign the methods to:

function validateString() {
  return this;
}

export class Validator {
    constructor(question) {
      data = question;
    }
}
Validator.prototype.validateString = validateString;

If you have a lot of functions you could do:

let validateOptions = {
  validateString,
  validateDate,
  validateAge
};

Object.keys(validateOptions).forEach((property) => {
  Validator.prototype[property] = validateOptions[property];
});


Using object oriented PHP to display users in a database

Some tips which might help you:

Make as few static methods as possible. Those functions should not
appear in any other function as they get in a way in unit tests. I usually use them to spit out html in views.
Don't use global varibales.
Hide as implementation as you can. Make public only those things that are vital for functionality.
I consider new operator harmful as it cannot be mocked. Use dependency injection instead to provide object with all necessary data.

Last but not least I highly recommend book Clean Code by Robert C. Martin if you care about keeping your code clean.


Avoid working in the global namespace

This makes maintenance of code a pain. Instead create a main or hangman function
Don't use global instead make these variables parameters of you function

def draw_man_and_show_word():
   global word

Could be

def draw_man_and_show_word(word):

Don't make lines to long, they become really hard to read

array=[[124,45,45,45,45,32,32,32],[124,32,32,32,124,32,32,32],[124,32,32,32,32,32,32,32],[124,32,32,32,32,32,32,32],[124,32,32,32,32,32,32,32],[124,32,32,32,32,32,32,32],[124,32,32,32,32,32,32,32]]

See how you need to scroll all the way to the right, this would be much more easy on the eyes

HANGMAN =  [
               ['|', '-', '-', '-', '-', ' ', ' ', ' '],
               ['|', ' ', ' ', ' ', '|', ' ', ' ', ' '],
               ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
               ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
               ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
               ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
               ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
           ]

I also changed it to their character form which makes it even more easy to read

And made the variable name ALL_CAPS since this is a constant
Use unpacking // Optional namedtuple

man=[[4,2,79],[4,3,43],[3,3,47],[5,3,92],[4,4,124],[3,5,47],[5,5,92]]
y=man[size][0]
x=man[size][1]
c=man[size][2]
array[x][y]=c
size=size+1

First I cleaned it up a bit

HANGMAN_STAGES = [
                     [4, 2, 'O'],
                     [4, 3, '+'],
                     [3, 3, '/'],
                     [5, 3, '\\'],
                     [4, 4, '|'],
                     [3, 5, '/'],
                     [5, 5, '\\']
                 ]

And we can unpack the values from the list of lists with this

x, y, value = HANGMAN_STAGES[size]

Alternatively you can use the namedtuple module to store information more visually

The it would become

from collections import namedtuple

Stage = namedtuple('Stage', 'x, y, value')
HANGMAN_STAGES = [
                     Stage(4, 2, 'O'),
                     Stage(4, 3, '+'),
                     Stage(3, 3, '/'),
                     Stage(5, 3, '\\'),
                     Stage(4, 4, '|'),
                     Stage(3, 5, '/'),
                     Stage(5, 5, '\\')
                 ]

And you can call them like this

stage = HANGMAN_STAGES[size]
HANGMAN[stage.y][stage.x] = stage.value

Make the guessed_letters a set()

For fast lookup O(0)
join() instead of manually appending chars

for y in range(0,7):
    for x in range(0,7):
        print (chr(array[y][x]),end='')
    print()

Could be rewritten as print('\n'.join(''.join(row) for row in draw_list))

If we have changed the HANGMAN to contain chr instead of the ordinal values
Instead of the find and replace methods you could have used enumerate

pos=theword.find(letter)
if (pos >= 0):
    tmpword=theword
    while (pos >= 0):
        word[pos]=letter
        tmpword=tmpword.replace(letter,'#',1)
        pos=tmpword.find(letter)

Can be rewritten in the form of

for idx, char in enumerate(theword):
    if char == letter:
        guessed_word[idx] = letter

But strings can't be assigned... so you should set the data type of guessed_word to a list
Lastly top it off with a if __name__ == '__main__'

Putting it all together

import random

HANGMAN =  [
                ['|', '-', '-', '-', '-', ' ', ' ', ' '],
                ['|', ' ', ' ', ' ', '|', ' ', ' ', ' '],
                ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
                ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
                ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
                ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
                ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
           ]

HANGMAN_STAGES = [
                    [4, 2, 'O'],
                    [4, 3, '+'],
                    [3, 3, '/'],
                    [5, 3, '\\'],
                    [4, 4, '|'],
                    [3, 5, '/'],
                    [5, 5, '\\']
                 ]
SPACE = '_'

def print_man_and_word(draw_list, guessed_word):
    print('\n'.join(''.join(row) for row in draw_list))
    print()
    print(''.join(guessed_word))

def get_random_word():
    # Your logic here (I don't have linux atm ;)
    word_list = ['cheese', 'pepper', 'sausage']
    return random.choice(word_list)

def get_letter(guessed_letters):
    letter = ''
    while len(letter) != 1 or not letter.islower() or letter in guessed_letters:
        letter = input("Enter your choice of (single lowercase) letter:")
    return letter

def hangman(word=None, draw_list=HANGMAN):
    if word is None:
        word = get_random_word()

    guessed_word = [SPACE] * len(word)
    guessed_letters = set()
    tries = 0

    while True:
        print_man_and_word(draw_list, guessed_word)
        letter = get_letter(guessed_letters)
        guessed_letters.add(letter)

        if letter in word:
            for idx, char in enumerate(word):
                if char == letter:
                    guessed_word[idx] = letter
        else:
            x, y, value = HANGMAN_STAGES[tries]
            draw_list[y][x] = value
            tries += 1

        if all(char != SPACE for char in guessed_word):
            print_man_and_word(draw_list, guessed_word)
            print('\nYou got it!')
            exit()

        elif tries == len(HANGMAN_STAGES):
            print_man_and_word(draw_list, guessed_word)
            print('You lost! it is {}'.format(word))
            exit()

if __name__ == '__main__':
    hangman()


You seem to be mixing compiled Haskell (import ...) with GHCi commands (top-level lets).

Top-level definitions should all be given type signatures, e.g.,

sel3 :: (a, b, c) -> c

Try to break down your functions into semantically interesting (and therefore nameable) chunks. For instance, (sel3 . toWeekDate) d /= 6 is a proposition on Days to ensure it isn't Saturday. So say that.

-- Usage: isSaturday (fromWeekDate 2016 06 22) == False
--        isSaturday (fromWeekDate 2016 06 25) == True
isSaturday :: Day -> Bool
isSaturday d = weekday d == 6
  where
    weekday :: Day -> Int
    weekday = sel3 . toWeekDate

Take advantage of available instances! Days are instances of Enum, so you can enumerate them directly without that messy map and takeWhile you've got going on.

rangeWithoutSaturdays :: Day -> Day -> [Day]
rangeWithoutSaturdays start end = filter (not . isSaturday) [start .. end]


Bash on Synology - Delete recycle bin entries over X days old

If this is intended to be run as a command, I recommend you add a suitable shebang line.  Although the question is tagged bash, there's nothing here that isn't portable POSIX shell, so I recommend

#!/bin/sh

Is it intentional that the paths all share a common initial prefix /volume1 and that the log and error paths share a longer common prefix?  If so, encode that for easier re-use:

volume=/volume1
scriptdir=$volume/share2/SynoScripts
logpath=$scriptdir/logs/deleteOlderThanXDays.txt
errorpath=$scriptdir/errors/deleteOlderThanXDays.txt

Personally, I'd call those last two logfile and errorfile for clarity.

There's no need to quote the values in these assignments, but the values should be quoted when used later, so that we don't break the script when they change to include spaces or other significant characters.

Instead of multiple echo commands, consider using a single date with tee:

date '+%n%Y-%m-%d %T' | tee -a "$logpath" >>"$errorpath"

After that, we can simply redirect all output and errors:

exec >>"$logpath" 2>>"$errorpath"

When using find, prefer to group many arguments into a few commands, using + instead of \;:

find "$deletepath" \! -type d -mtime +60 -exec rm -v '{}' +
find "$deletepath" -mindepth 1 -type d -empty -exec rmdir -v '{}' +

I assume you meant to use -v consistently for both commands here.

Modified version

#!/bin/sh

volume=/volume1
scriptdir="$volume/share2/SynoScripts"

deletepath="$volume/share1/#recycle"
logpath="$scriptdir/logs/deleteOlderThanXDays.txt"
errorpath="$scriptdir/errors/deleteOlderThanXDays.txt"

# redirect all output and errors
exec >>"$logpath" 2>>"$errorpath"

# log the start time to both logs
date '+%n%Y-%m-%d %T' | tee -a "$errorpath"

# delete old non-directory files (including devices, sockets, etc)
find "$deletepath" \! -type d -mtime +60 -exec rm -v '{}' +

# delete empty directories, regardless of age
find "$deletepath" -mindepth 1 -type d -empty -exec rmdir -v '{}' +


Implementation of oil-painting filter for images

Just my few cents...
There is no reason to treat distance == 1 differently:
    public static int findNumberOfPixels(int distance)
    {
        int numberOfPixels = 0;
        int increment = 4;
        for (int i = 1; i <= distance; i++)
        {
            numberOfPixels += increment;
            increment += 4;
        }
        return numberOfPixels;
    }

Furthermore, this method returns the same output for the same input every time. But you are calling it once for every pixel. It might be better to compute this value only once.


Displaying nested arithmetic expressions as a string using Scala pattern matching

You're right.  That repeated code in nestOperations() can be eliminated.

def nestOperations(es: Expr*): String =
  es.map {
    case Number(n) => n.toString
    case Prod(x, y) => nestOperations(x, y)
    case Var(s) => s
    case Sum(x, y) => "(" + show(x) + " + " + show(y) + ")"
  }.mkString(" * ")

But why stop there?  You can pull much the same stunt with show() and eliminate nestOperations() altogether.

def show(es: Expr*): String = es.map{
  case Number(n) => n.toString
  case Sum(e1, e2) => if (es.length > 1) "(" + show(e1) + " + " + show(e2) + ")"
                      else show(e1) + " + " + show(e2)
  case Prod(e1, e2) => show(e1, e2)
  case Var(s) => s
}.mkString(" * ")


Not sure if there are any other constraints but here is one possible solution:

private void enableFolderVariableRemoval_CheckedChanged(object sender, EventArgs e)
{
    cleanFolderTextPanel.Visible = enableFolderVariableRemoval.Checked;
    cleanTextPanel.Visible = cleanFolderTextPanel.Visible || cleanFilenameTextPanel.Visible;
}


Save all HTML field names in Controller - it is bad or not bad idea?

I recomend you to use Symfony like form builder. There you can create one form and reuse it anywhere.

$form = FormFactory::create(FormType::class, $user)
    ->add('name', TextType::class)
    ->add('email', EmailType::class, [
        'rules' => 'unique:users,email',
    ])
    ->add('save', SubmitType::class, ['label' => 'Save user']);

What is also good is with this form you can also validate your input at the same time.

 $form->handleRequest();

 if ($form->isSubmitted() && $form->isValid()) {
      //Your code
 }

Here is link for repository


Idiomatic Ruby if/else in a Sinatra route

I agree that re-assigning variables is not great. The most 'obvious' way to improve this is to extract a helper method like
def fetch_link
  if (existing_link = MinifiedUrl.where(:code => params[:code]).first)
    existing_link
  else
    MinifiedUrl.create(:target_url => params[:url], :code => generate_code)
end

def generate_code
  Digest::MD5.hexdigest(incoming_url)[0..5]
end

or if you prefer or memoization
def fetch_link
  return existing_link if existing_link.present?

  MinifiedUrl.create(:target_url => params[:url], :code => generate_code)
end

def existing_link
  @existing_link ||= MinifiedUrl.where(:code => params[:code]).first
end

def generate_code
  Digest::MD5.hexdigest(incoming_url)[0..5]
end

Another approach could be to implement a class method on your model which does it for you like
class MinifiedUrl
  def self.find_or_create_by(original_url:, code:)
    if (existing_link = MinifiedUrl.where(:code => code).first)
      existing_link
    else
      MinifiedUrl.create(:target_url => original_url, :code => generate_code)
    end
  end
end

post '/' do
  incoming_url = params[:url]

  link = MinifiedUrl.find_or_create_by(url: incoming_url, code: params[:code])

  link[:slug]
end

## Edit
Adding some more thoughts about error handling here.
URL
There are several things which can go wrong with the URL like invalid or already taken.
The invalid case I would cover with a validation but there is not much what you can validate here to be honest except the format. Mongoid comes with ActiveSupport validations so you could do something like this.
class MinifiedUrl
  validates_format_of :original_url, with: /regex/
end

MinifiedUrl.create(url: 'invalid').valid?
# false

It can be that your URL is already taken, e.g. somebody else already added this URL. What do you want to do in this case? Give an error or allow it? I think it's a valid use case to allow the same URL twice with a different code (you don't want to have the same code as e.g. you want to have a visit counter as well). If you want to allow the same URL twice, your approach with the MD5 hash does not work anymore as it would be the same obviously so in this case you should use something more random.
The hex digest is anyway a problem in case of collisions you would fail at the moment. I think a better approach is to just generate a random code in a loop.
def generate_code
  100.times do
    code = SecureRandom.hex
    break code unless MinifiedUrl.find_by(code: code)
  end
end

I'm also wondering why your POST does accept a code parameter but I don't know your user interface, I just found it a bit confusing.
I wouldn't be too concerned about DB not available and would not put any code handling this in my application to be honest. If you need this safety you should have DB replicas which can handle if a node goes away.
I would also calculate if a 5 digit code is big enough for your use case.
I'm also wondering why you chose to use to Mongoid? I don't think a document store is a good data storage here? I think a key/value store like Redis would be a better alternative here because you basically just do key lookup and you can store everything in a hash. But again, I don't know the requirements.


Extending java.util.Random.nextInt(int) into nextLong(long)

Try it with n>2^32 and your code will fail. 0x7FFFFFFFL reduces your code to int, breaking your extension to long. You need to use the maximal value of long not int in your mask. i.e. 7FFFFFFFFFFFFFFFL.


There is no need to pass linker flags to the compile stage. You only them when you link the final executable.
Traditionally (aligned with make defaults) the flags variables are CFLAGS for C compiler, CXXFLAGS for C++ compiler, and LDFAGS for the link stage specifics. It is not recommended however to have -c as a part of CFLAGS: the CFLAGS can be reused for non-compile action (e.g. dependency generation as described below).
exe is a phony target (and better be specified as such); a file named exe is never created, so it is never up to date, and the makefile forces linking even if nothing has been changed. I recommend to change the link recipe to

$(OBJ_NAME): $(OBJS)
    ....

Stem rules let you DRY:

%.o: %.cpp
    $(CC) $(CXXFLAGS) $<

For a separate build directory you may look at VPATH; I prefer to to point it explicitly in the stem rule:

$(BUILD)/%.o: %.cpp
    $(CC) -o $@ $(CXXFLAGS) $<

As a side note, I'd go one step further, and separate debug and release builds.
Dependency generation. The stem rules above do not specify #include dependencies. With gcc it is easy to automate. -M family of flags:

$(BUILD)/%.d: %.cpp
    $(CC) -o $@ -MM -MT $(CXXFLAGS) $<

create a makefile fragment which you'd include in your makefile.

Since the dep and obj file names mirror the source file names (only the extension differs) it is recommended to generate them using the patsubst function.
Never use -w. Warnings are your friends. I highly recommend passing at least -Wall -Wextra.
Putting it (almost) all together,

SRC = close.cpp init.cpp main.cpp texture.cpp load_media.cpp
OBJ = $(patsubst %.cpp,$(BUILD)/%.o,$(SRC))
DEP = $(patsubst %.cpp,$(BUILD)/%.o,%(SRC))

TARGET = run

$(BUILD)/%.o: %.cpp
    $(CXX) -c      -o $@ $(CXXFLAGS) $<

$(BUILD)/%.d: %.cpp
    $(CXX) -MM -MT -o $@ $(CXXFLAGS) $<

-include $(DEP)

$(BUILD)/$(TARGET): $(OBJ)
    $(CXX) -o $@ $(CXXFLAGS) $(LDFLAGS) $(OBJ)