Create matrices of a certain format I need to create matrices that follow a specific format: the matrix is a square NxN matrix and the off-diagonals all have the same value (param) and the diagonals have values such that the rows sum to zero (in other words, they are equal to 0 - param * (N-1). The output is a numpy array

Here is my code. Is there any way I can make this more readable/elegant? Speed is also important.

import numpy as np

def makeMatrix(param, N):
    ar = []
    for i in range(N):
        ar.append([ param for st in range(N) ])
        ar[i][i] = 0-(param*(N-1))

    return np.array(ar, dtype=np.double)

One of the main features of NumPy is that you can work with matrices without explicit looping.  To get the diagonal, use np.identity().  To set everything else, use broadcasting.

def make_matrix(value, dim):
    return value - value * dim * np.identity(dim, dtype=np.double)

param and N don't mean anything to me.  I suggest value and dim.  The function name should preferably be make_matrix, according to PEP 8.

Question is, do you really need an explicit matrix? For large \$N\$ it occupies a significant space while containing very little information. I'd go for a (wrapped) function instead:

    def make_special_matrix(N, param):
        def special_matrix(i, j):
            if i == j:
                return (N-1)*param
            return param
        return special_matrix


Triaging items according to a time threshold I'm having this part of code which I want to make smaller, more readable and easy to manage. Any thoughts? I tried linq but got lost.

foreach (var o in state.s)
        {
            TimeSpan timeDiff = (DateTime.Now - o.time);
            if (timeDiff.TotalSeconds < 300)
            {
                richTextBox.AppendColoredText(o.name + " ", Color.Green);
            }
            else
            {
                richTextBox.AppendColoredText(o.name + " ", Color.Red);
                if (f == false)
                {
                    listA.Add(o.name);
                    listA_clone.Add(o.name);
                }
                else
                {
                    listA.Add(o._name);
                }
            }
        }

I tried linq but got lost.

LINQ stands for Language-INtegrated Query - and querying objects (or data) is not something that should have side-effects... and the very purpose of that loop is to have side-effects. In other words, using LINQ here would be abusing the language.

Your usage of var is inconsistent, and the naming is... dangerous - I like var, a lot. So I like that you're having it in your loop declaration. You see, I can guess that timeDiff is a TimeSpan just by looking at its name - and its assignment makes it pretty obvious what the type is as well. But I have no clue whatsoever what an o is, and all I know about s is that it's probably an IEnumerable<whatever-the-type-of-o-is>. Readable code is code that one can... read.

o.time and o.name are confusing, because they don't follow the typical PascalCase naming convention for public members. If they're public property getters, they should be o.Time and o.Name.

o._name is confusing at best, and a clear violation of encapsulation at worst. _name looks very much like a name for a private field - which shouldn't be accessible from this code. And if it's a public field, then you've broken encapsulation (because fields should never be public). And if _name isn't the backing field for the name property, then you have another problem: you clearly aren't writing code as if the next maintainer were a violent psychopath that knows where you live:

listA.Add(o.name);
...
listA.Add(o._name);

Another thing to note, is that the Boolean expression in an if condition doesn't need to involve a comparison against a Boolean value here:

if (f == false)

if f is a bool, then if (!f) is a Boolean expression... that would be perfectly clear if f had a meaningful name. By convention bool variable names start with is, or has:

if (!isHairyCode)

or

if (!hasBugs)

I always like to put my brackets with the statement, instead of giving every single bracket a line for itself, Like this:

foreach (var o in state.s) {
        TimeSpan timeDiff = (DateTime.Now - o.time);
        if (timeDiff.TotalSeconds < 300) {
            richTextBox.AppendColoredText(o.name + " ", Color.Green);
        } else {
            richTextBox.AppendColoredText(o.name + " ", Color.Red);
            if (f == false) {
                listA.Add(o.name);
                listA_clone.Add(o.name);
            } else {
                listA.Add(o._name);
            }
        }
    }

This might not be what you are looking for, But it is smaller


Input validation for text boxes in a Form In a Win Form I'm doing initial validation in the Form. So before saving data, I want to validate whether all the required fields are filled (Text Boxes) by the user. There are about 18 such Text Boxes in the Form. Currently I'm doing it as follows. To make the code short only three fields are shown in the code.

     private void cmbSave_Click(object sender, EventArgs e)
     {
         if(IsFilled (txtApplicationNumber.Text))
         {
             if(IsFilled (txtEmployeeID.Text))
             {
                 if (IsFilled(txtNIC.Text))
                 Save(sender, e);
             }
         }
    }

    private bool IsFilled(string s)
    {
        if (s != "")
        { return true; }
        else
        { return false; }
    }

Another option would be to use the logic inside the cmbSave_Click straightaway as follows,

    private void cmbSave_Click(object sender, EventArgs e)
    {
        If (txtApplicationNumber.Text!="" & txtEmployeeID.Text!="" & txtNIC.Text="")
        Save(sender, e)
    }

Basically the code should be readable, consistent and should perform the validation properly.

Which option could be considered better? If both are not good please propose a way to do this?

Another option would be to handle the Validating event:

private void textBox_Validating(object sender, CancelEventArgs e)
{
    TextBox currenttb = (TextBox)sender;
    if(currenttb.Text == "")
        MessageBox.Show(string.Format("Empty field {0 }",currenttb.Name.Substring(3)));
        e.Cancel = true;
    else
    {
        e.Cancel = false;
    }
}

Adding the handler to the textboxes is easily done with a foreach loop in the form constructor:

foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
{
    tb.Validating += textBox_Validating;
}

Now the user can't leave a textbox empty.  The handler returns the focus back to the textbox.  To exclude a textbox from being validated simply set the CausesValidation property to false.

In my windows form projects , i have validated the fields using Boolean method.
Find the below sample screen shot for validating the fields before saving the data
Img 3: Validation method

Here I have validated the fields using the Boolean method, If all the field values are entered properly it will return true, other wise it will return false and will display an error message.


python Guess The Number This is my take on the guess the number game. The user has three attempts to guess the number chosen at random. The number is between 0 and 9, including. It tells the user to guess higher or lower and reveals the number if the game is lost.
Input that is not a number between 0 and 9, including, is not accepted and the cursor will remain on the same line.
Green is for win and red is for retry.
I have tested the code and it works correctly. Please have a go.
guess_the_number.py
"""The user has three attempts to guess what number was chosen at random"""

__all__ = []

import random
import string

from colorama import deinit, init

right_answer = random.choice(string.digits)

as_int = int(right_answer)

MSG_ANS = 'The answer was ' + right_answer
MSG_ASK = 'Guess the number (0-9) '
MSG_OK = '\033[92mCorrect!\033[0m'
MSG_TRY = '\033[91mTry again *\033[0m'

def ask(msg_wrong):
    """
    One attempt

    Non-digits are not accepted

    Digits accepted are removed from the pool
    and are not accepted in subsequent attempts
    """
    global pool

    cursor_up = '\033[A'

    cursor_up_ask = cursor_up + '                       '

    while True:
        answer = input(MSG_ASK)

        if answer and answer in pool:
            break

        answer_sz = len(answer)
        answer_sz = answer_sz * ' '

        line = cursor_up_ask + answer_sz + cursor_up

        print(line)

        print()
        print()

        print(line, end='\r')

    if answer == right_answer:
        print(MSG_OK)

        exit()

    if msg_wrong == MSG_TRY:
        i = int(answer)

        if i > as_int:
            hint = '>'
        else:
            hint = '<'

        msg_wrong = msg_wrong.replace('*', hint)

    print(msg_wrong)

    pool = pool.replace(answer, '')

if __name__ == '__main__':
    pool = string.digits

    init()

    ask(MSG_TRY)

    ask(MSG_TRY)

    ask(MSG_ANS)

    deinit()

Positives

Your function docstring was informative and helped me understand the code better.
Good use of variables like cursor_up to manage the ANSI control characters

Small improvements

As long as you're bringin in colorama, can you use any of the named constants in provides instead of the control characters?
If you need to do something multiple times, I like to see if there's a good way to do n times instead. See if you can make the number of turns more configurable.
I'm not sure what you're doing with line = cursor_up_ask + answer_sz + cursor_up. This would be a good place for a comment or a function with a clear name.
You're taking len(answer), but shouldn't that always be 1? My understanding is that you're expecting a one-digit answer. It would be nice to have some error handling so that, e.g. 23 isn't treated as a valid guess.
You could eliminate the pool global by wrapping it and your functions together in a class. You could also eliminate the global by having more focused functions.
Instead of doing a find-replace on the * in MSG_TRY, you can do something like this:

MSG_TRY = '\033[91mTry again {}\033[0m'
msg_wrong = msg_wrong.format(hint)

Larger gripes

I'm finding the flow of the program hard to follow. Consider breaking it down into smaller functions so it's more clear what's going on. It could look something like:

def play_one_turn(final_turn = False):
    guess = get_player_input()
    if guess == right_answer:
        print(OK_MSG)
        return True
    if not final_turn:
        show_hint(guess)
    else:
        print(MSG_ANS)

(I'm not saying this is the best way to do things. It's showing how smaller well-named functions can give more clarity with the same structure)

exit() in the middle of a function is suspicious. (Is the code missing from sys import exit?) I'd expect to see it at the end of a main function to return a status code back to the user. It should not be used for control flow. It would make more sense to return True or False depending on whether the guess is correct, and let the caller manage things from there.

Your code does work, nice try :)
It's an interesting exercise. If you are open to another way of approaching the game, here's what I'd suggest:
import random
import string

def possible_answers() -> list:
    #['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    return [char for char in string.digits]

def generate_answer() -> str:
    return random.choice(possible_answers())

def ask_for_input() -> str:
    print('Your guess > ', end='')
    return input()

def new_game(max_attempts: int):
    correct_answer = generate_answer()
    attempts = []
    print('Welcome to the new round :) ')
    while len(attempts) < max_attempts:
        attempt = ask_for_input()
        if attempt == correct_answer:
            print('Bingo')
            break
        elif attempt not in possible_answers():
            print(f'Invalid input, possible answers: {possible_answers()}')
        elif attempt in attempts:
            print('You already guessed that one, my friend. Try something new :)')
        else:
            attempts += [attempt]
            print('Please try again, best of luck with the next attempt :)')

if __name__ == '__main__':
    while True:
        new_game(max_attempts = 3)

We are creating a new game after the previous game ends.

In Each game we:

accept a max_attempts as the game configuration

generate a random correct answer

accept attempts and act on the attempts accordingly

You can easily change the random set by changing the possible_answers() method

I'm ignoring output formatting here, but it can be easily added in the new_game() method.

If you don't mind doing a bit of reading, SOLID is something that's worth exploring. Hope you enjoy the reading and keep up the good work :)


Project Euler - Smallest multiple (Ruby) My code is very slow to run, and I am trying to find a way to make it more efficient. I know there must be a better way than to write each modulo operation.

The goal of the script is to find the smallest possible number than can be divided by numbers 1 to 20 without a remainder.

def divide
  (2..Float::INFINITY).each do |x|
      if x % 2 == 0 && x % 3 == 0 && x % 4 == 0 && x % 5 == 0 && x % 6 == 0 && x % 7 == 0 && x % 8 == 0 && x % 9 == 0 && x % 10 == 0 && x % 11 == 0 && x % 12 == 0 && x % 13 == 0 && x % 14 == 0 && x % 15 == 0 && x % 16 == 0 && x % 17 == 0 && x % 18 == 0 && x % 19 == 0 && x % 20 == 0
        print x
        break
      end
  end
end

divide

Array provides lcm() which gives you the least common multiple of two numbers. You can apply this to an entire array by applying it to each result as you go through it. This is what reduce does.

puts (1..20).reduce{|m,n| m.lcm(n)}

or even shorter:

puts (1..20).reduce(:lcm)

Because most of the calculations are done in the ruby implementation (e.g. C for MRI), this will be fast.

I would start at 20 and increase the number by 20 each time it loops:

def divide
  (20..Float::INFINITY).step(20).each do |x|
    if x % 2 == 0 && x % 3 == 0 && x % 4 == 0 &&
      x % 5 == 0 && x % 6 == 0 && x % 7 == 0 &&
      x % 8 == 0 && x % 9 == 0 && x % 10 == 0 &&
      x % 11 == 0 && x % 12 == 0 && x % 13 == 0 &&
      x % 14 == 0 && x % 15 == 0 && x % 16 == 0 &&
      x % 17 == 0 && x % 18 == 0 && x % 19 == 0 && x % 20 == 0

      puts x
      break
    end
  end
end

puts divide

Since 20 is the smallest number it could possibly be, we start there, since we know that it has to be evenly divisible by 20, we can continue increasing the number by 20 until it finds the solution.

At first I tried replacing your large conditional with a loop that would go from 2 to 20, testing the remainder, but this was much slower than your conditional.


Get an array of currency exchange prices based on asset Function getMarkets

Makes a call to get Cryptocurrency Exchange data based on asset (USD, USDC, USDT)

It calls the endpoint 3 times to return 3 arrays which are then returned to the callee.

I have an endpoint which hits gets exchange-markets/prices for any asset.

In my case I need to check all the paired cryptocurrency listings for USD, USDC and USDT.

At first I just tried calling getMarkets 3 times passing in the currency each time. I would then get an array of 3 responses from each call, however the last call would always replace the data for the 2 previous calls.

In order to fix that I had to use this ugly if statement indentation hell... which defeats the purpose of using async await. How should this be refactored to be cleaner, or is there a better way?

const nomicsAPI = 'https://api.nomics.com/v1/';
const nomicsKey = '8feb...;'

interface IParams {
  key: string;
  currency?: string;
}

interface IHeaders {
  baseURL: string,
  params: IParams
}

const headers: IHeaders = {
  baseURL: nomicsAPI,
  params: {
    key: nomicsKey
  }
};

const prepHeaders = (currency: string) => {
  headers.params.currency = currency;
  return axios.create(headers);
};

export const getMarkets = async (): Promise<any> => {
  try {
    let marketUSD;
    let marketUSDC;
    let marketUSDT;

    const nomicsUSD = prepHeaders('USD');
    marketUSD = await nomicsUSD.get('exchange-markets/prices');

    if (marketUSD) {
      const nomicsUSDC = prepHeaders('USDC');
      marketUSDC = await nomicsUSDC.get('exchange-markets/prices');

      if (marketUSDC) {
        const nomicsUSDT = prepHeaders('USDT');
        marketUSDT = await nomicsUSDT.get('exchange-markets/prices');

        return {
          marketUSD: marketUSD.data,
          marketUSDC: marketUSDC.data,
          marketUSDT: marketUSDT.data
        }
      }
    }
    else {
      throw new Error('USD Markets unavailable.');
    }
  } catch (err) {
    console.error(err);
  }
}

^ above produces the desired results:

And the actions file where this function is called from:

// Fetch USD, USDC & USDT markets to filter out Exchange List.
export const fetchMarketPrices = (asset: string) => (dispatch: any) =>
  getMarkets().then((res) => {
    console.log('res', res);

  // const combinedExchanges = res[0].data.concat(res[1].data).concat(res[2].data);
  // console.log('combinedExchanges', combinedExchanges);
  // const exchangesForAsset = combinedExchanges.filter((marketAsset: IMarketAsset) =>
  //   marketAsset.base === asset);
  // console.log('exchangesForAsset', exchangesForAsset);
  // return dispatch(actionGetMarketPrices(exchangesForAsset));
});

A common convention used in TypeScript/Javascript and other C-based languages is to use all uppercase letters for constants. This makes it easy to spot values that cannot be changed.

So instead of lowercase constants:

const nomicsAPI = 'https://api.nomics.com/v1/';
const nomicsKey = '8feb...;'

make them uppercase. The naming also could be improved - e.g. NOMICS_API_BASE_URL would better describe that the value is the base URL of the API than NOMICS_API.

const NOMICS_API_BASE_URL = 'https://api.nomics.com/v1/';
const NOMICS_KEY = '8feb...;'

You could also consider using the readonly modifier with those constants.

This code (as well as the updated code in your self-answer) is quite repetitive. It would be wise to abstract the common code. That way if something needs to be updated, it can be done in one place. This adheres to the Don't Repeat Yourself
 (i.e. D.R.Y.) principle.

I would first recommend storing each currency in an array:

const currencies = ['USD', 'USDC', 'USDT'];

And abstract out the common code of making the request and throwing an error if the request fails:

const getCurrencyPrice = async (currency) => {
  try {
    const request = prepHeaders(currency);
    const response =  await request.get(NOMICS_PRICES_ENDPOINT);
    if (!response) {
      throw new Error('USD Markets unavailable.');
    }
    return response.data;
  }
  catch(err) {
    console.error(err);
  }
};

That way if any of the requests fail, the Error will be thrown immediately. Also, this function has one job and could easily lend itself to unit testing.

Then use that function to iterate over the array of currencies - optionally with a for...of loop, Array.prototype.reduce(), Array.prototype.forEach(), etc

const getMarkets = async _ => {
  const returnObj = {};
  for (let currency of currencies) {
    const key = 'market' + currency;
    returnObj[key] = await getCurrencyPrice(currency);
  }
  return returnObj;
};

Notice that the code above uses a new constant - NOMICS_PRICES_ENDPOINT - this can be defined with the other constants:

const NOMICS_PRICES_ENDPOINT = 'exchange-markets/prices';

That way if the endpoint needs to be updated, in can be done in one place. Additionally, if the constants were stored in a separate file, you wouldn't need to alter the file that contains all of this code.

Improved code:

The problem was that the headers object needed to be updated before each new await. This separated the calls into 3 different calls.

When I had the all the header objects created before the awaits they all took the last header object created.

Now the code can be re-written in a synchronous way and if statements can be avoided.

export const getMarkets = async (): Promise<any> => {
  try {
    const nomicsUSD = prepHeaders('USD');
    const marketUSD = await nomicsUSD.get(exchangeMarketPrices);
    const nomicsUSDC = prepHeaders('USDC');
    const marketUSDC = await nomicsUSDC.get(exchangeMarketPrices);
    const nomicsUSDT = prepHeaders('USDT');
    const marketUSDT = await nomicsUSDT.get(exchangeMarketPrices);

    return {
      marketUSD: marketUSD.data,
      marketUSDC: marketUSDC.data,
      marketUSDT: marketUSDT.data
    }
  } catch (err) {
    console.error(err);
  }
}


Adding time to struct tm Simply put, is this function a correct and safe way to add and/or subtract time to a tm struct (from <time.h>)?

void AddTime(int seconds, tm *date)
{
    date->tm_sec += seconds;
    mktime(date);
}

seconds could be any value, supposedly larger than 60 (or smaller than -60). I'm using mktime to readjust the other values in tm, but I don't know if that's right.

I'm also not taking into account going below 1970 or above 3001 for the year, which I think are the default bounds for mktime to operate. I can check for that elsewhere.

I would add a sanity check on the pointer as well:

void AddTime(int seconds, tm* date) {
    if (date == NULL) return;
    date->tm_sec += seconds;
    mktime(date);
}

But other than that it looks correct.

Reading some documentation on mktime, this appears to be what it was meant for.

You should put more validations. For example, if you add more than 60 seconds, you need to increment minutes too. If the minutes value is 59, you must increment hours too.


How would you improve this object model design to get around Covariance Issues with ObjectModel.Collection? Consider the following simple relationship.

Code

[DataContract(Name = "Wheel")]
public class Wheel { }

[DataContract(Name = "OffRoadWheel")]
public class OffRoadWheel : Wheel { }

[DataContract(Name = "RoadVehicle")]
public class RoadVehicle
{
    public Collection<Wheel> Wheels { get; private set; }

    public RoadVehicle()
    {
        Wheels = new Collection<Wheel>();
    }
}

[DataContract(Name = "Truck")]
public class Truck : RoadVehicle
{
    public Collection<OffRoadWheel> OffRoadWheels { get; private set; }

    public Truck()
    {
        OffRoadWheels = new Collection<OffRoadWheel>();
    }
}

The Collections are configured as Read-Only and initiated in the class constructor as per FXCop recommendation CAS2227. http://msdn.microsoft.com/en-us/library/ms182327(VS.80).aspx

Now I know all the rules about Covariance & Contravariance, and the varying capabilities of using Collections vs. Lists vs. Enumerables (vs. their Interface Equivalents). However the above object model creates a number of competing difficulties.

If you create a truck with 4 Off-Road Wheels, down cast it to a RoadVehicle, and then iterate the Wheels collection... it's empty.

One way around this would be to create a public new Collection<Wheel> Wheels property on the Truck class which on-the-fly casts the contents of the OffRoadWheel collection, but this breaks behaviour if you go to add or remove on that collection.

Another problem is serialization, you can alter the above to store and duplicate the inner Wheels and OffRoadWheels properties, but then you'd end up complete serializing both if you wanted to serialize Truck

Any other suggestions on how to make this more Developer Friendly object model where things happen as you'd expect them to?

I think the model here is broken. If you have a RoadVehicle that's actually Truck, the interface lets you to add a normal Wheel to it, which is wrong.

One way to make it work is to make the collection immutable (e.g. IEnumerable<T>). This can be a reasonable solution if you're okay with setting the wheels only in the constructor.

Create constructors that take appropriate wheel collections. then RoadVehicle constructor looks like this public RoadVehicle(Collection<OffRoadWheel> hotWheels) : base(hotWheels) {}


Is this timer efficient? I found myself writing code to run at a specified frequency more than once, so I decided to make this simple timer. My main concern is that this is not the most efficient way of doing this since with SDL I would just ask for the time in ms and sleep in ms.

I'm storing the current time in timer_update() to avoid the possibility of it becoming greater than the final time and generating a huge pause since it's unsigned.

Usage is pretty simple, timer_init() is called once before the loop and timer_update() is called once at the end of every iteration.

timer.h

#ifndef TIMER_H
#define TIMER_H

typedef struct {
    double step;
    double tfinal;
} Timer;

void timer_init(Timer *timer, double hertz);
void timer_update(Timer *timer);

#endif

timer.c

#include "timer.h"

#define _POSIX_C_SOURCE 199309L
#include <time.h>
#include <errno.h>
#include <stdio.h>

static unsigned long get_ms(void)
{
    struct timespec buffer;
    unsigned long temp;

    if(clock_gettime(CLOCK_MONOTONIC, &buffer) != 0){
        perror("clock_gettime");
        return 0;
    }

    temp = buffer.tv_sec * 1000;
    temp += buffer.tv_nsec / 1000000;
    return temp;
}

static struct timespec ms_to_timespec(unsigned long ms)
{
    struct timespec temp = {ms / 1000, (ms % 1000) * 1000000};
    return temp;
}

void timer_init(Timer *timer, double hertz)
{
    timer->step = 1000 / hertz;
    timer->tfinal = get_ms() + timer->step;
}

void timer_update(Timer *timer)
{
    unsigned long now = get_ms();
    struct timespec required_sleep, rem;

    if(now < timer->tfinal){
        required_sleep = ms_to_timespec(timer->tfinal - now);
        timer->tfinal += timer->step;

        try_to_sleep:
        if(nanosleep(&required_sleep, &rem) == -1 && errno == EINTR)
            if(nanosleep(&rem, &required_sleep) == -1 && errno == EINTR)
                goto try_to_sleep;
    }

    else
        timer->tfinal += timer->step;
}

Is this timer efficient?

Yes, but there are two optimizations that I can see.  Get rid of the goto
and use a do-while loop.  I have noticed a slight performance
increase when it has been written this way in other programs.

This increase will become non-existent however if you have compiler
optimization settings enabled.  If they are enabled, they compile
into the exact same assembly code.  However, I also find a loop
more readable than a goto, so that is another reason to switch
over.
There other optimization I could see is by cleaning up your if-else a tiny bit (untested).  This should speed up your code a tiny bit (again, if optimizations on your compiler are enabled, your results will vary).

if(now < timer->tfinal)
{
    required_sleep = ms_to_timespec(timer->tfinal - now);

    // loop implementation
}
timer->tfinal += timer->step;

You may wonder why this will speed up your code.  The more branches you have, the more susceptible you are to a branch prediction failure and those failures can be expensive when it comes to efficiency.

A few other notes:

Use a designated initializer to initialize a structure (C99).

struct timespec temp =
{
    .step = ms / 1000,
    .tfinal = (ms % 1000) * 1000000
};

Group your #includes and #defines together in a more organized fashion.

#include <time.h>  // group library headers
#include <errno.h>
#include <stdio.h>
#include "timer.h" // group user defined headers

#define _POSIX_C_SOURCE 199309L  // group defines

Your != 0 comparision check in your if conditional could be removed since it is redundant (the if will always execute if the conditional isn't equal to 0).  However, this may increase readability to you, so it would be okay to keep it.

Rather than looping around goto, why not calculate how much time is remaining and convert it into ticks and sleep (ticks)?  It would also be better to find some way to generate an event rather than lopping continuously, if timing is not very strict.


Determining if there is a route between two nodes in a directed graph This algorithm should return a boolean value, telling if there is a path between two nodes in a given directed graph.

public enum State{
    White, Grey;
}

public class Node {
    State state = State.White;
    List<Node> neighbors = new ArrayList<Node>();
    //Assumption: Every node already knows about its direct adjacents
    public List<Node>getAdjacent(){ return neighbors;}
}

public static boolean isThereAPath(Node src, Node dst){
    //Assumption: Nodes are initialized with State.White
    if(src.state == State.White){
        src.state = State.Grey; //Means visiting this node right now
        for(Node node : src.getAdjacent()){
            if(node == dst){
                return true; //Hit - path found!
            }
            if(isThereAPath(node, dst))return true;

        }
    }
    return false; //NO path found
}

What do you think about the concept of it? What are the advantages of of an iterative solution?

You don't reset the src.state when you return the result.

This means that between isThereAPath calls you need to reset the state manually. Instead you should reset the state:

public static boolean isThereAPath(Node src, Node dst){
    //Assumption: Nodes are initialized with State.White
    if(src.state == State.White){
        src.state = State.Grey; //Means visiting this node right now
        for(Node node : src.getAdjacent()){
            if(node == dst){
                src.state = State.White;
                return true; //Hit - path found!
            }
            if(isThereAPath(node, dst)){
                src.state = State.White;
                return true;
            }

        }
    }
    return false; //NO path found
}

Style: avoid one-liners such as public List<Node>getAdjacent(){ return neighbors;}


Checking whether a timestamp is 10 minutes old I have a timestamp (searchTimestamp) which I need to check to see whether it is less than 10 minutes old or not:

long currentTimestamp = System.currentTimeMillis();

long searchTimestamp = getTheTimestampFromURL();// this also gives me back timestamp in 13 digit (1425506040493)

long difference = Math.abs(currentTimestamp - searchTimestamp);

System.out.println(difference);

if (difference > 10 * 60 * 1000) {
    System.out.println("timestamp is greater than 5 minutes old");
}

I have got the above code which is working fine. Is this the right way to do this or is there any better way?

getTheTimestampFromURL will always be older than the current timestamp in milliseconds.

Your description says that you want to check whether the searchTimestamp is less than 10 minutes old. Your code does something different, though.

Your code checks whether there's less than 10 minutes between the times (the difference is <= 10 minutes .... If the searchTimestamp is 2 minutes in the future, it will pass the test, if it is 9 minutes in the future, it will pass the test, and if it is 11 minutes in the future, it will fail the test.

Of interest, the math you use does a 10 minute check, but the message says "greater than 5 minutes old."

Your message should say: "timestamp is older than 10 minutes, or more than 10 minutes in the future"

So, changing your code to be what I think it should be, is a lot simpler than you would think.

What you want is for the searchTimestamp to have happened sometime after 10 minutes ago.... this is the way to do it:

private static final int TEN_MINUTES = 10 * 60 * 1000;

then, in your method:

long tenAgo = System.currentTimeMillis() - TEN_MINUTES;
if (searchTimestamp < tenAgo) {
    System.out.println("searchTimestamp is older than 10 minutes");
}

To check if date is today, use Android utils library

  DateUtils.isToday(long timeInMilliseconds)

This utils class also offers human readable strings for relative times. For example,

  DateUtils.getRelativeTimeSpanString(long timeInMilliseconds) -> "42
  minutes ago"

The are several parameters you can play with to define how precise the time span should be


Optional Consumer for ifNotPresent As Optional have only ifPresent and not have another function to be run in false case so I did the below class for that, please check it and give me your feedback:

public class OptionalConsumer<T> {
private Optional<T> optional;

private OptionalConsumer(Optional<T> optional) {
    this.optional = optional;
}

public static <T> OptionalConsumer<T> of(Optional<T> optional) {
    return new OptionalConsumer<>(optional);
}

public OptionalConsumer<T> ifPresent(Consumer<T> c) {
    optional.ifPresent(c);
    return this;
}

public OptionalConsumer<T> ifNotPresent(Runnable r) {
    if (!optional.isPresent())
        r.run();
    return this;
}

}
Then :

Optional<Any> o = Optional.of(...);
OptionalConsumer.of(o).ifPresent(s ->System.out.println("isPresent "+s))
        .ifNotPresent(() -> System.out.println("! isPresent"));

Two things:

Your class only provides a if-else statement, really. If it would also provide all the features in the existing java.util.Optional, it would have been slightly more useful.
private Optional<T> optional; should definitely be marked with final

Okay then, three things:

Your factory method takes an existing Optional<T>, but you don't provide a getter or anything for the Optional<T>, which means that you could also provide an ordinary OptionalConsumer<T> ofNullable(T value)

ifNotPresent method seems to be a bit outside the principle of its fellow opposite ifPresent.

Why does it take a Runnable as argument? I'd expect a Consumer<T> here also. Although Runnable is now a functional interface, it is more often associated with multithreading than with functional style. And if the intention was to use its threading abilities, the run() call in the method body is incorrect. new Thread(r).start(); should have been used.

Another remark, much less important. Since this wrapper class is very short and has only one field, there is no much sence in hiding the one-arg constructor allowing only the builder of() method publicly available. Both may be left public.


CSS for a calculator I've a small assignment to do: style a given HTML file with CSS.

My result looks exactly as it should. But I'm not really satisfied with my style sheet. I'm sure there are better ways to achieve the same.

The different sizes are not specified. I had just an image as template.

How would a real web design solve this task?

jsFiddle

body > div {
    width: 404px;
    border: 1px solid black;
    padding: 8px;
}

.header {
    margin-bottom: 5px;
}

.header input {
    width: 400px;
    height: 40px;
    border: 1px solid black;
    text-align: right;
}

.numberFields {
    margin: 0;
    width: 360px;
    font-size:0;
    overflow: auto;
    float: left;
}

.numberFields input {
    background-color: green;
    border: 1px solid black;
    width: 120px;
    height: 40px;
}

.numberFields input[name="0"] {
    width: 360px;
}

.operations {
    margin-left: 4px;
    width: 40px;
    font-size: 0;
    display: inline-block;
}

.operations input {
    background-color: purple;
    border: 1px solid black;
    width: 40px;
    height: 40px;
}

.sum {
    margin-top: 5px;
}

.sum input {
    background-color: purple;
    border: 1px solid black;
    width: 404px;
    height: 40px;
}

            <input name="1" value="1" disabled />

            <input type="button" name="1" value="1" />
            <input type="button" name="2" value="2" />
            <input type="button" name="3" value="3" />
            <input type="button" name="4" value="4" />
            <input type="button" name="5" value="5" />
            <input type="button" name="6" value="6" />
            <input type="button" name="7" value="7" />
            <input type="button" name="8" value="8" />
            <input type="button" name="9" value="9" />
            <input type="button" name="0" value="0" />

            <input type="button" name="+" value="+" />
            <input type="button" name="-" value="-" />
            <input type="button" name="*" value="*" />
            <input type="button" name="/" value="/" />

            <input type="button" name="=" value="=" />

First, your CSS has no errors, which is very good.  You can check for errors at the W3C validator.

Looking through your CSS, it looks very neat, and I would only remove a little bit of unnecessary code.  Also, the display seems to be optimized for IE.  I set it for FireFox and Chrome, and it displays almost correctly in IE.  The trouble is, the box for displaying the output is visibly small in FireFox and Chrome.  With my changes, it is 1 pixel too large in IE, but it is not as noticeable.

First, I would just use the body element here, instead of body > div:

body > div {
    width: 404px;
    border: 1px solid black;
    padding: 8px;
}

Right here, I adding a small padding so the font would have a small amount of space between it and the border:

.header input {
    /* ... */
    padding-right: 2px;
}

I found I could remove the overflow: auto; lines without effecting the display.

In .operations, you don't need to set font-size: 0;.  I do not know why you need to do that to remove the spacing in the .numberFields class, but I was unable to get it working without it.  I do not like that as it is not clear why you need to set the font-size there, and there is probably a cleaner way to do it, but the usual trick of using a negative margin value isn't working, and neither did setting the padding to 0px.

I did not make any other changes; as I said above, your CSS is very clean and neat.

in this version I added a little responsiveness,

it can be further optimized but it depends where and how you'll use it...

the main changes from yours are the fact that instead of using fixed width values I opted for percentages (to give horizontale responsiveness);

other less important changes (but more web-oriented) where made on the syntax of the CSS like:

last-of-type instead of selector by name=..

box-sizing:border-box; which is usually default in modern websites

overflow:hidden on calc screen

added some  display:block; to clear left-right

body > div {
    width:auto;
    max-width: 404px;
    height:auto;
    border: 1px solid black;
    padding: 2%;
    box-sizing:border-box;
    display:block
}

.header {
    margin-bottom: 5px;
    width: 100%;
    display:block

}

.header input {
    width: 100%;
    height:40px;
    border: 1px solid black;
    text-align: right;
    overflow:hidden;
}

.numberFields {
    display:block;
    margin: 0;
    width: 77%;
    font-size:0;
    overflow: auto;
    float: left;
}

.numberFields input {
    background-color: green;
    border: 1px solid black;
    width: 33.33%;
    height: 40px;
    display:inline-block;
}

.numberFields input:last-of-type{
    width: 100%;
}

.operations {
    margin-left: 4px;
    width: 20%;
    font-size: 0;
    display: inline-block;
    float:right;
}

.operations input {
    background-color: purple;
    border: 1px solid black;
    width: 100%;
    height: 40px;
}

.sum {
    display:block;
}

.sum input {
    background-color: purple;
    border: 1px solid black;
    width: 100%;
    height: 40px;
    margin-top: 5px;
}

            <input name="1" value="1" disabled />

            <input type="button" name="1" value="1" />
            <input type="button" name="2" value="2" />
            <input type="button" name="3" value="3" />
            <input type="button" name="4" value="4" />
            <input type="button" name="5" value="5" />
            <input type="button" name="6" value="6" />
            <input type="button" name="7" value="7" />
            <input type="button" name="8" value="8" />
            <input type="button" name="9" value="9" />
            <input type="button" name="0" value="0" />

            <input type="button" name="+" value="+" />
            <input type="button" name="-" value="-" />
            <input type="button" name="*" value="*" />
            <input type="button" name="/" value="/" />

            <input type="button" name="=" value="=" />

BTW your original code is fine and as I can see there aren't any drawbacks..


Express a number as a sum of powers of 2 This is my function:

def two_powers(num):
    powers = []
    i = 1
    while i <= num:
        if i & num:
            powers.append(i)
        i <<= 1
    return powers

I have python 3.6(Windows 10 64-bit). I want the result in the form of a list. My problem statement is to express a integer(num) in the form of sum of powers of 2.

Do I have to create a list in the beginning and then append to it each time ? Can I return a list directly without creating it in the beginning ?

This will will speed up my execution time, right ?

List building performance aside, there is a way to get the powers of two out without touching the bits in between, by using the formulas:

isolateLowestSetBit(x) = x & -x
resetLowestSetBit(x) = x & (x - 1)

These have been explained elsewhere.

Using those definitions, you can extract the powers of two like this:

def two_powers(num):
    powers = []
    while num != 0:
        powers.append(num & -num)
        num = num & (num - 1)
    return powers

Since it potentially avoids testing many bits (depending on the size and sparseness of the input) it may be faster. It can also work out not so well, for very dense numbers.

I think that list generator won't improve your performance in this case because it will require you to create another list (since range is not a good fit for this). You could create a generator that yields powers but it basically will be moving one piece of code to another function

So I don't think you can optimize this. Unless you allocate memory for a list before filling it but it won't improve readability.

IMHO

UPD. maybe this will be helpful: https://docs.python.org/3/library/stdtypes.html#int.to_bytes


Length of a C string, capped to some maximum If I have a oneliner in C such as

size_t maxSizeOf(const char *s)
{
     return strlen(s) > M_MAX_SIZE ? M_MAX_SIZE : strlen(s);
}

would it be better to have a macro defined such that

#define MAX_SIZE_OF(s) (strlen(s) > M_MAX_SIZE ? M_MAX_SIZE : strlen(s))

or would it be better to have

size_t maxSizeOf(const char *s)
{
     size_t len = strlen(s);
     return len > M_MAX_SIZE ? M_MAX_SIZE : len;
}

Also, is there a way to turn the second function into a macro for maximum efficiency?

All three versions can be improved.

The first function has the problem that strlen(s) is likely to be called twice.  strlen() is an expensive operation, as it walks along the entire string until it finds the NUL terminator.

The second version (the macro) has the same issue, with the additional caveat that it breaks if s is an expression with a side-effect, such as an assignment.  For example, MAX_SIZE_OF(str++) would expand to

(strlen(str++) > M_MAX_SIZE ? M_MAX_SIZE : strlen(str++))

and possibly lead to str being incremented twice.  (Even if you decide that the ALL_CAPS_NAME alerts programmers to the fact it is a macro and thus susceptible to this kind of thing, it's still a trap that is better avoided altogether.)

The last version is better, in that it avoids both the second call to strlen() and the double-argument-expansion problem.  However, I still have two objections.

First, I think that you would be better off decomposing the problem into two parts, like MIN(M_MAX_SIZE, strlen(s)).  The MIN() macro, although not in the C standard, is frequently reimplemented, and widely understood.  On the other hand, it is less obvious what your maxSizeOf() is supposed to do.  I'm not sure that it's even worth the brain power to keep track of the existence of this function.

Second, if the string that is passed to the function is much longer than M_MAX_SIZE, it still needs to walk all the way to the end of the string — even if M_MAX_SIZE is 5 and the string is a gigabyte long.  To avoid that problem, I think that you may be better off walking down s yourself.  And if you do hunt for the NUL terminator yourself, then it is suddenly worthwhile to have this function again.

More importantly, worrying about the efficiency of the function compared to the macro is a false optimization.  The operation that could potentially take a long time and scale poorly is strlen().  That's the performance problem that would bite you — not the function-vs.-macro stuff that you are worrying about.

I thought macro one is good because it's execute one time and inject the value everytime what we pass it's fast as compare to other , so better to go with macro


Return a string without the first two characters I'm new to Java and am trying to solve a scenario.  Even though I've succeeded and it works, I've just wondered if there was a more practical way of doing this task.  Is there a quicker or more efficient way of solving the task, or is this fine?

  Task:

  Given a string, return a version without the first 2 chars. Except
  keep the first char if it is 'a' and keep the second char if it is
  'b'. The string may be any length.

deFront("Hello") → "llo"
deFront("java") → "va"
deFront("away") → "aay"

Code:

public String deFront(String str) {
  if(str.length() > 0) {
    if(str.substring(0,1).equals("a") && !str.substring(1,2).equals("b")) {
      return str.substring(0,1) + str.substring(2,str.length());
    } else if(str.substring(1,2).equals("b") && !str.substring(0,1).equals("a")) {
      return str.substring(1,2) + str.substring(2,str.length());
    } else if(str.substring(0,1).equals("a") && str.substring(1,2).equals("b")) {
      return str;
    } else {
      return str.substring(2,str.length());
    }
  } else {
    return "";
  }
}

Yes, some of the things you are doing is redundant and quite messy. As this seems to be a homework assignment I will only provide hints for you here.

What you can do is:

If the string is empty, return an empty string immediately
Store the first character in a variable
Store the second character in a variable, if it exists
Store the rest of the string in a variable, if it exists
Check if the second character is 'b', if it is then add it to the beginning of the string
Check if the first character is 'a', if it is then add it to the beginning of the string
Return the string

A problem of your existing code is that it will fail for strings of length 1. So it is important to only use the first and second characters if they exist at all.

This seems to work:

public String deFront(String str) {
  return (str.startsWith("a") ? "a" : "") + (str.matches(".b.*") ? "b" : "") + (str.length() > 2 ? str.substring(2) : "");
}

Or even shorter with regex replaceAll:

public String deFront(String str) {
  return str.replaceAll("^((a)|[^a])((b)|[^b])?(.*)", "$2$4$5");
}


Using Support Vector Machine algorithm to analyze satellite image I am using Support Vector Machine (SVM) algorithm to perform a classification. The satellite image I am using is really big (5GB) that's why I am trying to take advantage of multiprocessing tool to speed up the process.

My problem is that my PC does not use all the available cores. I run the code to my laptop (4 cores) but it takes for ever for the process to finish. It uses all the 4 CPU cores though. When I try to run the same code on the desktop PC which has 12 CPU cores, only 5 of them reaches 100%.
below, we see the image to be classified and the training data that are used on the right

import os
import numpy as np
from osgeo import gdal, gdal_array, gdalconst
from osgeo import ogr
import pandas as pd
import image_slicer

from sklearn.svm import SVC
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score, StratifiedKFold, StratifiedShuffleSplit
from sklearn.model_selection import validation_curve, GridSearchCV
from sklearn.pipeline import Pipeline

from matplotlib.pylab import *
from multiprocessing import Pool
import time

img = 'sea_ice.tif' #image to be used for classification, 3000 x 3000 pixels
roi = 'training_data.shp' #training data

X = img[roi_int > 0, 2:] #X is the matrix containing our features
y = roi[roi>0] #y contains the values of our training data

#Split our dataset into training and testing. Test data will be used to make predictions
split_test_data = 0.30
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=split_test_data, random_state=42)
stratified = StratifiedShuffleSplit(len(y_train), 10, split_test_data, random_state=0)

#use pipeline method to do all the steps automatically
pip = Pipeline([ ('scale', MinMaxScaler()),
             ('svm', SVC())])
pip.fit(X_train, y_train)

def predict(input_data):
    img_predict = pip.predict(input_data)
    return img_predict

start = time.time()

tfs_shape = (img.shape[0] * img.shape[1], img.shape[2]-2 )
tfs_2D = img[:, :, 2:].reshape(tfs_shape)

# split good data into chunks for parallel processing
tfsChunks = np.copy(tfs_2D)
split = np.array_split(tfsChunks, 9)

# run parallel processing of all data with SVM
pool = Pool(9)
svmLablesGood = pool.map(predict, split)

# join results back from the queue and insert into full matrix
svmLabelsGood = np.hstack(svmLablesGood)

# reshape labels from vector into 2D raster map
svm_reshape = svmLabelsGood.reshape(img.shape[0], img.shape[1])
plt.imshow(svm_reshape)
plt.show()

end = time.time()
print 'the processing time is:', end - start, '\n'

#Evaluate the model using K-fold cross-validation
scores_svm = cross_val_score(pip, X_test, y_test, scoring='accuracy', cv=stratified)
print ('Accuracy: %0.2f (+/- %0.2f)' % (scores_svm.mean(), scores_svm.std())), '\n'
print ('10 parts cross-validation:' , scores_svm), '\n'

score_train = pip.score(X_train,y_train)
score_test = pip.score(X_test,y_test)
print 'training score:', score_train, '\n'
print 'testing score:', score_test, '\n'

below, the results from the classification are shown (after 3 days of processing). I need to classify areas with ice and ice free areas. Yellow areas show the ice.

I cannot wait for 3 days for my laptop to finish the process. I want to take advantage of the 12 CPU cores of the desktop PC to speed up the process, but I do not understand why only 5 cores are used.

When you want to parallelize a program you have to actually do it. When you're using C, you can hope that the compiler will spread the CPU "tension" to other CPU, which it will do with the right compiler command. But you're using Python so it cannot do the optimization since there is no (separate) compiler.

But even with C it doesn't work that well. Normally you have to do it yourself with threads. If you can make your calculation on threads you should do it. I didn't read your code in details, but when it comes to SVN I guess that the calculation doesn't depend on previous calculation. If that's the case you might be able to parallelize your program with as many threads as you have cores.

But I think that you have to do that step of parallelizing by yourself, you can't count on the machine to guess where it can or cannot parallelize.

And that will possibly reduce the execution time by the number of threads. (even if that not exactly true, that's a max).


PHP MVC controller code needs diet? This is the dashboard controller code in PHP Symfony 2. It collects some aggregate data and points for charts, but i don't like it very much. Do you think that this code belongs to what a controller should do in a MVC patter? How can i refactor it?

public function dashboardAction()
{
    $bag = array();

    // Helpers from service container
    $messaging = $this->get('messaging.helper');
    $charting  = $this->get('charting.helper');

    // Current logged user, subscription and message inhibitor
    $loggedUser   = $this->getSecurityContext()->getToken()->getUser();
    $subscription = $messaging->createSubscriptionFromUser($loggedUser);
    $usage        = $messaging->createUsageFromSubscription($subscription);

    $bag['subscription'] = $subscription;
    $bag['usage']        = $usage;
    $bag['inhibitor']    = $messaging->createInhibitor($usage, $subscription);

    // Get charts from usage raw data
    $rawData = $usage->getRawData();
    $start   = $usage->getStartDate();
    $end     = $usage->getEndDate();

    $bag['line_chart'] = $charting->createMessagesLineChart($rawData, $start, $end);
    $bag['pie_chart']  = $charting->createMessagesPieChart($rawData);

    // Customers and latest 5 added
    $customers = $loggedUser->getCustomers();

    $bag['customers_count']  = $customers->count();
    $bag['latest_customers'] = $customers->slice(0, 5);

    // Tags/keywords counts and latest 5 meta
    $metas       = $loggedUser->getMeta();
    $getTags     = function($m) { return $m instanceof Tag; };
    $getKeywords = function($m) { return $m instanceof Keyword; };

    $bag['tags_count']     = $metas->filter($getTags)->count();
    $bag['keywords_count'] = $metas->filter($getKeywords)->count();
    $bag['latest_meta']    = $metas->slice(0, 5);

    // SMS and newsletter counts
    $outgoingMessages = $loggedUser->getOutgoingMessages();
    $getSms           = function($m) { return $m instanceof SmallTextMessage; };
    $getNewsletters   = function($m) { return $m instanceof Newsletter; };

    $bag['sms_count']        = $outgoingMessages->filter($getSms)->count();
    $bag['newsletter_count'] = $outgoingMessages->filter($getNewsletters)->count();

    return $bag;
}

A controller? No. A model? Sure. Not sure if Symfony defines a controller differently, but this is not what I think of as a controller.

As for refactoring, the easiest way would be to break it up into smaller methods. For instance, right off the bat I see at least 6 different potential methods here. You could create a bunch of smaller methods that returns a part of the bag (messaging, charting, etc...) and then merge them all together. In fact, that's the only real improvement I can see. I feel bad leaving such a short answer, so here's an example of a couple of those smaller methods, which is actually about half that code.

private function getUsageCharts ( $usage ) {
    $rawData = $usage->getRawData();
    $start   = $usage->getStartDate();
    $end     = $usage->getEndDate();

    $line_chart = $charting->createMessagesLineChart($rawData, $start, $end);
    $pie_chart  = $charting->createMessagesPieChart($rawData);

    return compact( 'usage', 'line_chart', 'pie_chart' );
}

private function getMessagingFields( $loggedUser ) {
    $messaging = $this->get('messaging.helper');

    $subscription = $messaging->createSubscriptionFromUser($loggedUser);
    $usage = $messaging->createUsageFromSubscription($subscription);
    $inhibitor = $messaging->createInhibitor($usage, $subscription);

    extract( $this->getUsageCharts( $usage ) );//$line_chart, $pie_chart
    return compact( 'subscription', 'usage', 'inhibitor', 'line_chard', 'pie_chart' );
}

Hope this helps!

Without knowing anything about sympony's details:

I'd refactor most of the code into your view. I prefer to pass the required objects to the view and let the view pull the information it needs from the object(s)
Rename the variable bag
Move the subscription data into your user-model
Make the helpers available to your views (especially the charting helper)

This decouples the controller from the display logic. The controller just determines the user to display the dashboard for and the view determines which data to display and how to display it (e.g. you could have to different dashboards (views)).

public function dashboardAction()
{
    return array('user' => $this->getSecurityContext()->getToken()->getUser());
}

In your view (not knowing how views are done in symphony):

// Helpers from service container
$messaging = $this->get('messaging.helper');
$charting  = $this->get('charting.helper');

// Current logged user, subscription and message inhibitor
$loggedUser   = $this->get('user);
$subscription = $messaging->createSubscriptionFromUser($loggedUser);
$usage        = $messaging->createUsageFromSubscription($subscription);

// Display charts from usage raw data
$rawData = $usage->getRawData();
$start   = $usage->getStartDate();
$end     = $usage->getEndDate();

echo $charting->createMessagesLineChart($rawData, $start, $end);
echo $charting->createMessagesPieChart($rawData);

// Display the 5 newest customers
$customers = $loggedUser->getCustomers();

echo $customers->count();
echo $customers->slice(0, 5);

// Display the 5 latest Tags/keywords & total count
$metas       = $loggedUser->getMeta();
$getTags     = function($m) { return $m instanceof Tag; };
$getKeywords = function($m) { return $m instanceof Keyword; };

echo $metas->filter($getTags)->count();
echo $metas->filter($getKeywords)->count();
echo implode(",", $metas->slice(0, 5));

// Display SMS and newsletter counts
$outgoingMessages = $loggedUser->getOutgoingMessages();
$getSms           = function($m) { return $m instanceof SmallTextMessage; };
$getNewsletters   = function($m) { return $m instanceof Newsletter; };

echo $outgoingMessages->filter($getSms)->count();
echo $outgoingMessages->filter($getNewsletters)->count();

Another view of the same dashboardAction just might decide to display only a welcome message, other information, or even be customizable by the user without changing the controller every time (possibly passing the superset of all variables required by any view to each view).

Going further you might want to move some get logic (which you're doing by filtering) into your model: $getTags = $loggedUser->getMeta()->getTags();


Instantiating if null I often have static classes which uses the DataContext somehow, and they all make a new DataContext, but often I already have one instantiated elsewhere, so why not use that?

public static bool SignIn(string email, string password, DataContext db = null)
{

    bool disposeDb = false;
    if (db == null)
    {
        disposeDb = true;
        db = new DataContext();
    }

    //Sign In stuff, or any other stuff...

    if (disposeDb) db.Dispose();
}

But is there a cool trick to do this, or am I just coding it wrong?  Or is it ok?

Update

The DataContext is not expensive to instantiate.  I guess I just leave it be.

But here is another example:

public static User GetUser(DataContext db = null)
{
    if (HttpContext.Current.Request.Cookies["Id"] == null)
    {
        return null;
    }
    else
    {
        bool disposeDb = false;
        if (db == null)
        {
            disposeDb = true;
            db = new DataContext();
        }

        int id = Convert.ToInt32(HttpContext.Current.Request.Cookies["Id"].Value);
        string cookieKey = HttpContext.Current.Request.Cookies["CookieKey"].Value;

        User user = db.Users.FirstOrDefault(x => x.Id == id && x.CookieKey == cookieKey);

        if (disposeDb) db.Dispose();
        return user;
    }
}

This is again nice because if I already have a context, I can provide it, and then I won't have to attach the entity (User) to another context if I want to modify it:

User user = MyClass.GetUser(db);
user.Email = "asdsasd";
db.SaveChanges();

How can I improve it?  Or is it okay?

Update 2

The DataContext should only be instantiated once per page request. And here is a neat way to do it, that actually allows me to access it even from static methods.

At the very least, you should place the second if statement in a finally block.  As things stand, the code is not generally correct from a purely mechanical perspective.  I would also phrase it as:

bool dbDispose = db == null;
db = db ?? new DataContext();

From a design point of view: yes, I'd say this violates the single responsibility principle.  You have a method that not only does certain calculations, but also creates a DataContext if necessary.  If creation has to be modified at any point, then you'll have many places to change that.  (Unlikely if it's default-constructed like this, but I doubt it's that simple in practice.)

It looks to me like SignIn should actually be a member function of DataContext.

Instead of init DataContext inside static methods you can use Singleton pattern or Factory pattern depending on what kind of life cycle of the object DataContext. That patterns allows to encapsulate logic of DataContext initialization and provide more control over the life cycle of an instance(including implementation caching politics).

As for me correct variant GetUser method should look similar on that:

public static class UserService{

public static User GetUser(HttpContext context, DataContext db)
{
   if (db==null)
      throw new ApplicationException("Data Context is null");
   if (context==null)
      throw new ApplicationException("Http Context  is null");

    if (context.Request.Cookies["Id"] == null)
    {
       return null;
    }
    else
    {
         int id = Convert.ToInt32(context.Request.Cookies["Id"].Value);
         string cookieKey = context.Request.Cookies["CookieKey"].Value;

         User user = db.Users.FirstOrDefault(x => x.Id == id && x.CookieKey == cookieKey);

         return user;
    }

}

}


Python Bubble sort code I have written the below bubble sort code in Python.

def bubble_sort():
    num_list=[]
    list_cnt=input("How many numbers you would like to sort:")
    for i in range(int(list_cnt)): ### need to convert the value returned by input()
        num_list.append(input("Enter " +str(i)+" number:")) ##here we are using append method of list

    print("The values input are as follows:")
    print(num_list)

    print(len(num_list))
    ### Below new line of code added to convert list to integer###
    num_list=list(map(int,num_list))
    ## with the above line the code is now working as expected##
    max_index=len(num_list)-1 ## because list begins with 0
    print("max_index is:",max_index)
    for i in range(len(num_list)-1):
        j=0
        swapped=False
        for j in range(len(num_list)-1):
            if num_list[j] > num_list[j+1]:
                num_list[j],num_list[j+1]=num_list[j+1],num_list[j]
                print("Sorted when j=" +str(j)+ " and i=" + str(i)+ " is:\n ")
                print(num_list)
                swapped=True
        if not swapped:
            break

    print("The sorted list is :")
    print(num_list)

bubble_sort()

Your code's quite good. I'd however change it in the following ways:

Move the creation of the lits out of the buble_sort.
Remove the prints from buble_sort.
Follow PEP8.
Change for i in range(...) to while True:.
Use better variables. num_list to array could do.
Use str.format, rather than string addition.
Change the creation of num_list to use a list comprehension.

def bubble_sort(array):
    while True:
        swapped = False
        for j in range(len(array)-1):
            if array[j] > array[j+1]:
                array[j], array[j+1] = array[j+1], array[j]
                swapped = True
        if not swapped:
            break

if __name__ == '__main__':
    amount = input("How many numbers you would like to sort:")
    array = [
        int(input("Enter {} number:".format(i)))
        for i in range(int(amount))
    ]

    print("The values input are as follows: {}".format(array))
    bubble_sort(array)
    print("The sorted list is: {}".format(array))

def bubble(items):
    num = len(items)
    for scan in range(num-1):
        swaped = False
        #takes care of the scanning through the array
        for swap in range(num-1-scan):
            if items[swap]>items[swap+1]:
                temp_var = items[swap]
                items[swap]=items[swap+1]
                items[swap+1]=temp_var
                swaped = True
            if swaped == True:
                break;

items = [90,23,95,56]
bubble(items)
print("sorted itema are:",items)


Blackjack casino game Blackjack (twenty-one) is a casino game played with cards. The goal of
  the game to draw cards that total as close to 21 points as possible
  without going over. All face cards count as 10 points, aces count as 1
  or 11, and all other cards count their numeric value.

  The game is played against a dealer. The player tries to get closer to
  21 (without going over) than the dealer. If the dealer busts (goes
  over 21) the player automatically wins (provided the player had not
  already busted). The dealer must always take cards according to a
  fixed set of rules. The dealer takes cards until he or she achieves a
  total of at least 17. If the dealer's hand contains an ace, it will be
  counted as 11 when that results in a total between 17 and 21
  inclusive; otherwise, the ace is counted as 1.

  Write a program that simulates multiple games of blackjack and
  estimates the probability that the dealer will bust. Hints: treat the
  deck of cards as infinite. You do not need to keep track of the cards
  in the hand, just the total so far (treating an ace as 1) and a bool
  variable hasace that tells whether or not the hand contains an ace. A
  hand containing an ace should have 10 points added to the total
  exactly when doing so would produce a stopping total(something between
  17 and 21 inclusive).

It runs, but I'm just looking to improve it if possible.

def printIntro():
    print("This program simulates a bunch of blackjack games.")

def getInputs():
    while True:
        n = eval(input("How many games should be simulated? "))
        if n <= 0:
            print("You must enter a number greater than zero!")
        else:
            break

    return n

def simOneGame():
    score = 0
    blacklist = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
    while not gameOver(score):
        blackscore = blacklist[randrange(len(blacklist))]
        score = score + blackscore

        if score >= 17:
             break
        if blackscore == 11 and (score >= 6 and score <= 10):
            score = score + 11
        else:
            score = score + 1

    return score

def simNGames(n):
    holds = 0
    busts = 0
    for i in range(n):
        score = simOneGame()
        if score >= 22:
            busts = busts + 1
        else:
            holds = holds + 1

    return holds, busts

def gameOver(score):
    return score >= 22 or score >= 17

def printSummary(holds, busts):
    n = holds + busts
    print("Number of holds and busts: Holds: {0:0} Busts: {1:0}".format(holds, busts))
    print("Percentage of holds and busts: Holds: {0:0.1%}".format(holds / n), end = " ")
    print("Busts: {0:0.1%}".format(busts / n))

def main():
    printIntro()
    n = getInputs()
    score = simOneGame()
    holds, busts = simNGames(n)
    printSummary(holds, busts)

if __name__ == "__main__":
    main()

def printIntro():
    print("This program simulates a bunch of blackjack games.")

Python style guide recommend lowercase_with_underscores for function names

def getInputs():
    while True:
        n = eval(input("How many games should be simulated? "))

not a really good idea to use eval, because that allows the user to input any python expression which may not make sense. Instead use int, which will only allow numbers

        if n <= 0:
            print("You must enter a number greater than zero!")
        else:
            break

    return n

def simOneGame():
    score = 0
    blacklist = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
    while not gameOver(score):
        blackscore = blacklist[randrange(len(blacklist))]

Python has a function, random.choice() which returns a random element from a list.

        score = score + blackscore

        if score >= 17:
             break

Why? The loop will terminate anyways. There doesn't seem to be a reason to break here

        if blackscore == 11 and (score >= 6 and score <= 10):
            score = score + 11
        else:
            score = score + 1

I assume that this has to do with handling aces, but I don't understand the logic. You've already added blackscore to score, so I wouldn't think this would do the right thing. Also, couldn't you need to change the value of an ace to a 1, from an eleven due to later cards?

    return score

You only really care about busts/holds so maybe you should return True or False?

def simNGames(n):
    holds = 0
    busts = 0
    for i in range(n):
        score = simOneGame()
        if score >= 22:
            busts = busts + 1
        else:
            holds = holds + 1

    return holds, busts

def gameOver(score):
    return score >= 22 or score >= 17

That's the same as score >= 17, no reason to include the first part of the condition

def printSummary(holds, busts):
    n = holds + busts
    print("Number of holds and busts: Holds: {0:0} Busts: {1:0}".format(holds, busts))
    print("Percentage of holds and busts: Holds: {0:0.1%}".format(holds / n), end = " ")
    print("Busts: {0:0.1%}".format(busts / n))

def main():
    printIntro()
    n = getInputs()
    score = simOneGame()
    holds, busts = simNGames(n)
    printSummary(holds, busts)

if __name__ == "__main__":
    main()

You didn't import the randrange function from the random module. Without this, it won't work.


Filtering out empty Optionals I want to convert my list of optional strings to a list of strings by getting rid of the empty Optionals.

Is there a shorter version for achieving this than the following code (except statically importing the methods of Collectors)?

List<Optional<String>> stringsMaybe = Arrays.asList(Optional.of("Hi"),
                                      Optional.empty(), Optional.of(" there!"));

List<String> strings = stringsMaybe
            .stream()
            .filter(Optional::isPresent)
            .collect(Collectors.mapping(Optional::get, Collectors.toList()));

It's more idiomatic to use .map on the stream instead of Collectors.mapping:

stringsMaybe.stream()
    .filter(Optional::isPresent)
    .map(Optional::get)
    .collect(toList());

Without introducing a helper method or a custom collector, that's the shortest and clearest way to do this.

Since Java 9, Optional offers a stream method, enabling you to do .flatMap(Optional::stream) instead of .filter(...).map(...).

If you are using rxJava you can do something like:

Flux<Optional<String>> maybeStrings = Flux.just(
    Optional.of("Hi"),
    Optional.empty(),
    Optional.of(" there!"));

Flux<String> strings = maybeStrings.handle((maybeString, synchronousSink) ->
    maybeString.ifPresent(synchronousSink::next));


Equivalent of C-style "Static Local Variable" in Swift I'm porting some Obj-C code to Swift, and I've written the following code to allow me to deal with "static local variables" which do not exist in Swift.

A static local variable has these requirements:

it is shared between all instances that access it
it has one assignment method which only sets the value when it is first declared.
has another assignment method which sets its value normally (i.e. any time it is used)

There has to be a better way then what I have coded. For starters, I know that using  UnsafeBitcast is not good practice.

class Container<T:Any>{

    var _memory:Any
    var memory:T {
        get {

            if let typed_value = self._memory as? T {
                // for value types, such as "String"
                return typed_value
            } else {
                // for types conforming to "AnyObject", such as "NSString"
                return unsafeBitCast( self._memory, T.self )
            }

        }
        set {
            self._memory = newValue
        }
    }

    init( memory:Any ){
        self._memory = memory
    }

}

var Static_Containers = [String:AnyObject]()

func static_var <T:Any>(
    value:T,
    file: StaticString = __FILE__,
    line: UWord = __LINE__,
    col: UWord = __COLUMN__,
    fun: StaticString = __FUNCTION__
) -> Container<T> {

        let unique_key = "FUNC_\(fun)__LINE\(line)_COL\(col)__FILE_\(file)"

        let needs_init = !contains( Static_Containers.keys, unique_key )

        if needs_init {
            Static_Containers[unique_key] = Container<T>( memory:value )
        }

        return Static_Containers[unique_key]! as! Container<T>

}

Here's a couple tests:

func test_with_nsstring( str:NSString, init_only:Bool ) -> NSString {
    var stat_str = static_var( str )
    if !init_only {
        stat_str.memory = str
    }
    return stat_str.memory
}
test_with_nsstring( "this should get set", true )
test_with_nsstring( "this should be ignored", true ) // only repeated declaration
test_with_nsstring( "this should change the value", false )
test_with_nsstring( "as should this", false )

func test_with_int( i:Int, init_only:Bool ) -> Int {
    var stat_int = static_var( i )
    if !init_only {
        stat_int.memory = i
    }
    return stat_int.memory
}
test_with_int( 0, true )
test_with_int( 1, true ) // only repeated declaration
test_with_int( 2, false )
test_with_int( 3, false )

func test_with_optstr( optstr:String?, init_only:Bool ) -> String? {
    var stat_optstr = static_var( optstr )
    if !init_only {
        stat_optstr.memory = optstr
    }
    return stat_optstr.memory
}
test_with_optstr( nil, true )
test_with_optstr( "this should be ignored", true ) // only repeated declaration
test_with_optstr( "this should change the value", false )
test_with_optstr( "as should this", false )

When I test this code in a Playground, it seems to behave correctly. I'd just like a less nutty, and less brittle, way to accomplish this.

The only work around for this that I've come up with thus far is something that looks like this:

func foo() -> Int {
    struct Holder {
        static var timesCalled = 0
    }
    return ++Holder.timesCalled;
}

It's pretty clunky in my opinion, and I'm not sure why Apple doesn't just allow straight static function variables, but this seems quite a bit cleaner than your approach.

it seems working in Xcode 6.3.1.. as stated in Apple manuals, we can use static as we do in "C". (let's forget theoretical differences... )

import Foundation

class Shape{

    private static var shapeCount = 0

    init() {
        Shape.shapeCount++
        println("I am \(Shape.shapeCount)' shape")
    }

    deinit{
        Shape.shapeCount--
    }

    class func ClassInfo()->String{
        return "we have \(Shape.shapeCount) instances"
    }
}

class Circle : Shape {

    override class func ClassInfo()->String{
        return "we have \(Circle.shapeCount) instances"
    }

}

var s1 : Shape? = Shape()
var s2 : Shape? = Shape()
var c1 : Shape? = Circle()

println(Shape.ClassInfo())
println(Circle.ClassInfo())

s1 = nil
s1 = nil
c1 = nil

println(Shape.ClassInfo())

As You can see, shapeCount seems working as expected, even if we cannot use "class" qualifier.

OR you can use exactly as in old "C" program, moving property outside ALL the class doing:

import Foundation

private  var shapeCount = 0

class Shape{

....

(God bless us.. but the effect is the same)

Another big issue to be noted is thread-safe access..


SQL-injection mitigation script I'll gladly appreciate it if you could review my code below and let me know if they are sufficiently secure.

My main website and these scripts will use same database, so I need to make sure they are sufficiently secure before I put them live.

Since I cannot post more than two links, I'll post my Anti-SQL Injection script, and below are the actual two scripts.

<?php
if (!function_exists('sql_inject_chec')) {
function sql_inject_chec(){
 // Anti-SQL Injection
 $badwords = array("--",";","'",'"',"DROP",
                   "SELECT", "UPDATE", "DELETE",
                   "drop", "select", "update", "delete",
                   "WHERE", "where","exec","EXEC",
                   "procedure","PROCEDURE");
 foreach($_REQUEST as $value)  {
  foreach($badwords as $word)
   if(substr_count($value, $word) > 0) {
    die("SQL Эnjection Denemesi Yaptэnэz... ama Baюarэsэz Oldunuz ;)");
    }
  }
 }
}
sql_inject_chec();
?>

Ingame registration - SCRIPT

Score display - SCRIPT

This is not a constructive way to protect your scripts from SQL injection — the objective of SQL-injection prevention should not be to disallow characters or words, but to escape characters. What you have now, prevents your users from submitting perfectly valid English words such as select, update, etc. and/or perfectly valid characters such as --, " and '.

Consider this fictional comment:

  When I select "where" from the menu, it updates the procedure -- strange.

This would be rejected by your code.

Now, I'm sure, for your application, this might (currently) be irrelevant, but your code is not very flexible or portable. What happens if your current application, or another future application needs to accept these words? You'd have to rewrite your code, and for a possible new application you wouldn't be able to copy existing code.

More importantly though, your current code is probably not elaborate enough to mitigate all possible attack vectors. You'd really be wise to implement prepared, parameterized  statements by using PDO, instead of trying to prevent your users from entering possible SQL keywords and characters. With prepared, parameterized statements you don't have to worry about escaping the correct characters anymore — PDO (or, if the driver supports it natively, the database driver) will escape the parameter values you supply for you.

Let me give you a short introductory example of how you could implement SQL-injection prevention with PDO:

// create a database connection handle
$driver   = 'odbc';
$database = 'kn_online';
$username = '*redacted*';
$password = '*redacted*';
$dbh = new PDO( "$driver:$database", $username, $password );

// create a parameterized statement to select a record from CURRENTUSER
// uses a named parameter (denoted by :), called accountId
// that will be properly escaped by PDO
$sql = 'SELECT * FROM CURRENTUSER WHERE StrAccountID = :accountId';

// prepare the statement; returns a PDOStatement object
$stmt = $dbh->prepare( $sql );

// execute the statement by passing the parameter values in an associative array
$executionResult = $stmt->execute( array(
    ':accountId' => $acc
) );

// if the execution succeeded
if( $executionResult )
{
    // fetch the record as an associative array
    $record = $stmt->fetch( PDO::FETCH_ASSOC );
}

The beauty of prepared statements is that you can also easily execute them repeatedly, with new parameter values. Consider this example (connection handle creation omitted for brevity):

// insert into some table
$sql = 'INSERT INTO SOMETABLE VALUES( :id, :name )';

$stmt = $dbh->prepare( $sql );

// some fictional data
// parameter value keys don't need : prepended
$data = array(
    array( 'id' => 1, 'name' => 'Name One' ),
    array( 'id' => 2, 'name' => 'Name Two' ),
    array( 'id' => 3, 'name' => 'Name Three' )
);

foreach( $data as $datum )
{
    // using the same prepared statement
    // to execute for each datum
    $stmt->execute( $datum );
}

Trying to improve the structure of the code which you posted by removing the inner foreach loop.

foreach($_REQUEST as $value)  {
  if isset($badwords[$value]) {
   die("SQL -njection Denemesi YaptMnMz... ama BaNarMsMz Oldunuz ;)");
  }
}


find longest common substring in space O(n) I am working on the class question find the longest common substring from 2 strings but I would like to return the longest common substring instead of just size of longest common substring.like

s1 = 'abcdex', s2 = 'xbcdey' => 'bcde'
s1 = 'abcxyx', s2 = 'xbcydey' => 'bc'

The way I do it is using dynamic programming to create a memo table and update each cell that required space \$O(n * m)\$. How can I implement the code so I can only using space as \$O(n)\$?

    def longestCommonSubstring(self, s1, s2):
        """
        :type s: str
        :rtype: str
        """
        m, n = len(s1), len(s2)
        dp = [[''] * (n + 1) for _ in range(m + 1)]
        max_len = ''
        for i, ic in enumerate(s1):
            for j, jc in enumerate(s2):
                dp[i][j] = dp[i - 1][j - 1] + ic if ic == jc else ''
                max_len = dp[i][j] if len(max_len) < len(dp[i][j]) else max_len
        return max_len

PEP 8

You are following most of the PEP 8 style guidelines.  One that you are breaking is method names should be snake_case; your function should be named longest_common_substring.

Tricky Code

Your dp matrix is properly allocated to the size m+1 by n+1.

When you index your matrix, you access [i-1][j-1] with \$0 \le i \lt m\$ and \$0 \le j \lt n\$.  This means you never access the last allocated row m or the last allocated column n, but instead rely on accessing the -1 row and the -1 column wrapping around to reach these "unused" spaces.  This is "surprising" code at best, and "crashing" code if translated to a different programming language.

It would be better to add one to the indices used to index the dp matrix.  The simplest way would be to start the i and j enumerations at one:

    for i, ic in enumerate(s1, 1):
        for j, jc in enumerate(s2, 1):

Useless else

Expand out this ... if ... else ... statement:

            max_len = dp[i][j] if len(max_len) < len(dp[i][j]) else max_len

Initially, this produces:

            if len(max_len) < len(dp[i][j]):
                max_len = dp[i][j]
            else:
                max_len = max_len

But we can immediately see the else: clause is a no-op, and can be removed:

            if len(max_len) < len(dp[i][j]):
                max_len = dp[i][j]

Which reads much more clearly than the original.

From \$O(n m)\$ to \$O(n)\$ space

During the first iteration of outer loop, you only access rows -1 and 0.  During the second iteration of outer loop, you only access rows 0 and 1.  During the third iteration of outer loop, you only access rows 1 and 2.  Etc.  You only need two rows of the dp matrix!

More over, you create the 0 row from the -1 row, you create the 1 from the 0 row, you create the 2 row from the 1 row, and so on.

Do you really need to keep the dp matrix?  Or could you use a previous_row and a current_row?  Only storing two length n rows reduces your space to \$O(2n)\$, which is simply \$O(n)\$.

You don't specify what n is, so I'm going to assume that n is the total combined length of the two strings s1 and s2 that are input.

Imagine you have a hashing function h(s) that computes a fixed-size hash value for a given string s. That is, given a string s = "abc" the function h(s) will return some number X that is computed from s, so that changing the contents of s will change the returned value X.

If you keep an array of hash values for the substrings of a given length k for each starting position i, you will have a total size of sizeof(h(s1)) * (n - 2k + 2) which is easily \$O(n)\$.

So, start from the longest possible substring and work your way down, computing the hashes of all substrings then checking to see if the two strings share a common substring. If two hashes are equal you can compare the resulting substrings and return if you find a match. If you get to k==1 and find no match, then there's no match to be had.

With that outline, I'll point out that python provides a built-in called hash() that does what you want.


Opening links in a new tab or window I've got a lot of links (150+) in an href (here I can only post 2) and I want them to be opened in a new tab or window. I've got this piece of code that works, but before I add it to my website and before I add it to a lot of articles of mine (250+), I want to make sure the syntax of the code is 100% correct. Also, do I need the
?

test

test

The code itself is fine, though I would flip it, first html, then the javascript (without the window.onload).

AN example to explain why: If you have a huge image and a slow connection the loading takes say 5 seconds. These 5 seconds all your anchors don't have the target="_blank" and if a user clicks they still leave your website.

I would not use this method meself (unless I have to) .
If you use AJAX to load content with anchors, those anchors will not have the target="_blank" either. This will require a bit more advances problem solving. If you want some links to be ignored, you can't with the current code. There are more small problems that will pop up which are all to minor to sum up here, but in the end are all just very ennoying.

I recommend that you do not rely on this method. Just take some time and update the content. I assume you have that in a datase, just FIND() and REPLACE(). Make it permanent.

You can use querySelectorAll to loop through all of your elements:

document.addEventListener('DOMContentLoaded', function(e) {
    document.querySelectorAll('#links a').forEach(function(el, i) {
        el.setAttribute('target', '_blank');
    });
});


LESS CSS, including support for shadowboxes I'm learning about using LESS and wanted to get anyone's input on if I'm using the concepts, syntax, etc. correctly.I know this might seem subjective and not the correct place to post, so please let me know if there is a more appropriate place to do this.

LESS code

.centered(@position: inline, @width: 100%){
    margin-left: auto;
    margin-right: auto;
    width: @width;
    display: @position;
}

.table-center(@width: 100%){
    width:@width;
    display:table!important;
    text-align:center;
    &:nth-child(1) {
        display:table-cell;
    }
}

.clear-border-radius{
     border-radius: initial;
    -webkit-border-radius: initial;
    -moz-border-radius: initial;
}

.shadowbox-format(@caption-font-size, @button-font-size, @shadowbox-margin) {
    display: block;
    position: absolute;
    min-height: 85px;
    width: 60%;
    margin: @shadowbox-margin;
    left: 20%;

    .shadowbox-caption {
        font-size: @caption-font-size;
        .table-center;
    }

    .shadowbox-button-wrapper {
        width: 35%;
        margin: 26px auto 0;

        & > a {
            .clear-border-radius;
            font-size: @button-font-size;
        }
    }
}

.home-slide-container{
    img{
        .centered(block);
        height:auto;
    }
}
.callout-header{
    text-align:center;
    width: auto;
    margin: 40px auto 0;
    border-bottom: 1px solid #9e9e9e;
    padding: 0 0 30px;
     @media (max-width: @screen-xs-max){
         width: 90%;
     }
          @media (min-width: @screen-sm-min){
         width: 60%;
     }
     span{
         font-size: 24px;
     }

}
 .carousel-shadowbox
 {
         text-transform: uppercase;
         color:#000;
         background-color:rgba(255,255,255,0.4);

     @media (max-width: @screen-xs-max)
     {
         background-color: white;
         opacity:1.0;

          .shadowbox-caption{
            .table-center;
             span{
                font-size: 16px;
                font-weight: 100;
                }
         }
     }
     @media (min-width: @screen-sm-min)
     {
        .shadowbox-format(20px, 16px, -91px auto 0);
     }
     @media (min-width: @screen-md-min)
     {
         .shadowbox-format(22px, 18px, -96px auto 0);
     }
     @media (min-width: @screen-lg-min)
     {
         .shadowbox-format(24px, 20px, -102px auto 0);
     }
}

 .callout{
     position:relative;
     margin-top: 5%;
     img{
         @media (max-width: @screen-xs-max){
             margin: 0 auto;
         }
     }
     .callout-text-container{
         padding:3px;
      @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max)
         {
            bottom:22px;
         }

         min-height: 200px;
         .callout-title{
             padding-top: 5px;
             text-transform: capitalize;
             font-size: 22px;
             display:table;
             width:100%;
             text-align:center;
             margin-bottom: 25px;
             span{
                 display: table-cell;
             }
         }
         .callout-body{
             font-size: 15px;
             padding:8px;
             text-align:justify;
         }
         .button-wrapper{
             padding: 10px;
             a{
                 text-transform: capitalize;
                 border-bottom: 4px solid #cb2b06;
                 background-color: #e6431e;
                .clear-border-radius;
                 font-size: 16px;
             }
         }
     }
 }

Syntax is correct. When I was learning it was helpful to me to view the major LESS libraries out there and see what they were doing.

There are some mixin techniques that you will stumble upon as you advance your proficiency with the language. Also if you have JavaScript skills you can easily add additional logic to the mixins that make them even more powerful.

Once I got to a specific level with my proficiency I wrote my own library and I still use this to date for all of my projects. You can view it here - feel free to pick it apart and see if you find anything useful to use.

Edits suggested by @Dannnno

A few good techniques you will stumble upon are looping through the variables passed into a mixin. This is very powerful because as you create your mixins you will no longer have to create large pass ins that require comma separated notation like your '.shadowbox-format' mixin.

Also using @media inside of each mixin will result in larger then normal CSS output.

You might want to look into some of the Javascript features of LESS and build yourself a way to pass in array values to a holding variable so that when the compiler hits the @media mixin all values are itteraed in one @media statement rather then scattered throughout the document.


Create a collection of functions tupled with a collection of parameters, and execute the collection in order in Scala I am trying to create a collection of Unit functions that have any arity and type, and will execute them in order.

This is the working implementation that I have:

/** A Subroutine simply represents a unit function that takes any number of parameters. */
type Subroutine = (Any) => Unit

/** A Routine represents a collection of functions which may consume a collection of parameters and will always
  * complete an action.
  */
type Routine = List[(Subroutine, Seq[_])]

/** This function will consume a list of functions executing them in order.
  *
  * @param routine is the list of functions and their parameters to be consumed.
  */
def executeRoutine(routine: Routine): Unit = {
  routine.headOption match {
    case Some((f, x)) =>
      f(x)
      executeRoutine(routine.tail)
    case None => ()
  }
}

and when I declare a function or "subroutine", I have to declare it like this in order to extract the parameters:

def myFunction: Subroutine = {
  case (firstParam: Int) :: (secondParam: String) :: _ => ...
  case _ => throw new InvalidParameterException()
}

def myFunction2: Subroutine = {
  case (firstParam: Int) :: _ => ...
  case _ => throw new InvalidParameterException()
}

val routine: Routine = List(
  (myFunction, Seq(firstParam, secondParam)),
  (myFunction2, Seq(firstParam))
)

I realize that this is not close to idiomatic Scala code, and I've been working on implementing a different approach which will partially apply functions one parameter at a time, and then execute the function after the parameters are fully applied. I do not yet have a working version of this approach, but this is as far as I have gotten:

/** A Subroutine simply represents a unit function that takes any number of parameters. */
sealed abstract class Subroutine extends (Any => Unit)

case class Curried(partiallyApplied: Function[_, Function[_, _]], unapplied: Function[_, _]) extends Subroutine

case class Uncurried(function: Function[_, Unit]) extends Subroutine

/** A Routine represents a collection of functions which may consume a collection of parameters and will always
  * complete an action.
  * Using HList for the parameters, from Shapeless
  */
type Routine = List[(Subroutine, HList)]

/** This function will consume a list of functions executing them in order.
  *
  * @param routine is the list of functions and their parameters to be consumed.
  */
def executeRoutine(routine: Routine): Unit = {
  routine.headOption match {
    case Some((f, x)) =>
      executeSubroutine(f, x)
      executeRoutine(routine.tail)
    case None => ()
  }
}

private def executeSubroutine(subroutine: Subroutine, params: HList): Any = {
  subroutine match {
    case Curried(partiallyApplied, unapplied) =>
      partiallyApplied(params.head)(executeSubroutine(unapplied, params.tail))
    case Uncurried(function) => function(params.head)
  }
}

If anyone can help me out that would be greatly appreciated!

Unless I misunderstand your question, I think this is what you want:

type Subroutine[Param] = Param => Any

type Routine = Seq[(Subroutine[_], Seq[Any])]

def execRoutine(routine: Routine): Unit = routine foreach { case (sub, params) => execSubroutine(sub, params) }

def execSubroutine[SubParam] (subroutine: Subroutine[SubParam], params: Seq[Any]): Unit = {
    require(params.nonEmpty)

    subroutine(params.head.asInstanceOf[SubParam]) match {
        case sub: Subroutine[_] => execSubroutine(sub, params.tail)
        case () => require(params.tail.isEmpty) // Require correct number of params.
        case _ => throw new IllegalStateException()
    }
}

val add2 = (a: Int) => (b: Int) => println(a + b)
val add3 = (a: Int) => (b: Int) => (c: Int) => println(a + b + c)

execRoutine(List(
    (add2, List(3, 4)),
    (add3, List(3, 4, 5))
))

Try it online!

This program prints 7 and 12. Unfortunately, if the parameters are of the wrong type, a runtime exception occurs instead of a compile time one. Attempting to apply the less or more than the required parameters also results in a runtime exception.