Find the minimum number of operations (concat, add and subtract) for the numbers 1-9 to equal 100 I am beginning to learn Scala and functional programming, and I came across this puzzle.

This looked like good practice and I have a solution but just want some hints in terms of functional approach to this. I did rip off the evaluate function from Stack Overflow.

I particularly am interested in if the approach of creating 3 function and creating a function in the main solve routine is considered a good approach.

def gchq(): Int = {
  def solve(total: String, currentValue: Int, f: (String, Int) => String): Int = {

    val newtotal: String = f(total, currentValue)

    if (currentValue == 9 && evaluate(newtotal.split("\\s").toList) == 100) {
      print("SOLUTION: ")
      println(newtotal + "/" + currentValue)
      1
    }
    else if (currentValue == 9) 0
    else {
      solve(newtotal, currentValue + 1, concat)
      solve(newtotal, currentValue + 1, minus)
      solve(newtotal, currentValue + 1, plus)
    }
  }

  solve("0", 1, concat)
}

def plus(a: String, b: Int): String = {
  a + " + " + b
}

def minus(a: String, b: Int): String = {
  a + " - " + b
}
def concat(a: String, b: Int): String = {
  "" + a + b
}

//this function is taken off stackoverflow
def evaluate(expression: List[String]): Int = expression match {
  case l :: "+" :: r :: rest => evaluate((l.toInt + r.toInt).toString :: rest)
  case l :: "-" :: r :: rest => evaluate((l.toInt - r.toInt).toString :: rest)
  case value :: Nil => value.toInt
}
gchq()

Nesting

Using nested functions is not a bad practice per se, but all depends on the concrete case. Often they are used to enrich the parameters, to share with locally scoped values, or to hide the def from other members of the same object.

In many cases, they are just equivalent of functions with private visibility. But when too much nesting appears, I'd suggest to flatten the things for the sake of readability.

In this example I don't see any special reason to make the function nested. It does not use any of the values available to gchq. Keeping it nested would not be a mistake, but the flat approach seems cleaner:

def gchq2(): Unit = solve("0", 1, concat)

private def solve(total: String,
                  currentValue: Int,
                  f: (String, Int) => String) = ???

Moreover, other referenced functions (plus, minus...) are flat, so all of the pieces are well kept at same level.

Other Considerations

Returned values. The Int return type from gchq() seems suspicious. I hope to understand the meaning (1 for successful result, 0 for no solution found), but the returned values are hugely falsified. solve() will return an Int only from the last call of solve(newtotal, currentValue + 1, plus), the others will remain hidden. Since the solutions are output into the console, I'd suggest to return nothing from solve:

private def solve(total: String, currentValue: Int, f: (String, Int) => String): Unit = ???

Conditinals. There are two checks for currentValue == 9. One should be enough:

if (currentValue == 9) {
  if (evaluate(newtotal.split("\\s").toList) == 100) {
    ...
  }
}
else {
  ...
}

It introduces one more case of nested ifs, but is fully justified here: this is the end condition of the calls sequence, while else adds more recursion.

Naming. Names like gchq or f are awful and should be changed to more meaningful.


Extension method for getting custom Principal Claim I'm writing extension methods to shorten the code required to get custom Claims from an IPrincipal. I have two general forms for the bodies of these methods.

Form 1

public static long? GetFirmId(this IPrincipal principal)
{
    return ((ClaimsPrincipal) principal)?.FindFirst(nameof(User.FirmId)) == null
        ? default(long?)
        : long.TryParse(((ClaimsPrincipal) principal).FindFirst(nameof(User.FirmId)).Value, out var firmId)
            ? firmId
            : default(long?);
}

Form 2

public static long? GetFirmId(this IPrincipal principal)
{
    if (principal == null)
    {
        return default(long?);
    }

    var claim = ((ClaimsPrincipal) principal).FindFirst(nameof(User.FirmId));

    if (claim == null)
    {
        return default(long?);
    }

    if (long.TryParse(claim.Value, out var firmId))
    {
        return firmId;
    }

    return default(long?);
}

Please note that safely casting IPrincipal to ClaimsPrincipal is not necessary as IPrincipal in an ASP.NET Identity application is guaranteed to be a ClaimsPrincipal. I personally like form 1 better due to the brevity. The only thing I'm not super fond of is having to repeat ((ClaimsPrincipal) principal).FindFirst(nameof(User.FirmId)). However, I would say that form 2 is easier to understand for anyone not familiar with modern C# features (or ternary operators, which I have found to be surprisingly unheard of).

ReSharper suggests a middle ground (probably because it isn't sophisticated enough to transcribe form 2 to form 1):

public static long? GetFirmId(this IPrincipal principal)
{
    var claim = ((ClaimsPrincipal) principal)?.FindFirst(nameof(User.FirmId));

    if (claim == null)
    {
        return default(long?);
    }

    return long.TryParse(claim.Value, out var firmId) ? firmId : default(long?);
}

I'm looking for recommendations as to which form is "best," or an alternative suggestion. The project this is from has about ten of these methods for various custom claims of bool, bool?, char, char?, int, int?, long, long? and string. We are using custom claims to prevent needing a database trip (and additional code to make said database trip) to fetch commonly-used  user-specific data.

Sometimes breaking things up into smaller manageable chunks makes them easier to swallow

Break the responsibilities up into more focused concerns.

public static class PrincipalExtension {
    /// <summary>
    /// Retrieves the Firm Id claim if it exists
    /// </summary>
    public static long? GetFirmId(this IPrincipal principal) {
        return long.TryParse(principal.FindFirstOrEmpty(nameof(User.FirmId)), out var firmId)
            ? firmId
            : default(long?);
    }
    /// <summary>
    /// Retrieves the first claim that is matched by the
    /// specified type if it exists, String.Empty otherwise.
    /// </summary>
    public static string FindFirstOrEmpty(this IPrincipal principal, string type) {
        return principal is ClaimsPrincipal p
            ? p.FindFirst(type)?.Value ?? string.Empty
            : string.Empty;
    }
}

FindFirstOrEmpty handles the finding of the claim value if it exists.

This allows the main function to perform its designed role.


Function to remove specified html tags from string I recently wrote this function that, when supplied a string and an array of element types, will remove those element types from the string.

As you could imagine this is a very very simple function, but I wanted to get opinions on speed, functionality, and any other comments anyone can come up with that can improve this function.

<?

    $str = <<<STRING
        Chocolate is very
Chocolate
!
        England is very
City
!
        England is my
city

        England is my
city

        England is my city
        Name

STRING;

    echo htmlentities(removeTags($str, array("b", "div", "span")));

    function removeTags($str, $tags) {

        $tagsString = "";
        foreach($tags as $key => $v) {
            $tagsString .= $key == count($tags)-1 ? $v : "{$v}|";
        }

        $patterns = array("/(<\s*\b({$tagsString})\b[^>]*>)/i", "/(<\/\s*\b({$tagsString})\b\s*>)/i");
        $output = preg_replace($patterns, "", $str);

        return $output;

    }

?>

Alright!  You made me do it.  I'm posting an answer :)

Parsing arbitrary HTML via regular expressions is nearly impossible.  If you were using this on HTML code that you control yourself, it is certainly possible, because you can make sure that all of the edge cases never happen.  However, if you are going to set this loose on arbitrary HTML from the internet, you will find that it fails to work in a number of cases.  Your use case is a little simpler because you are just trying to remove the tags themselves (and not their contents), but even still it can be surprisingly tricky.  You probably need a straight-up HTML parser.  There are a bajillion of them for PHP.  Other than the easy ones I mentioned in my initial comment, here are some more variations that I think will completely sink your current code.  I have actually seen this first one in use on the intertubes: it is technically valid HTML:

Hover me

Another good one: your new regular expression allows for more flexibility in the tag contents at the expense of tag specificity.  In other words, I'm pretty sure that if you use your script to try to remove  tags, you will also end up removing
 tags.

These, and the examples in my initial comment, are some exceptions I came up with just off the top of my head.  In contrast, the internet cumulatively has a bajillion hours experience writing hard-to-parse HTML strings.  Sure, your code might even work 90% of the time, but if you stick with regular expressions it will definitely fail on a regular basis.  It's up to you to decide if the failure rate is low enough.

Especially important: If you are trying to use this as a security tool then definitely don't.  It is nowhere near reliable enough.  Sorry.  It's not that your algorithm isn't well thought out.  It's just that HTML is a full dialect that needs an actual parser: regular expressions just aren't meant for this kind of thing.  It's like trying to build an actual house out of toothpicks.

See this similar question/answer:

Regex to remove inline javascript from string


Automating the install of PostgreSQL from Shell When my Debian server deploys it can run a shell script so I wanted to make one to install postgreSQL, create a role, create two databases and then import a schema into one.

Can anyone please look at this code and tell me if I have done an ok job?

 # POSTGRES
apt-get install -y postgresql
echo "CREATE ROLE deploy LOGIN ENCRYPTED PASSWORD '$APP_DB_PASS';" | sudo -u postgres psql
su postgres -c "createdb db1 --owner deploy"
su postgres -c "createdb db2 --owner deploy"
service postgresql reload

# IMPORT SQL
psql --username=postgres spider < /etc/schema.sql

I recommend using psql -c command for the first invocation of psql, or better yet, just use the createuser command.

For the second invocation, you might want psql -f /etc/schema.sql.  I would also suggest using the --single-transaction flag, so that in the unlikely event of an error, the failure will be blatantly obvious since the spider database will be empty.  (I assume you will also create a database named spider sometime before trying to import data into it.)


Rendering partials dynamically in Rails 3 My User model has multiple roles (utilizing CanCan). Each role's dashboard view is different enough to warrant a partial for each role (admins get big-picture reports of users and app activity, students get big-picture overviews of grades, current courses, and lessons to be taken).

At first I had a case statement to iterate through the views based on current_user.role (of course, that was just temporary, even I know that!). Now, I have this:

<%= render "#{current_user.role}" %>

This doesn't feel right. What's the proper way to dynamically render partials (or maybe this method is perfectly fine)? Also, please mention why the proper way is best, as I want to learn from this.

You can override ActiveModel#to_partial_path if you want - same as how you might override to_param. See the documentation (and be sure to check the source too - they're doing some caching that's elided in the docs, but might be worth looking in to).

Anyway, in your case, you could likely just redefine the method on the User model like so:

# in app/models/user.rb
class User < ActiveRecord::Base
  # ...
  def to_partial_path
    collection = ActiveSupport::Inflector.tableize(self)
    "#{collection}/#{self.role}"
  end
end

This way, you can use render as you would normally. You'll only be doing what Rails is already doing - just a little differently.


How do I reduce lines of code in this piece of code? A number of lines are being repeated in updateProfileFlags and fetchProfileObj This method initiates a new connection with the thrift client and returns a profile object

 private TResume fetchProfileObj(int userId) {
    try{
        TTransport transport = new TSocket("172.XX.X.XXX”, 9311);
        transport.open();
        TProtocol protocol = new  TBinaryProtocol(transport);
        Map<String, String> ids = new HashMap<String, String>();
        ids.put("requestId", "settingsService");
        TResumeService.Client resumeServiceClient = new TResumeService.Client(protocol);
        TResume profileObj = resumeServiceClient.getFullActiveProfileFromUserId(ids, 105, userId, "resman5_1");
        transport.close();
        return profileObj;
    } catch(Exception e) {
        e.printStackTrace();
        return null;
    }
}

This method updates the profile object recieved from the fetchProfile method

private void updateProfileFlags(TResume profile,int recruiterJobAlert) {
    try{
        TTransport transport = new TSocket("172.XX.X.XXX", 9321);
        transport.open();
        TProtocol protocol = new  TBinaryProtocol(transport);
        Map<String, String> ids = new HashMap<String, String>();
        ids.put("requestId", "settingsService");
        TUpdateResume.Client updateResumeClient = new TUpdateResume.Client(protocol);
        profile.getUser().setResdexVisibility(recruiterJobAlert>0?"a":"c");
        updateResumeClient.saveProfile(ids, 105, profile.getProfile(), "now", "resman5_1", null);
        transport.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

Now calling the above methods

public void myTestMethod(){
updateProfileFlags(fetchProfileObj(userId),settings.getRecruiterJobAlert());
}

I am not sure how many lines of code can be reduced but one thing is for sure: whenever you encounter a resource that can be closed, you should use Java try-with-resources feature (since java 7).  Not only this feature saves you the close() operation (one line less!) but also ensures that the resource is properly closed by the end of the try block no matter if it ended successfully or not (the compiler adds a finally clause). in the current code, if an exception is thrown, the Ttransport resource is not closed properly.

I looked at the thrift javadoc and indeed from version 0.10.0, Ttransport is auto-closeable.  So the code on both methods should be

try (TTransport transport = new TSocket("172.XX.X.XXX", 9321)) {
  transport.open();
  ...  // do not call close()!!
  // do not call close()!! it is added by the compiler
} catch(Exception e) {
  e.printStackTrace();
}

Regarding reducing duplicated lines, I can offer that you make a method to create the ids map.  so if the contents of the map need to be modified due to modifications in the requirements or API, there will be only one place to modify them.  creating constant variables instead of embedded literals is also considered best practice.  This can apply to other literals used in the code

public static final String PROFILE_REQUEST_KEY = "requestId";
public static final String PROFILE_REQUEST_VALUE = "settingsService";
public static final int    PROFILE_WHATEVER_105_MEANS = 105;
public static final String PROFILE_WHATEVER_RESMAN5_1_MEANS = "resman5_1";

public Map<String, String> getProfileRequestProperties() {
  return Collections.singletonMap(PROFILE_REQUEST_KEY, PROFILE_REQUEST_VALUE);
}

now, since we eliminated close(), we can return the value direct from the call to the client, eliminating the creation of the profileObj reference:

return resumeServiceClient.getFullActiveProfileFromUserId(
         getProfileRequestProperties(),
         PROFILE_WHATEVER_105_MEANS,
         userId,
         PROFILE_WHATEVER_RESMAN5_1_MEANS);

so, I ma not sure how many LOC are now present, but im my eyes, the code is clearer and more maintainable and extensible.


Nginx-WordPress conf This is how I create am Nginx virtual host for a WordPress webapp. I did best to keep it as minimal as I can while having a working webapp. Please review it:

#!/bin/bash
domain="$1" && test -z "$domain" && exit 2
drt="/var/www/html"

cat <<-EOF > "$s_a/$domain.conf"
    server {
        root ${drt}/${domain};
        server_name ${domain} www.${domain};
        index index.php index.html index.htm;
        location / {
                try_files $uri $uri/ /index.php?q=$uri&$args;
            }
        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
            }
        location ~* \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ {
            expires 365d;
        }
    }
EOF

You are putting your server_name to be $domain and www.$domain. What if, someone puts in www.example.com for the script argument? You will thne be serving www.example.com and www.www.example.com. Instead; replace possible www. from the domain variable.

domain="${domain#www\.}"

Each of your location section has a different indentation. Keep it consistent. Since server section is the root level, you do not need to indent it out. I understand that you are flushing the left indentation from the conf, but I would suggest keeping it, since one might want to peek at them in future, and would like to tweak it?

#!/bin/bash
domain="$1" && test -z "$domain" && exit 2
domain="${domain#www\.}"
drt="/var/www/html"

cat <<EOF > "$s_a/$domain.conf"
server {
    root "${drt}/${domain}";
    server_name ${domain} www.${domain};
    index index.php index.html index.htm;
    location / {
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
    location ~* \.(jpe?g|png|gif|ico|css|js|ttf|woff|pdf)$ {
        expires 365d;
    }
}

EOF


Automated Teller Machine (ATM) implementation in Java I am trying to improve my Java skill, so I wrote a simple ATM program.
I would like a review, to help me make the code more effective.
Main
public static void main(String[] args) {
    ATM a = new ATM("A", "S", 20000);
    Scanner in = new Scanner(System.in);
    while(true){
        System.out.println("Please choose: " + "\n" +
                "1. Deposit" + "\n" + "2. Withdraw" + "\n" + "3. Info" + "\n" + "4. Exit");
        int option = in.nextInt();
        switch (option) {
            case 1:
                System.out.println("How much would you like to Deposit?");
                double depositValue = in.nextDouble();
                a.deposit(depositValue);
                System.out.println("Your current balance is : " + a.getBalance() + "\n") ;
                break;

            case 2:
                System.out.println("How much would you like to Withdraw?");
                double withdrawValue = in.nextDouble();
                a.withdraw(withdrawValue);
                break;

            case 3:
                System.out.println(a.toString() + "\n" );
                break;

            case 4:
           System.exit(0);

        }
    }

}

ATM
private String name;
private String lastName;
private double balance;

public ATM(String name, String lastName, double balance) {
    this.balance = balance;
    this.lastName = lastName;
    this.name = name;
}

public String getName(){
    return this.name;
}

public String getLastName(){
    return this.lastName;
}

public double getBalance(){
    return this.balance;
}

public void setBalance(int newValue){
    this.balance = newValue;
}

public void deposit(double value){
    balance += value;
}

public void withdraw(double value){
    if(value > balance){
        System.out.println("You can't withdraw that amount of money." +"\n"+ "Your balance is: " + getBalance() + "\n");
    } else {
        balance -= value;
        System.out.println("You withdraw " + value +"from your account!" + "\n");
    }
}
public String toString(){
    return "First name: " + getName() +"\n" + "Last name: " + getLastName() + "\n" + "Your balance: " +getBalance();
}

This is fairly good for a program in this category for being well formatted and having variable names that mostly make sense. I.e. I have no trouble figuring out what the code tries to do.
ATM a = new ATM("A", "S", 20000);

Here you create an ATM with a name and balance. If you think about what an ATM does, this does not reflect real life. ATM's have a balance as in how much money they contain but they do not have a first and last name. You may have been thinking of a BankAccount when implementing the code. This is supported by the code not having a step where the user tells the machine who they are and what account to access. But then again, bank accounts are identified by account number, not by the account owner name.
System.out.println("Please choose: " + "\n" +
    "1. Deposit" + "\n" + "2. Withdraw" + "\n" + "3. Info" + "\n" + "4. Exit");

This is just hard to read and maintain. In these situations I prefer reflecting the end result in the formatting so that the intended output is more clear.
System.out.println("Please choose:\n" +
    "1. Deposit\n" +
    "2. Withdraw\n" +
    "3. Info\n" +
    "4. Exit");

Now it is also instantly clear to the code maintainer what the valid input options are.
int option = in.nextInt();

Because you have not written any error handling, your program will show an ugly error message to the user and it will immediately exit if they make a wrong choice, such as enterin a letter instead of a number.
switch (option) {
    ....

Switch statements should always have a default-case. This is especially important as you are handling user input.
    default:
        System.err.println("Invalid input " + option + ". Please choose a value between 1 and 4.");
        break;

This also holds true if the swich handles an enumeration and you have handled all the cases because a change to the enumeration might add a new value and your code would then be unable to handle it. In such cases the default case should throw an IllegalArgumentException with a message describing the problem.
case 4:
    System.exit(0);

It is pretty much never Ok to exit from a Java program using System.exit(int). It's akin to pulling the power cord from the computer to exit. It exits your program but also takes out everything else that might have been running in the JVM. In this case the correct choice would be to set the loop condition in the while-loop to false.
boolean exitRequested = false;
while (! exitRequested) {
    ...
    switch (option) {
    ...
    case 4:
        exitRequested = true;
        break;
    }
}

Now that you have a variable controlling the exit, you can use it to search for the code that makes the program exit. This is a useful feature when the programs that you work with are larger.
public ATM(String name, String lastName, double balance) {

Money should never be handled using floating point numbers. Use either integers and divide the result with 100 to obtain euros and cents or use BigDecimal. For classroom code we can let it pass, but it's really not a good idea to learn that habit. I have seen it in production and it is neither nice to fix the issues nor explain to customers why our software stole a cent of their money.
public void withdraw(double value){
    if(value > balance){
        System.out.println("You can't withdraw that amount of money." +"\n"+ "Your balance is: " + getBalance() + "\n");

You've placed a user interface inside the ATM class (if we call it "BankAccount", it might be more obvious why this is a bad idea, bank accounts don't have a user interface). Instead of placing error messages in the withdraw method, you should throw an exception that describes the error and let the user interface code in your main class to decide what message to show to the user.


Single instance of reusable HttpClient I've got this method and I realize that an instance of HttpClass is going to be created for each call to it. While working seemingly OK, I'm considering moving it out and placing it as a private property accessible to each call to the method. There might be other methods making use of it in the future as well. I have no information on how often these calls will occur. (There's a try/catch too but it's omitted for brevity's sake.)

[OperationContract]
[WebGet(UriTemplate = "Poof"]
public async Task<String> GetPoof()
{
  String url = BaseUrl + "poofy";
  using (HttpClient client = new HttpClient())
  {
    client.DefaultRequestHeaders.TryAddWithoutValidation(
      "Authorization", GetAuthorizationSchema());
    HttpResponseMessage message = await client.GetAsync(url);
    return await message.Content.ReadAsStringAsync();
  }
}

What I'm thinking of is something like this:

private HttpClient _Client
private HttpClient Client { get { return _Client ?? GetNewClient(); } }

[OperationContract]
[WebGet(UriTemplate = "Poof"]
public async Task<String> GetPoof()
{
  String url = BaseUrl + "poofy";
  HttpResponseMessage message = await client.GetAsync(url);
  return await message.Content.ReadAsStringAsync();
}

My worry is, though, that the different calls utilizing the same client instance will somehow collide and call huge issues later on, especially if the number of calls per time unit raises beyond a critical level. Should I be worried?

You don't need multiple instances. In fact, HttpClient is designed specifically to persist and be used for multiple requests (see: HttpClient.DefaultRequestHeaders).

There's already a lot written about this so I'll redirect you to those resources:

Do HttpClient and HttpClientHandler have to be disposed?
Is HttpClient safe to use concurrently?
What is the overhead of creating a new HttpClient per call in a WebAPI client?


Calculating the connectance of a matrix iteratively I have a performance issue in R. I have a function that iterates over a dataframe for different levels of "site" and "method". The function samples 1:1000 interactions (rows), converts these to matrices and calculates a value of connectance for each matrix. This is repeated n times. The function runs exactly as I want it, returning a dataframe with connectance values for 1 to 1000 interactions when repeated a small number of times. The problem is when I increase the number of repetitions (say to 100) the function runs progressively slower.

df <- read.table(text = "bird_sp plant_sp value site method
                    1  species_a  plant_a     1    a      m
                    2  species_a  plant_a     1    a      m
                    3  species_b  plant_b     1    a      m
                    4  species_b  plant_b     1    a      m
                    5  species_c  plant_c     1    a      m
                    6  species_a  plant_a     1    b      m
                    7  species_a  plant_a     1    b      m
                    8  species_b  plant_b     1    b      m
                    9  species_b  plant_b     1    b      m
                    10 species_c  plant_c     1    b      m
                    11 species_a  plant_a     1    a      f
                    12 species_a  plant_a     1    a      f
                    13 species_b  plant_b     1    a      f
                    14 species_b  plant_b     1    a      f
                    15 species_c  plant_c     1    a      f
                    16 species_a  plant_a     1    b      f
                    17 species_a  plant_a     1    b      f
                    18 species_b  plant_b     1    b      f
                    19 species_b  plant_b     1    b      f
                    20 species_c  plant_c     1    b      f", header = TRUE)

xDegrees <-function(df, size, numRep){

  #Loading required library
  require(bipartite)

  #Creating vector of unique combinations
  df <- within(df, {SiteMethod <- paste(site, method, sep = ":")})

  #Creating empty dataframe
  connectMatrix <- as.data.frame(matrix(rep(0,4), ncol = 4))
  colnames(connectMatrix) <- c("Site","Method","Size","connectance")

  #Beginning of matrix
  k <- 1

  #Beginning subsetting loop
  for(i in 1:length(unique(df$SiteMethod))){

  #subsetting dataset
  dfSub <- subset(df, SiteMethod == unique(df$SiteMethod)[i])

  #Storing site for matrix
  site <- as.character(dfSub[1,]$site)

  #Storing method for matrix
  method <- as.character(dfSub[1,]$method)

  for(l in 1:numRep){
    #Beginning calculation loop
    for(j in 1:length(size)){

    #show progress
    print(paste("S:M", i,j , "completed", sep = " "))

    #The size being calculated
    subSize <- size[j]

    #generate random samples and convert to matrices
    rows <- sample(1:nrow(dfSub), subSize, replace=T)
    intlist <- dfSub[rows,]
    mat <- with(intlist, tapply(value, list(plant_sp, bird_sp), sum))
    mat[is.na(mat)] <- 0

    #network level function to calculate connectance
    con <- networklevel(mat,  index = c("connectance"))

    #Stitch matrix together
    connectMatrix[k,] <- c(site, method, subSize, con)

    #Update row
    k <- k + 1
      }
    }
  }

#Return complete matrix
return(connectMatrix)

}

#run the function. 1:1000 interactions, 100 reps
stuff <- xDegrees(df, size = 1:1000, numRep = 100)

Any ideas on how to speed this up?

Without installing bipartite and getting into the exact details of what the actual calculations are looking to do, there are a few things that jump out at me that might help you.

Growing the Object (connectMatrix)

It looks like you're in Circle 2 - Growing Objects of the R Inferno.
Specifically, the line where you've got:

#Stitch matrix together
connectMatrix[k,] <- c(site, method, subSize, con)

In that scenario, every time you add another row to the connectMatrix, you're expanding and fragmenting the memory you're using, which as you've observed starts out okay but then starts to really drag. Here's another resource on that same issue, and a much less intricate Stack Overflow question.

nested for loops

You've got three layers of nested for loops

for(i in 1:length(unique(df$SiteMethod))){

    #subsetting dataset
    ...
    ...
    ...

    for(l in 1:numRep){
        #Beginning calculation loop
        for(j in 1:length(size)){

        ...
        ...

        }
    }

The outside for loop jumps out at me as something the plyr package might be good for -- essentially it looks like you're splitting the main dataframe into subsets, then doing things to it (the meat of your second and third for loops). Basically, plyr was designed for splitting-applying-and combining, and there's a really great paper on how to implement it.

You may be able to do two (or maybe even three) layers of splitting-applying-combining.

If the data lend themselves to grouping operations, those tend to help, too, but it doesn't seem like it based on the comments in the code.

Parallel processing

If, after you've optimized for not growing the object and chunked the code for splitting/combining (or another method of getting to the same outcome), you're still not at the level of performance you're looking for, you can journey into parallel application.

Basically, parallel application works well when you're using apply or plyr approaches and you can convert over to mcmapply or one of the other parallel approaches.

For example, we use mcmapply in production at work to take a 30 minute process and trim it down to about 6 minutes. Parallel processing tends to be worth it (in my personal experience) only once you've done everything else you can to get to the best speed you can without parallelizing - it tends to be more work to get it right, and, as a bonus, once you've done the other things it tends to make it easier to convert the process to run on multiple cores.

Finally, Efficient R is a good general resource on optimizing R processes.


XML format for game data I want to create an XML format in which I will define data objects for a game I am currently working on.

The base idea is that I will have Elements which can be combined in other Elements, Items or Spells.

A primal element is an element which is directly available.
If an element is not primal then in order to create it, it must be combined from other elements so it will have a recipe definition (list of components required to combine in order to create the specific entity).

Items and Spells also need to have a recipe.

As of now I created the sample XML:

<TechTree>

    <ElementDefinitions>
        <Element name="Fire" primal="true"/>
        <Element name="Earth" primal="true"/>
        <Element name="Nature" primal="true"/>
        <Element name="Mana" primal="true"/>

        <Element name="Lava">
            <Component>Fire</Component>
            <Component>Fire</Component>
            <Component>Earth</Component>
        </Element>

        <Element name="Grass">
            <Component>Nature</Component>
            <Component>Mana</Component>
            <Component>Earth</Component>
        </Element>

    </ElementDefinitions>

    <ItemDefinitions>
        <Item name="ManaPotion">
            <Component>Mana</Component>
            <Component>Grass</Component>
            <Component>Nature</Component>
        </Item>
    </ItemDefinitions>

    <SpellDefinitions>
        <Spell name="FireSpell">
            <Component>Fire</Component>
            <Component>Fire</Component>
            <Component>Mana</Component>
        </Spell>

        <Spell name="HealingSpell">
            <Component>Nature</Component>
            <Component>Nature</Component>
            <Component>Mana</Component>
        </Spell>

        <Spell name="MoltenArmor" selection="ordered">
            <Component>Lava</Component>
            <Component>Nature</Component>
            <Component>Mana</Component>
        </Spell>

        <Spell name="RestoreMana">
            <Component>Mana</Component>
            <Component>Mana</Component>
            <Component>Mana</Component>
        </Spell>

    </SpellDefinitions>

</TechTree>

As of now there aren't too many attributes, but in the future the entities will have all kind of attributes (damage, effect, usable conditions etc) so I need to have a format that would allow me to extend, for instance, all items but not spells or elements.

I will enforce with an XML schema that components used in the recipe must be already defined. So writing Air as a component without firstly defining it will yield an error.

Although as of now all recipes have 3 elements in the future I might decide to create some with a different number.

I would greatly appreciate feedback or tips on how can I improve the format.

I'd wrap the <Component>s in a <Components> tag. Maybe you want to add more attributes to spells later. In fact, I'd probably make <ItemComponents> and <SpellComponents>.

I'm also thinking you might be better off here and there by using some sort of "quantity". Lets say a spell had 10 components (for some arbitrary game design reason)...

    <Spell name="RestoreMana">
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
    </Spell>

or

    <Spell name="RestoreMana">
        <Component quantity="10">Mana</Component>
    </Spell>

I like the second one more, it's smaller. Plus, I don't wanna be the one who has to check if the balancing is done right by counting whether this spell has 10 components via a process which includes manually counting lines.

From this point, however, you can go pretty much everywhere. Future proofing your schema is hard without fully knowing what data it will have to support, so I'd focus on getting the domain model right and then looking at the xml schema again.


Driving 7-segment displays I made a little JavaScript app here that let people generate bitmap for generating characters. Currently it generate code of a dictionary. But I want to also generate a example that let them play like the Arduino samples, use it as starting point or use it as-is.

This is the code I wrote to enable someone to use 7-segment displays

I want some feedback on the code itself also things like suggestions for variable and function names, order of things, aesthetics etc...

//common cathode turns on with HIGH, and common anode turns on with LOW
const bool LED_P HIGH

const uint8_t myDisplayPins[8] = {3, 4, 5, 6, 7, 8, 9, 10}; //dp A B C D E F G

byte font[] = {
    B1111110,   // [0] => "0"
    B0110000,   // [1] => "1"
    B1101101,   // [2] => "2"
    B1111001,   // [3] => "3"
    B0110011,   // [4] => "4"
    B1011011,   // [5] => "5"
    B1011111,   // [6] => "6"
    B1110000,   // [7] => "7"
    B1111111,   // [8] => "8"
    B1111011,   // [9] => "9"
    B1110111,   // [10] => "A"
    B0000001,   // [11] => "dash"
};

void setup(){
    display7Setup(myDisplayPins); //configure myDisplayPins as outputs
}

void loop(){

  display7(myDisplayPins, font[0]); //display "0"
  delay(1000);
  display7(myDisplayPins, font[9]); //display "A"
  delay(1000);
  display7(myDisplayPins, font[11]); //display "-"
  delay(1000);
  display7(myDisplayPins, B00000000); //turn all segments OFF
  delay(1000);

  //count 0 to 9
  for(int i=0; i<=9; i++){
    display7(myDisplayPins, font[i]);
    delay(1000);
  }

}

/* Configure pins as outputs */
void display7Setup(const uint8_t displayPins[]){
  for(uint8_t i=0; i<8; ++i){
    pinMode(displayPins[i], OUTPUT);
  }
}

/* Function that writes a bitmap to a 7-segment display */
void display7(const uint8_t displayPins[], byte bitmap){
  for(uint8_t i=0; i<8; ++i){
    byte segment = bitmap & (0x1<<i); //apply a mask to select just the desired segment bit
    bool state = segment>>i;          //shift the bit to LSF (rightmost) to get a boolean value 0x1 or 0x0
    if(!LEDP) state = !state;         //invert level for common anode
    digitalWrite(displayPins[i], state);
  }
}

I would rename loop to demo.
The spec says that the value argument to digitalWrite may only be HIGH or LOW, and it doesn't spell out their bit representations. Even though your code works (I presume), it is better to stick with the spec.
LEDP never changes. You don't have to invert each individual bit in the loop. It looks better to invert the whole bitmap at once:

if (LEDP == LOW) {
    bitmap ^= 0xff;
}

Now the body of display7 loop could be streamlined to

for (uint8_t i=0; i<8; ++i) {
    digitalWrite(displayPins[i], (bitmap & 0x01)? HIGH: LOW);
    bitmap >>= 1;
}

Notice that segment and state disappear altogether.


Algorithm to say if win or lose using player's rating and randomness I wrote a small simulator to understand the Elo rating system. I can create players, matches and tournaments, and I want to be able to predict the match ending depending on the rating of each player and some randomness. At the beginning the ratings are all around the same values (say 600) and it appears to stay between 400 and 1600. This is what I've tried :

p1 and p2 are instances of Player, rating is an integer attribute.

def random_win(self):
    q = float(self.p2.rating)/float(self.p1.rating)
    if q>2:
        self.win_2()
    elif q<0.5:
        self.win_1()
    else:
        d = float(self.p2.rating)-float(self.p1.rating)
        lim = max(self.p1.rating, self.p2.rating)/2
        r = random.randint(-lim, lim)
        if r > d:
            self.win_1()
        else:
            self.win_2()

I'd like to know if there are some "official" ways of doing this, this custom one works quite fine but I think it can be improved or at least simplified. Any ideas ? The best would be to get something closer the World Chess Ratings.

Once the wins and losses calculated and stored into the Player as a list attribute, I calculate the new rating for each player using this algorithm.

World Chess Ratings are going to be skewed: people that lose are less likely to play than people who win, so it's quite possible that everyone who went to a single tournament and got wrecked is not going to play in tournaments anymore. And Elo is a measurement of skill, not skill itself, so of course it won't go past a certain value. A good chess player who played 1 competitive match has a lower rating than his playing strength. So even though his rating is lower, he'll win more than his rating suggests, that's why his rating goes up.

As such, your simulation is going to keep giving skewed results until you give each player a "skill" attribute which determines their real playing strength. That means each player would have a rating (which starts at 1000) and a skill (which starts at a randomized value between 0 and 2500 or so, where the distribution is, say, Gaussian), and where you used to compare rating, you compare skill instead. This should give you a more realistic simulation of Elo rating, but you'll still be assuming that players all play equally as much (which is not the case in real life).


Stack implementation with singly linked list The following is my implementation of a stack using a linked list.

class EmptyStackError(Exception):
    def __init__(self):
        super().__init__("Stack is empty: Invalid Operation!")

class LinkedList:
    class _Node:
        def __init__(self, data, next_node=None):
            self.data = data
            self.next_node = next_node

    def __init__(self):
        self._head = None
        self._tail = None

    def add_first(self, data):
        """ Add data to the beginning of the linked list"""
        node = self._Node(data)
        if not self._head and not self._head:
            self._head = self._tail = node
            return
        node.next_node = self._head
        self._head = node

    def add_last(self, data):
        """ Add data to the end of the linked list """
        node = self._Node(data)
        if not self._head and not self._tail:
            self._head = self._tail = node
            return
        self._tail.next_node = node
        self._tail = node

    def remove_last(self):
        """ Remove the last element in the linked list """
        if not self._head and not self._tail:  # if linked list is empty
            raise EmptyStackError
        elif self._head is self._tail:  # if only one element
            data = self._head.data  # or data of tail
            self._head = self._tail = None
            return data
        data = self._tail.data
        current = self._head
        while current.next_node.next_node:
            current = current.next_node
        current.next_node = None
        self._tail = current
        return data

    def remove_first(self):
        """ Remove the first element in the linked list """
        if not self._head and not self._tail:  # if linked list is empty
            raise EmptyStackError
        elif self._head is self._tail:  # if only one element
            data = self._head.data
            self._head = self._tail = None
            return data
        data = self._head.data
        self._head = self._head.next_node
        return data

    def __str__(self):
        if not self._head and not self._tail:
            return "Stack is empty!!"
        items = []
        current = self._head
        while current:
            items.append(current.data)
            current = current.next_node
        return " ".join([str(i) for i in items])

class Stack:
    """ A stack implementation using a linked list

    Note: The reason add_first and remove_first are using for push and pop respectively is to keep them O(1).
          If adding and removing last were used, then remove last would O(n).
          This is because deleting the tail would require the traversal of the linked list to delete the last element.
    """
    def __init__(self):
        self.items = LinkedList()

    def push(self, data):
        self.items.add_first(data)

    def pop(self):
        data = self.items.remove_first()
        return data

    def peek(self):
        data = self.items.remove_first()
        self.items.add_first(data)
        return data

    def __str__(self):
        string = self.items.__str__()
        return string

Is there anything I need to improve? whether it's style or logic.

Can you find any bugs? Whether in the linked list or the stack.

My basic tests:

import pytest

def test_push():
    """ This is depending on another method """
    stack = Stack()
    stack.push(5)
    assert stack.peek() == 5

def test_pop():
    stack = Stack()
    stack.push(5)
    data = stack.pop()
    assert data == 5

def test_empty_pop():
    stack = Stack()
    with pytest.raises(EmptyStackError):
        stack.pop()

def test_peek():
    stack = Stack()
    stack.push(5)
    assert stack.peek() == 5

def test_empty_peek():
    stack = Stack()
    with pytest.raises(EmptyStackError):
        stack.peek()

test_push()
test_pop()
test_empty_pop()
test_peek()
test_empty_peek()

You have a typo/mistake in if not self._head and not self._head, I think you wanted to write self._tail in one of them.
I do not see the interest of making Node() inner to LinkedList(). In opposite, doing so condemns you not to reuse the Node() code and slaughters your code scalability (in case you will need to add functionality to your code by implementing a queue, for example)
You can refactor this code into one function and call it when necessary:

if not self._head and not self._head:
    self._head = self._tail = node
    return

While it apparently does the job, the return statement of your code in (3) is not in the right place. You should remove it and use the if ... else statements instead because this makes sense and that is what the reader of your code may expect.
Here, we can use more common sense: if not self._head and not self._tail: honestly, if the head is None, it must be obvious the tail is in the same condition. I mean you can replace similar lines to simply: if not self._head
You said you want to code a stack: by definition, in a stack, we need only a pointer to its head. The head is the tail, and the tail is the head because that is where operations occur.
Do not code what you do not need: it is unnecessary to use add_last() and remove_last(). Why? Because you are coding a stack, and a stack follows the principle of LIFO, so do not care  about the other end at all. In a stack, we need to perform the push and pop operations; at best, we would like to know its size, everything else does not belong to the stack notion.
The points (6) and (7) are a gentle introduction to what I will tell you here: you misunderstood the stack implementation: we can implement a stack using an array or a simple linked list. You chose the later one but you misunderstood it because you lost yourself in  implementing a linked list and you ended up by missing the notion of the stack.

If you carefully read this section, for example, you will understand that stack implementation using linked lists does not require you to implement a linked list and its different operations but simply having a data structure which looks like a node that belongs to a linked list, and by designing the pop and push operations, your stack will look, by default, as a singly linked a list. So based on your code, let me share with you the right way to implement a stack based on linked lists:

class EmptyStack(Exception):
    def __init__(self):
        super().__init__('Stack is empty: invalid operation!')

class Node:

    def __init__(self):
        self.data = None
        self.next = None

class Stack:

    def __init__(self):
        self.head = None
        self.size = 0

    def get_size(self):
        return self.size

    def push(self, item):
        self.node = Node()
        self.node.data = item
        self.node.next = self.head
        self.head = self.node
        self.size += 1

    def pop(self):
        if self.head == None:
            raise EmptyStack
        self.head_item = self.head.data
        self.head = self.head.next
        self.size -= 1
        return self.head_item

if __name__ == '__main__':
    stack = Stack()
    for i in range(10):
        stack.push(i)
    print('size: {}'.format(stack.get_size()))
    print(stack.pop())
    print(stack.get_size())


Year with the most living (given a list of births and deaths) I am trying to find the year most people are alive, given a list of births and deaths.  I am not sure my approach is optimal or if am calculating the time complexity correctly

Break down:
I sort the dates
O(n log n)
I walk the dates in order
O(b + n log n)

Hashing the births, because they pivot the shifts between the number of living from those already dead. Since a birth year will be the year in which most people lived.

I am also pushing the deaths into a common array.

I then loop over the deaths
O(n^2 + n log n)

grabbing the count of those deceased and subtracting that from those still alive, and resting the array with those still alive on every iteration.

finally, I loop over the hash results to get the highest result.
with a final time complexity after dropping all constants

O(n+m) or O(n^2)

const people = [{ birth: 1720, death: 1860 },{ birth: 1720, death: 1860 },{ birth:1803, death: 1809},{ birth: 1730, death: 1810 },{ birth: 1920, death: 1950 },{ birth: 1930, death: 1940 },{ birth: 1940, death: 1990 }, { birth: 1970, death: 2010 }]
function yearMaxAlive(people) {
  people.sort((a, b) => a.birth - b.birth)
  let high = {
      year: 0,
      count: 0
    },
    alive = 0,
    survivors = [];
  for (let [year, count] of Object.entries(people.reduce((deaths => (ledger, year) => {
      if (ledger[year.birth]) {
        alive++
        ledger[year.birth].alive = alive
      } else if (!ledger[year.birth]) {
        if (deaths.length > 0) {
          let deleted = deaths.filter((a, i, aa) => {
            if (a <= year.birth) {
              return true
            } else {
              survivors.push(a)
              return false
            }
          })
          deaths = survivors
          survivors = []
          alive = alive - deleted.length
          alive++
          ledger[year.birth] = {
            alive: alive,
            deaths: deaths
          }
        } else {
          alive++
          ledger[year.birth] = {
            alive: alive,
            deaths: deaths
          }
        }
      }
      deaths.push(year.death)
      return ledger
    })([]), {}))) {
    if (high.count < count.alive) {
      high = {
        year: year,
        count: count.alive
      }
    }
  }
  return high
}

console.log(yearMaxAlive(people))

The optimal algorithm is about O(n) to generate the count changes per year (and optionally get the first and last year), and about O(m) for enumerating them to find the first year with highest count (where m is preferably the number of years from the first to last year).

var people = [{ birth: 1720, death: 1860 },{ birth: 1720, death: 1860 },{ birth:1803, death: 1809},{ birth: 1730, death: 1810 },{ birth: 1920, death: 1950 },{ birth: 1930, death: 1940 },{ birth: 1940, death: 1990 }, { birth: 1970, death: 2010 }];

var counts = people.reduce((a, v) => (a[v.birth] = (a[v.birth] | 0) + 1,
                                      a[v.death] = (a[v.death] | 0) - 1, a), []);

var maxYear = 0, maxCount = 0, count = 0;
counts.forEach((c, y) => {
  count += c;
  if (maxCount < count) {
    maxCount = count;
    maxYear = y;
  }
});

console.log( maxYear, maxCount );
console.log( { ...counts } );

The above is just a sample, and can be much more efficient with for(;;) loops and starting the second loop from the first year 1720 instead of 0. The count changes can be in either object {} or Array object [] as long as they are enumerated in order from low to high.


Print the Twelve Days of Christmas without loops or conditionals For my AP Computer Science class, I am required to write a program that prints the Twelve Days of Christmas without loops or conditionals using static methods.

public class TwelveDaysOfChristmas {

    public static final String[] lines = new String[] {
        "A partridge in a pear tree",
        "Two turtle doves and",
        "Three French Hens,",
        "Four calling birds",
        "Five golden rings.",
        "Six geese a-laying,",
        "Seven swans a-swimming,",
        "Eight maids a-milking,",
        "Nine ladies dancing,",
        "Ten lords a-leaping,",
        "Eleven Pipers piping,",
        "Twelve drummers drumming,"
    };

    public static final String[] days = new String[] {
        "first",
        "second",
        "third",
        "fourth",
        "fifth",
        "sixth",
        "seventh",
        "eighth",
        "ninth",
        "tenth",
        "eleventh",
        "twelfth"
    };

    public static final String verseText =
        "On the %s day of Christmas,\n" +
        "My true love sent to me\n" +
        "%s";

    public static void main(String[] args) {
        //Print the song
        System.out.println(song());
    }

    public static String song() {
        //The song consists of all verses up to verse 12, but the index starts from 0
        //Print verses 0 to 11
        return versesBelow(11);
    }

    public static String versesBelow(int verse) {
        //Evil hack that allows me to check whether the input is zero without using a conditional ;)
        try {
            //Divide by verse. If the verse is zero, then an ArithmeticException is thrown.
            //I am not using a conditional here!!!
            int i = 1 / verse;
        }
        catch(ArithmeticException ex) {
            //Stop the recursion
            return verse(verse);
        }
        //else return this verse and all the verses below this one.
        return versesBelow(verse - 1) + verse(verse);
    }

    public static String verse(int verse) {
        //Format the string with the correct day and verse and add a newline for a blank space after
        return String.format(verseText, days[verse], linesBelow(verse)) + '\n';
    }

    public static String linesBelow(int line) {
        //Same evil hack
        try {
            int i = 1 / line;
        }
        catch(ArithmeticException ex) {
            //Stop the recursion if line is zero
            return line(line);
        }
        //Else return this line and all the lines below this line
        return line(line) + linesBelow(line - 1);
    }

    public static String line(int line) {
        //Return this line and a newline
        return lines[line] + '\n';
    }
}

Is there a better way to accomplish this than my way? I do kind of cheat a little, but it's not technically a conditional, is it?

Recursion is something that is often "unwrapped" to become loops, but the same is true, in the other direction. Almost all loops can be implemented as recursion.

Using your "trick" of throwing an exception to act as a conditional, it would be simple to turn all your code... this code:

public static final String verseText =
    "On the %s day of Christmas,\n" +
    "My true love sent to me\n" +
    "%s";

public static void main(String[] args) {
    //Print the song
    System.out.println(song());
}

public static String song() {
    //The song consists of all verses up to verse 12, but the index starts from 0
    //Print verses 0 to 11
    return versesBelow(11);
}

public static String versesBelow(int verse) {
    //Evil hack that allows me to check whether the input is zero without using a conditional ;)
    try {
        //Divide by verse. If the verse is zero, then an ArithmeticException is thrown.
        //I am not using a conditional here!!!
        int i = 1 / verse;
    }
    catch(ArithmeticException ex) {
        //Stop the recursion
        return verse(verse);
    }
    //else return this verse and all the verses below this one.
    return versesBelow(verse - 1) + verse(verse);
}

public static String verse(int verse) {
    //Format the string with the correct day and verse and add a newline for a blank space after
    return String.format(verseText, days[verse], linesBelow(verse)) + '\n';
}

public static String linesBelow(int line) {
    //Same evil hack
    try {
        int i = 1 / line;
    }
    catch(ArithmeticException ex) {
        //Stop the recursion if line is zero
        return line(line);
    }
    //Else return this line and all the lines below this line
    return line(line) + linesBelow(line - 1);
}

public static String line(int line) {
    //Return this line and a newline
    return lines[line] + '\n';
}

in to just:

public static void main(String[] args) {
    try {
        recurseDown(0);
    } catch (RuntimeException e) {
        // nothing.
    }
}

private static void recurseDown(int i) {
    System.out.println("\nOn the " + days[i] + " day of Christmas\nMy true love sent to me");
    try {
        recurseUp(i);
    } catch (RuntimeException e) {
        // nothing.
    }
    recurseDown(i + 1);
}

private static void recurseUp(int i) {
    System.out.println(lines[i]);
    recurseUp(i - 1);
}

you can see it running here: http://ideone.com/SAte6Z

Written properly, it would be:

public static void main(String[] args) {
    recurseDown(0);
}

private static void recurseDown(int i) {
    if (i == days.length) {
        return;
    }
    System.out.println("\nOn the " + days[i] + " day of Christmas\nMy true love sent to me");
    recurseUp(i);

    recurseDown(i + 1);
}

private static void recurseUp(int i) {
    if (i < 0) {
        return;
    }
    System.out.println(lines[i]);
    recurseUp(i - 1);
}


Generating an HTML table with colspan and rowspan from a one-dimensional array I will be given the following input:

const input = [
  { value: "a1", colspan: 1, rowspan: 1 },
  { value: "a2", colspan: 1, rowspan: 1 },
  { value: "a3", colspan: 1, rowspan: 3 },

  { value: "b1", colspan: 1, rowspan: 1 },
  { value: "b2", colspan: 1, rowspan: 1 },

  { value: "c1", colspan: 1, rowspan: 1 },
  { value: "c2", colspan: 1, rowspan: 2 },

  { value: "d1", colspan: 1, rowspan: 1 },
  { value: "d3", colspan: 1, rowspan: 1 },

  { value: "e1", colspan: 1, rowspan: 1 },
  { value: "e2", colspan: 2, rowspan: 1 },
];
const width = 3;

And from such, I need to construct an HTML table, taking into account colspan and rowspans. The resulting table would look like:

*----+----+----*
| a1 | a2 | a3 |
+----+----+    |
| b1 | b2 |    |
+----+----+    |
| c1 | c2 |    |
+----+    +----+
| d1 |    | d2 |
+----+----+----+
| e1 | e2      |
*----+---------*

This works, but I'm not sure if it's the best approach or if it could be tackled better:

// Define the total possible cell count
// This poorly assumes no gaps
const totalCellCount = reduce(input, (sum, c) => sum + (c.colSpan * c.rowSpan), 0);

// Fill a 2d array with placeholders so the below section
// can find the next available "spot". Chunk is being
// used to create the 2d array
const grid = chunk(fill(new Array(totalCellCount), -1), columnCount);

each(input, cell => {
    // A default "not found" state.
    let start = { x: -1, y: -1 };

    // Search for the next available spot working from
    // left to right, top to bottom
    outerLoop: for(let y = 0; y < grid.length; y++) {
        for(let x = 0; x < columnCount; x++) {
            if(grid[y][x] === -1) {
                // Found our starting position, save
                // it and exit out
                start = { x, y };
                break outerLoop;
            }
        }
    }

    // No more spots. There is no scenario where it
    // could only be -1 on x or y, so just check
    // the `x`
    if(start.x === -1) {
        return false;
    }

    // Fill area with null basically saying, don't
    // do anything in this area when we access
    // the grid later for processing
    for(let y = 0; y < cell.rowSpan; y++) {
        for(let x = 0; x < cell.colSpan; x++) {
            grid[start.y + y][start.x + x] = null;
        }
    }
    // Except the upper left spot, that is the actual
    // cell. The final result for a cell of 2 x 3
    // would look like:
    //
    //   +------+------+
    //   | cell | null |
    //   | null | null |
    //   | null | null |
    //   +------+------+
    //
    grid[start.y][start.x] = cell;

});

// At this point, we now have a grid populated
// with workable data - cells and null based
// on the surface area of each. Lets convert
// this to html table td's + tr's. This,
// imo, is the "easy" bit
let trs = [];
let tds = [];

for(let y = 0; y < grid.length; y++) {
  for(let x = 0; x < grid[y].length; x++) {
    // Fetch the cell at this location. If
    // it is null, its the consumed space
    // of a colspan or a rowspan, so we
    // can just ignore it
    const cell = grid[y][x];
    if(cell) {
      const { value, rowspan, colspan } = cell;
      tds.push(''+value+'	');
    }
  }

  // End of this row, assemble and push into
  // the tr array
  trs.push('
'+tds.join('')+'
');
  // Reset the td array for the next row
  tds = [];
}

// Simple join and attach to screen
$(".table").append(trs.join(''));

JS Bin

I'm using ES6/ES2015, although I could use template strings. Ignore them for now because it seems to freak out jsbin.

The data set is reasonably small, so although performance improvements are welcome, stability and edges cases would be preferred.

I really wanted to find a purely functional solution to this problem, but I wasn't able to.  Nevertheless, your basic idea is pretty simple, and can be made even shorter and more declarative:

// Cell calculations as pure data.  "cells" is the variable containing
// all cells, which we are filling in
var width     = 3,
    numCells  = input.reduce((m,x) => m += x.rowspan + x.colspan -1, 0),
    cells     = new Array(numCells).fill(false),
    dummy     = { dummy: true},
    addAcross = (i,n) => R.times(j => cells[i+j+1] = dummy, n),
    addDown   = (i,n) => R.times(j => cells[i+(j+1)*width] = dummy, n),
    nextIndex = () => cells.findIndex(x => !x);

 // Everything happens here.  We fill in "cells" with the real
 // cells and dummy cells for the span cells

 input.forEach(x => {
   var i = nextIndex();
   cells[i] = x;
   addAcross(i, x.colspan-1);
   addDown(i, x.rowspan-1);
 })

// HTML View Helpers
// Once we have the data, just split the array into subarrays
// for each row, and filter out the dummy cells.  In this format
// constructing the html itself is trivial

var rows = R.splitEvery(width, cells).map(r => r.filter(x => !x.dummy)),
    asTd = c => `<td rowspan=${c.rowspan} colspan=${c.colspan}>${c.value}</td>`,
    asTr = row => `<tr>${row.map(asTd).join('')}</tr>`,
    asTable = rows => `<table border=1>${rows.map(asTr).join('')}</table>`;

document.querySelector('body').innerHTML = asTable(rows);

Note: I used one ramda library function just to break the array into subarrays.  Lodash has a similar one, but I prefer ramda.

Here's a working bin of the final solution:
http://jsbin.com/nimuca/2/edit?js,output


More efficient version of an ID calculator in JavaScript The following function takes two numbers that are linked with a "user" and calculates an ID number based on that. I have been trying to make this as clean as possible, and would like some advice on how to make this more efficient. an example of the input would be  "12195491" for the num and "3120" for the ts, which would output "8511"

function getidnumber(num, ts) {
            num = num.substr(4, 4);
            ts = ((ts == undefined) ? "3452" : (ts));
            var _local5 = "";
            var _local1 = 0;
            while (_local1 < num.length) {
                var _local4 = Number(num.substr(_local1, 1));
                var _local3 = Number(ts.substr(_local1, 1));
                var _local2 = String(_local4 + _local3);
                _local5 = _local5 + _local2.substr(_local2.length - 1);
                _local1++;
            }
            return("@user" + _local5);
};

Here's a better implementation.

Used the unary + operator for number conversion.

Used null instead of undefined since it's shorter and produces the same result because of type coersion.

Avoid performing a substring operation by starting to iterate from index 4.

Cached num.length into len so that we save on property lookups when the condition is evaluated for every loop iteration.

Removed uneeded parenthesis.

Took advantage of the += operator.

Made sure that every variables were locally scoped. The _local1 variable in the selected answer isin't properly scoped.

Used a single var statement; it's a better practice to declare variables at the top of the function for readability.

Stole the % 10 idea from the other answer since I thought it was great ;)

 function getidnumber (num, ts) {
    var i = 4,
        len = num.length,
        res = '@user';

    ts = ts == null? '3452' : ts;

    for (; i < len; i++) {
        res += (+num[i] + +ts[i - 4]) % 10;
    }

    return res;
}


Two player tic tac toe Python Used classes to make this simple tic tac toe game.

Any improvements?

from itertools import chain

class Field:
    def __init__(self, sequence):
        self.sequence = sequence
        self.rows = [[sequence[i] for i in range(j, j + 3)] for j in range(0, 9, 3)]
        self.columns = [[row[i] for row in self.rows] for i in range(3)]
        self.first_diagonal = self.rows[0][0] + self.rows[1][1] + self.rows[2][2]
        self.second_diagonal = self.rows[0][2] + self.rows[1][1] + self.rows[2][0]
        self.diagonals = [self.first_diagonal, self.second_diagonal]

    def __str__(self):
        return '''\
---------
| {} {} {} |
| {} {} {} |
| {} {} {} |
---------\
'''.format(*self.sequence)

    def get_value(self, x, y):
        return self.rows[x][y]

    def set_value(self, x, y, value):
        self.rows[x][y] = value
        sequence = ''.join(list(chain.from_iterable(self.rows)))

        self.__init__(sequence)  # Reinitializing attributes.

    def get_state(self):

        num_x = self.sequence.lower().count('x')
        num_o = self.sequence.lower().count('o')

        if abs(num_x - num_o) not in {0, 1}:
            return 'Impossible'

        winners = []
        for sequence in chain(self.rows, self.columns, self.diagonals):
            if len(set(sequence)) == 1:
                if sequence[0] not in winners and sequence[0].lower() in ['x', 'o']:
                    winners.append(sequence[0])

        if len(winners) > 1:
            return 'Impossible'
        elif winners:

            return f'{winners[0]} wins'

        # No winner
        else:
            if '_' in self.sequence or ' ' in self.sequence:
                return 'Game not finished'
            else:
                return 'Draw'

def convert_index(x, y):
    x, y = abs(y - 3), x - 1

    return x, y

def make_move(field, move, value):
    try:
        x, y = move.split()
    except ValueError:
        print('You should enter numbers!')
        return False

    if x.isnumeric() and y.isnumeric():
        x, y = int(x), int(y)
        if x in {1, 2, 3} and y in {1, 2, 3}:
            x, y = convert_index(x, y)
            if field.get_value(x, y).lower() not in ['x', 'o']:
                field.set_value(x, y, value)
                return True
            else:
                print('This cell is occupied! Choose another one!')
        else:
            print('Coordinates should be from 1 to 3!')
    else:
        print('You should enter numbers!')

    return False

field = Field('_' * 9)  # Empty field.

i = 1

while True:
    print(field)

    player = 'X' if i % 2 == 1 else 'O'

    ordinates = input()

    if make_move(field, ordinates, player):  # Only change player if a move was successful
        i += 1

    if field.get_state() not in ['Game not finished', 'Impossible']:
        print(field)
        print(field.get_state())
        break

```

Input
One thing I would suggest is provide a hint to the user about the format of their coordinates input. It's not immediately obvious that the format should be x y. I had to look at the code to figure that out. Intuitively, one might expect to type in x and y on separate lines or maybe separate them with a comma.
One way to deal with this is to add a string in the input function, so rather than:
ordinates = input()
you could do something like:
ordinates = input("Please enter your coordinates (example: 1 2): ")
Better yet, it would be easier to deal with only individual x and y coordinates throughout the program, rather than  mixing them with strings combining the two. For this, you would simply ask for the two coordinates with separate input() statements (e.g. input("Enter your x: ", input("Enter your y: ")). Then you don't have to worry about splitting strings or unpacking tuples or anything or the sort.
Coordinates
Another point is that the vertical coordinates seem to be backwards, in that the 1st row is at the bottom and the 3rd row at the top. Again it would make the game more user friendly to either specify this to the user or rearrange the grid array so that [1, 1] is top left and [3, 3] is bottom right.


Build embedded XML based on string containment I have a list of strings that represent a path. These are unique, unsorted values that look like this:

li = ['1/', '1/2/4/', '1/23/4/', '1/2/', '1/1/3/', '1/2/3/4/', '1/1/', '1/23/', '1/2/3/']

It can also be assumed that every path has a parent, e.g. 1/2/ has parent 1/.

The goal is to organise these items in a structured XML format, where the parent-relation is clear, i.e. where deeper elements are part of their parents, mimicking a directory tree. Desired output for the list above would be:

<root>
  <include path="1/">
    <include path="1/1/">
      <include path="1/1/3/"/>
    </include>
    <include path="1/2/">
      <include path="1/2/3/">
        <include path="1/2/3/4/"/>
      </include>
      <include path="1/2/4/"/>
    </include>
    <include path="1/23/">
      <include path="1/23/4/"/>
    </include>
  </include>
</root>

The following works (run it here), but I am not sure about efficiency. The actual list can be thousands of values long. I am also curious about memory management, because I am writing all XML nodes in-memory. The eventual goal is to print the final XML to a file.

from xml.etree import ElementTree as ET
import re

li = ['1/', '1/2/4/', '1/23/4/', '1/2/', '1/1/3/', '1/2/3/4/', '1/1/', '1/23/', '1/2/3/']
li = sorted(li)
# In Python >= 3.6 dicts maintain order
# Sets don't? So use best of both worlds, dict: speed and order
di = {l: False for l in li}

root = ET.Element('root')

# First build the root nodes, remove them from dict
for p in list(di.keys()):
  if len(list(filter(None, p.split('/')))) == 1:
    del di[p]
    root.append(ET.Element('include', {'path': p}))

# Because dict (and so keys()) are ordered, we can assume that the nodes higher
# in the include tree are created before the more in-depth ones
for p in list(di.keys()):
  parent_path = re.sub('\d+\/$', '', p)
  try:
    parent = root.find(f'.//include[@path="{parent_path}"]')
    parent.append(ET.Element('include', {'path': p}))
  except Exception:
    print(f"parent not found for {p}")

print(ET.tostring(root))

This indeed returns the expected output (not pretty-printed). I am wondering if there is a better option and whether there are flaws in my approach. I'll only be using Python >= 3.6, which is quite important for the order of the dictionary.

Update

I noticed a bug with the sorting of the list/dict because actually the sorting was done on the strings which isn't what we want. (e.g. 1001/ would be before 134/) I rewrote part of the code, and use sets assuming these are faster.

from xml.etree import ElementTree as ET
import re

def get_xml(paths):
    root = ET.Element('paths')

    root_paths = set()
    for p in paths:
        # If only one item, use as first-level node - e.g. 1/
        if len(list(filter(None, p.split('/')))) == 1:
            root_paths.add(p)
            root.append(ET.Element('include', {'path': p}))

    # Remove root_paths from set
    paths = paths.difference(root_paths)

    # We can't use regular sort because that'll sort by string
    # Instead, sort by array of ints representation. E.g. `12/1001/14/` -> [12, 1001, 14]
    sorted_paths = sorted(paths, key=lambda item: [int(n) for n in list(filter(None, item.split('/')))])
    for p in sorted_paths:
        # Find parent_path by removing last part of string
        parent_path = re.sub('\d+\/$', '', p)
        try:
            parent = root.find(f'.//include[@path="{parent_path}"]')
            parent.append(ET.Element('include', {'path': p}))
        except AttributeError:
            print(f"parent {parent_path} not found for {p}", flush=True)

    return root

s = {'1/', '1/2/4/', '1/23/4/', '1/2/', '1/1/3/', '1/2/3/4/', '1/1/', '1/23/', '1/2/3/'}

xml = get_xml(s)

print(ET.tostring(xml))

Because you have the overall root node, (a bit confusing that it changes name from root to paths between the two versions) there shouldn't actually be any inherent difference between nodes of the form "1/" and nodes of the form "1/2/" or longer. It should be possible to completely remove the first loop, and just have a special case definition of parent_path to point it to the actual root.

If you do that, questions about whether dicts or sets are faster for deleting the length one paths, or suitably order preserving, or anything else, become a moot point. There's nothing left that you can't just do directly on lists/arrays, and for single pass iteration they are almost certainly the fastest option.

Memory consumption is something that I can't helpfully speculate about. It will depend on the particulars of your xml library and data. It's a problem if you're running out of memory, in which case profile it to check the usage is where you expect.
If you're allowed to mutate the input array, and are worried about memory, you'd get some small savings and possibly a small efficiency boost for doing the sort in place rather than using sorted. However, you'd need a streaming XML writer (and some moderately knotty logic about when things can be committed) to make a significant difference. As far as I can see from the docs, xml.etree.ElementTree does not have inbuilt support for such streaming.

In terms of runtime, I wouldn't want to speculate about efficiency without measuring it. It might be that you could speed up the regex search, for example, by using re.compile ahead of time. That's unlikely to harm, but it can't help much if parsing the regex is taking an insignificant amount of time to begin with.

Code style, it would be nice to use more descriptive names, and in particular to avoid single letter variables. The comments, especially the comment on the sorting explaining the subtle bug in the naive version, are very helpful.


XML settings implementation I'm trying to figure out how to do this more dynamically. Right now I save each and every form field individually/manually. I would love to maybe have some kind of master form list that I could loop through. I'm fairly new to C#, so I don't know many tricks yet. Please let me know what you think.

Here is my simplified version of my code:

Note: None of the variable names are numbered in my real code. I changed them for simplicity in my example. So I can't loop through form names by iterating.

//BINDED FORM COLLECTION
public class FormLink
{
    private string _fObj1;
    private string _fObj2;
    private string _fObj3;
    private string _fObj4;
    private bool _fObj5;
    private bool _fObj6;
    private bool _fObj7;

    public string fObj1
    {
        get
        {
            return this._fObj1;
        }
        set
        {
            this._fObj1 = value;
        }
    }

    public string fObj2 { /*...*/ }
    public string fObj3 { /*...*/ }
    public string fObj4 { /*...*/ }
    public bool fObj5 { /*...*/ }
    public bool fObj6 { /*...*/ }
    public bool fObj7 { /*...*/ }
}

//SETTINGS HANDLE
public class Settings
{
    private string SettingsFile = "settings.xml";
    FormLink form;

    public Settings(FormLink form)
    {
        this.form = form;
    }

    public void iStart()
    {
        if (!File.Exists(this.SettingsFile))
        {
            this.createDefaultsFile();
        }

        this.iLoad();
    }

    public void iEnd()
    {
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj1", this.form.fObj1.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj2", this.form.fObj2.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj3", this.form.fObj3.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj4", this.form.fObj4.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj5", this.form.fObj5.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj6", this.form.fObj6.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj7", this.form.fObj7.ToString());
    }

    private void createDefaultsFile()
    {
        XDocument xml = new XDocument(
            new XElement("Settings",
                new XElement("fObj1", "string"),
                new XElement("fObj2", "string"),
                new XElement("fObj3", "string"),
                new XElement("fObj4", "string"),
                new XElement("fObj5", false),
                new XElement("fObj6", false),
                new XElement("fObj7", false),
            ));
        xml.Save(this.SettingsFile, SaveOptions.None);
    }

    private void iLoad()
    {
        var settings = this.getNodes(XDocument.Load(this.SettingsFile, "Settings");

        this.form.fObj1 = Help.getDictVal(settings, "fObj1");
        this.form.fObj1 = Help.getDictVal(settings, "fObj2");
        this.form.fObj1 = Help.getDictVal(settings, "fObj3");
        this.form.fObj1 = Help.getDictVal(settings, "fObj4");
        this.form.fObj1 = Help.getDictVal(settings, Help.stringToBool("fObj5"));
        this.form.fObj1 = Help.getDictVal(settings, Help.stringToBool("fObj6"));
        this.form.fObj1 = Help.getDictVal(settings, Help.stringToBool("fObj7"));
    }

    private void alterNodeValue(string xmlFile, string parent, string node, string newVal)
    {
        /* Alters a single XML Node and saves XML File */
    }

    private Dictionary<string, string> getNodes(XDocument xml, string parent)
    {
        /* Retrieves all Child Nodes of specified Parent and returns them in a Dictionary */
    }
}

//Basic Utilies class
public static class Help
{
    public static bool stringToBool(string BoolMe)
    {
        /* Safely converts String to Bool */
    }

    public static string getDictVal(Dictionary<string, string> dict, string key)
    {
        /* Safely gets value from Dictionay based on Key*/
    }
}

you can just use an XML serializer?

var s = new XmlSerializer(typeof(FormLink));
TextWriter w = new StreamWriter("settings.xml");
s.Serialize(w, form);
w.Close();


Creating an MVC router I created an MVC router based on knowledge of an MVC design pattern.

It will simply take a URL as a string (class/method/params...), then it will instantiate a requested class controller and call its method.

In my class, I call a controller method and then include the view at the same time to display data.

My questions are:

Is this a valid MVC router?
Is it good practice to make this class call include views for our application?

class FrontController {
    //default view
    private $view = 'index';
    //default methode
    private $method = 'indexMethode';
    //default controller
    private $controller = 'Page';
    //this attribute to store data returned
    private $data;
    //to store methode parameters from url.
    private $param;
    public function __construct() {
        //getting user url request
        $url = $this->getUrl();
        //checking user input
        if (isset($url[0])) {
              //getting class name from user input
              $this->controller = ucwords($url[0]);
              unset($url[0]);
        }
        //checking if class file exsiste if yes we include it
        if(file_exists('controllers/'.$this->controller.'.php')){
              require 'controllers/'.$this->controller.'.php';
        }
        //instantiating the demanded class
        $this->controller = new $this->controller;

        //getting demanded class method if it is demanded by user
        if (isset($url[1])) {
              if(method_exists($this->controller, $url[1]))
                  $this->method = $url[1];

        }

        //checking if there is a view for our request
        if(file_exists('view/'.$url[1].'.php')){
            //setting the sutable template for the methode
            $this->view = $url[1];
            unset($url[1]);
        }

        //Getting methode parameters from user input if exsist
        $this->param = $url ? array_values($url) : [];

        //Calling the methode and getting the result
        $this->data = call_user_func_array([$this->controller,
        $this->method], $this->param);

        //Getting the sutable page for  the responde to display it.
        include 'view/' . $this->view . '.php';
    }
    //To get any private var in our class
    public function __get($name) {
        return $this->$name;
    }
    //Here we are gona take user input and devide it as array element
    public function getUrl() {
      //checking user input and filtring it for unwanted charecters
        if (!empty($_GET['url'])) {
            // remove / char from url
            $url = rtrim($_GET['url'], '/');
            //Checking url for unwanted chars
            $url = filter_var($url, FILTER_SANITIZE_URL);
            //forming array from url
            $url = explode('/', $url);
            //Sending back url array
            return $url;
        }
    }
}

This implementation of the Front Controller Pattern has knowledge over too many concerns. The Single Responsibility Principal states that a class should only have one reason to change. From what I can see if any of the following things change, this class will be affectetd:

The location of controller class files
The name of the controller classes
How controller classes are instantiated
The pattern used to match URLs
How view files are loaded
How controller methods are invoked
Which views correspond to which methods on a controller

All of these concerns mixed into one class means it is near impossible to unit test a very critical part of your application.

To be honest, if this is a small application it isn't too bad. If your application grows in size and complexity this will quickly show its limits.

The answer?

Split each concern into it's own class (Single Responsibility Principle)
Have each class interact with the others through an interface (Interface Segregation Principle)
Pass these objects to each other through their constructors (Dependency Inversion Principle)

Going with a minimum of 4 classes and interfaces gives you a lot more flexibility for your application to grow.

First, the interfaces:

interface IUrlRouter {
    function getRoute(Request $request) : UrlRoute;
    function getErrorRoute() : UrlRoute;
}

interface IControllerFactory {
    function createController($controllerName);
}

interface IActionResultExecutor {
    function executeResult($result);
}

Then your "front controller" really just becomes "the application" which handles the Big Picture steps of the process:

class MvcApplication {
    private $controllerFactory;
    private $resultExecutor;
    private $router;

    public function __construct(IUrlRouter $router, IControllerFactory $controllerFactory, IActionResultExecutor $resultExecutor) {
        $this->router = $router;
        $this->controllerFactory = $controllerFactory;
        $this->resultExecutor = $resultExecutor;
    }

    public function handleRequest(Request $request) {
        try {
            $route = $this->router->getRoute($request);
            $controllerName = $route->getControllerName();
            $actionName = $route->getActionName();
            $controller = $this->controllerFactory->createController($route->getControllerName());
            $result = $controller->$actionName($route->getParams());

            $this->resultExecutor->executeResult($result);
        }
        catch (Exception $ex) {
            $route = $this->router->getErrorRoute();
            $controller = $this->controllerFactory->createController($route->getControllerName());
            $controller->error($request, $ex);
        }
    }
}

And then just a smidgen of boiler plate code to kick start the process:

$app = new MvcApplication(new UrlRouter(), new ControllerFactory(), new ActionResultExecutor());
$request = new Request($_SESSION, $_SERVER, $_GET, $_POST);
$app->handleRequest($request);

And this doesn't even touch on user input validation, or resolving a view and then rendering it.


LeetCode 65: Valid Number (Python) Problem

Validate if a given string can be interpreted as a decimal or scientific number.

Some examples:

"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3   " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false

Code

I've solved the valid number LeetCode problem using Python re module. If you'd like to review the code and provide any change/improvement recommendations, please do so and I'd really appreciate that.

import re
from typing import Optional

def is_numeric(input_string: Optional[str]) -> bool:
    """
    Returns True for valid numbers and input string can be string or None
    """
    if input_string is None:
        return False

    expression_d_construct = r"^[+-]?(?:\d*\.\d+|\d+\.\d*|\d+)[Ee][+-]?\d+$|^[+-]?(?:\d*\.\d+|\d+\.\d*|\d+)$|^[+-]?\d+$"
    expression_char_class = r"^[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|[0-9]+)[Ee][+-]?[0-9]+$|^[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|[0-9]+)$|^[+-]?[0-9]+$"

    if re.match(expression_d_construct, input_string.strip()) is not None and re.match(expression_char_class, input_string.strip()) is not None:
        return True
    return False

if __name__ == "__main__":
        # ---------------------------- TEST ---------------------------
    DIVIDER_DASH = '-' * 50
    GREEN_APPLE = '\U0001F34F'
    RED_APPLE = '\U0001F34E'

    test_input_strings = [None, "0  ", "0.1", "abc", "1 a", "2e10", "-90e3",
                          "1e", "e3", "6e-1", "99e2.5", "53.5e93", "--6", "-+3", "95a54e53"]

    count = 0
    for string in test_input_strings:
        print(DIVIDER_DASH)
        if is_numeric(string):
            print(f'{GREEN_APPLE} Test {int(count + 1)}: {string} is a valid number.')
        else:
            print(f'{RED_APPLE} Test {int(count + 1)}: {string} is an invalid number.')
        count += 1

Output

--------------------------------------------------
 Test 1: None is an invalid number.
--------------------------------------------------
 Test 2: 0   is a valid number.
--------------------------------------------------
 Test 3: 0.1 is a valid number.
--------------------------------------------------
 Test 4: abc is an invalid number.
--------------------------------------------------
 Test 5: 1 a is an invalid number.
--------------------------------------------------
 Test 6: 2e10 is a valid number.
--------------------------------------------------
 Test 7: -90e3 is a valid number.
--------------------------------------------------
 Test 8: 1e is an invalid number.
--------------------------------------------------
 Test 9: e3 is an invalid number.
--------------------------------------------------
 Test 10: 6e-1 is a valid number.
--------------------------------------------------
 Test 11: 99e2.5 is an invalid number.
--------------------------------------------------
 Test 12: 53.5e93 is a valid number.
--------------------------------------------------
 Test 13: --6 is an invalid number.
--------------------------------------------------
 Test 14: -+3 is an invalid number.
--------------------------------------------------
 Test 15: 95a54e53 is an invalid number.

RegEx Circuit

jex.im visualizes regular expressions:

RegEx Demo 1

RegEx Demo 2

If you wish to explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.

Source

LeetCode Valid Number

Instead of diving into cumbersome and lengthy regex expressions consider the following improvement/correction:

The main thesis for the underlying aspect is:

  Numeric literals containing a decimal point or an exponent sign
  yield floating point numbers.

https://docs.python.org/3.4/library/stdtypes.html#numeric-types-int-float-complex

Therefore Python treats values like 53.5e93, -90e3 as float type numbers.

Eventually I would proceed with the following approach (retaining those cute icons) including additional small optimizations:

from typing import TypeVar, Optional

def is_numeric(input_string: Optional[str]) -> bool:
    """
    Returns True for valid numbers. Acceptable types of items: str or None
    """
    if input_string is None:
        return False

    try:
        input_string = input_string.strip()
        float(input_string)
    except ValueError:
        return False
    return True

if __name__ == "__main__":
    # ---------------------------- TEST ---------------------------
    DIVIDER_DASH = '-' * 50
    GREEN_APPLE = '\U0001F34F'
    RED_APPLE = '\U0001F34E'

    test_input_strings = [None, "0  ", "0.1", "abc", "1 a", "2e10", "-90e3",
                          "1e", "e3", "6e-1", "99e2.5", "53.5e93", "--6", "-+3", "95a54e53"]

    count = 0
    for string in test_input_strings:
        print(DIVIDER_DASH)
        count += 1

        if is_numeric(string):
            print(f'{GREEN_APPLE} Test {count}: `{string}` is a valid number.')
        else:
            print(f'{RED_APPLE} Test {count}: `{string}` is not a valid number.')

The output:

--------------------------------------------------
 Test 1: `None` is not a valid number.
--------------------------------------------------
 Test 2: `0  ` is a valid number.
--------------------------------------------------
 Test 3: `0.1` is a valid number.
--------------------------------------------------
 Test 4: `abc` is not a valid number.
--------------------------------------------------
 Test 5: `1 a` is not a valid number.
--------------------------------------------------
 Test 6: `2e10` is a valid number.
--------------------------------------------------
 Test 7: `-90e3` is a valid number.
--------------------------------------------------
 Test 8: `1e` is not a valid number.
--------------------------------------------------
 Test 9: `e3` is not a valid number.
--------------------------------------------------
 Test 10: `6e-1` is a valid number.
--------------------------------------------------
 Test 11: `99e2.5` is not a valid number.
--------------------------------------------------
 Test 12: `53.5e93` is a valid number.
--------------------------------------------------
 Test 13: `--6` is not a valid number.
--------------------------------------------------
 Test 14: `-+3` is not a valid number.
--------------------------------------------------
 Test 15: `95a54e53` is not a valid number.


Optimization of Javascript Function swapping out images for gifs Im working on a project where a grid of images are loaded all at once. when the mouse is on hover a certain image, a corresponding gif fades in and then fades out when the mouse moves away from the image.

I was able to get a working fiddle with the code i currently have. i have about 20 images that require this desired effect but my code is long and i feel like there is a better way to write my function where it can fade in and out as well as swapping out the images for gifs. Can someone help/point me in the right direction. still learning here!

code:

HTML

JAVASCRIPT
$(document).ready(function () {
    onHover();
    offHover();
    onHover1();
    offHover1();
    onHover2();
    offHover2();
    onHover3();
    offHover3();
});
function onHover()
{
    $(".img-ford").attr('src', 'http://reneinla.com/tasha/style/images/gifs/giphy.gif');

}
function offHover()
{
    $(".img-ford").attr('src', 'http://reneinla.com/tasha/style/images/stills/FORD-SUPER-BOWL.jpg');
}
function onHover1()
{
    $(".img-op").attr('src', 'http://reneinla.com/tasha/style/images/gifs/giphy.gif');
}
function offHover1()
{
    $(".img-op").attr('src', 'http://reneinla.com/tasha/style/images/stills/OPERATOR.jpg');
}
function onHover2()
{
    $(".img-op1").attr('src', 'http://reneinla.com/tasha/style/images/gifs/giphy.gif');

}
function offHover2()
{
    $(".img-op1").attr('src', 'http://reneinla.com/tasha/style/images/stills/FORD-SUPER-BOWL.jpg');
}
function onHover3()
{
    $(".img-ford1").attr('src', 'http://reneinla.com/tasha/style/images/gifs/giphy.gif');
}
function offHover3()
{
    $(".img-ford1").attr('src', 'http://reneinla.com/tasha/style/images/stills/OPERATOR.jpg');
}

UPDATE

Thanks for the help!
i was able to do some research and found something that works.
new fiddle

I think you could reduce a loot your code and do it in a way that it is more clear and effective.

First of all this part you could just remove without concerns:

$(document).ready(function () {
    onHover();
    offHover();
    onHover1();
    offHover1();
    onHover2();
    offHover2();
    onHover3();
    offHover3();
});

The reason, is because those functions are intended to be called on events triggering. This is the logic reason.
The functional reason, is that at the end you have the same situation of the beginning.

If your intention was to provide some sort of effect here, it is better to have a dedicated function to this. First of all because those kind of effects could change in time for different reasons than the event handlers.
Second reason is because the meaning is much evident.

I thin you could put all the url in your HTML using the data attribute:

<figure>
 <img src="#" alt="" class="img-ford"
   data-out="/tasha/style/images/gifs/giphy.gif"
   data-out="/tasha/style/images/stills/FORD-SUPER-BOWL.jpg"/>
</figure>

You can avoid to place the event handlers directly in HTML code, this could be done in the $(document).ready() section on startup.

Now you can have a function to initialize your images:

function initImages() {
    $('img').each(function(img) {
        $(img).prop('src', $(img).data('out'));
     });
}

Maybe you have to take care of the selector to get only and all the images you want to operate on.

Than start the initialization:

$(function() {
     initImages();
     $('img').on('mouseover', imageMouseOver);
     $('img').on('mouseout', imageMouseOut);
 });

This is the short version of $(document).ready() in jQuery.

Then your functions:

function imageMouseOver(event) {
    $(this).prop('src', $(this).data('over'));
}

And the same for out:

function imageMouseOut(event) {
    $(this).prop('src', $(this).data('out'));
}

Of course you can reduce more with a sort of toggle function, but have used 2 just for sake of clarity.


ASP.NET MVC 3 ModelBinder with string sanitizing I need to allow incoming HTML in string parameters in my projects action methods, so we have disabled Input Validation.  I have a good HTML sanitizer; the review I am interested in is the way I bound it into my project.

I have the following Model Binder:

    public class EIMBaseModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var boundValue = base.BindModel(controllerContext, bindingContext);
            return bindingContext.ModelType == typeof(string) ? HtmlCleaner.SanitizeHtml((string)boundValue) : boundValue;
        }

        protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
       {
            if (propertyDescriptor.PropertyType == typeof(string))
            {
              var stringVal = value as string;
              value = stringVal.IsNullOrEmpty() ? null : HtmlCleaner.SanitizeHtml(stringVal);
            }

            base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
       }
    }

I set it as my DefaultBinder in my set up and require that all custom model binders inherit from it. I know I can't completely defend against developers not following this rule, but we are a small team so I think we can police that well enough.

I have some basic unit testing pushing both string primitive values and strings as property values through the binder and those work as expected.  I will be asking the security team to do some penetration tests.

Can anyone see either a better way to have hooked into the incoming data or a base I have missed?

Can't comment on whether there is a better way or a better place in the framework to do this but some general remarks:

This doesn't make much sense: stringVal.IsNullOrEmpty() - should be string.IsNullOrEmpty(stringVal).
You are inconsistent: In the first method you check the type and use a direct cast vs in the second method you check the type and then use as - either you trust the type is correct or you don't. Also in SetProperty you try to not pass null or empty strings to the sanitizer helper while in BindModel you don't.
It would make sense if the helper method would support null and empty strings.

With the above the cleaned up code for SetProperty should probably look like this:

   protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
   {
        if (propertyDescriptor.PropertyType == typeof(string))
        {
            value = HtmlCleaner.SanitizeHtml((string)value);
        }

        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
   }