User class for future inheritance in other programs involving user activity

One of the most important things to take care of when writing a database application is to prevent unwanted access. This means that you always want to make sure that there is no user (and the programmer, i.e. you should be included in that) can supply an input that can escape the query and e.g. delete your whole database. This attack vector is called SQL injection and is very common. Avoiding it is relatively easy, thankfully, although you cannot do it for the table name:

@classmethod
def login(cls, user_name, password):
    db = mycon.connect(host=cls.host, user=cls.user, password=cls.password,
                       database=cls.database)
    cursor = db.cursor()
    query = f"SELECT firstName, lastName, password, UserName, email FROM {cls.table} WHERE UserName = %s;"
    r = cursor.execute(query, (user_name,))
    user_info = cursor.fetchone()
    if user_info is not None:
        if user_info[2] == password:
            print("Login Successful")
            return cls(user_info[0],user_info[1],user_info[3],user_info[4])
        else:
            print(f"INVALID PASSWORD {password} {user_info[2]}")
    else:
        print("USER DOES NOT EXIST")
    db.close()

Note that I followed Python's official style-guide, PEP8, which recommends using lower_case for variables and functions, spaces after commas and around = when using it as an assignment, but no space around the = when using it for keyword arguments.

Comparisons to None should always be done with is or is not and if conditions don't require parenthesis, since it is a keyword.

I also explicitly named the column names (they might be called differently, judging by UserName, so you would have to fix that), to ensure that you can change the table structure, as long as these names stay the same.

And I used an f-string for easy formatting in case of an invalid password. Note that in this case you do reveal the actual password (I guess this is just for testing, just make sure you don't forget to remove that information later). In a similar vein, you should not store passwords in plaintext. Hash them with a good hashing algorithm and ideally add a salt.

You could also use the mysql.cursor.MySQLCursorNamedTuple cursor, so you can say user_info.password instead of user_info[2]. Just use cursor = db.cursor(named_tuple=True).

You should do yourself a favor and add a docstring to every method you write, to explain what the method does, what its arguments are and what it returns.


It's hard to decide where to begin. OK: no comments whatsoever. You know how it works now, but it will not be obvious next month if you do anything but sit idly in a dark room being fed through a tube thinking about this code.

Indicies is not a word. Don't write code on a napkin, everything can spell check English nowadays.

  I also never worked with multithreading, so I can imagine I could be doing things better there.

It is best to learn how (and when) to do it and then try and come here. Don't just write something that compiles and throw at our face.

It is easier on the brain if you split this on a class that is your "driver", "main", "starter" which has a main() and does the instantiation and invocations and another one that is instantiated and called. I am not talking about correctness, obviously both approaches work, but the one I described above is clearer and wastes less cognitive power.

You forgot you were writing Java and accidentally wrote a C return statement.

return (foundPassword = genPassword().equals(testPassword));

You could afford another line, your IDE wouldn't run out of memory:

foundPassword = genPassword().equals(testPassword);
return foundPassword;

Responsibilities are a salad. See that advanceIndices checks if the password has been found. It was supposed to advance the indices but it is doing way more than that.

Performance-wise, the cost of synchronization is too high. A correct approach would be to partition the problem in n subproblems - where n is the number of threads you have - of almost the same size and solve each one in its own thread, with less synchronization.

Hypothesize that you have an array with 40 valid characters and 5 threads. Make thread A check all possible passwords that start with one of the first eight characters, thread B check all possible passwords that start with one of the next eight characters and so on until thread E.

Then throw in a volatile boolean flag that indicates termination which all threads refer to every now and then to know if they can stop because a thread found a solution.

It needs to be volatile so that any thread that reads it will see the most recently written value. You should know about this before attempting multithread programming in Java.

Summing it up

Learn how to do it before bashing your head against the wall.
Parallelization is good for this problem but you did it wrong, see the item above.


Converting file from Markdown-like markup into HTML using repeated substitutions

Here's what I would do (note: in ES6, though it is trivial to convert back to ES5). It doesn't match your code perfectly, but it should get get the point across. Essentially I extract everything out into smaller methods and then have a method that can perform batch replacements. It's not shorter nor really any less complex, but it is (to me) easier to read and follow.

Notes:

I'd normally comment this like crazy so that I could remember what the regexps do, but in this example I haven't. Almost all of them are your regexp's, and the ones that are different aren't so different that they won't be obvious to you.
I prefer HTML Entities for things like double quotes and dashes.
I'm not worrying about the p class="ni" stuff, but it would be trivial to add.

ES6 Code:

function massReplace(text, replacementArray) {
  let results = text;
  for (let [regex, replacement] of replacementArray) {
    results = results.replace(regex, replacement);
  }
  return results;
}

function transformHeadings(text, orig) {
  if (orig.match(/^#{1,6}\s/)) {
    return massReplace(text,
                       [ [/^###### (.*)/gm, '
$1
'],
                         [/^##### (.*)/gm,  '
$1
'],
                         [/^#### (.*)/gm,   '
$1
'],
                         [/^### (.*)/gm,    '
$1
'],
                         [/^## (.*)/gm,     '
$1
'],
                         [/^# (.*)/gm,      '
$1
'] ]
                      );
  }
}

function transformQuotes(text, orig) {
  if (orig.match(/"|'/)) {
    return massReplace(text,
                       [ [/"(?=\b|\*|')/g,             '&ldquo;'],
                         [/"(?!\b|\*|')/g,             '&rdquo;'],
                         [/'(?!\b|\*)|(?=\b)'(?=\b)/g, '&lsquo;'],
                         [/'(?=\b|\*)/g,               '&rsquo;'] ]
                      );
  }
}

function transformStyling(text, orig) {
  if (orig.match(/\*\*|\*/)) {
    return massReplace(text,
                       [ [ /\*\*([^\*|\s]+)\*\*/g, '$1'],
                         [ /\*([^\*|\s]+)\*/g,     '$1' ] ]);
  }
}

function transformDashes(text, orig) {
  if (orig.match(/\-\-/)) {
    return massReplace (text, [ [ /\-\-/g, '&mdash;' ] ]);
  }
}

function transformParagraphs(text, orig) {
  if (!orig.match(/^#{1,6} (.*)/)) {
    return `<p>${text}</p>`;
  }
}

function transformToHTML(markdownSource) {
  let data = markdownSource.split('\n\n'),
      orig = data.slice(),
      transforms = [ transformHeadings, transformQuotes, transformDashes,
                     transformStyling, transformParagraphs ];

  for (let i = 0, l = orig.length; i < l; ++i) {
    for (let transform of transforms) {
      let result;
      if ((result = transform(data[i], orig[i])) !== undefined) {
        data[i] = result;
      }
    }
  }

  return data.join('\n');
}

NOTE: For engines that don't support destructuring (looking at you, io.js), use this method instead:

function massReplace(text, replacementArray) {
  let results = text;
  for (let replacementArrayItem of replacementArray) {
    let regex = replacementArrayItem[0],
        replacement = replacementArrayItem[1];
    results = results.replace(regex, replacement);
  }
  return results;
}


Some ideas:

String concatenation

The method you're using for string concatenation (successively using the += operator) is the slowest method in Python for constructing strings.  Consider instead creating a list of strings and concatenating them at the end using return ''.join(created_strings).  Because your BER encoder is likely to be used with a protocol, speed may be important.

Checking of inputs

Your cls, pc and tag elements are not checked on input to the ber_encode routine and would allow constructs such as ber_encode(0xc3,7,3,"bongo") which gets coded with a tag of 0xcd.  That isn't necessarily wrong but it's not what I might have expected.

Orthogonality of ber_encode and ber_decode

It's not unreasonable for a user of your functions to assume that the two complementary functions can each be fed the output of the other, but that's not the case for these functions.  While ber_decode will happily digest the output of ber_encode, what ber_decode produces is a named tuple rather than an output that's compatible with ber_encode's input requirements.  Again, this isn't necessarily wrong, but it is a potential impediment to users of your functions.

Error checking

Generally, the code does a pretty good job of validating inputs and throwing appropriate errors, but there is at least one case which is accepted that should probably throw an error.  Specifically,

ber_decode(b'\x86\xff'+('a'*256).encode(encoding='ascii'))

results in a BER value which is 129 bytes long.  It's probably worth double checking ITU X.690 section 8.1.3.5 which says that an encoded length value of 11111111b shall not be used.

Similarly,

ber_decode(b'\x86\x80'+('a'*256).encode(encoding='ascii'))

is decoded as three BER encodings, the first of which is 128 bytes long (which is suspect), the second is 97 bytes long (which is OK) and the third is 27 bytes long, which may or may not be OK, but shouldn't a truncated message throw an exception?

Test vectors

You may simply have omitted them from the posted code, but I'd highly recommend including test vectors with the code. Python has a number of ways to do testing including doctest and unittest. Not only do they help you make sure you've considered many different types of input (both good and bad), but they also serve as documentation for users of the functions.


Instead of inheriting from ui_main.Ui_GraphPlotter, I would use the PyQt4.uic module to dynamically load your ui file in the __init__ method:

import os
import pyqtgraph

from PyQt4 import QtGui
from PyQt4 import uic

curdir = os.path.dirname(os.path.abspath(__file__))

class GraphPlotter(QtGui.QMainWindow):

    def __init__(self):
        super().__init__()
        uic.loadUi(os.path.join(curdir, 'GraphPlotter.ui'), self)
        pyqtgraph.setConfigOption('background', 'w')
        # ...


Some comments when looking through your code:

Successor

I think that's fine - how else were you going to do it? Metz does exactly the same thing doesn't she? When successor is called a new bottle number - 1 is created - unless of course the bottle number is zero, in which case you start right back at 100.

Knowledge of the arguments and their order:

Consider this:

BottleNumber.new(number, quantity: 'no more', successor_number: 99, action: 'Go to the store and buy some more')

I don't like this. Why? Because every time you need to instantiante a bottle you need to KNOW what goes in there and you also need to know the order in which the arguments go in. You could eliminate the need to know the argument order by passing in a hash. That's probably the only bit of criticism i can add.

Inheritance

for this particular problem, inheritance seems like a better fit. it just seems a lot cleaner than dealing with the messiness of passing in those parameters.

anyways those are just my thoughts and i hope you find them of some use.


Query an array at intervals and getting the highest number of values

Instead of writing two cases depending on the length of the chunk, you could certainly make one general way for each task. Doing so you simplify the code inside maxAtIntervals and get rid of findmax (as you can use .sort().slice(-n) to get the max n numbers).

The return of maxAtIntervals is [values]. If values is already an array, why would you create an array of 1 array?

There are so many comments I could not even focus on the code. Be succinct!

After applying this changes and removing unnecessary variables, the function looks like this:

function maxAtIntervals (intervalLength, grab, xs) {
    const comparator = (a, b, _) => a - b;
    const temp = [];

    for (var i = 0; i < xs.length; i += intervalLength) {
        const interval = xs.slice(i, i + intervalLength);
        temp.push(interval.sort(comparator).slice(-grab));
    }

    return temp;
}

Your original code makes 111ms on my machine. After my changes it goes to 51ms.


Assembly beginner exercise: Calculate the square numbers from 1 to n

The biggest problem here—and generally with assembly—is the use of registers in the code without explicit documentation of what those registers contain, e.g., in the form of comments. Certain assumptions can be made based on common calling conventions (like that functions will return their result in eax), but that should still be documented for clarity. In other cases, it is not quite so obvious. For example, in this code, ebp apparently contains the "upper limit", but other than assuming that the code works and reverse-engineering its logic, I have no basis for that assumption. In fact, in the current implementation, the contents of the ebp register are a pre-condition for the function, so its use should unarguably be documented as part of the function's signature.

I further assume that ebp is actually just 1000000, in which case this portion of your code is overly verbose (and thus inefficient). You can simply do:

cmp  eax, 1000000          ; see if input is over the upper limit
jle  createSquareNumbers   ; if not, skip the next line
mov  eax, 1000000          ; if it is, bound it

If you are targeting the Pentium Pro or later (so basically, any modern x86 processor) you can use conditional move instructions like so:

cmp    eax, ebp
cmovg  eax, ebp

In some cases, conditional moves will make the code faster by eliminating the possibility of branch mispredictions. In this case, you won't see any performance improvement, but these instructions are still something to be aware of and this does make the code slightly easier to read. (Assuming that you want to keep the dependency on the ebp register, which might be handy if you want to make the upper limit variable. Otherwise, just hard-code the 1000000 and use the first version. Better yet, define a constant for that upper bound so you can give it a readable name.)

mov edx, 0

This is completely correct code for setting a register to 0. However, it is not idiomatic x86 assembly because it is inefficient. Both compilers and expert assembly-language programmers will instead write this as:

xor  edx, edx

This works because bitwise XORing any value with itself gives you back 0. The advantage is that it is shorter (2 bytes instead of 5 bytes) and faster.

The only time you would ever want to use mov  reg, 0 is if you didn't want to clobber the flags, which is handy when you're preparing to do a conditional move and in certain other tightly hand-optimized code. Otherwise, whenever you want to clear a register, think xor  reg, reg. While this is arguably a micro-optimization, you really do need to know this idiom so you can read other peoples' (and compilers') assembly code, so you might as well use it yourself.

I can tell that you're working with signed integer values because you're using the l and g condition codes. If you were working with unsigned integer values, you'd be using the b and a condition codes. Therefore, you should be doing a signed integer multiply (imul instead of mul). In fact, imul is preferable for a number of reasons, chief among them is the fact that it has a normal, two-operand form that works just like any other instruction, which means you don't have to worry about the hard-coded register operands that mul requires. This makes the code easier to optimize and, frankly, easier to read. You can use imul for unsigned multiplications, too, as long as you aren't worried about overflow, since the lower 32 bits are always the same. (And clearly you aren't worried about that here, since your print_eax function used to display the output can only print 32-bit values!)

There is, unfortunately, one bug lying in wait here:

You are only checking the upper bound, so what happens when the input value is 0? Your code will print 1, when instead it should print nothing! Also, I wonder if it is possible for read_hex to return a negative value? I don't have the function's implementation, or any documentation for it, so I can't tell. If you're not confident that it won't ever return a negative value, your code needs to handle this case. Fortunately, you can fix both of these potential problems easily by adding a check for the lower bound before entering the loop.

And while we're nitpicking, some of your comments have "bugs", too:

call print_eax ; ; Provided by teacher. Prints eax to stdin.

That should be stdout, not stdin! :-)

; ===========================================
; = Displays the square number from 1 until =
; =  number n. n is given by the user.      =
; = @param [ integer ] n - The upper        =
; =  limit. The last integer to calculate   =
; =  the square number of.                  =
; ===========================================

Your function does not actually take a parameter. Rather, it retrieves the input by calling the read_hex function. Therefore, this documentation is wrong, because it suggests that the function should be able to read a parameter from the normal register used for passing parameters in whatever calling convention it uses, which is not correct. It is important to document your functions, and it's important to document them accurately. In actuality, the function neither receives nor returns any values.

In terms of readability, you should align your code into vertical columns so that instruction opcodes are clearly separated from their operands. This makes it much easier to read and scan. Also, you should either vertically align your end-of-line comments, or put them above the code.

I would also rename your createSquareNumbers label to printSquares, since (1) it prints output rather than simply creating things, and (2) "numbers" is redundant. I also personally like to use PascalCase for labels to make them distinct, but whichever is fine, as long as you're consistent.

Finally, I would prefer to use the ecx register as my loop "counter", since that's what it was originally intended for (the "c" stands for "counter"). Technically, this doesn't matter at all in modern x86 code, and you can treat all of the registers as general-purpose registers, using them interchangeably. And, indeed, in optimized code, you will want to do this. But when you're writing it by hand and don't necessarily care about speed, it is just nice and readable to use registers in a predictable way.

Here is how I would personally write the code for your function, taking all of these things that I've mentioned into account:

start:
    ; Provided by teacher: reads in a hexadecimal number from stdin,
    ; returning it in EAX.
    call   read_hex

    ; Check for underflow: if the input value is less than or equal to 0,
    ; we skip the loop altogether.
    ; NOTE: The naive way to do this check is "cmp eax, 0", but as with
    ;       the XOR trick discussed above, "test eax, eax" is both
    ;       shorter and faster, so that's what everyone uses when they
    ;       want to test the value of a register against 0.
    ;       (You still use CMP with memory operands, of course.)
    test   eax, eax
    jle    finished

    ; Check for overflow: if the input value is larger than 1000000,
    ; we bound it to be exactly 1000000.
    cmp    eax, 1000000
    mov    edx, 1000000
    cmovg  eax, edx

    ; Prepare to enter the loop:
    mov    edx, eax        ; make a copy of the input
    mov    ecx, 1          ; initialize our counter

printSquares:
    mov    eax, ecx        ; put the counter into our scratch register, EAX
    imul   eax, eax        ; EAX = EAX * EAX

    ; Print the square (in EAX) by calling teacher-provided function,
    ; which prints the contents of EAX to stdout.
    ; It may or may not clobber EAX (we don't care),
    ; but it does not return a significant value.
    ; TODO: Make sure it doesn't clobber ECX or EDX!
    call   print_eax

    inc    ecx             ; increment our counter

    ; See if we've reached the input value yet.
    ; If not, continue looping.
    cmp    ecx, edx
    jle    printSquares

finished:
    ; We're now done with the loop, so exit.
    push   0
    call   [ExitProcess]

Warning: There is still potentially a bug in here, depending on how the print_eax function behaves. Normally, in most calling conventions, a function is allowed to clobber the eax, ecx, and edx registers. Therefore, to be on the safe side, you would have to assume that print_eax could clobber the values in these registers, meaning that you would have to either pick different registers to store your temporary values in, or you would have to explicitly save the contents of these registers before calling print_eax and restore them afterwards. However, if you know from the documentation or implementation of print_eax that it does not clobber either ecx or edx, then you are safe. Your original code had this bug, too, yet it worked properly, so I assume this is safe.


Keeping UI responsive while performing long running task

1) I would use the ProgressChanged event with a custom object as my e.UserState which is updated within the code.

// sample worker state class definition
internal class WorkerState
{
    public Exception ExceptionThrown { get; set; }
    public string ProgressMessage { get; set; }
    public int MaximumProgressValue { get; set; }
    public int ProgressValue { get; set; }
    public int Actions { get; set; }
}

Sample Usage

// this would likely be initialized / reinitiatlized before the RunWorkerAsync is called
private WorkerState m_WorkerState;

private void buttonUpdateContacts_Click(object sender, EventArgs e)
{
    // for question 2) this could be convered into some form of
    // factory where providing delegates for the ProgressChange and WorkCompleted
    BackgroundWorker worker = new BackgroundWorker();

    worker.UserState = new WorkerState();

    worker.WorkerReportsProgress = true;
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
    worker.RunWorkerAsync();
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    Worker worker = (sender as BackgroundWorker);
    WorkerState state = worker.UserState;

    state.UserState.ProgressMessage = "Parsing word document...";
    state.UserState.MaximumProgressValue = 100;
    state.UserState.ProgressValue = 0;

    worker.ReportProgress(0, state);

    // ...

    try
    {
        // do something
    }
    catch (InvalidCredentialsException argumentException)
    {
        e.ExceptionThrown = argumentException;
        return;
    }
    catch (ArgumentNullException nullArg)
    {
        e.ExceptionThrown = nullArg;
        return;
    }

    // ..
}

2) There is not too much wrong with putting the code in the button click event but you could make better use of OO concepts like factories for creating the BackgroundWorker component etc. I personally would split the bulk of the code in the DoWork method into seperate classes following SOLID principles (especially the Single Responsibility... this class is responsible for blah, blah blah).

3) Tasks are likely to be unsuitable in this case as this is exactly what the BackgroundWorker component was designed for.


Handling success and failure when retrieving product information

First, your controller is written weirdly. It could be simplified into:

// Since we're inlining everything, we don't need to wrap it in IIFE.
// Also, `readProductController` isn't a good name. Controllers are things,
// nouns, not verbs.
angular.module( 'app.purchases.products' ).controller('ProductController',[

  // A controller accepts either a function with implicit dependencies based on
  // argument names, or an array of dependency names, and whose last element
  // is the controller function.
  '$scope', 'productFactory'
, function(

  // I've read somewhere that factories and services should be named with first
  // letter as small since we're not exporting a constructor. Reserve Capital
  // names for things that return a constructor function.
  $scope, productFactory
){

  // Not sure why `vm` exactly. It doesn't tell me what it is. Name it something
  // meaningful, like `controller`.
  var controller = this;
  controller.products = {};
  controller.product = {};

  // You can simply inline the functions. No need for the indirection.
  this.getProductsList = function(columnOrder, sortOrder){

    // Promises are simply just objects that hold state for an async operation.
    // They still accept "callbacks" via the `then` method they provide.
    productFactory.getProducts({
      columnOrder: columnOrder,
      sortOrder: sortOrder
    }).then(function(products){
      controller.products = products;
    }, function(error){
      console.log(error);
    });
  };

  this.getProductDetails = function(id){
    productFactory.getProductDetails({
      id: id
    }).then(function(product){
      controller.product = product;
    }, function(error){
      console.log(error);
    });
  };

}]);

We can do the same with your service

// `readProductFactory` isn't really a good factory name. Factories are things
// that create things. They're not actions, so drop the read. It's just
// productFactory starting now.
angular.module('app.purchases.products').factory('productFactory', [
  'Restangular',
function(
  Restangular
){
  return {

    // Functions are "actions", verbs, commands. They should be named in a
    // "do something to that something" manner, like `getList`, or `sendMail`
    getProducts: function(data){

      // Restangular appears to already return a promise (because you "then'ed")
      // All we have to do is just return that promise to the controller so that
      // it listens with `then`.
      return Restangular.all( '/purchases/products/list' ).getList()
    },
    getProductDetails: function(data){

      // Doing the same
      return Restangular.one( '/purchases/products/', data.id ).all( '/detail' ).getList()

    }
  };
}]);


Creating accounts in a cpanel/whm account

Let's start with the easy fish - $_REQUEST. Going by the PHP manual, $_REQUEST is a combination of $_POST, $_GET, and $_COOKIE.

In your getVar(...) function, you reference the request superglobal, and in the following lines, you use it to get a password. Using the request superglobal would allow a password to be given in via insecure methods like GET and COOKIE. Ideally, you want to POST any sensitive data like a password, so let's modify the code to just grab from POST by default, and let's add a third parameter in case we need to get certain values from GET or COOKIE.

function getVar($name, $def = '', $sg_method = 'POST') {
  switch($sg_method){
      case 'POST'   : return isset($_POST[$name])   ? $_POST[$name]   : $def;
        break;
      case 'GET'    : return isset($_GET[$name])    ? $_GET[$name]    : $def;
        break;
      case 'COOKIE' : return isset($_COOKIE[$name]) ? $_COOKIE[$name] : $def;
        break;
      default : return $def;
  }
}

One glaring security issue is the following line:

$whm_host = $_SERVER['HTTP_HOST'];

You have to remember that HTTP_HOST is gotten from a user-defined header. Unless a business requirement dictates it, you should use SERVER_NAME. See HTTP_HOST vs. SERVER_NAME on Stack Overflow for a better explanation - specifically this answer by BalusC.

Now, we can compress the multiple IF statements into a simpler foreach, as follows:

$user_data = array(
    "domain"   => array($user_domain, 'user_domain'),
    "user"     => array($user_name,   'user_name'),
    "password" => array($user_pass,   'user_pass'),
    "package"  => array($user_plan,   'user_plan'),
    "email"    => array($user_email,  'user_email')
);

foreach($user_data as $key => $val){
    if(empty($val[0])){
        $$val[1] = getVar($key);
    }
}

Below is how I've modified your code:

# Your WHM login data
$whm_user   = "username";  # reseller username
$whm_pass   = "password";  # the password you use to login to WHM

#####################################################################################
##############          END OF SETTINGS. DO NOT EDIT BELOW    #######################
#####################################################################################

$whm_host   = $_SERVER['HTTP_HOST'];

function getVar($name, $def = '', $sg_method = 'POST') {
  switch($sg_method){
      case 'POST' : return isset($_POST[$name]) ? $_POST[$name] : $def;
        break;
      case 'GET' : return isset($_GET[$name]) ? $_GET[$name] : $def;
        break;
      case 'COOKIE' : return isset($_COOKIE[$name]) ? $_COOKIE[$name] : $def;
  }
}

# Domain name of new hosting account
# To create subdomain just pass full subdomain name
# Example: newuser.zubrag.com
$user_data = array(
    "domain"   => array($user_domain, 'user_domain'),
    "user"     => array($user_name,   'user_name'),
    "password" => array($user_pass,   'user_pass'),
    "package"  => array($user_plan,   'user_plan'),
    "email"    => array($user_email,  'user_email')
);

foreach($user_data as $key => $val){
    if(empty($val[0])){
        $$val[1] = getVar($key);
    }
}

# if parameters passed then create account
if (!empty($user_name)) {
  # create account on the cPanel server
  $script = "http:#{$whm_user}:{$whm_pass}@{$whm_host}:2086/scripts/wwwacct";
  $params = "?plan={$user_plan}&domain={$user_domain}&username={$user_name}&password={$user_pass}&contactemail={$user_email}";
  $result = file_get_contents($script.$params);
} else {
    $frm = <<<EOD
EOD;
    echo $frm;
}


Here is my version of your code.

You never use "max" so I used it by throwing an exception if you are trying to insert too many elements.
You should make everything that shouldn't be public; private.
In your binaryInsert() you should move your base case to the begining.
Your binaryInsert() is a bit wonky but it works. I think this would do but I haven't checked it. Looks a bit neater and has one unnecessary if removed.

public int binaryInsert(long insertKey) {
   if (nElems == 0)
     return 0;
   int lowerBound = 0;
   int upperBound = nElems - 1;
   int curIn = 0;
   while (true) {
     curIn = (upperBound + lowerBound) / 2;
     if (a[curIn] == insertKey) {
       return curIn;
     } else if (a[curIn] < insertKey) {
       lowerBound = curIn + 1; // its in the upper
       if (lowerBound > upperBound)
         return curIn + 1;
     } else {
       upperBound = curIn - 1; // its in the lower
       if (lowerBound > upperBound)
         return curIn;
     }
   }
 }

Just use methods that return things directly. Don't need to store them in a temporary variable first. Talking about curIn here in your insert function.
If you want to return something (like an object) as a String or print something out. You should override the toString() method as I have done. Then you can just call System.out.println(arr.toString()) whenever you want to print the Object.
The whole point of doing a binary insert would be to quickly find out where to insert an element. Your implementation does this, however your implementation isn't super useful because you have to move each and every element foward by one. A double linked list (as usually taught in C++ classes) is ideal for your implementation of this better version of insertion sort. The java equivalent of a doubly linked list is a LinkedList. Which will give you much better performance as you will not need to move elements forward by one.

.

public class OrdArray {

  final private long[] a; // ref to array
  private int nElems; // number of dataitems
  private final int MAX;

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

  public OrdArray(int max) { // constructor
    this.MAX = max;
    a = new long[MAX]; // create array
    nElems = 0;
  }

  private int binaryInsert(long insertKey) {
    if (nElems == 0) {
      return 0;
    }

    int lowerBound = 0;
    int upperBound = nElems - 1;

    while (true) {
      int curIn = (upperBound + lowerBound) / 2;
      if (lowerBound == curIn) {
        if (a[curIn] > insertKey) {
          return curIn;
        }
      }
      if (a[curIn] < insertKey) {
        lowerBound = curIn + 1; // its in the upper
        if (lowerBound > upperBound) {
          return curIn += 1;
        }
      } else if (lowerBound > upperBound) {
        return curIn;
      } else {
        upperBound = curIn - 1; // its in the lower
      }
    }
  }

  @Override
  public String toString() { // display array contents
    StringBuffer sb = new StringBuffer();
    for (int j = 0; j < nElems; j++) { // for each element,
      sb.append(a[j] + " "); // display it
    }
    sb.append(System.lineSeparator());
    return sb.toString();
  }

  public void insert(long value) throws Exception { // put element into array
    if (nElems == MAX)
      throw new Exception("Can not add more elements.");
    int j = binaryInsert(value);
    int k;
    for (k = nElems; k > j; k--) { // move bigger ones one up.
      a[k] = a[k - 1];
    }
    a[j] = value; // insert value
    nElems++; // increment size.
  }
}

I'm sure I didn't get everything you need to improve on but hopefully that is atleast one step forward in the right direction. :)


Use backticks

Backticks allow you to put the function name between the values instead of before:

isDivisor n a = mod n a == 0

becomes:

isDivisor n a = n `mod` a == 0

Give less general names

The name upUntil tells nothing about perfect numbers, in a tiny script like this this is no problem, but the habit of meningful names will play yo your advantage in  larger scripts

Do not write wrong comments

Comments don't run, but you are not justified to write wrong comments

-- The main prime-finding function:

The function does not find primes.


Image upload script more cleaner and secure using php 7 oop style.

To elaborate on the answer from Stexxe...

  it can have connection to database ($this->connect of your Image class) as dependency

A database class is different from all other classes. It cannot be created any time on demand. It has to be created only once, connect to a database, and hold this connection all the time. Otherwise numerous connections from the same script will crash your database server.

So it has to be:

class ImageMapper{

    private $connect;

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

and called like this:

$dbh = new Db();
$connect =  $dbh->connect();

$image = new Image($connect);

  manipulation images classes should not expose any information about their inner workings

Among other things, it means that error reporting should never reveal the actual error to a site user. Therefore you should never ever do anything like die($error) -- which also makes the whole try..catch business misplaced in this code.  So it should be:

public function upload_image($filename, $image_name)
{
    $sql = "INSERT INTO images (img, image_name) VALUES (?, ?)";
    $this->connect->prepare($sql)->execute([$filename, $image_name]);
}

whereas a possible exception thrown by PDO must be caught elsewhere. Learn more from my article on PHP error reporting.

Some other stuff has also been fixed, mostly your extremely confusing way assigning a filename, when you are adding, removing and re-adding the directory name. Some useless variables like $directory and $filename are also removed.


Manage a collection of settings in memory with global scope

Is this a type-safe way to get the setting values?

It's not type-safe in the sense that if you make a mistake in specifying the type parameter of GetSetting, or if someone sets  setting to the wrong type, you're going to get an exception.

I've struggled with this issue before and I have created a solution to this that uses generic keys. It's by no means perfect, but you can use it as an inspiration.


From a short review;

You use globals instead of parameters for activePage and pageNeighbours
You need at least one comment stating what pageNeighbours stands for, without knowing this the code looks meaningless to me
You need at least one comment on the top explaining what the range is supposed to contain
On the whole I think this could use more comments
Why actualPageRange instead of simply pageRange, or even range since it would be clear from context what range we're reading about

Okay, so since the code does not work, expect this question to be closed.
That doesn't mean that functionally this isn't a great question.

This is my approach to what I believe you are looking for:

const pageRange = ((activePage, pageNeighbours, totalPages) => {

  let range = [];
  //Add active page and neighbouring pages
  for(let page = activePage - pageNeighbours; page <= activePage + pageNeighbours; page++)
    range.push(page);
  //Make sure we dont show pages that dont exist
  range = range.filter(page=> page > 0 && page <= totalPages);
  //Allow user to go to the first page if need be
  //The second entry should be either 2 or ellipsis(...)
  if(range[0]!=1){
    if(range[1]!=2){
      range.unshift('...');
    }
    range.unshift(1);
  }
  //Allow user to go the last page, second last entry should be second last page or ellipsis
  if(range[range.length-1] != totalPages){
    if(range[range.length-2]!= totalPages-1){
      range.push('...');
    }
    range.push(totalPages);
  }

  return range;
})(activePage, pageNeighbours, totalPages);

Note that this avoids accessing activePage etc. as a global.


Simple Grid Builder for Future Maze Applications

Docstrings go BEFORE the arglist

(defn my-function
  "with aweseome documentation"
  [all the args]
  :insert-code-here)

Visited really shouldn't be a property of a cell.  Instead of mutating your cell, you should maintain a set of visited nodes.  Maybe you want to run two different path finding algorithms over the same data?

Your case corners are a little strange.  Whenever you see this, you should probably think map:

(def corner-cells
  {:top-left #{:east :south}
   :top-right #{:west :south}
   :bottom-left #{:east :north}
   :bottom-right #{:west :north}})

(defn create-corner-cell
  "Creates a corner cell which has two valid directions."
  [corner]
  (create-cell (corner-cells corner)))

Do you really need :top-left and all those combinations?  Consider instead:

(def open-block #{:north :east :south :west})
(def wall-for-side
  {:top :north
   :bottom :south
   :left :west
   :right :east})

(defn add-walls [block & sides]
  (clojure.set/difference block
                          (map wall-for-side sides)))

mazer.core> (add-walls open-block :top)
#{:west :south :east}
mazer.core> (add-walls open-block :top :left)
#{:south :east}
mazer.core> (add-walls open-block :bottom :right)
#{:west :north}

A function like corner-cell? doesn't need to return a list like that.
 Simply return nil for false and the direction for true. You can use (if-let [dir (corner-cell? ...)] :something-with-dir :something-without-dir) to differentiate.  And, since this isn't strictly a predicate, you really shouldn't name it with a question mark.  Maybe corner-cell-type.

I wouldn't use memoization here. You almost never need to memoize. If you REALLY think you need to cache this, that's the kind of information that probably would go on the cell.  But I think you should just convert the index to an x/y (math is fast) and compare that.


First and foremost: Never use datetime to measure performance! There is timeit and profile/cProfile for that. With that out of the way, let's talk about NumPy.

Python in general does not like loops if you want to go fast. NumPy can help you here since a lot of the heavy lifting can be done by the C backend where loops are orders of magnitudes faster. But you have to allow it to play its strengths. Broadcasting and slicing to the rescue!

def slice_transformrequest(request_parameters: list):
    ids = request_parameters[-1]
    allexceptid = request_parameters[:-1]

    # create an empty array of the appropriate size
    transformed = np.empty((len(ids), len(allexceptid)+1))
    # fill all but the ID column
    transformed[:, :-1] = allexceptid
    # now fill the ID column
    transformed[:, -1] = ids

    return transformed

Now to the timing part:

import timeit

n_loops = 10000
request_parameters = [
    1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15,
    [
        110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
        123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
        136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148,
        149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161,
        162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174,
        175, 176, 177, 178, 179, 180
    ]
]

start = timeit.default_timer()
for i in range(n_loops):
    transform_nested_list(request_parameters)
end = timeit.default_timer()
print(f"transform_nested_list: {end-start:.3f}s")

start = timeit.default_timer()
for i in range(n_loops):
    old_transform_nested_list(request_parameters)
end = timeit.default_timer()
print(f"old_transform_nested_list: {end-start:.3f}s")

start = timeit.default_timer()
for i in range(n_loops):
    longer_vector_transformrequest(request_parameters)
end = timeit.default_timer()
print(f"longer_vector_transformrequest: {end-start:.3f}s")

start = timeit.default_timer()
for i in range(n_loops):
    slice_transformrequest(request_parameters)
end = timeit.default_timer()
print(f"slice_transformrequest: {end-start:.3f}s")

And the results:

transform_nested_list:            11.231s
old_transform_nested_list:        8.375s
longer_vector_transformrequest:   0.623s
slice_transformrequest:           0.140s

About 4x faster than your fastest solution and about 80x faster than transform_nested_list.


At the top of your file you put all of your imports in one line, but from PEP8:

  Imports should usually be on separate lines

You define offset, but the next line you define it again.  That makes the first definition completely useless.
timeChangeSRT() should not be splitting up a string to get the right minutes, seconds, and milliseconds.  Those should be passed as arguments.
Those backslashes at the end of the lines are useless.  The indentation tells the reader, and the unclosed parentheses tells the interpreter.
You have two lines that are used both in the if and in the else blocks (the definition of newline and writing it to new).  That is a sign that they should be outside of the blocks and executed just afterwards.
Instead of using newline = '0' + str(start)[:11] + " --> " + '0'..., use a format string: newline = '0{} --> 0{}\n'.format(str(start)[:11], str(end)[:11])
You use old-style string formatting, but from the docs on .format() from Python2:

  This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.

Your second function pretty much needs the same modifications as the first.  Your second function, in fact, is so similar to the first that I am sure you could define some helper functions to do some of the work so as to reduce the duplicate code.


I personally don't see any problem with this (maybe someone else might provide better insight) but in this situation I do tend to do it differently but instantiating it via constructor overloading and making the private field readonly.

e.g.

public class RoleProvider : RoleProviderBase
{
    private readonly IRoleDataProvider _roleDataProvider;

    public RoleProvider()
       : this(new RoleDataProvider())
    {
    }

    public RoleProvider(IRoleDataProvider roleDataProvider)
    {
        _roleDataProvider = roleDataProvider;
    }
}

Perhaps this question might be better asked on PE as well?


You're writing to a MemoryStream only to get a byte[] to write to another stream, you can definitely avoid this intermediate conversion:

private string ConvertToXSLX(string inputPath)
{
    string outputPath = Path.ChangeExtension(inputPath, ".xlsx");

    using (var input = File.OpenRead(inputPath))
    using (var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write))
    {
        XLS_to_XLSX_Converter.Convert(input, output);
    }

    return outputPath;
}

The change in Convert() should be trivial.

Also note that I'm using Path.ChangeExtension() instead of manually adding a character, code is clear without any comment and it handles special cases for you (for example a trailing space).

In CopyRows() you create an empty List<ICell>, you do not need to and you can avoid the initial allocation simply using Enumerable.Empty<ICell>() (and changing your code to work with an enumeration) or - at least - reusing the same empty object (move it outside the loop and create it with an initial capacity of 0).

In CopyCellValue() you have an empty default case for your switch. It's a good thing to always have default but it has a purpose: detect unknown cases. If you put a break then you're silently ignoring them. Is it on purpose? Write a comment to explain you ignore unknown cells. It's an error? Throw an exception.

I never used DotnetCore.NPOI then I can't comment about the way you use it, be sure to dispose all the intermediate IDisposable objects.


You may replace the lines as

text = open("plaintext.txt").read()

with so called context manager approach (see PEP 343 -- The "with" Statement):

with open("plaintext.txt") as pt:
    text = pt.read()

which has the advantage of automatically closing the open file, even if an exception is raised on the way.

sets_of_chars = text.split(" ")

is somehow different from

sets_of_chars = text.split()

in two ways - if there are more consecutive spaces, and if it is applied to the empty string:

'abc  def'.split(' ')        # returns ['abc', '', 'def']
'abc  def'.split()           # returns ['abc', 'def']

''.split(' ')                # returns ['']
''.split()                   # returns []

Consider which one is more appropriate for your code.

chars = "(stephn)a*dowjzr.b\nm,uvklc ?qig!fyx-"

It is a constant, so by PEP 8 -- Style Guide for Python Code its name should be in uppercase letters:

CHARS = "(stephn)a*dowjzr.b\nm,uvklc ?qig!fyx-"

Both functions for converting from base 10

def base_10_to_base_6(n):
    s = ""
    while n:
        s = str(n % 6) + s
        n //= 6

    if len(s) == 1:
        s = "0" + s

    if not s:
        return "00"

    return s

def base_10_to_base_26(n):
    s = ""
    while n:
        s = string.ascii_lowercase[n % 26] + s
        n //= 26

    if len(s) == 1:
        s = "a" + s

    if not s:
        return "aa"

    return s

have very similar structure - by the DRY principle (Don't Repeat Yourself) why not to substitute them with one common function, e. g. with

def base_10_to_other(n, base):
    if base not in (6, 26):
       raise ValueError("Illegal base - allowed values are only 6 and 26")

    DIGIT_SYMBOLS = {6: "012345", 26: string.ascii_lowercase}
    zero_symbol = DIGIT_SYMBOLS[base][0]

    s = ""
    while n:
        s = DIGIT_SYMBOLS[base][n % 6] + s
        n //= base

    if len(s) == 1:
        s = zero_symbol + s

    if not s:
        s = 2 * zero_symbol

    return s

Moreover, they are the same in your both modules (encoder.py and decoder.py) - why don't use the 3rd module for all common functions and import from it?
(The same for the other pair of converting functions, of course.)


Making the Levenshtein distance code cleaner

It would seem that you try to do more than is sufficient for computing the Levenshtein edit distance. You could try this:

def levenshtein_distance(string1, string2):
    n = len(string1)
    m = len(string2)
    d = [[0 for x in range(n + 1)] for y in range(m + 1)]

    for i in range(1, m + 1):
        d[i][0] = i

    for j in range(1, n + 1):
        d[0][j] = j

    for j in range(1, n + 1):
        for i in range(1, m + 1):
            if string1[j - 1] is string2[i - 1]:
                delta = 0
            else:
                delta = 1

            d[i][j] = min(d[i - 1][j] + 1,
                          d[i][j - 1] + 1,
                          d[i - 1][j - 1] + delta)

    return d[m][n]

def main():
    print(levenshtein_distance("code", "rodde"))

if __name__ == "__main__":
    main()

Hope that helps.

Edit

The following extension will also give you the edit sequence, and the alignment of the two input words:

def levenshtein_distance(s, z):
    s = "\u0000" + s
    z = "\u0000" + z

    n = len(s)
    m = len(z)
    d = [[0 for x in range(n + 1)] for y in range(m + 1)]
    parent_map = dict()
    parent_map[(0, 0)] = None

    for i in range(1, m + 1):
        d[i][0] = i

    for j in range(1, n + 1):
        d[0][j] = j

    for j in range(1, n + 1):
        for i in range(1, m + 1):
            if s[j - 1] is z[i - 1]:
                delta = 0
            else:
                delta = 1

            tentative_dist = d[i - 1][j] + 1
            operation = 1 # Insert

            if tentative_dist > d[i][j - 1] + 1:
                tentative_dist = d[i][j - 1] + 1
                operation = 2 # Delete

            if tentative_dist > d[i - 1][j - 1] + delta:
                tentative_dist = d[i - 1][j - 1] + delta
                operation = 3

            if operation is 1:   # Insert
                parent_map[(i, j)] = (i - 1, j)
            elif operation is 2: # Delete
                parent_map[(i, j)] = (i, j - 1)
            else:                # Substitute
                parent_map[(i, j)] = (i - 1, j - 1)

            d[i][j] = tentative_dist

    edit_string_top = ""
    edit_string_bottom = ""
    edit_sequence = ""

    current = (m, n)

    while True:
        predecessor = parent_map[current]

        if not predecessor:
            break

        if current[0] != predecessor[0] and current[1] != predecessor[1]:
            schar = s[predecessor[1]]
            zchar = z[predecessor[0]]

            edit_string_top += schar
            edit_string_bottom += zchar

            if schar is zchar:
                edit_sequence += "N"
            else:
                edit_sequence += "S"
        elif current[0] != predecessor[0]:
            edit_string_top += "-"
            edit_string_bottom += z[predecessor[0]]
            edit_sequence += "I"
        else:
            edit_string_top += s[predecessor[1]]
            edit_string_bottom += "-"
            edit_sequence += "D"

        current = predecessor

    edit_string_top = edit_string_top[:-1][::-1]
    edit_string_bottom = edit_string_bottom[:-1][::-1]
    edit_sequence = edit_sequence[:-1][::-1]

    return d[m][n], edit_sequence, edit_string_top, edit_string_bottom

def main():
    dist, edit_sequence, edit_string_top, edit_string_bottom = levenshtein_distance("handball", "aballad")
    print("Distance: ", dist)
    print("Edit sequence: ", edit_sequence)
    print(edit_string_top)
    print(edit_string_bottom)

if __name__ == "__main__":
    main()


Efficiently matching pairs of elements and applying specific hover trigger/animation to each pair

`

$(function(){

    $('.logo').fadeTo("fast", 0);

    $(".logo").hover(function() {
        $(this).stop().animate({"opacity": "1"}, "500");
        $('.sliding_titles div#content-'+this.id).stop().animate({opacity: 1, width: "500px", overflow: "visible" }, 400);},
    function() {
        $(this).stop().animate({"opacity": "0"}, "500");
        $('.sliding_titles div#content-'+this.id).stop().animate({opacity: 0, width: "0px", overflow: "hidden" }, 1);
    });

`

YouTube slideout placeholder content

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 ... etc ...

    ... etc ...


Is there a better way to extract a single value instead of a sequence?

Why not use just what you posted? Like this:

;use better names
(defn sel-adj-idx-fixed [reading] (first (reverse (sel-adj-idx reading))))

for is used to generate sequences. Try loop for more general looping needs.
You should not hard code the length of a data structure. Each time you update read-levels you will need to update usage-vec-len. Use count instead. It is supposed to be fast for vectors.
A suggestion follows, Not a clojure programmer, so ignore the style:

(defn bin-idx [reading]
   "......"
   (second (first (drop-while #(> reading (first %))
                              (map vector
                                   (reverse read-levels)
                                   (range))))))


It turns out accessing console take's more time than pushing a value in an array. Console.log is indeed implemented as a synchronous function (next print starts only after last print finishes).
Meaning, there is no buffering system. The program goes to blocking state until console.log() finish printing, everytime.
Performance difference in above two cases is due to the difference in the number of console.log() call.


Creating a structured category list in F#

Here is an optimized version that I have discovered:

let getStructuredCategories ()  =

let fullList = allCategoriesAndDetails ()

let parentList () =
    allCategoriesAndDetails ()
    |> Seq.filter (fun p -> p.ParentStructureId = NotValid)

let rec toTree (fullList': seq<CategoryStructure>) (parent: CategoryStructure) =

    fullList'
    |> Seq.filter (fun x -> x.ParentStructureId = parent.Id)
    |> Seq.map (fun x ->
                    {
                        Category = x;
                        SubCategories =
                            toTree fullList' x
                    })
seq {
    for row in parentList () do
    yield {

        Category = row;
        SubCategories = toTree fullList row
    }

}

Can someone else do better?


Checking user input for boxing sim engine

Assuming that each Boxer object has a .name attribute…

BOXERS = [None, JS, MJ, SR]
for i in range(1, len(BOXERS)):
    print("%d) %s" % (i, BOXERS[i].name))
boxer1 = BOXERS[int(input("Choose a fighter: "))]
boxer2 = BOXERS[int(input("Choose his opponent: "))]

You want to generate the menu using the names already in the boxer objects, and retrieve the result with an array lookup.

Note that with this solution, you'll get an IndexError if the user picks an invalid entry.  You should decide how such errors should be treated, since your original code also lacked error handling.


Determining the next payment renewal date

An interesting question..

I am assuming that the values of PAYMENTS_PER_YEAR can only be these:

var paymentFrequencies = [ 1 , 2 , 3 , 4 , 6 , 12 ];

If that is the case, then the renewalyear can only be todays year or tomorrows year.

I would create a cache that pre-calculates for each month and each payment frequency what the next payment month is, and whether a year will be skipped.

Then you can simply use a look up to determine when the next payment month is, there should be no faster way than that.

I am currently looking into building just that, it is definitely possible, but slightly harder than expected ;)

This is what I have, I tested it a bit, the principal should be clear:

function createCache( monthsOffset ){
  var cache = {},
      paymentFrequencies = [ 1 , 2 , 3 , 4 , 6 , 12 ],
      todaysMonth = (new Date ()).getMonth() + monthsOffset,
      renewalYear, renewalMonth, targetMonth, frequency, monthsShort, nextYear, term;
  for( var month = 0 ; month < 12 ; month++ ){
    cache[month] = {};
    for( var i = 0 ; i < paymentFrequencies.length ; i++ ){
      frequency = paymentFrequencies[i];
      term = 12 / frequency;
      targetMonth = todaysMonth < month ? todaysMonth + 12 : todaysMonth;
      monthsShort = ( targetMonth - month ) % term;
      cache[month][frequency] = todaysMonth + (monthsShort ? term - monthsShort : 0);

    }
  }
  return cache;
}

var stillThisMonth = createCache( 0 ),
    nextMonth = createCache(1);

function determineRenewalDate( startDate , paymentsPerYear  ){

    var today = new Date(),
        todaysYear =  today.getFullYear();
        startMonth =  startDate.getMonth();
  /*Compare the days, if we renew say monthly, and we start on the 15th,
    but today is the 20, then we need to renew for next month, if we are the
    the 8th then you can stick to this month */
  var todaysDayOfTheMonth = today.getDate(),
      startDayOfTheMonth = startDate.getDate();
  //One more cool thing, `setFullYear` and `new Date` will roll over the year if you set the month too high
  if( todaysDayOfTheMonth > startDayOfTheMonth  ){
     return new Date( todaysYear, nextMonth[startMonth][paymentsPerYear], startDayOfTheMonth );
  } else {
     return new Date( todaysYear, stillThisMonth[startMonth][paymentsPerYear], startDayOfTheMonth );
  }
}

document.write(  determineRenewalDate( new Date(2010 , 1 , 1 ) , 12 ) + '
' );
document.write(  determineRenewalDate( new Date(2010 , 1 , 2 ) , 2 ) + '
' );


Is this the best message delay algorithm?

I can see some problems with the code:

As @fge mentions, catching Exception is problematic.  You should catch the exceptions that you are expecting to occur, and let any other unchecked exceptions propagate.
Wrapping the exceptions in RuntimeException is a bad idea unless it is really necessary.  It is better to either let them propagate, or wrap them in a custom checked or unchecked exception.
The behaviour of the code doesn't match your description in one respect.  You talk about queuing messages. In fact, messages are being sent immediately in all cases, and you are delaying after sending the message in the sendRawLine case.
In reality, you are blocking client threads rather using a queue data structure and a separate output thread.  This might be the right things to do ... but it might be the wrong thing.  It depends whether the client threads should be blocked until the their respective messages are sent.  Either way, your characterization this as a "message queuing" problem is a bit misleading.

  Re: #3) The idea was to delay the next message from sending. Otherwise all calls to sendRawLine would have a weird pause before doing anything. I'm looking into using the current time though to determine if waiting is even necessary.

First, that is NOT what your description of "message queuing" implies ... to me.  And consider me as an examplar of someone else reading your code.

Second, (if I understand you correctly) using the current time to decide to whether to wait before a send would require that something keeps track of when each thread last sent a message.

Third, there is actually a good reason to not wait before sending a message.  If you do wait before then, by the time the wait period has finished, the message could be rather out of date ... especially if there were a number of resets.

Finally, it strikes me that you may be over-using threads here and/or that it might be better for the entity (thread or FSM) responsible for generating messages should check whether a message needs to be sent before generating it.


Throwaway memory

I haven't done any analysis on the code but based on my experience the worst part is the allocation of throwaway memory inside the innermost loop. Instead of allocating a 3x3 array 9 million times and throwing it to the garbage colletor immediately, allocate it once at the start of the method and reuse it in the loop.

int[][] kernel = new int[][] { ... }

Repeated calculations

Second obvious thing is the repeating of same mathematical operations. You calculate the right and bottom border several times inside the innermost loop even though the result never changes during the image processing. Calculate these at the start of the method and store the results to local variables:

sourceImage.getHeight() - 1
sourceImage.getWidth() - 1

Sacrifice readability for performance

After solving the obvious parts, you can start breaking good coding conventions. The only reason you have those mile long unreadable ternary operations is to handle the edge cases that affect 0.1% of your data. Take out the easy code inside the edges that covers 99.9% of your running time, that doesn't need any bounds checking, and make it as fast as possible. Then make a separate loop that handle only the edges.

Bad variable naming

The choice of loop variables are bad. Width and height are constants of the image that refer to the right and bottom border. You are using these names to refer to single pixels inside the image. The correct names here would be x and y. This makes following your code extremely difficult.

Refer to the good old StackOverflow-side of this site for more info about accessing the color values directly:

https://stackoverflow.com/questions/37779515/how-can-i-convert-an-imageview-to-byte-array-in-android-studio


Filter some Apache Conf to extract all ServerName and ServerAlias, then output them one per line

What is "bad match" in here?

RemoveBadMatch="s/^\s*($GrepAndFilter)\s+//gI"

My understanding is that this pattern is used to remove the $GrepAndFilter prefix from lines, with any surrounding whitespace. I don't see that prefix as "bad match" in any sense of the word. It seems RemoveFilterPrefix would be a better fit.

Here, instead of \s*$ as the pattern, I'd use \s+$,
to emphasize that the content will be modified only when there are non-zero trailing whitespaces.

RemoveTrailingWhitespaces="s/\s*$//"

Here, the pattern doesn't match the name:

ReplaceSpacesWithNewLines="s/ +/\s/g"

I think you meant \n as the replacement,
because \s doesn't have a special meaning in a replacement string,
so as written,
this command will replace spaces with the letter s.

grep assumes /dev/stdin as input by default, no need to specify it explicitly.

In many systems, the Apache configuration files often contain ServerName and ServerAlias on commented out lines.
The posted script won't work with such lines,
and I can easily imagine such lines in production systems too.
I suggest to make the script more robust by excluding commented lines.
This could be as simple as making the first filter more strict:

GrepAndFilter="^\s*(ServerName|ServerAlias)\s+"


Search a search button on page and toggle open class and focus on the input

I am confident the solution can be made better in terms of OO way using constructor pattern

Here's the first problem: You assume writing (classical) OO makes everything better. Personally, it's more cumbersome and confusing. You worry what this is, there is state literally everywhere, methods are very side-effect-y, all that unnecessary boilerplate to make a simple operation look fancy but more complicated.

Keep it simple. I'd prefer simple functions over classical OOP.

On the other hand, you are already doing OO. It's just that it's not classical OO, but you're still operating on objects.

Here's a few corrections to the snippet

const $search = $('.search');

A $() function returns an instance of jQuery. It's similar to doing jQuery search = new jQuery('.search') if you're into classical OOP notation.

$search.removeClass('dropdown radix-dropdown-processed');

jQuery objects are array-like objects, containing the matches of your selector. Unless explicitly stated, most methods loop through that array and apply to each item. No items, no loop, therefore method won't run. This makes the length check redundant.

$('.search').on('click', '.search__button', function (e) {
  e.preventDefault();
  e.delegateTarget.toggleClass('open');
});

Now assuming .search__button resides inside .search, you can use delegation. This is where jQuery attaches the handler on an ancestor element to listen for descendant events. The advantage is that it does not rely on the descendant to be there on bind. Also good if you have a lot of descendants to listen. You attach the handler once on the ancestor and not per descendant.

Additionally, you don't need to keep reference of the ancestor you attached the handler to. The event object has a delegateTarget which references the ancestor you attached the event to, in this case .search.

$('#site_search_query').focus();

IDs are brittle. The can only appear once in the page but nothing stops you from putting more than one. The problem appears when you try to grab their reference. document.getElementById as well as jQuery only return the very first one it finds. If your element's id collides with another's and that other comes first, you get the idea.


Toggle nav that switches a banner section

The only thing I would change, without having anymore info about how the page is built, is from this

$('.thm-banner--toggles').find('a').on('click', function(e){

to

$('.thm-banner--toggles').on('click', 'a', function(e){

or this

$('.thm-banner--toggles a').on('click', function(e){


Well I'm going to start by saying that your end result is confusing. sym2mod and create_symbol_module_d aren't clear names that indicate what's going on. In particular I don't know why this would be necessary, so it wouldn't occur to me that these are custom adding and dividing functions that are placed so erratically in a package that you can't even find them. Also there is already an operator module that contains these functions. If yours are more specialised or complex, then you should use different names to distinguish them and reduce confusion.

Which brings me to another problem, why are they in random places? It sounds like your problem entirely exists just because of the package structure. To me that means you ought to improve the actual structure rather than treating the symptom of the problem.

Anyway, onto your actual functions. The docstring for import_module
is a little off. It says the import is recursive, but it isn't necessarily recursive, it's optionally so. I don't think you need to mention it since it's easy to see the arguments with introspection. ie.

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

import_submodules(package, recursive=True)
    Import all submodules of a module, recursively, including subpackages

The fact that your importer is also printing out messages could be quite a problem for people who might have a large package, and there's no way to turn it off! I'd add an argument like logging and default it to False. Only print if its been explicitly asked for. After all there's a dictionary record of the importing that can be inspected for what was imported.

create_symbol_module_d is quite confusing to me. It's a bad name, so is module_name_module_d. They're both long and communicate little. Then there's include and exclude. Are they meant to be lists of symbols like ['+', '-', '/']? You give no examples or indication. Then when I look at what they do... they do nothing! In every result of your if statements you end up just performing the same test. In the current function there's no need for if statements at all, let alone include and exclude. This is equivalent to your function:

def create_symbol_module_d(module_name_module_d, include=None, exclude=None):
    """ Create mapping of symbol to module

    :param module_name_module_d
    :type module_name_module_d: dict[str, types.ModuleType]
    :rtype: dict[str, types.*]
    """
    inv_res = {}
    for mod in module_name_module_d.itervalues():
        for sym in dir(mod):
            inv_res[sym] = mod
    return inv_res

You need better names and documentation for me to even be able to give feedback on it. I also don't know what inv_res is or means.


Please take care to use consistent indentation for your JavaScript, HTML, and CSS.  In particular, avoid mixing spaces and tabs.

Avoid using meaningless variable names such as check and temp.  In this case, you didn't even need temp, because:

  If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

Your sleep() function appears to be unused.  In any case, you should avoid having a while loop that simply wastes CPU power; setInterval() and setTimeout() are much more appropriate ways to control timing. For DOM-related updates and animations, though, you should use requestAnimationFrame().

The entire problem would be better solved using CSS animations, which are supported by a large proportion of modern browsers.  In fact, the set of browsers that support the let keyword (which you used) is a subset of the browsers that support CSS Animations.

@keyframes slide {
    from { left: 0; }
    to   { left: 180px; /* 200px - 20px */ }
}

#plan {
    width: 200px;
    height: 200px;
    background: #00C0FF;
    position: relative;
}

#box {
    width: 20px;
    height: 20px;
    background: red;
    position: absolute;
    animation: 3.6s linear infinite alternate slide;
}


Stick closely to the sources

It's helpful when coding math in cases like this to base your approach on established methods and language.

It might seem a bit extreme, but this can include:

Following a published method to the letter.
Linking to a readily-available description of it.
Naming your variables and laying out your code as closely as possible to that description.

eg.

def gini_index(*args*):
    """
    Calculates the Gini Index G given data of the form:
    *whatever form your data is*
    Using summation as described in:
    *reference* (can be textbook, arxiv etc)
    Via the formula:
    *include formulae if possible*
    Essentially as described here:
    https://en.wikipedia.org/wiki/Gini_coefficient#Alternate_expressions
    Example input:
    *your example input*
    Example output:
    *your example output*
    """
#   your code proper starts here

An example of this is here, a  collection of basic number theory and elliptic curve utilities that eventually became SageMath.

For example, were you actually to use this formula as a basis, you would name your counter i, your total number of values n, and use the summation functions provided in numpy.

Trust me, if you think you'll revisit your code at a later date (when memory fails), or have it used or modified by someone else, this is a lifesaver.

(Edit: As you are integrating a polynomial, you can use the integ method of poly1d included with numpy rather than importing scipy.)


Unit tests for a function that calculates demerit points for speeding

You probably want to

add a constant for speed 0
create a test for MaxSpeed
create a test case for 64 (it's one edge of the partition class  0 <= x < speedlimit and it could replace 60 which is in the same partition class)

I would keep the 66 test case since it is and edge case.

Even though the edges are cut pretty clear with ints (compared to using float values) you might still want to test them explicitly.


Putting read data into a combined file based on certain attributes

I have to scroll to read it all, so without looking at the code: Yes, split it.

And now with looking at the code:
I would try to extract the content of your for loop and give the method a nice name.

Afterward you can check how to split this method.

Maybe you want to have a look at one-thing-extract-till-you-drop (also check the comments)


I would make also this function a generator and make printing the responsibility of the caller. This makes the function more reusable.

def print_mult_table(row_start, row_end, col_start, col_end):
    """
    Print multiplication table fragment for all numbers in the interval
    [:param row_start; :param row_end] for all of the interval [:param col_start; :param col_end]
    """
    table = list(list([row] + list(range(col_start * row, (col_end + 1) * row, row))) for row in ([1] + list(range(row_start, row_end + 1))))
    table[0][0] = ""    # This is done, because it is the desired output format
    max_width = len(str(table[-1][-1])) + 1
    for row in table:
        yield '\t'.join(str(col).rjust(max_width) for col in row)

for row in print_mult_table(1, 10, 4, 8):
    print(row)

Note that I gave the variables easier to understand names. This makes the list comprehension longer. Which leads to the next point:

While the list comprehensions are nice and compact (with short incomprehensible variable names), they are starting to stretch what is still easily readable. A general rule is, if your list comprehension is longer than a line (80 characters) it is probably too complicated.  Therefore I would unfold it:

from itertools import chain

def get_mult_table(row_start, row_end, col_start, col_end):
    """
    Yield multiplication table fragment for all numbers in the interval
    [:param row_start; :param row_end] for all of the interval
    [:param col_start; :param col_end]
    """
    for row in chain([1], range(row_start, row_end + 1)):
        yield [col * row for col in chain([1], range(col_start, col_end + 1))]

def print_mult_table(row_start, row_end, col_start, col_end):
    table = list(get_mult_table(row_start, row_end, col_start, col_end))
    table[0][0] = ""    # This is done, because it is the desired output format
    max_width = len(str(table[-1][-1])) + 1
    for row in table:
        print '\t'.join(str(col).rjust(max_width) for col in row)

if __name__ == '__main__':
    print_mult_table(1, 10, 4, 8)

This makes it a lot more obvious what happens (because it includes the actual multiplication, it is not hidden in the step size of the inner range). This might make it slightly slower (when generating multiplication tables from, say, 1 to 1,000,000).

It also separates the generation of the table from the actual printing logic.


Detecting a cycle in a directed graph via an adjacency list implementation and a recursive DFS

I didn't find another way to do it, but I will give you some tips on the current implementation.
Always add curly braces to loop & if
In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.
Simplify the boolean conditions.
In both of the method, you can simplify the boolean validations.
Equivalence
isCyclic(visited, node) == true can be isCyclic(visited, node)
Before
if (isCyclic(visited, node) == true) {
   return true;
}

After
if (isCyclic(visited, node)) {
   return true;
}

Code reduction
In the second method, instead of using the java.util.Set#contains method, you can check the returned boolean of the java.util.Set#add directly; this will allow you to remove an instruction.
Documentation:
Returns:
true if this set did not already contain the specified element

Basic example
Set<Character> set = new java.util.HashSet<>(Set.of('A', 'B', 'C'));
System.out.println(set.add('A')); // false
System.out.println(set.add('D')); // true

This will add the element, if not already present and return true if it was not present.
Before
if (visited.contains(connectedNode)) {
   // We've reached back to a vertex, i.e. a back-edge
   return true;
} else {
   visited.add(connectedNode);
   if (isCyclic(visited, connectedNode)) {
      return true;
   }
}

After
if (!visited.add(connectedNode)) {
   // We've reached back to a vertex, i.e. a back-edge
   return true;
} else {
   if (isCyclic(visited, connectedNode)) {
      return true;
   }
}

In the second method, you can remove the retval variable, since it does nothing.


Longest substring with unique characters

Time complexity

The time complexity is not \$O(N^2)\$ as you estimated, but actually \$O(N M)\$, where n is the length of the input string and m is the number of unique characters in the input string. This makes a big difference, because in practice m is typically bounded by a constant, the size of the alphabet, which in the case of ascii is 256. If m is a constant then the asymptotic complexity becomes simply \$O(N)\$, which is great news for you.

Optimizations

A small tweak can make the implementation significantly faster: change the loop condition in the outer function to go until n - max instead of n.

If you know the size of the alphabet in advance, then you can use a boolean[] instead of a set, with the character codes as indexes. It's simpler, and by reducing the autoboxing, faster too.

Use interface types instead of implementations

You could declare the HashSet as a Set instead.


int[] arr

You can probably create it only once, with maximum possible size, outside for for loop.

System.out.print(arr[ii]);

You need to use StringBuilder and output only whole string in single println call. Multiple System.out.print calls are what makes it slow.


Let's speed that file sentence searching program

Yay, PEP 8

72 characters for docstrings, 79 for the code. The rest seems fine.

Separation of concerns

search_sentence_in_file should search, and return its results. Not print, it is the duty of the caller.

I feel it is also wrongly named as it search a sentence in several files. So at least add the missing s at the end of the name. And to make it even more reusable, why not pass an iterable of filepath (like the get_magic_files generator)?

Genericity

Besides search_sentence_in_file accepting an iterable, you could make get_magik_files more generic by passing the required extension as a parameter. This will let you extend your script to allow search in various kind of files.

First rewrite

from os import walk
from os.path import join, splitext

def get_files(base_path, extension=None):
    """
    Yields each path from all the base_path subdirectories

    :param base_path: this is the base path from where the
                      function start looking for relevant files
    :param extension: filter files using provided extension.
                      If None, no filter is applied.
    :return: yield full path of a requested file
    """
    if extension is None:
        def filter_files(filenames):
            yield from filenames
    else:
        def filter_files(filenames):
            for filename in filenames:
                if splitext(filename)[1] == extension:
                    yield filename

    for dirpath, _, filenames in walk(base_path):
        for filename in filter_files(filenames):
            yield join(dirpath, filename)

def search_sentence_in_files(files, sentence):
    """
    Yield each file path, line and line content where
    sentence was found.

    :param files: iterable of files to search the sentence into
    :param sentence: the sentence we're looking up for
    :return: yield the file path, line number and line
             content where sentence was found
    """
    for filepath in files:
        with open(filepath) as fp:
            for line_number, line in enumerate(fp):
                if sentence in line:
                    yield filepath, line_number, line.strip()

def main():
    basepath = r'some_path'
    sentence_to_search = 'some sentence'

    files = get_files(basepath, 'magik')
    results = search_sentence_in_files(files, sentence_to_search)
    for filepath, line, content in results:
        print('[# FILE PATH    #]', filepath, '...')
        print('[# LINE NUMBER  #] At line', line)
        print('[# LINE CONTENT #] Content:', content)
        print('-'*80)

if __name__ == '__main__':
    main()

Reusability

Your script make it hard to reuse for other purposes: different sentences, different kind of files. Better to add a CLI using argparse. Provide sensible default for your current usage but allows for customization at will.

from os import walk
from os.path import join, splitext
import argparse

def get_files(base_path, extension=None):
    """
    Yields each path from all the base_path subdirectories

    :param base_path: this is the base path from where the
                      function start looking for relevant files
    :param extension: filter files using provided extension.
                      If None, no filter is applied.
    :return: yield full path of a requested file
    """
    if extension is None:
        def filter_files(filenames):
            yield from filenames
    else:
        def filter_files(filenames):
            for filename in filenames:
                if splitext(filename)[1] == extension:
                    yield filename

    for dirpath, _, filenames in walk(base_path):
        for filename in filter_files(filenames):
            yield join(dirpath, filename)

def search_sentence_in_files(files, sentence):
    """
    Yield each file path, line and line content where
    sentence was found.

    :param files: iterable of files to search the sentence into
    :param sentence: the sentence we're looking up for
    :return: yield the file path, line number and line
             content where sentence was found
    """
    for filepath in files:
        with open(filepath) as fp:
            for line_number, line in enumerate(fp):
                if sentence in line:
                    yield filepath, line_number, line.strip()

def main(files, sentence):
    results = search_sentence_in_files(files, sentence)
    for filepath, line, content in results:
        print('[# FILE PATH    #]', filepath, '...')
        print('[# LINE NUMBER  #] At line', line)
        print('[# LINE CONTENT #] Content:', content)
        print('-'*80)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Search text in files')
    parser.add_argument('sentence')
    parser.add_argument('-p', '--basepath',
                        help='folder in wich files will be examinated',
                        default=r'some folder')
    parser.add_argument('-e', '--extension',
                        help='extension of files to examine',
                        default='magik')
    args = parser.parse_args()

    files = get_files(args.basepath, args.extension)
    main(files, args.sentence)

You can also allows for other improvements such as the sentence being a regular expression.


Distinguishing user input numbers and characters

Variables in java are camelCase, it's odd that you follow it in cases like strName but  ignore it with MarkTotal or totalaverage. No matter what style you choose, be consistent about it, for instance I like here how the latter variable has an equals sign between it and the 0, yet everything's together in the proceeding line. Try to maintain a space between your variables, and declare only 1 variable per line. Additionally, make it a habit to define variables near where they're actually used. Narrow your scope as much as possible as it will help in future maintainability.

These may seem like nitpicks for now, but down the line and as your programs grow they will make things easier to locate, read, and understand.

You don't need to repeatedly call System.out.println, you can use \n to add a new line where necessary. Your several calls in the beginning can be something like this:

This line:

 Marktotal= Marktotal + Mark;

Can be shortened to MarkTotal += Mark; but minding the tips I said earlier it would be more markSum += mark;

Lastly you have some variables that are only used once, when that's the case you can usually get rid of them and simply replace them with the method call.

Here's your implementation with these suggestions:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ForNing {
    public static void main(String args[]) throws IOException {
        BufferedReader input = new BufferedReader(
            new InputStreamReader(System.in)
        );

        System.out.print(
            "This program will calculate an individual's personal average" +
            " and then calculate the class average when instructed. " +
            "\nEnter a name: "
        );

        String studentName = input.readLine();
        int studentCount = 0;
        double classAverage = 0;

        while (!studentName.equals("finish")){
            System.out.println(
                "The follwing will calculate the average five marks of "+
                studentName +".\nPlease enter 5 marks."
            );

            studentCount++;

            int markSum = 0;
            for (int i = 1; i <= 5; i++) {
                markSum += Integer.parseInt(input.readLine());
            }

            double average = markSum / 5;
            markSum = 0;
            classAverage += average;

            System.out.println(
                studentName + "'s average is: " + average +
                ".\n\nPlease enter the next student's name " +
                "or enter 'finish' to calculate the class average."
            );

            studentName = input.readLine();
        }

        classAverage /= studentCount;

        System.out.println(
            "The class average of all input grades is: " + classAverage +
            ".\n\nThank you for using the program."
        );
    }
}


Resx Translation Helper, V.2.0 Remove Files Window

public class Files
{
    public string Value { get; private set; }
    public bool Selected { get; set; }

    public Files(string value, bool selected = false)
    {
        Value = value;
        Selected = selected;
    }
}

Huh? Files? Plural? There's no collection here. Just File is good. And this confirms it.

OpenFiles = new ObservableCollection<Files>();

What does Value represent? Is it a name? Full file path? What is it man?! =;)-

Seriously though. I've no idea. A better property name is in order.

    var handler = FilesSelected;
    if (handler != null && !_eventFired)    // only fire once
    {
        _eventFired = true;
        handler(this, selectedFiles);
    }

Potentially useless comment, but I don't suppose it's causing any active harm at the moment. What I'm more concerned about is setting _eventFired to true before the event has actually fired. The chances of it not firing after setting the boolean variable are slim to none, but it's still odd enough that it caught my eye.

    _window.Closed += (s, e) =>
    {
        OnRemoveFiles(new List<string>());
    };

There are so many examples of using one letter variables for lambda expressions out there that I don't blame you. I don't. We all do it, and often we shouldn't. I think this is one of those times. Sure, I think I know what these stand for, but am I certain? No. Either way, I had to think about it longer than I should have.

public interface IDisplayOpenFiles
{
    object DataContext { set; }

    event EventHandler Closed;

    void Show();
    void Close();
}

I'm always a bit wary of "set only" properties. I would take a moment to consider why you're doing this and if there's a better way. If you've done that, and decided that this is good, leave a comment explaining why it's good.

I feel like that was just a whole bunch of nitpicking though. It seems to me that you've really improved as a developer over the last few months.


Writing a better alternative to jQuery Autocomplete

You should strongly consider using a JS templating language such as Handlebars.js when rendering the interface.

  // Add the group if it doesn't exist
  var group = callbacks.getGroup(result);
  if ($.type(group) == 'string' && !groups[group]) {
    var $groupHeading = $('<li />').addClass('group')
      .append($('<h3 />').html(group))
      .appendTo($results);
    groups[group] = $groupHeading;
  }

  var $result = $('<li />').addClass('result')
    .append(output)
    .data('result', result) // Store the result object on this DOM element
    .addClass(result.addClass);

You are doing enough dom manipulation to warrant its use (above is just one part of your code). Furthermore, templates will help separate presentation logic from your business logic which at the moment is quite tangled.


Setting the default display name for my model

The method is doing three things:

Determining whether or not to set display_name.
Determining the default display name.
Setting display_name to the default value.

Each of those adds to the Abc metric. The biggest contributor to the Abc metric is determining the default display name. To me, that also seems like the most logically separate. We can lower the Abc metric by extracting that responsibility to its own method.

def set_default_display_name
  self.display_name = default_display_name if display_name.blank?
end

def default_display_name
  credentials_of_type = user.credentials.where(type: type)
  return name if credentials_of_type.none? || user.credentials.where(display_name: name).none?
  "#{name} #{credentials_of_type.count + 1}"
end

Extracting default_display_name makes it slightly simpler to test the default display name logic. You could also use that logic elsewhere, e.g., a UI could show the current display name and ask if they want to reset it to the default display name.

At this point, I'd question whether set_default_display_name is necessary or if it could be inlined.

Another option, is to keep your code as is and modify your .rubocop.yml file to increase the threshold of the Abc metric, or disable it entirely. The Abc metric is all about code size, not complexity. Theoretically, bugs increase with code size. You'd have to determine if this low of a threshold makes it easier to mask bugs. (Based on an earlier thread, the answer is probably, "yes", since your original code seems to have a bug. I retained the functionality of your original code in this example.)

--- Addendum ---

@ramonrails makes a good point in the comments. I'm usually fine with return guard clauses at the top of ruby methods. However, I agree that having a return in the middle of this method is not ideal.

This answer was only addressing the ABC question. If this were my code, I'd extract the credentials logic completely from this "view" code.

Something like:

def default_display_name(type_credentials)
  type_credentials.any? ? "#{name} #{type_credentials.count + 1}" : name
end

We're far afield from the question at that point though.


Database query inside a method of a class and return data

Let me first say that any answer you get here is going to by biased by each person's personal preference. What you're doing isn't dangerous or breaking any rules, so it's 'fine' as far as that's concerned. So with that in mind I'll give you my opinion on a few things to consider, and you can decide from there.

Returning true and false to me is a bit old-school and doesn't take advantage of php's flexible variable type handling. I typically return FALSE if there's an error, and return the results if not. The calling code can then just do a if($result !== FALSE) and you're good to go.

The other thing to consider is the format of your return data.

One method is to dump it into some predefined objects. This is a very clean approach that makes code reliable and easy to read, but it isn't always that easy to implement. I would only do this if you're going to be creating a large and complex project.

If you've got a simple project, then returning arrays is the fastest and easiest way to go. It's a little less reliable if your database is likely to change, so watch out for that. I typically massage my arrays in the method prior to returning them. Since in your example you're breaking out specific operations, you can do custom data formatting in each. This is encouraged since it will make your calling code much easier to create, read, and maintain.

Lastly I wanted to talk about your error handling. What I prefer to do is return FALSE on error only, and return data every other time. You've chosen to return FALSE if no results are found which makes a bit of sense as it will simplify the calling code. The change I would suggest you make is to remove your trigger_error method and instead set the error message to a class variable that can be retrieved by your calling code. Your should then return FALSE after the catch. This will allow your code to fail more gracefully and also give you more control in your calling code as to how to handle the error (think MVC).

Of course I am making some assumptions as to what trigger_error does. I see you have an $errors variable so perhaps you're already on that track. If you are then I recommend always returning FALSE from the method after an error, and adding hasErrors and getErrors methods to your class.


The key point in tokenizing strings is that

  The number of resulting token would not be known in prior

One good approach is the one you have followed,

Allocate some memory
Use it
Allocate more if needed

I want to answer some of the questions that you have asked.

  Is it feasible to split this into several functions? Where would you
  split it?

As you see, there is the repetition of error handling (freeing up the argv array). Well this can be separated into another function.

  Is this easily readable to a more experienced C programmer?

Not sure of the level of expertise you mean, but I can read it and understand without any problems. I am a 2 year experienced C Professional.

  Any corner cases where it might break? Does it leak memory?

There is no obvious memory leak I could see in the program. But you can use tools like valgrind to detect such leaks.

I am just posting few code, that I would use, if I am given the same program.

int free_argv_q(struct queue *q)
{
    int i;
    int q_len = q_length(q);

    for (i = 0; i < q_len; i++) {
        char *arg = dequeue(q);
        free(arg);
    }

    return 0;
}

int parse_cmdline(char ***argv, char *input)
{
    int i;
    int argc = 0;

    char *arg = NULL;
    char *token = NULL;

    struct queue q;

    token = strtok(input, " ");

    do {
        /* strdup may fail due to low memory */
        arg = strdup(token);

        if (arg == NULL) {
            free_argv_q(&q);
            return 0;
        }

        /* add to queue */
        enqueue(&q, arg);
        token = strtok(NULL, " ");
    } while (token);

    /* length of the queue is the number of splits */
    argc = q_length(&q);

    *argv = malloc(argc * sizeof(char *));

    if (*argv == NULL) {
        free_argv_q(&q);
        return 0;
    }

    /* now we have all memory allocated */
    for (i = 0; i < argc; i++)
        argv[i] = dequeue(&q);

    return argc;
}

The explanation is as follows.

I use a queue to split the tokens and store them. Well this would grow dynamically.
After parsing whole input, the argv array is allocated
argc is the length of the queue
Memory allocation failures are handled though
The cleanup function is separated

Note: The implementation of queue is skipped for simplicity. Hope this program is self explanatory.


Egg drop problem solution in template meta-programming

Template metaprogramming is all about rewriting your program to be functional instead of imperative, and then not worrying about caching since the compiler takes care of that for you. The other important guideline is that the return of a metafunction is a type named type. Template metaprogramming is about types - anything that isn't a type is just really annoying to have to deal with, so stay in the type world for as long as possible.

So how do we write this functionally? Let's look at the loop - which is the only really interesting part of the code:

int result = INT_MAX;
for(int current_floor = 1; current_floor <= floor; ++current_floor) {
    int local = std::max(solve(egg - 1, current_floor - 1), solve(egg, floor - current_floor));
    if(local < result)
        result = local;
}

Rewriting this in Python as a generator comprehension (even if you don't know Python, hopefully this is clear):

result = 1 + min(
           max(solve(egg-1, current-1), solve(egg, floor-current))
           for current in range(1, floor+1)
           )

Going from 1 to floor is a little more awkward than going from 0 to floor-1, so let's just subtract 1 from current everywhere:

result = 1 + min(
           max(solve(egg-1, current), solve(egg, floor-current-1))
           for current in range(floor)
           )

Now, this is the right form for template metaprogramming! So what tools do we need to build this up?

A way to iterate from 0 to floor-1
A way to take the min and max of lots of things at compile time
A way to add one to a type

For the former, we have std::make_index_sequence and the latter two I will leave as an exercise.

Once we have these things though, we directly translate the generator comprehension into actual template code thanks to the power of unpacking variadic templates:

template <int Egg, int Floor, typename = std::make_index_sequence<Floor>>
struct SolveImpl;

template <int Egg, int Floor, size_t... Current>
struct SolveImpl<Egg, Floor, std::index_sequence<Current...>>
{
    using type = add1<                            // result = 1 +
        min<                                      //   min(
            max<                                  //     max(
                Solve<Egg-1, Current>,            //        solve(egg-1, current),
                Solve<Egg, Floor - Current - 1>   //        solve(egg, floor-current-1)
            >...                                  //     ) for current in range(floor)
        >                                         //  )
    >;
};

Dealing with the base cases is just a matter of wrapping with std::conditional:

template <int Egg, int Floor>
struct Solve;

/* the SolveImpl code goes here */

template <int Egg, int Floor>
struct Solve
    : std::conditional_t<
            (Floor == 0 || Floor == 1 || Egg == 1),
            int_<Floor>,
            SolveImpl<Egg, Floor>
            >::type
{ };

Again, leaving out the base case details where Floor == 0, Floor == 1, or Egg == 1 since those are less interesting. As always, with template metaprograms, static_assert is your friend:

static_assert(Solve<2, 10>::value == 4, "!");

Check!