Your indentation and Java-style braces make it very hard to follow. Compare this:

void Patrol() {
            Vector3 Position = transform.position;
            if (patrolPositions != null && patrolPositions.Count > 1) {
                    Vector3 Destination = patrolPositions [patrolPositionIndex];
                    if (Destination != Position && CurrentDestination != Destination) {
                            Debug.Log (String.Format ("Patrol plotting route to {0}", Destination.ToString ()));
                            navMeshAgent.SetDestination (Destination);
                            CurrentDestination = Destination;
                            isAtPatrolPosition = false;
                    } else if (Destination == Position && !isAtPatrolPosition) {
                            isAtPatrolPosition = true;
                            Debug.Log (String.Format ("Patrol waiting {0} seconds", PatrolHoldTime));
                            StartCoroutine (Wait (PatrolHoldTime));
                    }
            } else if (Position != StartPosition) {
                    navMeshAgent.SetDestination (StartPosition);
            }
    }

to that:

void Patrol()
{
    Vector3 Position = transform.position;
    if (patrolPositions != null && patrolPositions.Count > 1)
    {
        Vector3 Destination = patrolPositions[patrolPositionIndex];
        if (Destination != Position && CurrentDestination != Destination)
        {
             Debug.Log(String.Format("Patrol plotting route to {0}", Destination.ToString()));
             navMeshAgent.SetDestination(Destination);
             CurrentDestination = Destination;
             isAtPatrolPosition = false;
        }
        else if (Destination == Position && !isAtPatrolPosition)
        {
             isAtPatrolPosition = true;
             Debug.Log(String.Format("Patrol waiting {0} seconds", PatrolHoldTime));
             StartCoroutine(Wait(PatrolHoldTime));
        }
    }
    else if (Position != StartPosition)
    {
        navMeshAgent.SetDestination(StartPosition);
    }
}

I'd remove this comment:

// Use this for initialization

And I'd avoid #region blocks - you're not showing your entire class, but regions are typically a sign that too many things are going on, and can often be extracted into their own class (or method, when the region is defined within a method's body).

I don't understand why a method called Wait would return an IEnumerator, and it seems a bit counter-intuitive that Wait would have the side-effect of changing the patrolPositionIndex - could the method have a more descriptive name?

These initializations are redundant, since they're initializing to the default value for their type:

private NavMeshAgent navMeshAgent = null;

public float StoppingDistance = 0.0f;

public float PatrolHoldTime = 0.0f;

private int patrolPositionIndex = 0;

private bool isAtPatrolPosition = false;


You could add state to the reader: e.g. have a std::string variable target outside of the loop, read the lines in a while loop and...

while (getline(file, line)) {
  if (line=="enemy" || line=="player") {
    target=line; // remember where to put things
  }
  else {
    const std::string::size_type p=line.find(":");
    if (p!=std::string::npos) {
      assert(!target.empty());
      const std::string tag=line.substr(0, p);
      const std::string val=line.substr(p+1);

      // parse val (maybe with istringstream),
      // then put values into appropriate destination,
      // by using target and tag
    }
  }
}


As written in the relative MSDN page, the cause of the warning is

  The parameter signature of an externally visible generic method does not contain types that correspond to all the type parameters of the method.

Looking at your code, you get the type of the generic param into the method body (which can be seen also as a violation of the Separation of Concerns principle). In order to solve the issue, you can pass the type as a parameter. The resulting code should be something like the following:

public static IList<SelectListItem> SelectListFor(Type enumType)
{
    if (enumType.IsEnum)
    {
        return Enum.GetValues(enumType)
            .Cast<int>()
            .Where(i => !i.Equals(0))
            .Select(e => new SelectListItem()
            {
                Value = e.ToString(),
                Text = GetDisplayName(enumType, Enum.GetName(enumType, e))
            })
            .ToList();
    }

    return null;
}

and can be called in the following way:

EnumExtensions.SelectListFor(typeof(BrochureTypes))

As an alternative, you can make it an extension method of the Type class, and I'd suggest a rename of the method in this case:

public static IList<SelectListItem> GetSelectList(this Type enumType)
{
    if (enumType.IsEnum)
    {
        return Enum.GetValues(enumType)
            .Cast<int>()
            .Where(i => !i.Equals(0))
            .Select(e => new SelectListItem()
            {
                Value = e.ToString(),
                Text = GetDisplayName(enumType, Enum.GetName(enumType, e))
            })
            .ToList();
    }

    return null;
}

and call it like this:

(typeof(BrochureTypes)).GetSelectList();

or:

enumInstance.GetType().GetSelectList();


The Model wouldn't change regardless of whether you were viewing it or editing the records in the given model.

Let's go ahead and create a view and edit model from the information you have given us, it will look like this

Note: this doesn't work, it is here to make a point.

public abstract class Setting
{
    [Required]
    public int SettingId { get; set; }

    public string Name { get; set; }

    [Required]
    [MaxLength(255)]
    public string Value { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime ModifiedDt { get; set; }
}

public class ViewSetting : Setting
{
    public int SettingId { get; }
    public string Name { get; }
    public string Value { get; }
    public string ModifiedBy { get; }
    public DateTime ModifiedDt { get; }
}

public class EditSetting : Setting
{
    [Required]
    public int SettingId { set; }

    public string Name { set; }

    [Required]
    [MaxLength(255)]
    public string Value { set; }
    public string ModifiedBy { set; }
    public DateTime ModifiedDt { set; }
}

and then you don't want to go setting the ID Field because that would change more than the properties of the data, it would be changing indexing in your database, so we would take that out too.  And if you were going to edit the Record you should also make the ModifiedBy and ModifiedDt required.

Also, because if you implement the Abstract class you implement everything anyway, it really doesn't make sense to create an abstract class, so I make them all regular classes and you can see what is really going on here.

public class Setting
{
    [Required]
    public int SettingId { get; set; }

    public string Name { get; set; }

    [Required]
    [MaxLength(255)]
    public string Value { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime ModifiedDt { get; set; }
}

public class ViewSetting
{
    public int SettingId { get; }
    public string Name { get; }
    public string Value { get; }
    public string ModifiedBy { get; }
    public DateTime ModifiedDt { get; }
}

public class EditSetting
{
    public string Name { set; }

    [Required]
    [MaxLength(255)]
    public string Value { set; }
    [Required]
    public string ModifiedBy { set; }
    [Required]
    public DateTime ModifiedDt { set; }
}

you wouldn't really make separate models for editing and viewing. it isn't needed.

The properties do the getting (get = view) and setting (set = edit). so there isn't really a reason to make two separate models, one for getting and one for setting, when one class/model can do it all


SpringData: filtering fields of Entity in Repository

I think that this is not a good practice, but it still may be acceptable in some situations.

The reasons to avoid this:

1) default methods are not intended to introduce new functionality, but rather to provide backwards compatibility for older APIs. The official tutorial says:

  Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

2) It looks like you are using JPA. In a Spring repository, you can achieve the same result by using @Query, without detailing the implementation:

@Query("SELECT DISTINCT ol.addresses FROM OfficeLocation ol ...") // TODO complete the HQL
List<Address> findOfficeLocations();

3) If it cannot be done with a query, you are right, a better place for it is a service.


Grade calculator for a project with four aspects

Because there are no holes you can simply have an array of "breakpoints".

int [] steps = new int[] { 2, 4, 13, 22, 31, 41, 54, 67, 80 };
int i;

for(i=0; i<steps.length && totalmark>=steps[i]; i++);
grade = i==0 ? "U" : ""+i;
if(i<steps.length) marksaway=steps[i]-totalmark;
nextgrade=""+(i+1);


Plotting with interpolation using Matplotlib

As I pointed out in the comments, I do not think smoothing is needed when plotting functions that are already smooth, such as polynominals. In those cases, the graphs would look rough only if the points plotted are not dense enough (on the x axis).

Since you have already imported and used numpy, it would be better to use numpy.polyval for vectorized evaluation of polynominals.

Drawing spines at zero would not work well if the input range does not include zero. In that case, the "center" position might be used instead of "zero". (I will not implement this logic in my code below)

The top and right spines should not be shown.

Consider using plt.style.use for setting common style information. See here for alternative options for style setting.

Avoid constants like "#47c984". Name them with appropriate constant names for better readability.

It is a good practice to comply to the PEP 8 style when writing Python code. Use an IDE (such as PyCharm) or an online checker (such as this) for automatic PEP 8 violation checking.

When running code outside a method / class, it is a good practice to put the code inside a main guard. See here for more explanation.

Here is an improved version:
import numpy as np
import matplotlib.pyplot as plt

if __name__ == "__main__":
    # Define constants (color names come from https://colornamer.robertcooper.me/)
    INPUT_MESSAGE = "Lower and upper bounds of x, separated by a space: "
    NUM_POINTS = 300
    PARIS_GREEN = "#47c984"
    BLAZE_ORANGE = "#fc6703"

    # Read input
    lb, ub = map(float, input(INPUT_MESSAGE).split())

    # Compute coordinates of points to be plotted
    x = np.linspace(lb, ub, NUM_POINTS)
    f_x = np.polyval([1, -6, 1, 5], x)
    g_x = np.square(x - 2) - 6

    # Plotting
    plt.style.use({"lines.linestyle": "solid", "lines.linewidth": 1})
    plt.plot(x, f_x, color=PARIS_GREEN)
    plt.plot(x, g_x, color=BLAZE_ORANGE)

    # Adjust spines
    spines = plt.gca().spines
    spines["left"].set_position("zero")
    spines["bottom"].set_position("zero")
    spines["right"].set_visible(False)
    spines["top"].set_visible(False)

    # Display plot
    plt.show()


Project Euler #3 (Largest prime factor) in Swift

Naming

Your naming is misleading, and effectively broken:

fromNumber is a bad name for that variable. Something like toFactor would be better.
largestPossibleFactor is very broken. The function does not return the largestPossibleFactor, it instead returns an approximate square value. Take the number 36, the largest possible factor (other than 36 itself), is 18, yet your function returns 6. What you should call the function is something like .... actually, I don't think it needs to be a function at all.... it's over-extracted, calling a 1-liner function who's code is easier to write than describe. It's buggy code, anyway....

Bug

Your range limit is the 'half-open' range limit: 2..<Int(ceil(squareRoot))

The intention of this code is to identify where to stop the factor checking. This code will fail for values like ... 9. For 9 your code will not factor it at all, because it is a square of a prime, so your squareRoot will calculate the valeu 3, and you will do the ceil of that (3), and then exclude 3 in the range, so you will not factor the value 9 at all, and call it prime.

Instead, you should simply use the full range operator, and truncate the square-root:

for i in 2...Int(squareRoot)

Performance

A small optimization is possible if you are interested, by limiting the start of the range of the factor tests. Consider converting the recursive part of your function to include the start of the range as well as the number to factor. Something like:

func findLargestPrimeFactorFrom(let smallest: Int, let toFactor: Int) -> Int {
    for factor in smallest...Int(sqrt(Double(toFactor))) {
        if toFactor.isMultipleOf(factor) {
            return findLargestPrimeFactor(factor, toFactor/factor)
        }
    }
    return toFactor
}

The reason it will be faster is because in your recursion, you will never need to check values smaller than factors you have already eliminated higher up the stack.


Use of the naked utilities (cp, mkdir, sed, and especially rm) is usually frowned upon. It makes your makefile vulnerable to a path attack; aliasing may also result in some strangeness (for example, many distros come with rm aliased to rm -i); also keep in mind that GNU make works nativly in Windows environment, which lacks those utilities.

Typically what you do is to define them like RM := /bin/rm (conditionally tailoring for all expected platforms), etc and forget all the complications once and forever. Or use autotools.
mkdir fails if the target directory exists. -mkdir is a usual practice.
I prefer to have separate rules for dependencies and objects. Having them combined, make builds the .o file based on old dependencies. You may end up in an inconsistent state.


The aside element already creates a section, there is no need for an additional section element.

If you use h1 for the aside element’s heading, the headings in the article elements should be h2 instead of h3 (or also h1, but that’s not recommended).

But using article for these short snippets might not be a good idea in the first place (unless they will contain more than just a date and an image), because each article also creates a section.

For the date you should use the time element.


Propagating table cell border colors to adjoining cells

Recursion is a handy way to remove repetition...

function paintConnectedBorder(cellId, selectedBorderColor, selectedBorderSide) {
  const width = $("#pixels").data("defaultGrid").grid.width,
    totalCells = width * $("#pixels").data("defaultGrid").grid.height;

  let changedCells = [];

  if (selectedBorderSide === "all") {
    ['top','bottom','left','right'].forEach(side=>
        changedCells.push(...paintConnectedBorder(cellId, selectedBorderColor, side)));
  } else {
    if (selectedBorderSide === "top" && cellId >= width) {
      $("#cell-" + (cellId - width)).css("borderBottomColor", selectedBorderColor);
      changedCells.push("cell-" + anId - width);
    } else if (selectedBorderSide === "right" && (cellId % width - 1 !== 0)) {
      $("#cell-" + (cellId + 1)).css("borderLeftColor", selectedBorderColor);
      changedCells.push("cell-" + anId + 1);
    } else if (selectedBorderSide === "bottom" && anId < totalCells - width - 1) {
      $("#cell-" + (cellId + width)).css("borderTopColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + width);
    } else if (selectedBorderSide === "left" && (cellId % width !== 0)) {
      $("#cell-" + (cellId - 1)).css("borderRightColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - 1);
    }
  }
  return changedCells;
}

Basically if 'all' is selected the function will call itself once for each of the individual selections.

As requested, here's the ES5 version for older browsers...

function paintConnectedBorder(cellId, selectedBorderColor, selectedBorderSide) {
  const width = $("#pixels").data("defaultGrid").grid.width,
    totalCells = width * $("#pixels").data("defaultGrid").grid.height;

  let changedCells = [];

  if (selectedBorderSide === "all") {
    var sides = ['top','bottom','left','right'];
    for(var i=0, side; side=sides[i]; i++)
        changedCells.push.apply(changedCells, paintConnectedBorder(cellId, selectedBorderColor, side)));
  } else {
    if (selectedBorderSide === "top" && cellId >= width) {
      $("#cell-" + (cellId - width)).css("borderBottomColor", selectedBorderColor);
      changedCells.push("cell-" + anId - width);
    } else if (selectedBorderSide === "right" && (cellId % width - 1 !== 0)) {
      $("#cell-" + (cellId + 1)).css("borderLeftColor", selectedBorderColor);
      changedCells.push("cell-" + anId + 1);
    } else if (selectedBorderSide === "bottom" && anId < totalCells - width - 1) {
      $("#cell-" + (cellId + width)).css("borderTopColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + width);
    } else if (selectedBorderSide === "left" && (cellId % width !== 0)) {
      $("#cell-" + (cellId - 1)).css("borderRightColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - 1);
    }
  }
  return changedCells;
}


Best way to handle repetitive error code or return value

Okay, well here is what I would probably do in this situation. If the error codes you are getting are consistent this will make this type of solution even better (consistent as in "FileNotFound" error code is always -42 or something like that).

I would add a private method that throws an "Uninitialized" exception if the object has not been initialized. There is no need to be checking that twice for each function call.

private void ValidateInitialized()
{
    throw new LibraryUninitializedException(); // Just create this exception class
}

Then I would create a helper method that takes a Func<int> that you can call from each of the wrapper methods. The helper method will handle the error code stuff for you. It would look something like this (note: I have not compiled this, so I may have some minor syntax errors).

private void DoThirdPartyOperation(Func<int> operation, string message = "")
{
     ValidateInitialized();
     switch(operation())
     {
         case 0:
             // No error - do nothing
             break;
         case someErrorCode:
             throw new SomeErrorException(message);
             break;
         case someOtherErrorCode:
             throw new SomeOtherErrorException(message);
             break;

         default:
             // Choose either to throw some sort of general exception and include
             // the error code in it OR throw an UnrecognizedErrorException
     }
}

public void Operation1(someParameter)
{
    DoThirdPartyOperation(() => { ThirdParty.Operation1(someParameter); });
}

public void Operation2(someParameter)
{
    DoThirdPartyOperation(() => { ThirdParty.Operation2(someParameter); },
        "Failed performing Operation2");
}


Qt foreach-like alternative to iterate over value AND key of an associative container

You can probably do something simpler to avoid making this a special case macro, e.g. using std::tie or boost::tie if that's not available:

#include <map>
#include <functional>
#include <boost/foreach.hpp>
#include <iostream>

int main() {
  std::map<int, std::string> map = {std::make_pair(1,"one"), std::make_pair(2,"two")};
  int k;
  std::string v;
  BOOST_FOREACH(std::tie(k, v), map) {
    std::cout << "k=" << k << " - " << v << std::endl;
  }
}


Store a hash in a cookie to identify the user's account to keep logged in after close browser

I think this is a bad approach on two fronts (the second one is more important):

Having to check a randomly generated 'hash' against the database, to see if it has been used before, is inefficient. First of all, this is not a hash, it's a random string. A hash is created from something sensible, to verify it later. Can I assume you already have an unique identifier for each user in your database? You could store that in the cookie, it tells you which user it is. User id's don't need to be a secret. However, you don't want someone to change it and see information from another to user. To prevent this, you could add a small random string to the cookie, and in your database, to verify that they are who they say they are. Such a string is called a 'token'. An user is only valid if the user id and the token in the cookie match with the id and token in the database. Your queries will now probably be quicker because you can use the user id to look up the token.
Staying 'logged in' after closing the browser is done by not erasing the session cookie when the browser closes. It's as simple as that. See: https://www.php.net/manual/en/function.session-set-cookie-params.php (see 'lifetime', it defaults to 0).


import java.util.Stack;

public class StackQueue<T> {
    private Stack<T> writeStack = new Stack<T>();
    private Stack<T> readStack = new Stack<T>();

    public void enqueue(T element) {
        writeStack.push(element);
    }

    public T dequeue(){
        if (readStack.empty()) {
            while (!writeStack.empty()) {
                readStack.push(writeStack.pop());
            }
        }
        return readStack.pop();
    }
}

Algorithm

You only need two stacks. Always write to the writeStack, read from the readStack. If the latter is empty, copy everything over.

Naming

Use meaningful names, such as writeStack and readStack instead of stack1 and stack2. Declare them private. A queue's user doesn't care about the internals. Import only what you need, in this case java.util.Stack.

Generics

The Stack<T> is a generic datatype, make use of it. Make your StackQueue generic as well. Instanciate it using

StackQueue<String> queue = new StackQueue<String>();

Return value

dequeue() should return a value. Print it with

System.out.println(queue.dequeue());


Efficient LC3 assembly code to print the numbers leading up to any digit

Points about your program.

The 2 instructions at the top don't match the 3 dumped values! There are 12 lines of source but there are 13 values in the dump. .ORIG X3000 is not an instruction. It's rather a directive and you should not find any value from it in the dump.
Why don't you place the data below the HLT instruction? A much safer place than within the instructions that get executed. Your trick works because of how the BR instruction is encoded.
On an architecture with limited registers available, it's best to try to use as few as possible to get the work done. Your code uses 5 registers where you can easily do it with 2 registers.
You don't need to use the extra register R4 to find out if the input was 0. AND-ing R1 to itself will not destroy it and will set the flags for inspecting:

AND R1, R1, R1
BRz X300B      ;Skip if input was 0

It's inefficient to branch always to just another branch instruction. See how I solved the same branching.

An improved version.

  My goal is to print all the numbers leading up to a set value

Let's presume the user selects a value from 0 to 9.

For now you've manually set the user's value in R1. You can use it as a (down)counter. You stop the program as soon as a negative value appears.

.ORIG X3000
LEA   R0, X3030     ;Loads "0" in R0[7:0]
BRnzp X3004         ;Go test for 0 input
OUT                 ;Display R0[7:0]
ADD   R0, R0, #1    ;R0++
ADD   R1, R1, #-1   ;R1--
BRzp  X3002         ;Continue with zero or positive
HLT                 ;Stop (R1 = #-1)

OUT only depends on bits [7:0]. The high bits loaded with LEA don't matter.
If you don't like this trick, then go with the usual way of loading a constant from memory:

.ORIG X3000
LD    R0, X3007     ;Loads "0" in R0
BRnzp X3004         ;Go test for 0 input
OUT                 ;Display R0[7:0]
ADD   R0, R0, #1    ;R0++
ADD   R1, R1, #-1   ;R1--
BRzp  X3002         ;Continue with zero or positive
HLT                 ;Stop (R1 = #-1)
.FILL X0030         ;Character "0"


How can I speed up my RSS feed Android App?

none of those Variables need to be set to "" inside the for loop, they have already been set.

This can be set early and outside of the if block and the for loop:

 dbimg = "http://s14.postimg.org/cs10sq11d/whitemega.png";

Otherwise it is a Magic string that you will have to search for later.

The id isn't doing anything here, I don't think that you need it at all, you should be able to call the code like this

handler.insertrssfeedData(dbtitle, dbDesc, dbimg, dbimgicon, dblink, dbpubdate, dbfff, dbsourcename , dbimagecheck);

otherwise you are creating this variable and assigning a lot of data to it and never using it every time you go through the loop.


as mentioned in the comments it might be helpful to extract methods to remove redundant code - you might want to read a more detailed explanation on "methods in java" to gain basic knowledge on methods.
tl;dr
"A Java method is a collection of statements that are grouped together to perform an operation"
let's collect your your statements that all checks have in common
Map<String,String> dtlLogMap = new HashMap<>(4);
dtlLogMap.put("transId",String.valueOf(record.getTransactionId()));
dtlLogMap.put("firstName",record.getFirstName());
dtlLogMap.put("validationName","VALID_FIRSTNAME_CHECK");
dtlLogMap.put("validationStatus","passed");
DetailedLogger.log(dtlLogMap);

we can extract a lot of stuff here into a method named Map<String,String> createLog(Record record, String checkResult) - noteworthy is, that we only group things together, that belong together - we do not (yet) extract the logging action - to maintain the Single Responsibility-principle. That makes it also a lot easier to find proper method names (instead of creating an obfucasting method name createAndPrintLog())
private Map<String,String> createLog(Record record, String checkName, String checkResult){
    Map<String,String> logs= new HashMap<>(4);
    logs.put("transId",String.valueOf(record.getTransactionId()));
    logs.put("firstName",record.getFirstName());
    logs.put("validationName",checkName);
    logs.put("validationStatus",checkResult);
    return logs;
}

note that a method has parameters that let you control the output of the method: the parameters should be self-explaining (Tell - dont Ask)
we can now apply this method in your checks and remove redundant code
...
if(record.isDetailedLoggingEnabled()){
    //here: method call instead of redundancy
    Map<String,String> dtlLogMap = createLogs(record,"VALID_FIRSTNAME_CHECK",  "Errored");
    dtlLogMap.put("errorCode",record.getErrorCode());
    DetailedLogger.log(dtlLogMap);
}
...

use more methods to remove more reduncancy!


void tre(struct node * p) //function that I am using to convert the string to a tree
{
        if(a[i]=='(')
        {

I recommend not using such short variable names

            i++;
            struct node *temp=malloc(sizeof(struct node));
            temp->x=a[i];
            temp->left=temp->right=NULL;

You basically repeat these three lines three times. If you instead do this at the beginning of tre you can avoid the duplication.

            i++;
            if(p->left==NULL)

Given the way your code is structured, won't p->left always be null? The value passed to tre is always a freshly created node

            {
                p->left=temp;
                tre(p->left);
            }
            if(a[i]!='('&&a[i]!=')')

Why do you need to check for this? Wouldn't this indicate an invalid input? If so, perhaps you should report the error somehow.

            {
                struct node *tempp=malloc(sizeof(struct node));
                tempp->x=a[i];
                i++;
                p->right=tempp;
                tre(p->right);
            }

        }
        else
        if(a[i]==')')
        {
            i++;
        }

Again, in what situation will this be called?

}

How I'd approach that function

stuct node * tre()
{
     struct node * node = malloc(sizeof(struct node));
     node->x = a[i++];
     if(a[i] == '(')
     {
          node->left = tre();
          node->right = tre();
          assert(a[i++] == ')');
     }
     else
     {
          node->left = node->right = NULL;
     }
     return node;
}

Unless I'm missing something, your example output and code do not match. So I'm not going to comment on that.


Creating change with the smallest number of coins

So .. you're repeatedly subtracting a number from another number, and seeing how many times you can do that without going negative? There's a word for that: division.

EDIT: Since you want the actual code

const generateCoinChange = cents => {
    let quarter = Math.floor(cents/25);
    cents -= 25*quarter
    let dime = Math.floor(cents/10);
    cents -= 10*dime
    let nickel = Math.floor(cents/5);
    cents -= 5*nickel
    let penny = cents;
    console.log(`Quarters: ${quarter}, Dimes: ${dime}, Nickels: ${nickel},Pennies: ${penny}`)
};

You can also do:

 const generateCoinChange = cents => {
     let counts = [0,0,0,cents]
     let denominations = [25,10,5]
     for (i=0,i<3,i++){
         counts[i] = Math.floor(counts[3]/denominations[i])
         counts[3] -= counts[i]*denominations[i]
     }
 console.log(`Quarters: ${denominations[0]}, Dimes: ${denominations[1]}, Nickels: ${denominations[2]}, Pennies: ${denominations[3]}`)
 };


I consider this to be obfuscated code.  Consider:

There are no comments: no guidance on how to call the function, and no explanation of how it works internally.
All variables have one-character names, as if you had filtered the code through a minifier.  The sole exception is ofs — which is still cryptic and meaningless to me.
You have used nearly the minimum amount of whitespace possible:

SpaceSpacefor(big i=0;i<m;++i)n[i]=true;

The code would be more readable with deeper indentation than two spaces per level.  It would be easier to see the individual parts of the loop header if you put spaces after each semicolon.  The loop body would be easier to see if it didn't immediately follow the closing parenthesis.

    for (big i = 0; i < m; ++i) {
        n[i] = true;
    }

All these changes cost you nothing, and have tangible benefits.
This loop header is trying to accomplish way too much!

for(big j=i,t=s;j<=m/i;j+=ofs[t],++t==8?t=0:0)

Also, why is the code guarded by #ifndef _pes30_cxx_?  Is this code living inside a header file?  If so, move it out to a .cpp file where it belongs.

Given the serious stylistic issues with the code, I doubt that anyone would voluntarily reverse-engineer it and review its substance.  I suggest that you work on expressing yourself clearly, then post a follow-up question asking about memory or other performance concerns.


Simplify & Reduce steps in the IsDistinct function

You have no idea how excited I am about this.  Years after learning about the Xor operator and I finally get to use it!!

VBA - Logical Operators: Xor Operator

  Called Logical Exclusion. It is the combination of NOT and OR Operator. If one, and only one, of the expressions evaluates to be True, the result is True.

The Xor seems like a great fit because both the parameters need to be tested for nulls and the values can not equal one another.

My Version

Public Function NotEquals(LeftValue As Variant, RightValue As Variant) As Boolean
    If IsNull(LeftValue) Xor IsNull(RightValue) Then
        NotEquals = True
    ElseIf LeftValue <> RightValue Then
        NotEquals = True
    End If
End Function

Results

Crude Tests

Option Explicit
Public Const Repetitions = 10000000

Public Function IsDistinct(LeftValue As Variant, RightValue As Variant) As Boolean
    If IsNull(LeftValue) Then
        If IsNull(RightValue) Then
            IsDistinct = False
        Else
            IsDistinct = True
        End If
    Else
        If IsNull(RightValue) Then
            IsDistinct = True
        Else
            IsDistinct = Not (LeftValue = RightValue)
        End If
    End If
End Function

Public Function NotEquals(LeftValue As Variant, RightValue As Variant) As Boolean
    If IsNull(LeftValue) Xor IsNull(RightValue) Then
        NotEquals = True
    ElseIf LeftValue <> RightValue Then
        NotEquals = True
    End If
End Function

Sub CompareResults()
    Dim SumOfTime As Double
    Debug.Print "Number of Repetitions: "; FormatNumber(Repetitions, 0)

    Debug.Print
    Debug.Print "IsDistinct Test"
    Debug.Print "Left"; Tab(8); "Right"; Tab(16); "Time"; Tab(24); "Result"
    SumOfTime = TestIsDistinct(1, 1)
    SumOfTime = SumOfTime + TestIsDistinct(1, 0)
    SumOfTime = SumOfTime + TestIsDistinct(Null, 1)
    SumOfTime = SumOfTime + TestIsDistinct(0, Null)
    SumOfTime = SumOfTime + TestIsDistinct(Null, Null)
    Debug.Print "Total Time for All IsDistinct Test: "; SumOfTime

    Debug.Print
    Debug.Print "NotEquals Test"
    Debug.Print "Left"; Tab(8); "Right"; Tab(16); "Time"; Tab(24); "Result"
    SumOfTime = TestNotEquals(1, 1)
    SumOfTime = SumOfTime + TestNotEquals(1, 0)
    SumOfTime = SumOfTime + TestNotEquals(Null, 1)
    SumOfTime = SumOfTime + TestNotEquals(0, Null)
    SumOfTime = SumOfTime + TestNotEquals(Null, Null)
    Debug.Print "Total Time for All NotEquals Test: "; SumOfTime

End Sub

Function TestIsDistinct(LeftValue As Variant, RightValue As Variant) As Double
    Dim t As Double
    t = Timer
    Dim Result As Boolean
    Dim n As Long
    For n = 1 To Repetitions
        Result = IsDistinct(LeftValue, RightValue)
    Next

    Dim SumOfTime As Double
    SumOfTime = Round(Timer - t, 4)

    Debug.Print LeftValue; Tab(8); RightValue; Tab(16); SumOfTime; Tab(24); Result

    TestIsDistinct = SumOfTime
End Function

Function TestNotEquals(LeftValue As Variant, RightValue As Variant) As Double
    Dim t As Double
    t = Timer
    Dim Result As Boolean
    Dim n As Long
    For n = 1 To Repetitions
        Result = NotEquals(LeftValue, RightValue)
    Next

    Dim SumOfTime As Double
    SumOfTime = Round(Timer - t, 4)

    Debug.Print LeftValue; Tab(8); RightValue; Tab(16); SumOfTime; Tab(24); Result

    TestNotEquals = SumOfTime
End Function


Search every char from a string for every char in another

First of all let's address some of the more prominent style issues of your code, before diving into an alternate approach to solving it.

Have imports at top of code – At first I didn't see the from string import ... line as it was hidden in the code, but this is not good coding practice. Put this at the top of the file, so it is easy to see.
Have more vertical space – Please add an extra line here and there, to increase readability in your code. Typically I would add spaces in front of for loops or if block to accentuate these blocks.
Be consistent in variable naming – Naming variables is hard but choose one style for variable naming, and don't mix it like name_of_new_library, validFilenameChars and stringofnewname. This make the code a whole lot harder to read, which in turns makes it harder to maintain in the long run.
Functions should return, not print their result – To have a function print its output is usually a code smell, and it would be better to have it return the result. If by some reasoning it's required to print it out, I would maybe indicate that in the function name.
Using the % operator is depreceated in favor of str.format – See format examples for the newer and better method of adding arguments into strings.
Why the event=None – I haven't used tkInter a lot, so you might need it for some reason, but it kind of looks superfluous to me as you don't use the event in the function at all.
Why the str(some_variable)? – Why do you do this? Is this related to tkInter somehow as well? Do you really need to "stringify" the return from tkInter?
Only join when needed! – The join command is mainly used to join lists, so joining a list of one character is extra work, and not needed. To append a single character you could do txt += char. See below for a better use of join.

Algorithm comments

When summarized your code does the following things:

Reads a suggestion using tkInter
Builds a constant of validFilenameChars
Converts any spaces into underscores, and
lowercases all other characters

As covered before the import should be done at top, and so should also declaration of constants. When you start validifying the name you split the string into single characters, and use a somewhat strange += ''.join(new_i) to add onto the new filename.

There does however exist functions which does both of your required operations. See str.lower() and str.replace(). Do however note that, the latter replace substrings. In your case str.replace(' ', '_') would work, but if replacing multiple chars see how to replace multiple characters in a string?

The only part not covered then is the valid characters part, and this is the slightly ugly part of the new alternative. My proposed solution is to do:

''.join(c for c in suggested_name if c in VALID_CHARS)

And this possibly requires a little explanation:

''.join(_some list_) – This expects a list of something, which it will join together by the separator in front, that is the empty string.
c ... – If the for loops is valid, then return the c
for c in suggested_name ... – Split the suggested_name into single characters
if c in VALID_CHARS – Only do the action (that is return c) from the for loop if the if expression is true. And the expression verifies that the character c is within the string VALID_CHARS.

In other words, the previous statements joins all characters from suggested_filename using the empty string separator, for those characters who are present in VALID_CHARS. That is quite a mouthful, but it is a very useful expression!

A longer version to write the same is something like (with a lot of edge cases removed):

my_list = []
for c in suggested_name:
  if c in VALID_CHARS:
    my_list.append(c)

my_separator = ''
my_txt = my_list[0]
for c in my_list[1:]:
  my_txt += my_separator
  my_txt += c

I'm also accustomed to separating how you get stuff (aka the tkInter dialog) from validation/transformation of the result, so I would make a function to handle this.

Code refactored

So what would the code look like if applying all of this? Maybe something like this (untested as I don't have tkinter available):

from string import ascii_letters, digits
VALID_CHARS = '-_.() {}{}'.format(ascii_letters, digits)

def get_valid_library_name(suggestion):
  valid_filename = ''.join(c for c in suggestion if c in VALID_CHARS)
  valid_filename = valid_filename.replace(' ', '_').lower()
  return valid_filename

a_name = tkinter.simpledialog.askstring(
                 'Create New Note Library',
                 'Alphanumeric lowercase and "_" only',
                 initialvalue = "Name_Here")

print('{} into {}'.format(a_name, get_valid_library_name(a_name))

filename = get_valid_library_name("MY someWHAT ugly suggestion#$!&&")
print(filename)    # Would output "my_somewhat_ugly_suggestion"

Note that one could join the valid_filename transformation into fewer lines, but keeping it readable is also a good thing. For real code I would most likely have the valid_filename = ''.join(..) on one line, and then do a return valid_filename.replace().lower() instead of the two next lines.

As a final note, also see Turn a string into a valid filename which I found when researching for this answer. It uses some alternate stuff from unicode, and has some other related ideas on how to handle validation of filenames.


Project Euler #12: Highly divisible triangular number

The Algorithm

Let's just look at your top level algorithm:

n = 0
while True:
    n = n + 1
    Triangular_number = n * (n + 1) / 2
    prime_factorization(Triangular_number)
    num_divisor = find_number_of_divisor(Triangular_number)

Factoring is hard. It's a difficult problem in the best of cases. You are taking a difficult problem and making it harder. You are starting with n * (n + 1) / 2 - that is already a partial factorization. You are then throwing out that information and factoring the whole number. It is much easier to factor 7 * 4 than it is to factor 28, but you are choosing to do the latter.

It would be much more efficient to do something like:

factor1 = prime_factorization(n/2 if n % 2 == 0 else n)
factor2 = prime_factorization(n+1 if n % 2 == 0 else (n+1)/2)
full_factorization = merge(factor1, factor2)

If you memoize prime_factorization, then you're only doing a little bit of work each iteration. Let's consider just going from the 49th triangular number to the 50th and assume we have a very good memoized prime factorization (more on this later). Factoring the full number:

(1275)
--> 3 * (425)
--> 3 * 5 * (85)
--> 3 * 5 * 5 * (17)

None of 1275, 425, or 85 were in the table. 17 was the first number we would have found. Consider the alternative, we are instead finding the prime factorization of:

(25)
--> memoized as 5*5 (already done when finding the 24th triangular number)
(51)
--> 3 * (17)

And 17 is memoized already (from the 16th triangular number). So we did one division. That time difference adds up. The full solution I present later in this answer takes just under 1.0s (when run 10x) if I factor each factor independently, but 4.46s when I factor the whole number. That is a lot slower.

And when you find yourself doing a counting loop, you should really use itertools.count() so that the main loop becomes:

for n in itertools.count(start=1):
    factors1 = prime_factorization(n/2 if n % 2 == 0 else n)
    factors2 = prime_factorization(n+1 if n % 2 == 0 else (n+1)/2)
    full_factorization = merge_factors(factors1, factors2)

    if num_factors(full_factorization) >= 500:
        return n * (n+1) / 2

Memoization

Now, you're kind of memoizing, but then not really, since the first thing you do is wipe memoi_table[x]. If should definitely start with:

def prime_factorization(x):
    if x in memoi_table:
        return memoi_table[x]

    ...

In any event, it's simpler to just write a decorator:

def memoize(f):
    cache = {}
    def wrapper(*args):
        if not args in cache:
            cache[args] = f(*args)
        return cache[args]
    return wrapper

@memoize
def prime_factorization(x):
    ...

Prime Finder

If you do your loop correctly, you don't actually need prime_finder(i). What does that function do? It looks over all the numbers smaller than i... but we're already doing that in prime_factorization! You're just doubling work for no reason. The whole body should just be something like:

for i in range(2,math.floor(math.sqrt(x)+1)):
    if x%i == 0:
        old_factorization = prime_factorization(x / i).copy()
        old_factorization[i] += 1
        return old_factorization

# still here? we didn't find a factor, must be prime
res = collections.defaultdict(int)
res[x] = 1
return res

That's it.

Putting it all together

All we need is merging two dictionaries, which is an easy loop:

def merge_factors(f1, f2):
    res = f1.copy()
    for k, v in f2.items():
        res[k] += v
    return res

And finding the number of factors, which is just a product:

def num_factors(factorization):
    product = 1
    for v in factorization.values():
        product *= (v+1)
    return product

The times based on finding the first triangular number with at least X factors:

      mine      OP
  5   0.0005s   0.0007s
 10   0.0009s   0.0041s
 25   0.0039s   0.0860s
100   0.0256s   6.0304s
500   0.9849s   ???????


C++ performance: Linear regression in other way

Optimizing the algorithm
If \$M\$ is the number of steps between minimum and maximum, and \$N\$ is the size of the input and output vectors, then your algorithm has complexity \$\mathcal{O}(N \cdot M^3)\$. Also, it likely doesn't find the optimal solution unless you use a very small step size, and you have to choose minimum and maximum correctly. There are other algorithms that will both give you a guaranteed optimal solution without having to specify a range and a step size, and which have complexity \$\mathcal{O}(N)\$. This is possible since the problem of linear least squares can be solved analytically, and can be implemented efficiently on a computer.
If you don't want to go for the exact mathematical approach, and perhaps want to perform regressions of more complex functions that don't have an exact solution, then you might want to look into algorithms that approach the problem in a smarter way than just brute-forcing all possible values of the parameters. A typical solution to this kind of problem is to implement a gradient descent algorithm.
Choosing the right error function
The way you calculate the error (or rather the residual to be more precise) is quite strange. Normally one would try to minimize the sum of the squares of the difference between a data point and the predicted value. However, your error function is using the linear difference, and weighting it such that the first datapoint has the least weight, and the last datapoint weighs as much as all the other datapoints combined:
float error = Module(Predict(a, b, c, input[0]) - output[0]);
for (int i = 1; i < input.size(); i++)
    error = (Module(Predict(a, b, c, input[i]) - output[i]) + error)/2;

Unless this is really the intended function, you should probably replace this with a function that calculates the least squares residual.


First of all, I would question the need for such interface. It makes sense for a type to hold a value, but I think it doesn't make much sense for a type to decide to what types to convert that value, or how.

Second, if you really do need this, then I would prefer each target type to have a separate method, like ConvertToInt() (or ConvertToInt32() if you follow the naming guidelines).

You don't necessarily need an interface for this, but even if you do, you're exchanging a small inconvenience in implementation (having to write few very simple interfaces with some repetition) for a big inconvenience in usage (having to write that Specialisation<int>.Instance every time and making the code less readable). So, I think using this approach is worth it even with interfaces.

Third, if you really do need this and you want to take advantage of generics, you could use explicit interface implementation and casting to decide to what type to convert. Something like:

public interface IConvertible<T>
{
    T Convert();
}

public sealed class ConvertMe : IConvertible<int>, IConvertible<float>
{
    public double Value;
    int IConvertible<int>.Convert() { return (int)Value; }
    float IConvertible<float>.Convert() { return (float)Value; }
}

public static class Program
{
    public static void Main()
    {
       ConvertMe c = new ConvertMe();
       c.Value = 12.3456789;
       Console.WriteLine(((IConvertible<int>)c).Convert());
       Console.WriteLine(((IConvertible<float>)c).Convert());
    }
}

This results in code that is shorter and more readable (I think) than your version.

One issue with it is that if you don't make ConvertMe sealed, trying to convert to an unsupported type becomes a runtime exception, instead of a compile-time error.


Indentation
The standard indentation style in Ruby is two spaces, not four.
Single-quoted strings
If you don't use string interpolation, it is helpful if you use single quotes for your strings. That way, it is immediately obvious that no string interpolation is taking place.
Frozen string literals
Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a magic comment you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:
# frozen_string_literal: true

It is generally preferred to add this comment to all your files. In your case, you are only actually mutating one of the many strings in your code, the one assigned to ciphered.
You can make only this string mutable by either not using a literal to initialize it:
ciphered = String.new

Or by using the unary prefix String#+@ operator for strings, which turns a frozen string into a mutable string:
ciphered = +''

Linting
You should run some sort of linter or static analyzer on your code. Rubocop is a popular one, but there are others.
Rubocop was able to detect all of the style violations I pointed out, and also was able to autocorrect all of them. Note, however, that automatically adding the magic comment broke the code originally, because Rubocop does not automatically detect which strings are mutated. So, I had to add the + manually afterwards. That's where good tests come in handy!
Inconsistent use of parentheses
Sometimes, you use parentheses around arguments, and sometimes you don't. The general rule is to always use parentheses around arguments if you have arguments, and leave out the parentheses only for "procedure-like" methods such as puts, attr_reader, require, private, etc.
For example, you are using parentheses for split and index but not for include?.
Constants
There is no need to re-compute low_alpha, high_alpha, and length_alpha every time you call the method. Their values will always be the same. Therefore, it makes sense to turn them into constants and initialize them at the beginning of the file:
LOW_ALPHA = ('a'..'z').to_a
HIGH_ALPHA = ('A'..'Z').to_a
LENGTH_ALPHA = LOW_ALPHA.length

Object#freeze
Object#freeze is a method that allows you to freeze an object. A frozen object will no longer allow itself to be modified. It is good practice in general to freeze objects that you don't intend to modify, both as a signal to the reader that this object will not be modified, and as a safety net, in case you ever accidentally try to modify it regardless.
We already made all but one of our strings frozen, so let's do that with the arrays as well:
LOW_ALPHA = ('a'..'z').to_a.freeze
HIGH_ALPHA = ('A'..'Z').to_a.freeze
LENGTH_ALPHA = LOW_ALPHA.length

Numbers are immutable anyway, no need to freeze them.
length vs. size
Many Ruby collections have both length and size methods, but some have only one. In general, IFF a collection has a size method, then that method is guaranteed to be "efficient" (usually constant time), whereas length may or may not be efficient (linear time for iterating through the collection and counting all the elements), depending on the collection.
In your case, you are using an array, for which both are constant time, but if you want to guarantee efficiency, then it is better to explicitly use size instead.
String#chars
Instead of using String#split, you can use String#chars to create an array of characters:
chars = str.chars

String#each_char
Actually, you don't need the array of characters at all. Instead, you can use the String#each_char iterator directly:
str.each_char do |char|

The conditional expression is … an expression
In Ruby, the conditional expression if / else is an expression, not a statement. (In fact, everything in Ruby is an expression, there are no statements.) Therefore, the conditional expression evaluates to a value, it evaluates to the value of the branch that was taken.
This means you can remove the duplicated ciphered << X from each branch, and instead pull it out of the conditional expression:
ciphered << if LOW_ALPHA.include?(char)
              i = LOW_ALPHA.index(char)
              shifted = (i + shift) % LENGTH_ALPHA

              LOW_ALPHA[shifted]
            elsif HIGH_ALPHA.include?(char)
              i = HIGH_ALPHA.index(char)
              shifted = (i + shift) % LENGTH_ALPHA

              HIGH_ALPHA[shifted]
            else
              char
            end

Code duplication
Speaking of duplicated code: Your then branch and your elsif branch are virtually identical. We can simplify them by extracting the duplicated code into a method:
def encrypt_letter(char, alphabet, shift)
  i = alphabet.index(char)
  shifted = (i + shift) % LENGTH_ALPHA

  alphabet[shifted]
end

and then using this method in the two branches instead:
ciphered << if LOW_ALPHA.include?(char)
              encrypt_letter(char, LOW_ALPHA, shift)
            elsif HIGH_ALPHA.include?(char)
              encrypt_letter(char, HIGH_ALPHA, shift)
            else
              char
            end

Higher-level iterators
Ruby has many powerful iteration methods in its collections library. Using each (or in this case each_char) directly is almost always sub-optimal. This particular pattern that you are using:

Initialize an accumulator. (In this case the string assigned to ciphered.)
Iterate over the collection and add to the accumulator.
Return the accumulator.

Is known as a Fold, and is available in Ruby in two forms, Enumerable#each_with_object and Enumerable#inject. Using Enumerable#each_with_object, we can further simplify your code to:
def caesar_cipher(str, shift)
  str.each_char.each_with_object(+'') do |char, ciphered|
    ciphered << if LOW_ALPHA.include?(char)
                  encrypt_letter(char, LOW_ALPHA, shift)
                elsif HIGH_ALPHA.include?(char)
                  encrypt_letter(char, HIGH_ALPHA, shift)
                else
                  char
                end
  end
end

The right higher-level iterator!
But actually, what you are doing here is simply transforming each element of the collection. You don't need something as powerful as a fold for that. This is a much simpler operation called Map, and it is also available in Ruby as Enumerable#map:
str.each_char.map do |char|
  if LOW_ALPHA.include?(char)
    encrypt_letter(char, LOW_ALPHA, shift)
  elsif HIGH_ALPHA.include?(char)
    encrypt_letter(char, HIGH_ALPHA, shift)
  else
    char
  end
end.join

Rubocop, revisited
I didn't mention this before, but in addition to the style violations I mentioned at the beginning, Rubocop was also complaining about the complexity and the length of the caesar_cipher method. At this point, Rubocop is actually happy with everything!
But we can do better.
The Algorithm
What the Caesar Cipher is really doing, is shifting the alphabet. You have recognized this, as can be seen by your variable names (shift), but you are not really taking advantage of it.
What we can do, is take our alphabets, shift them, and then use them for a key-value mapping, i.e. a Hash:
Now, our entire code looks like this:
#!/usr/bin/env ruby
# frozen_string_literal: true

LOW_ALPHA = ('a'..'z').to_a.freeze
HIGH_ALPHA = ('A'..'Z').to_a.freeze

def caesar_cipher(str, shift)
  low_encrypted = LOW_ALPHA.rotate(shift)
  high_encrypted = HIGH_ALPHA.rotate(shift)

  character_map =
    Hash.new { |_, k| k }
        .merge((LOW_ALPHA.zip(low_encrypted) + HIGH_ALPHA.zip(high_encrypted)).to_h)
        .freeze

  str.each_char.map(&character_map).join
end

Okay, there's a lot going on here. We are using Array#rotate to create the shifted character arrays:
LOW_ALPHA.rotate(3)
# => ["d", "e", "f", …, "a", "b", "c"]

Then we use Array#zip to create an array of pairs with the original character and the encrypted character:
LOW_ALPHA.zip(LOW_ALPHA.rotate(3))
# => [["a", "d"], ["b", "e"], ["c", "f"], …, ["x", "a"], ["y", "b"], ["z", "c"]]

With Array#+ we concatenate the two arrays together, and then call Array#to_h, which turns an arrays of pairs (two-element arrays) into a hash, which looks like this:
{
  'a' => 'd',
  'b' => 'e',
  'c' => 'f',
# …
  'x' => 'a',
  'y' => 'b',
  'z' => 'c',

  'A' => 'D',
  'B' => 'E',
  'C' => 'F',
# …
  'X' => 'A',
  'Y' => 'B',
  'Z' => 'C',
}

This contains our entire encryption scheme.
We have already created a hash with a default value that will simply return the key for any unknown key (so that, e.g. '!' maps to '!') and use Hash#merge to merge these two hashes into one.
Last, we call map as before, but now, as our transformation function, we simply pass the hash itself. For that, we use the & operator, which turns a Proc into a block. But wait, we don't have a Proc, we have a Hash? Indeed, but Hash implements Hash#to_proc, which converts the hash into a proc that is equivalent to using the hash's Hash#[] method.
The power of strings
The String class in Ruby is really powerful as well. For example, it has the method String#tr which does the same thing as the POSIX tr utility, it translates characters in a string. This is really the right method to use for this job:
#!/usr/bin/env ruby
# frozen_string_literal: true

LOW_ALPHA = ('a'..'z')to_a.join.freeze
HIGH_ALPHA = ('A'..'Z')to_a.join.freeze

def caesar_cipher(str, shift)
  low_encrypted = LOW_ALPHA.chars.rotate(shift).join.freeze
  high_encrypted = HIGH_ALPHA.chars.rotate(shift).join.freeze

  str.tr(LOW_ALPHA + HIGH_ALPHA, low_encrypted + high_encrypted)
end

Final thoughts
Lastly, I just want to give you something to think about, without any comments from me:
# frozen_string_literal: true

class CaesarCipher
  LOWER = ('a'..'z').to_a.join.freeze
  UPPER = ('A'..'Z').to_a.join.freeze

  def initialize(key)
    self.encrypted = (LOWER.chars.rotate(key) + UPPER.chars.rotate(key)).join.freeze
  end

  def encrypt(str)
    str.tr(LOWER + UPPER, encrypted)
  end

  alias_method :call, :encrypt

  def to_proc
    ->str { encrypt(str) }
  end

  private

  attr_accessor :encrypted

  freeze
end

caesar5 = CaesarCipher.new(5)

puts caesar5.encrypt('What a string!') # Bmfy f xywnsl!
puts caesar5.('Abc') # Fgh
puts CaesarCipher.new(3).('Xyz') # Abc
puts CaesarCipher.new(1).('Test') # Uftu
puts CaesarCipher.new(10).('Zoo') # Jyy

puts ['What a string!', 'Abc'].map(&caesar5)


I think the logic for getting the minimal distance between the points would work even without the explicit check against MAX_INT:

private void updateClosestPair() {
    for (int i = 0; i < points.size() - 1; i++) {
        int testDistance = getDistance(points.get(i), points.get(points.size() - 1));
        if (testDistance < minDistance) {
            minDistance = testDistance;
            closestPairIndices[0] = i;
            closestPairIndices[1] = points.size() - 1;
        }
    }
}

Although I did not run the above code, I am convinced that it would just work also for the first pair (or it could be fixed with minimal changes), since it would just check the second point against the first one, and set their distance as the minimum.
Going one step further, you also don't need to check that there are at least two points, when calling updateClosestPair. In this case, the iteration would never start at all.


Using Java to Add the Contents of two EditText views in Android

That code is a bit dangerous. Integer.valueOf() can throw NumberFormatException which you make no effort to catch. This will happen if you have commas in numbers or non-digit characters. Your other comments are also very important.

As for simplifying the method, it is not good that you call findViewById 3 times every time you press a button. I would store references to editText1, editText2 and textView externally (of this method), as then you can reuse all three here and elsewhere in your code with subtract/multiply etc. You can then remove three lines of code and just have:

Integer s = Integer.valueOf(et1.getText().toString()) + Integer.valueOf(et2.getText().toString());
tv.setText(s.toString());

Remember that you should probably wrap the code in a try catch block unless you can guarantee the text field will only contain decimal numbers. Also, add in your overflow/underflow logic as well.


Nice solution, these are my suggestions:

Parsing the input: in Python 3 the function input always returns a string, so the mapping can be removed. In Python 2, you can use raw_input.
Naming: ls is too generic. In this case, a suggestion is to take the names from the problem description. From:
a = input()
ls = list(map(str, a.split()))

To:
S, k = input().split()

Sort in advance: the problem requires to output the combinations in lexicographic sorted order. The doc says:

The combination tuples are emitted in lexicographic ordering according
to the order of the input iterable. So, if the input iterable is
sorted, the combination tuples will be produced in sorted order.

So, instead of sorting each combination, it's enough sorting the input S at the beginning and all the combinations will be automatically sorted.

Use the output of itertools.combinations: the output of itertools.combinations is an iterable or tuples, which can be used in a for-loop to print the combinations one by one. The only change is to convert the tuple to a string, and can be done with string.join.

Revised code
from itertools import combinations

S, k = input().split()
S_sorted = ''.join(sorted(S))
for i in range(1, int(k)+1):
    for c in combinations(S_sorted, i):
        print(''.join(c))


Bug

Your computation of last_bits is wrong:

unsigned int last_bits = check_n_bits <= 8 ? check_n_bits : (bytes * 8) - check_n_bits;
last_bits = last_bits == 0 ? 8 : last_bits;

Suppose check_n_bits were 18 as in your example.  This would make bytes 3, and so last_bits would be set to 24 - 18 = 6 instead of 2.  Later, you would check 6 bits in the 3rd byte instead of 2 bits.  This must mean that your unit tests aren't covering enough cases.

Awkward array usage

There are a couple of lines that are really awkward:

sprintf((char *) &tmp_bin_repr, BYTETOBINARYPATTERN, BYTETOBINARY(c));

Here you are casting the address of a character array into a character pointer.  Any time you use a cast, you should think about whether you really need that cast or if you are simply doing something wrong.  In this case, you are doing it wrong.  You can just pass the array like this:

sprintf(tmp_bin_repr, BYTETOBINARYPATTERN, BYTETOBINARY(c));

The second awkward line is this:

tmp_bin_repr_2[j] = *(&(bin_string[i * 8]) + j);

which can be simplified to this:

  tmp_bin_repr_2[j] = bin_string[i*8 + j];

No need for temp copy

Actually I don't think you really even need tmp_bin_repr_2 because all you are doing is making a copy of part of bin_string.  You could just compare with that part of bin_string directly if you modified your call to memcmp().  You can also remove the unnecessary casts as well:

if (memcmp(&tmp_bin_repr[skip_bits_if_last], &bin_string[i*8], bits_to_compare) != 0) {


Instead of trying to match whole lines, it would be simpler to match smaller chunks of the input and the combine the smaller regexes.  For example, one regex could match any of the registers, a different one could match the segment registers, etc.  Order of the patterns may be important if one regex is be a prefix of another, but that doesn't seem to apply in this case.
Use capture groups to get the important information, and MatchObject.lastgroup to see which part of the regex matched.
The flags pattern probably needs to have other codes added.
The (?x) in the pattern is for verbose mode, which lets you add whitespace and comments to the regex pattern.
pattern = r"""(?x)
     (?P<REG>r\w{1,2})=(?P<RVAL>[0-9a-f]{16})            # registers
    |iopl=(?P<IOPL>[0-9a-f]+)                            # iopl
    |(?P<FLAGS>(\s+(?:nv|up|ei|pl|zr|na|po|nc))+)        # flags
    |(?P<SREG>[csdefg]s|efl)=(?P<SVAL>[0-9a-f]+)         # segments
    |(?P<LABEL>^[\w\+]+:)                                # label
    |[0-9a-f]{8}`[0-9a-f]{8}\s+(?P<ENCODING>[0-9a-f]+)\s+(?P<INSTRUCTION>.+)
    |(?P<NL>\n)
    """
regex = re.compile(pattern)

registers = {}

lineno = 1

for line in trace:
    print(f"line = {lineno}")

    for mo in regex.finditer(line):
        group_name = mo.lastgroup

        if group_name == 'NL':
            lineno += 1

        else:
            if group_name == "RVAL":
                registers[mo['REG']] = mo['RVAL']
                print(f"   {mo['REG']} = {mo['RVAL']}")

            elif group_name == "IOPL":
                print(f"   iopl = {mo['IOPL']}")

            elif group_name == "FLAGS":
                print(f"   FLAGS = {mo['FLAGS'].strip().split()}")

            elif group_name == "SVAL":
                print(f"   {mo['SREG']} = {mo['SVAL']}")

            elif group_name == "LABEL":
                print(f"   LABEL = {mo['LABEL']}")

            elif group_name == "INSTRUCTION":
                print(f"   {mo['INSTRUCTION']} = {mo['ENCODING']}")

For the sample input, the code outputs:
line = 1
   rax = 0000000000000000
   rbx = 0000000000000000
   rcx = 0000000000000000
line = 2
   rdx = 0000000000000000
   rsi = 0000000000000000
   rdi = 0000000000000000
line = 3
   rip = 000000000040100a
   rsp = 0000000000000000
   rbp = 0000000000000000
line = 4
   r8 = 0000000000000000
   r9 = 0000000000000000
   r10 = 0000000000000000
line = 5
   r11 = 0000000000000000
   r12 = 0000000000000000
   r13 = 0000000000000000
line = 6
   r14 = 0000000000000000
   r15 = 0000000000000000
line = 7
   iopl = 0
   FLAGS = ['nv', 'up', 'ei', 'pl', 'zr', 'na', 'po', 'nc']
line = 8
   cs = 0033
   ss = 002b
   ds = 002b
   es = 002b
   fs = 0053
   gs = 002b
   efl = 00000246
line = 9
   LABEL = lol+0x1000:
line = 10
   mov rbx,0CE83520306878A4h = 48bba47868302035e80c
line = 11
   rax = 0000000000000000
   rbx = 0000000000000000
   rcx = 0000000000000000
line = 12
   rdx = 0000000000000000
   rsi = 0000000000000000
   rdi = 0000000000000000
line = 13
   rip = 000000000040100a
   rsp = 0000000000000000
   rbp = 0000000000000000
line = 14
   r8 = 0000000000000000
   r9 = 0000000000000000
   r10 = 0000000000000000
line = 15
   r11 = 0000000000000000
   r12 = 0000000000000000
   r13 = 0000000000000000
line = 16
   r14 = 0000000000000000
   r15 = 0000000000000000
line = 17
   iopl = 0
   FLAGS = ['nv', 'up', 'ei', 'pl', 'zr', 'na', 'po', 'nc']
line = 18
   cs = 0033
   ss = 002b
   ds = 002b
   es = 002b
   fs = 0053
   gs = 002b
   efl = 00000246
line = 19
   LABEL = lol+0x1000:
line = 20
   mov rbx,0CE83520306878A4h = 48bba47868302035e80c

Obviously, do something useful instead of just printing the information.


Given req.user is set at the server then, unless your server is compromised, you can ignore the 1%.

Relying on server-side user data is the correct approach - never trust the client.


This is probably the way I would write it:

let stripLast punct word =
  match String.length word with
  | n when n > 0 && word.[n-1] = punct -> word.[..n-2]
  | _ -> word

let countWord (dictionary : Dictionary<_,_>) = function
  | null | "" -> ()
  | word when blacklisted word -> ()
  | word ->
    match dictionary.TryGetValue(word) with
    | true, n -> dictionary.[word] <- n + 1
    | _ -> dictionary.Add(word, 1)

Here's a rundown of the changes:

In stripLast:

Use String.length instead of a type annotation (punct can also be inferred)
Capture the length (which is used multiple times) using pattern matching
Check only the last char (LastIndexOf searches the whole string)
Use string slicing over Substring for conciseness

In countWord:

Allow the type args for Dictionary<_,_> to be inferred
Use pattern matching to clearly show the cases to be handled
Replace calls to ContainsKey and Item ([]) with one call to TryGetValue

A more functional approach, assuming you have a list of words, might be:

words
  |> Seq.countBy (stripLast stripChar)
  |> Seq.filter (fun (word, _) ->
    match word with
    | null | "" -> false
    | _ -> not (blacklisted word))


I don't like the 3 argument return you're doing. You're using status and msg to actually do the same thing. They both return a signal of success unless the dollar is truncated. You don't need both pieces of information. Personally, I'd just say that you only need to print a note about the dollar being truncated so that the function only returns the cents value.

Now, you're also overlooking a very simple formula to convert this:

cents = dollars * 100

You don't need anything more complicated than that for the basic function:

def safe_dollar_to_cent(dollar):
    cents = dollar * 100
    return cents

If you're not sure that dollar will be a number, you can try converting it:

def safe_dollar_to_cent(dollar):
    cents = float(dollar) * 100
    return cents

As for truncating, I think it's better as an option. Let the user choose whether or not something will be truncated:

def safe_dollar_to_cent(dollar, truncate=True):
    cents = float(dollar) * 100
    if truncate:
        return int(cents)
    else:
        return cents

int will turn cents into a whole number instead of a decimal, so it's effectively truncating everything after the ..


Long expression to sum data in a multi-dimensional model

First of all, use helper functions or explicit for loops.

E.g. you're looping over m.tm four times. This can be done in a single loop. It might need more lines of code, but it will get much more readable.

E.g.

def res_stock_total_rule(m, co, co_type):
    if not co in m.co_stock:
        return Constraint.Skip

    val = 0
    for tm in m.tm: # one single loop instead of four
        for p in m.pro_tuples:
            if p[1] == co:
                val += m.e_pro_in[(tm,) + p)]
            if p[2] == co:
                val += m.e_pro_out[(tm,) + p)]
        for s in m.sto_tuples: # one single loop instead of two
            if s[1] == co:
                val += m.e_sto_out[(tm,) + p)] - m.e_sto_in[(tm,) + p)]
    return val <= m.commodity.loc[co, co_type]['max']


Grouping and summing values for food takeout

Scope

If all you need is to calculate some values from a set of data tables, it would suffice to use LINQ. However, if you prefer to provide an API with common functionality concerning orders and order details, you should really create your own domain classes and map the data tables to your domain classes. For the sake of this question, I would opt for using LINQ directly on the data tables.

Review

You are iterating your 3 data tables kassaOrders, orderDetails and menuDetails over and over again with each order detail having a link to a kassa order and each menu detail having a link to a kassa order. We can easily optimize performance and reduce code redundancy by caching these tables in lookup collections.

Lookup Tables

Start by caching the kassa orders in a dictionary by order id (called serial in the orders). This way, fast lookup is possible to join the details.

Data.kassaOrders.AsEnumerable()
    .Where(x => x.Field<bool>("btwticket") &&
          !x.Field<bool>("terugname") && !x.Field<bool>("teruggenomen"))

 var orders = Data.kassaOrders
    .AsEnumerable()
    .Where(x =>
         x.Field<bool>("btwticket") &&
        !x.Field<bool>("terugname") &&
        !x.Field<bool>("teruggenomen"))
    .ToDictionary(order => order.Field<int>("serial"));

We can then use lookup tables - which are dictionaries that store a sequence of values instead of a value - to cache the order and menu details by order id. This code shows how to do it for eating in, equivalent LINQ could be written for take out.

Data.orderDetails.AsEnumerable()
   .Where(d => d.Field<int>("orderid") == x.Field<int>("serial")
       && !d.Field<bool>("takeout"))

 var orderDetailsEatIn = Data.orderDetails
    .Where(order => !order.Field<bool>("takeout"))
    .ToLookup(detail => detail.Field<int>("orderid"));

and

Data.MenuDetails.AsEnumerable()
   .Where(d => d.Field<int>("orderid") == x.Field<int>("orderid"))

var menuDetailsEatIn = Data.MenuDetails
   .Where(order => !order.Field<bool>("takeout"))
   .ToLookup(detail => detail.Field<int>("orderid"));

Calculate Amount

You're calculating the amount using a peculiar GroupBy. There is no reasong to group by the take out variable, because you filter on a specific value right before !d.Field<bool>("takeout"). The call to Distinct also doesn't make sense since details are already grouped by key and keys are distinct anyway.

GroupBy(x => new {
    takeout = x.Field<bool>("takeout"),
    orderid = x.Field<int> ("orderid") }).Distinct().Count();

Using our lookup tables, we can easily calculate the amount as below. To stay within your spec, we count the number of orders that have at least one order detail available. Note that an empty collection is returned orderDetailsEatIn[key] is the key is not present in an ILookup.

 var EatinAmount = orders
    .Select(order => orderDetailsEatIn[order.Key])
    .Count(details => details.Any());

Calculating Total

Your spec is a bit strange to me. I would expect Order 1-->* OrderDetail 1-->* MenuDetail. Instead the cardinality is Order 1-->* OrderDetail, Order 1-->* MenuDetail with the price for each menu detail multiplied by the number of order details to calculate the subtotal by menu detail.

We could calculate the subtotal for the order details as follows:

var subtotalOrderDetailEatIn = orders
    .SelectMany(order => orderDetailsEatIn[order.Key])
    .Select(detail => detail.Field<decimal>("price"))
    .DefaultIfEmpty(0).Sum();

and the subtotal for menu details:

var subtotalMenuDetailEatIn = orders
    .SelectMany(order => orderDetailsEatIn[order.Key]
        .SelectMany(detail => menuDetailsEatIn[order.Key]))
    .Select(detail => detail.Field<decimal>("prijs"))
    .DefaultIfEmpty(0).Sum();

yielding a grant total of:

var TotalEatin = subtotalOrderDetailEatIn + subtotalMenuDetailEatIn;

Note that this is just one possible way to use LINQ to calculate these values from data tables. Other ways could include:

Create intermediate classes, value tuples or domain classes to store strongly typed properties to facilitate querying readability.
A more advanced LINQ approach using GroupJoin to build complex classes given several flattened collections and join selectors.

It's really up to you to see how comfortable you are exploring the realms of LINQ.


Your code looks mostly fine—if you're just performing this specific functionality in one place, some repetition is okay—but there's one thing that could definitely be simplified. Your ready function could be reduced to simply this:

$(document).ready(function () {
    $('#count').click(counter);
    $('#post_body, #post_title').on('change keydown keypress keyup blur focus', counter);
});

If, however, you really wanted to reduce all repetition, you could generalize the counter function until you ended up with a fairly reusable component.

Your counter function currently performs two actions (word counting and character counting) on two separate elements (the body and the title). To make the code as DRY as possible, you should employ the single responsibility principle to break up the function into composable bits.

function countUpdater(element, transformations) {
    return function () {
        var value = element.val();
        transformations.forEach(function (transformation) {
            transformation.display.html(value.length === 0 ? 0 : transformation.counter(value));
        });
    }
}

function wordCounter(value) {
    return value.trim().replace(/\s+/g, ' ').split(' ').length;
}

function characterCounter(value) {
    return value.length;
}

Your event handler code would then become this:

$(document).ready(function () {
    var changeEvents = 'change keydown keypress keyup blur focus';

    var bodyUpdater = countUpdater($('#post_body'), [
        { display: $('#wordCountBody'), counter: wordCounter },
        { display: $('#totalCharsBody'), counter: characterCounter },
    ]);
    var titleUpdater = countUpdater($('#post_title'), [
        { display: $('#wordCountTitle'), counter: wordCounter },
    ]);

    $('#count').click(function () {
        bodyUpdater();
        titleUpdater();
    });
    $('#post_body').on(changeEvents, bodyUpdater);
    $('#post_title').on(changeEvents, titleUpdater);
});

Is that better? Worse? Well, it's certainly less clear, but it's also much more reusable. If you're going to use this type of functionality many times, it might be worth it, but otherwise, I might prefer the simpler, more explicit version.


Extracting top subreddits from an HTML table

Yes, there is a more concise way to do it - using CSS selectors and a list comprehension:

top_subreddits = [
    td.get_text()
    for td in soup.select("tbody tr td")
    if '/r/' in td.text
]

tbody tr td would locate all td elements under tr elements which are under tbody.

I don't really like getting texts of td elements twice here, there is possibly a way to filter the desired information directly. E.g. if you were up to the subreddit links, we could've applied the /r/ check inside a selector:

top_subreddits = [
    a.get_text()
    for a in soup.select('tbody tr td a[href^="/r/"]')
]

^= here means "starts with".


I would suggest the following points to make this programme more object-oriented:

Try using a collection object provided by Java instead of using array

String[] word = userInput.split(" ");

could be

List<String> words = Arrays.asList(userInput.split(" "));

or using external library Guava

List<String> words = Splitter.on(" ").splitToList(userInput);

Avoid comments where you can.

In this case I can see you can easily avoid comment if you can wrap up the particular code snippet with the meaningful name. For instance You could take the user input and breaking it in a list in separate class and call the class from your main

List<String> words = new UserInputHandler().getInputAsList();

Try to use foreach loop over for loop:

You can easily use the foreach loop to iterate over words

for (String word : words) {
    String pigLatinWord = translateWord(word); // Translates each word individually
    output += pigLatinWord + " "; // Joins the translated word back into the output
}

Again as suggested before you can wrap the code inside for loop in a separate class so that you could call

for (String word : words) {
    output = new PigLatinTranslator(word, output).translate();
}


Compile time integer square root for large numbers

Since you're on a C++14 compiler, the simplest solution is just to stick constexpr in front of your runtime algorithm:

template <typename T>
constexpr T rt_square_root(T num)
{
    /* exact same code as before */
}

static_assert( rt_square_root(N_1 * N_1) == N_1, "bad square root" );

I'm not sure there's a compelling reason to do it any other way.


Checking whether any of some large collection of attributes has changed

(In the following, I'm assuming this is a regular ActiveRecord-derived model class, you're dealing with.)

I'd do something like this for a 1st pass (note that I've elided some of the many attribute names in the array):

def bio_updated?
  [:occupation, :date_of_birth, :religion, ...].any? do |attribute|
    __send__(:"#{attribute}_changed?")
  end
end

after which you can just call self.bio_updated?.

A second pass would be add some more declarative way of handling this at the model class level. E.g. implement something that'd let you write:

class SomeModel < ActiveRecord::Base
  # idea is to write something like
  #
  #   tracked_attributes [group name], [array of attributes]
  #
  # to define stuff
  tracked_attributes :bio, [:occupation, :date_of_birth, :religion, ...]
  tracked_attributes :something_else, [...]
end

Which would do some meta-programming magic to give you a bio_updated? method and a something_else_updated? method (like seen above) you can call. (you may want to stick to *_changed? instead of *_updated? to keep to the Rails convention, though you can also argue that it'd be more confusing, since you're dealing with groups of attributes not single ones. Your call.)

There's probably a gem somewhere that does something like this already.

A middle way would be to abstract the any? matching into a generic method, just to stay DRY:

def bio_updated?
  any_attributes_changed? :occupation, :date_of_birth, :religion, ...
end

def something_else_updated?
  any_attributes_changed? ...
end

private

def any_attributes_changed?(*attrs)
  attrs.any? do |attribute|
    __send__(:"#{attribute}_changed?")
  end
end


To your questions:

More options; sure you could provide a wait time to setInterval to control the speed of the scrolling down, you could also increase the scrollTop increment to make it scroll down faster.
Less code; I think this is pretty much the bare minimum, a little too bare really.

I think func and interval are very generic names, I wasnt even sure if the code works / what it does until I clicked the fiddle link.

I would counter propose the following code, it is longer, but far more readable.

var scrollDownInterval;

function scrollDown() {
  document.body.scrollTop++;
}

function startScrollingDown(){
  scrollDownInterval = setInterval( scrollDown );
}

function stopScrollingDown(){
  clearInterval( scrollDownInterval );
}

window.onmouseover = function() {
  stopScrollingDown();
};

window.onmouseout = function() {
  startScrollingDown();
};

//Start scrolling down immediately
startScrollingDown();


Use open in a with

...so that you can be guaranteed of file closure regardless of any potential exceptions.

Use f-strings

So that something like this:

x='Tab_'+str(i)

turns into

x = f'Tab_{i}'

Computers are good at repetition

a.append(random.choice(name)+'_'+str(i))
a.append(random.choice(ssn)+'_'+str(i))
a.append(random.choice(address)+'_'+str(i))
a.append(random.choice(dob)+'_'+str(i))
a.append(random.choice(phone)+'_'+str(i))

can be

a.extend(f'{random.choice(n)}_{i}' for n in (name, ssn, address, dob, phone))

Injection attacks

Unless you're really confident about the source, safety and validity of your data, constructing a string and sending it off as executable SQL is enemy number one of database security. This is what prepared statements are for. It's unclear what flavour of SQL you need, so it's unclear which library you'll need for this.

Combined assignment/increment

count=count+1

can be

count += 1


Divide Logic and User Intereaction

Why should a function to decide if a move is valid print to the screen? What if you want to change the message? Will you look inside a logic function to change a user-interface message?

I like to keep as many as possible of my functions "pure" so that they only make a calculation and return a result and build a thin interaction skin over it.

Long story short, is_move_valid should not print anything.

Simplification

As far as simplification is concerned, you can just flatten the board, and the function becomes:

def is_move_valid(move):
    return flatten(board)[move] not in ("X", "O")


Class for simple python object to be hashed and referenced

The python dictionary assumes that the keys are immutable. It assumes they will not change. That's why mutable classes in python (such as lists) don't hash. Its to prevent you from putting them in dicts which just won't work.

As a result the entire premise of your class is wrong. You shouldn't do that. To follow what python expects, an object should return the same hash and be equal to the same objects throughout its lifetime. If it can't it shouldn't support hashing.

We might be able to suggest a better way to do this, but you'll need to show more of how you want to use this class.


Return path to a value in a nested object

Recursion & JavaScript don't mix.

I am a big fan of recursion, but with JavaScript there are some issues that make recursion a dangerous animal to play with.

Call stack limit

One of JavaScript's limitations, lack of proper tail calls, (ES6 has it slated but there is a world of noncompliance out there) is both a saving grace and a curse.

Consider the object

var cyclic = {me : null};

Your function deals with it and exits. But there are many objects in the JavaScript environment that are self referencing. It is perfectly normal for me to do,

cyclic.me = cyclic;

and your code will thankfully bail with the lovely

RangeError: Maximum call stack size exceeded at Object (native)

This is because there is a limit to the depth of the call stack. It is also why recursion is not always safe. It may be ridiculous in this example but a recursive function can not be said to be safe. You can not know when you will exceed the call stack, especially if you are calling the recursive function innocently from within another recursive function. You can not enforce calling conditions so recursion is really something to be avoided in JavaScript.

As for the cyclic object. You will have to implement a check to ensure you are not chasing your own tail.

So the rest will ignore the fact that you should not be writing recursive code in JavaScript unless you extremely careful.

Some problems

Not so much about recursion, you have the understanding of how they work.

Bad naming. Functions each and isLeaf to findPrimitives and  isPrimitive
It is not immediately clear what the callback function is for, and its return type is a ambiguous. See below for more.
Memory usage. Don't use Array.concat inside recursive code, if you can avoid it. Array.concat creates a new reference to the array, so each step into the recursion you create a new reference that is closed over, effectively creating may similar copies of the same data.
isleaf now isPrimitive is failing. There is a more robust way to test if the current "leaf" is a primitive type. See rewrite at bottom.

The callback function is ambiguous. One of JavaScript's flaws is no way to force a return type for a function. Many people consider undefined == false, and not undefined !== false and would expect that the unspecified return value (functions return undefined by default) to mean false. I would remove the ambiguity and require that the callback function answer the question "Has the object you are looking for been found?" and return true to exit from the recursion"

So by changing the callback return requirement to true to exit early the findPrimitive return value makes more sense.

if(findPrimitives(deep,report) === false){  // did not find what I am looking for

Neither right or wrong.

There are some differing schools of thought as to the use of the let token and the importance of block scope. When I see it being used inconsistently and interchangeably with either const or (in this case) var, I consider that it is not being correctly used and must consider if in fact the author has sound logic for creating block scoped variables or just using a trendy new feature because it is there.
There were many ways to make the function fail, though it is only an exercise, testing is still very important. Bad habits can form and incorrect assumption made when you don't test your experiments to their destruction.
I am not a fan of anonymous functions if they can be avoided as it make debugging so much more difficult. I have seen traces that are just anon calling anon all the way from the top,the only way to trace the actual path is to step out one by one.
For all of us JavaScript programmers it is a time of transition. Some will use ES6 to the full, and others avoid it because of the legacy browsers (Dam you IE for freezing just as ES6 was adopted!). But with ES6 it's in for a penny, in for a pound. You have clearly opted in for ES6 so you should use it to the full. Currently your code is a mixture of ES5 and ES6, being incompatible to ES5 only environments and not getting the full benefit of ES6.

Style

Your style is not horrible, but it's not excellent either.

There are two issues. Your use of let and naming as noted above. And  the following

If you can say that you have never ever had to look for a bug caused by

if(bar){
    if(blah) foo = true;
    boo = false;
}

that was meant to be

if(bar){
    if (blah) {
        foo = true;
        boo = false;
    }
}

then ignore this point. If you have you will know how hard they are to spot, especially when you have masses of complex code. There is one way to avoid this frustration. All conditional statements are blocks and blocks require the embrace of {curlies}. You can still keep the single line space saving style if ( blah ) { foo=true; }

The rewrite.

This was hard to do as I would implement this type of function completely differently. So it is a compromise between your implied requirements (from your code) and my A.D.D. driving me to start it from scratch.

I changed the arguments. Separating out the current object / property name. I keep the same path array reference rather than create a new one each time. I use Object.keys to get an array of property names rather than for(k in obj) I vet for callback function. I vet for obj being a primitive or not having properties. I changed isPrimitive to a more suitable solution.

"use strict"; // make code run quicker and helps catch many potencial bugs
              // that otherwise may go unnoticed until it's to late.
function isPrimitive (val) {
    // typeof null returns object but for this null is a primitive
    return val === null || ["object","function"].indexOf(typeof val) === -1;
}
// added propName as argument. It is the name of the object being examined
// ES6 default argument assignment. Rather than in the function having
// path = path || [] put it in
// the function argument declaration
function findPrimitives (obj, callback, propName, path = []) {
    var keys, name;                 // don't use let if the variables are just one block
                              // in from the function scope on entry and exit.
    if(typeof callback !== "function"){ // no point if there is no callback
        return undefined;     // Return neither true or false as the question
                              // has not been asked.
    }
    if (typeof obj === "object") {
        keys = Object.keys(obj); // As this is ES6 code Object.keys can be used
                                 // to get all the own properties
    } else {
        if( isPrimitive(obj) ) {
            return callback(obj, propName, path);
        }
        return false;
    }
    path.push(propName);
    for(name of keys){
        if (isPrimitive(obj[name]) ) {
            if (callback(obj[name], name, path) === true) {  // explictly true to exit
                return true; // This is early exit not popping values
                             // of the path to keep it intact
            }
        } else {
            if (findPrimitives(obj[name], callback, name,  path)) { // implied true
                return true; // This is early exit not popping values of
                             // the path to keep it intact
            }
        }
    }
    path.pop();  // done with this branch pop it from the path
    return false;
}

and debugging code, is just a quick run test and is not an example of how to test code. It is to help debug and refine the code.

var deep = {
    foo: {
        bar: true
    },
    baz: 2,
    blurg: {
        fop: {
            hif: [],
            hof: /hi/g, // regExp
            now : new Date(),
            what : "String",
            undef : undefined,
            nulls : null,
            nan : NaN,
        }
    },
    verb : function(){return "hi"},
    cur : 10,

};
var cyclic = {}
cyclic.me = cyclic;

function report(value,name,path){  // avoiding anon function for callback
    log(path.join(".")+"."+name + "=" + value + " type ("+(typeof value)+")")
}
findPrimitives(deep,report);
findPrimitives(deep,report,"deep");
findPrimitives(deep,report,"deep",["window"]);

// the following will be inconsistant with expectations
findPrimitives(deep);
findPrimitives("hi");
findPrimitives("hi",report);

// the following will crash and burn....
findPrimitives(cyclic,report);


First, let me review some of of the code you have

public function getTodoList()
{
    return $this->oConnection->query('SELECT * FROM t_todolist')->fetchAll();
}

This is actually all the code you need for this task. Just one line. Thanks PDO being not an ordinary database driver like mysqli. You can check other PDO wonders in my article

There is also one important issue that should be fixed in the controller

public function index($aRequest)
{
    $connection = new Database; // whatever you have to supply a database connection
    $oModel = new todoModel($connection);
    $aTodoList = $oModel->getTodoList();
    return ['type' => 'view', 'view' => 'view/index.tpl', 'data' =>
    ['aTodoList' => $aTodoList]];
}

You may check the above article in order to learn why it is very important to create a database connection only once instead of making each model to create its own.

Now, to the template.

First off, there is absolutely nothing wrong with having some PHP code in a template. PHP is a template language after all, and a good one. All you need is to keep an eye on your template and make sure that all PHP code does in it is actually related to the output only. You can only make it a bit prettier and safer

<?php foreach ($aTodoList as $aTodo): ?>

       <?= htmlspecialchars($aTodo['todo']) ?>
       update
         delete

<?php endforeach ?>

However, to answer your question literally, you will need a dedicated template engine, like Twig. Twig has many good features compared to raw PHP. One of them is autoescaping. There is one critical flaw in your current template, namely

<?php echo $aTodo['todo'];?>

The moment a malicious user will put some bad Javascript in the todo description, your site will be hacked. So you have to escape HTML when echoing a variable.

Unlike PHP, Twig escapes your values automatically, so a code

{% for aTodo in aTodoList %}

        {{ aTodo.todo }}
        update
          delete

{% endfor %}

will be automatically protected from XSS


Is there any flaw in the logic of this problem?

There's no flaw in the logic, just a couple of implementation errors. And if e.g. 1/10 + 1/15 = 1/6 and 1/15 + 1/10 = 1/6 shall not be counted as different solutions but as one, then of course you need (1 + number of divisors)/2.

Here

for(int i=0; prime[i]<=n && i<count; i++)

you ought to check i < count before accessing prime[i]. If n > 999983, you will try to access prime[78498], which is undefined behaviour.

And - assuming that int is as usual 32 bits (or 36, wouldn't apply to 64-bit ints, however) - here

int num_fac_of_factorial(int n, int x)
{
    int p=x, z=0;
    while(n/p>0)
    {
        z+=n/p;
        p*=x;
    }
    return z;
}

you have overflow for large enough primes x (typically > 46340) when calculating x*x, which is also undefined behaviour. And with the not uncommon wrap-around for int overflow, that will cause wrong results for n >= 65537. Replace the while loop with

do {
    n /= x;
    z += n;
while(n > 0);

to avoid the overflow.


Naming

I won't list every bad name but you need to think more carefully about the names you choose.

ID should be Id Microsoft have very specific guidelines for this.

  The two abbreviations that can be used in identifiers are ID and OK. In Pascal-cased identifiers they should appear as Id, and Ok. If used as the first word in a camel-cased identifier, they should appear as id and ok, respectively.

Now on to some more of your names in general:

public int Add(Companionship pC) - What is pC? Full name please. I'd suggest one but I actually haven't been able to figure out what it might mean.

var gda = new USDataAccess(); Again - What is gda? I can't make a suggestion again...

new gDataAccess() - Types should be Pascal case and not start with a prefix.

dtEnd - Don't abbreviate in names - endDate is much more readable.

cDetails - wouldn't companyDetails be easier to read?

To be honest, 80% of your names are less than ideal - it's an easy thing to fix though!

Weirdness

This looks very odd to me:

new Company().Get(clientID)

I'd expect to be able to get a company by id without newing up a Company

Company.GetByClientId(clientId);

Note that would be even better on another class - e.g. CompanyRepository.

What on earth does this do:

new DirectoryGroup().Add(clientID, pC.UserSID, "ChangeMe In Companionship");

You don't use the result so I can only assume this persists something somewhere - that's not obvious at all from the code.

Parsing

This sort of code:

DateTime? dtEnd = string.IsNullOrEmpty(pC.EndDate) ? (DateTime?)null : DateTime.Parse(pC.EndDate);

Is fragile, you might have a string but that's no gauranteee that it's a valid date. You should also specify a culture or a pattern.

Other things

Why are you using public fields? Make them properties.

Why are you returning 1 from your methods? It's C# you don't need to return an exit code. Throw an exception if something goes wrong and if you don't need a return value, set the return type of the method as void.


Question

  But now I'm worried a hacker could do something with the app_name and model_name values.

  Can he crash my server when he manipulate these values? (maybe "ajax-injection" or something like this?)

I'm not sure what the best approach to this would be. Perhaps it would be wise to define a list of the values that are acceptable for a user to pass there, though maybe that wouldn't be sufficient.

Other review points

function vote(bool){

The name bool is not very descriptive. Given that it is used as the value for the voted parameter a name like voted would be more appropriate. And if your code complies with ecmascript-6 standards you could simply write
    voted

in the list of parameters as a shorthand for voted: voted

The success handler looks like this:

success: function(data) {
    if (!data.error){
        if (bool){
            $(".half .fa-thumbs-up").removeClass("far").addClass("fas");
            $(".half #count").text(parseInt($(".half #count").text()) + 1);
        } else {
            $(".half .fa-thumbs-down").removeClass("far").addClass("fas");
            $(".half #count").text(parseInt($(".half #count").text()) - 1);
        }

There is quite a bit of redundancy in both cases. Also parseInt() calls should pass a radix1.

if (!data.error){
    const thumbClass = '.fa-thumbs-' + bool ? 'up' : 'down';
    $(".half " + thumbClass).removeClass("far").addClass("fas");
    const toAdd = bool ? 1 : -1;
    $(".half #count").text(parseInt($(".half #count").text(), 10) + toAdd);

In the vote function in ajax/views.py there is this line:

votedFor = True if request.GET.get("voted") == "true" else False

This could be simplified to just:

votedFor = request.GET.get("voted") == "true"

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Octal_interpretations_with_no_radix