C++ vectors sort ascending/descending How can I eliminate repetition from this code?

std::vector<std::wstring> vec;
bool                      descending;
if (descending)
{
    std::sort(vec.begin(),
              vec.end(),
              std::greater<std::wstring>());
}
else
{
    std::sort(vec.begin(),
              vec.end(),
              std::less<std::wstring>());
}

I tried

std::sort(vec.begin(),
          vec.end(),
          descending
             ? std::greater<std::wstring>()
             : std::less<std::wstring>());

but it fails because greater and less do not evaluate to the same type.

Another question: is it possible to automatically retrieve the required type, std::wstring, from the object vec?

There are a few ways of going about this. One is creating an aggregate type that can forward to the call to the correct comparator.

template <typename T>
struct comp
{
private:
    bool desc;
    std::greater<T> great;
    std::less<T> less;

public:
    explicit comp(bool descending = false)
      : desc(descending)
    { }

    bool operator()(const T& f, const T& g) const
    {
        return (desc) ? great(f, g) : less(f, g);
    }
};

The downside of this is that a comp object will be at least sizeof(greater + less + bool). This may or may not be a problem. Your call to sort would then look something like:

typedef std::wstring str_t;
bool descending = true;
std::sort(vec.begin(), vec.end(), comp<str_t>(descending));

If the decision is always known at compile time, you can play some template tricks:

template <typename T, bool desc>
struct comp;

template <typename T>
struct comp<T, true>
{
private:
    std::greater<T> great;

public:
    bool operator()(const T& f, const T& g) const
    {
        return great(f, g);
    }
};

template <typename T>
struct comp<T, false>
{
private:
    std::less<T> less;

public:
    bool operator()(const T& f, const T& g) const
    {
        return less(f, g);
    }
};

This requires descending to be const or constexpr:

constexpr bool descending = false;
std::sort(v.begin(), v.end(), comp<str_t, descending>());

This might be a one step forward, two step back kind of solution. It's quite a bit of code to avoid an if/else - you'll need to decide if this is worth it at all.

Edit: As @LokiAstari pointed out, you can simplify the above with inheritance:

template <typename T>
struct comp<T, true>
  :  std::greater<T>
{ }

template <typename T>
struct comp<T, false>
  : std::less<T>
{ }


Successful Encoder and Decoder for messages I recently wrote a code for a encoder and decoder that works off of a key and the only way to decode the message is with this program and the case-sensitive key. I have yet to incorporate punctuation but that will come soon. I am currently designing a GUI using the  Tkinter module. I would love any feedback.

from random import seed, shuffle
#Encoder Function
def Encoder(user_input,SEED):
    user_input = user_input.lower()
    letter = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    Letter_code = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}
    code = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]
    n = []
    seed(SEED)
    shuffle(code)
    for letter in user_input:
        for let in letter:
            if letter != " ":
                if letter == let:
                    first = Letter_code[let]
                    n.append(code[first])
            else:
                n.append("~")
    return ''.join(n)

#Decoder Function
def Decoder(user_input,SEED):
    user_input = user_input.lower
    key_list = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    final = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    seed(SEED)
    shuffle(key_list)
    key_code = {}
    z = 0
    n = []
    for key in key_list:
        key_code[key] = z
        z += 1
    for let in user_input:
        if let != "~":
            for Ke in key_list:
                if let == Ke:
                    a = key_code[Ke]
                    n.append(final[a])
        else:
            n.append(" ")
return ''.join(n)

#Prompt
encode_decode = raw_input("Would you like to encode or decode a message?(encode/decode)")
encode_decode = encode_decode.lower()
if encode_decode == "encode":
    message = raw_input("Message to encode (no puncuation):")
    SEED = raw_input("Key:")
    print Encoder(message,SEED)
elif encode_decode == "decode":
    message = raw_input("Message to decode:")
    SEED = raw_input("Key:")
    print Decoder(message,SEED)
else:
    print "!!!INVALID RESPONSE!!!"

Concept

Interesting idea to use the pseudo-random number generator seed as an encryption key.  Note, however, that there's no guarantee that the PRNG implementation will be consistent from release to release of Python, or that it will act identically across platforms.  The same goes for the shuffle() function.

As you probably know, you should never try to implement your own cryptography for any meaningful usage, and this substitution cipher is trivially crackable by letter frequency analysis.  I'll treat this as nothing more than a fun programming exercise.

Correctness

In the decoder, the call to lower() is missing parentheses.  The return statement is incorrectly indented.

In the encoder, the letter iteration dummy variable shadows the letter array defined earlier.  In effect, the code becomes:

def Encoder(user_input,SEED):
    user_input = user_input.lower()
    letter = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    Letter_code = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}
    code = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]
    n = []
    seed(SEED)
    shuffle(code)
    for letter in user_input:    # Note: This letter variable shadows the previous letter
        let = letter             # Originally… for let in letter:
        if letter != " ":
            if True:             # Originally… if letter == let:
                first = Letter_code[let]
                n.append(code[first])
        else:
            n.append("~")
    return ''.join(n)

That happens to mostly work!  The only thing that breaks was that you had intended to filter out unencodable characters, and now it will raise a KeyError if user_input contains anything other than letters or spaces.

If you dig deeper for a root cause of your bug, you can blame it on a proliferation of variables, causing confusion.  See if you can eliminate some variables, and name the remaining ones better.

Efficiency

In the encoder, your if letter != " " should be put between the outer and inner for-loops.  The decoder does it right.

Nested for-loops are a sign of poor efficiency.  Lookups should be done using a dictionary.  A dictionary would be more efficient (constant-time access rather than a scan through 26 list items), and it would look cleaner in the code.  (If you were doing serious cryptography, you would need all operations to be constant-time, to thwart attacks based on analyzing timing.)

Style

Naming conventions:

Encoder(user_input, SEED) → encode(user_input, seed) because it's a function, not a class.  You want a verb, not a noun.  SEED is not a constant.
Decoder(user_input, SEED) → decode(user_input, seed) for the same reasons.
letter → LETTER because it's a constant.
Letter_code → LETTER_CODE because it's a constant.
n → encoded or n → decoded because n has the connotation of being a number.

Prefer list comprehensions to loops: If you ever want to transform one list into another list, use a list comprehension instead of a for-loop if it's at all possible.  It's one assignment statement, and it forces you to express yourself using higher-level functions rather than step-by-step procedural code.
Work smarter, not harder: Save yourself some error-prone typing — let the computer generate your lists of letters and their corresponding codes.
Symmetry: The decoder is just the inverse of the encoder, so there's no reason why it should be any more complex.
If-else: Whenever you have an if-else construct, prefer to put the branch with the shorter body first to reduce mental workload.  For example, write the decoder this way:

if let == "~":
    n.append(" ")
else:
    for Ke in key_list:
        if let == Ke:
            a = key_code[Ke]
            n.append(final[a])

Proposal

from collections import defaultdict
from random import seed, shuffle

def encode(plaintext, key):
    """
    Performs a toy-grade substitution cipher on plaintext using the key.
    Any characters other than letters and spaces in plaintext will be discarded.
    """
    LETTERS = [chr(ord('a') + i) for i in range(26)]
    seed(key)   # influences shuffle()
    code = LETTERS[:] ; shuffle(code)
    # letter_code maps LETTERS to a copy of LETTERS that is scrambled using the key;
    # unrecognized characters map to the empty string.
    letter_code = defaultdict(str, zip(LETTERS, code))
    letter_code[' '] = '~'
    return ''.join([letter_code[c] for c in plaintext.lower()])

def decode(ciphertext, key):
    """
    Performs the inverse of encode().
    Any characters other than letters and spaces in ciphertext will be discarded.
    """
    LETTERS = [chr(ord('a') + i) for i in range(26)]
    seed(key)   # influences shuffle()
    code = LETTERS[:] ; shuffle(code)
    # The inverse of letter_code in encode()
    code_letter = defaultdict(str, zip(code, LETTERS))
    code_letter['~'] = ' '
    return ''.join([code_letter[c] for c in ciphertext.lower()])


internal links b/w sheets of merged workbooks, using VBA (EXCEL MACROS) My aim is to merge all workbooks having multiple sheets from any specified folder to one workbook of multiple sheets. The problem is I don’t want external links to be maintained, If I use "breaklink" it will break all links(external links) b/w sheets of all workbooks. what I exactly I need is, After merging all sheets of workbooks in one workbook, I need links b/w these merged sheets.
CODE FOR MERGE ALL WORKBOOKS INTO ONE WORKBOOK :
Sub merge()

Dim FolderPath As String

Dim Filename As String

Dim Sheet As Worksheet

Application.ScreenUpdating = False

FolderPath = "C:\Users\Samiya jabbar\Desktop\test"

Filename = Dir(FolderPath)

Do While Filename <> ""

Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True

For Each Sheet In ActiveWorkbook.Sheets

Sheet.Copy After:=ThisWorkbook.Sheets(1)

Next Sheet

Workbooks(Filename).Close

Filename = Dir()

Loop

Application.ScreenUpdating = True

End Sub
```

Here are a couple of pointers:

FolderPath should be a constant because it's value will never change
Using a wildcard Filter with the path will ensure that you open the correct files
Although ActiveWorkbook does the job, it is best to get in the habit of using qualified references
Workbook.Worksheets returns a Worksheets Collection (not to be confused with a normal VBA Collection)
Worksheets can be used to perform group operations on all of it's Worksheets at one time
Download RubberDuck.  Among its many great features is Code Indentation.  It will save you a ton of time reformatting and show you unclosed code blocks

Sub merge()
    Const FolderPath As String = "C:\Users\Samiya jabbar\Desktop\test"
    Const Pattern As String = "*.xl*"

    Dim Filename As String

    Dim Sheet As Worksheet

    Application.ScreenUpdating = False

    Filename = Dir(FolderPath & Pattern)

    Do While Filename <> ""

        Workbooks.Open(Filename:=FolderPath & Filename, ReadOnly:=True).Worksheets.Move After:=ThisWorkbook.Sheets(1)

        Filename = Dir()

    Loop

    Application.ScreenUpdating = True

End Sub


Simple addition calculator accepting addition expressions Maybe someone can help me to optimize the calculate method. I think that it can be simplified from that what I have now.

The objective is: grab a string via the incoming argument of the calculate method and get the amount of it or difference (based on the sign standing between numbers). Count of numbers should be  2.

My function, method and constructor are working fine, but I think it is too lengthy/complex for such a simple task.

function Calculator() {

  this.calculate = function(sum) {
    this.summ = 0;

    this.sumArr = sum.split(' '); // make array from string to clear from non-numbers values
    this.newSum = this.sumArr.filter(function(number) {
      return number > 0;
    });

    for (var i = 0; i < this.sumArr.length; i++) { // based on the sign standing between numbers calculate it
      if (this.sumArr[i] == '+') {
        return this.summ = parseInt(this.newSum[0]) + parseInt(this.newSum[1]);
      } else if (this.sumArr[i] == '-') {
        return this.summ = parseInt(this.newSum[0]) - parseInt(this.newSum[1]);
      }
    }
  };
};

var calc = new Calculator;

console.log(calc.calculate("3 + 7")); // 10
console.log(calc.calculate("3 - 7")); // -4

Instance method vs. class method vs. function:
You declared a constructor function Calculator whose instances all come with their own individual calculate method. Since the calculate method doesn't rely on other instance properties, it should probably be a class method instead.
In JavaScript, a class method is simply a property of the constructor function:
function Calculator() { ... }

Calculator.calculate = function(sum) { ... };

Using class syntax, this is equivalent to:
class Calculator {
  ...
  static calculate(sum) { ... }
}

However, unless your Calculator will have additional properties later on, a simple function calculate(sum) { ... } instead of a class will do the job just fine.
Instance properties and side effects:
Within your calculate method, you create new instance properties such as this.sumArr, this.newSum and this.summ holding the result of the calculation. This is called a side effect. Pure functions without such side effects are easier to understand and debug.
Also, those property names are not very descriptive.
Consistency:
For different inputs, the values of this.summ and the return values of calculate(sum) are inconsistent:
sum         calculate(sum)  this.summ
-------------------------------------
undefined   TypeError       0
""          undefined       0
"1 x 1"     undefined       0
"1 + x"     NaN             NaN

Filtering your operands with number > 0 leads to strange effects such as returning NaN for inputs with a zero such as 0 + 1 and returning 1 for input bla - bla + 3 + 2.
Parsing:
Instead of parseInt(str) I recommend using the unary plus operator +str which is "the fastest and preferred way of converting something into a number" according to MDN.
To split an expression into operands and operator, I recommend using robust regular expressions. A regular expression makes it much easier to understand which input strings will be accepted as valid and which input strings will be rejected.
Implementation:
First, the available operations are declared. Then, the input is parsed. For valid input, the result of the operation is returned. For invalid (non-matching) input, undefined is returned:

function calculate(expression) {
  const operations = {
    '+': (left, right) => left + right,
    '-': (left, right) => left - right,
  };
  const [match, left, op, right] = expression.match(/^(\d+) (\+|\-) (\d+)$/) || [];
  return match ? operations[op](+left, +right) : undefined;
}

// Example:
console.log(calculate("3 + 7")); // 10
console.log(calculate("3 - 7")); // -4

Replacing above regular expression with e.g. a much more refined ^\s*([\+\-]?(?:\d*[.])?\d+)\s*(\+|\-)\s*([\+\-]?(?:\d*[.])?\d+)\s*$/ allows you to capture floating point numbers, negative numbers and whitespace. To support more operations, simply append them to the operations object literal, e.g. '*': (left, right) => left * right and add \* to the operator capture group within the regular expression.


Detecting if two strings are anagrams using TreeMap I decided to use Java TreeMap because it seems like a great data structure to fit this problem. However, I am not sure if there could be much simpler methods using better data structure or how I could start improving the time complexity of this algorithm. I would also like to know how I can improve the style of the current code.

Is the time complexity of following algorithm \$O(n \log n)\$?

/**
 * Created by mona on 5/25/16.
 */
import java.util.Map;
import java.util.TreeMap;

public class isAnagram {

    public static boolean areAnagrams( String s1 , String s2 ) {

        if ( s1.length() != s2.length() ) {
            return false;
        }

        Map< Character , Integer > charFrequencyS1 = new TreeMap<>();
        Map< Character , Integer > charFrequencyS2 = new TreeMap<>();

        for ( int i=0 ; i<s1.length() ; i++ ) {
            if ( charFrequencyS1.containsKey(s1.charAt(i)) ) {
                int freq = charFrequencyS1.get(s1.charAt(i));
                charFrequencyS1.put(s1.charAt(i), freq+1);
            }

            else {
                charFrequencyS1.put(s1.charAt(i), 1);
            }

            if ( charFrequencyS2.containsKey(s2.charAt(i)) ) {
                int freq = charFrequencyS2.get(s2.charAt(i));
                charFrequencyS2.put(s2.charAt(i), freq+1);
            }

            else {
                charFrequencyS2.put(s2.charAt(i), 1);
            }

        }

        return charFrequencyS1.equals(charFrequencyS2);

    }

    public static void main( String args[] ) {

        String s1="mona";
        String s2="noea";

        System.out.println(areAnagrams(s1,s2));

    }
}

Replace the TreeMap with a HashMap since a TreeMap offers \$O(log(n))\$ lookup (containsKey and get) and insertion (put) time whereas a HashMap offers amortized constant or \$O(1)\$ time for those same methods.

The time complexity of this algorithm (with a HashMap) is in fact O(length(s1)) or rather \$O(n)\$ because the contains, add and remove methods of a HashMap work in amortized constant or \$O(1)\$ time (it is \$O(n)\$ when the internal arrays have to be expanded).

You can make the code cleaner by getting rid of all those ifs in the loop. The get method returns null if the key doesn't exist, which helps us remove that containsKey call.

    for ( int i=0 ; i<s1.length() ; i++ ) {
        Integer freq = charFrequencyS1.get(s1.charAt(i));
        charFrequencyS1.put(s1.charAt(i), freq == null ? 1 : freq.intValue() + 1);

        Integer freq = charFrequencyS2.get(s2.charAt(i));
        charFrequencyS2.put(s2.charAt(i), freq == null ? 1 : freq.intValue() + 1);
    }

You could even go a step further and extract those two lines into a method, like

void addCharToMap(Map<Character, Integer> charMap, Character char) {
    Integer freq = charMap.get(char);
    charMap.put(char, freq == null ? 1 : freq.intValue() + 1);
}

And use the above method twice.

One thing to note is that if you are sure that your input is going to be numeric or alphanumeric, you can set the initialCapacity of the HashMap to be 26 or 36 respectively, because that amount is the maximum number of possible unique characters in the strings.


Simple Java Singleton Below is a Singleton that I designed as a piece of sample code for a website I'm working on for fun. The goal is to use the Singleton to hold an Earth object since Earth is unique and there is only 1 of them. Please let me know your thoughts on the implementation.

Singleton.java

package design.patterns;

 /**
  * This class is a Singleton, we can only have 1 instance of it no matter what!
  *
  * We mark the class final so that no other classes try to extend it. Some
  * designs would want the Singleton to be extendable but we do not!
  */
public final class Earth {

    // A static instance of an Earth object
    private static Earth earth;

    // Some earthly variables
    private long ageInYears = 4500000000L;
    private float daysForFullOrbit = 365.26f;
    private float degreesOfAxisTilt = 23.4f;
    private long population = 7046000000L;

    // Prevent client from instantiating new Earth objects
    private Earth() {
    }

    /**
     * Global access point (no pun intended :)
     *
     * Synchronized so its thread safe.
     */
    public static synchronized Earth getInstance() {

        // "Lazy load" an Earth Object
        if (earth == null) {
            earth = new Earth();
        }

        return earth;
    }

    // Basic getters and setters
    public double getAgeInYears() {
        return ageInYears;
    }

    public void setAgeInYears(long ageInYears) {
        this.ageInYears = ageInYears;
    }

    public float getdaysForFullOrbit() {
        return daysForFullOrbit;
    }

    public void setdaysForFullOrbit(float daysForFullRotation) {
        this.daysForFullOrbit = daysForFullRotation;
    }

    public float getDegreesOfAxisTilt() {
        return degreesOfAxisTilt;
    }

    public void setDegreesOfAxisTilt(float degreesOfAxisTilt) {
        this.degreesOfAxisTilt = degreesOfAxisTilt;
    }

    public double getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public static void setEarth(Earth earth) {
        Earth.earth = earth;
    }
}

Client.java

package design.patterns;

public class Client {

    public static void main(String args[]){

        Earth earth = Earth.getInstance();

        //Invoke Earth's methods from the instance created on line 7
        System.out.printf("Earth is over %1$,.0f Days old. \n", earth.getAgeInYears());

        //Invoke Earth's methods from the Singleton directly
        System.out.println("Earth's orbit takes " + Earth.getInstance().getdaysForFullOrbit() + " days to complete.");

        //Invoke Earth's methods both ways
        System.out.println("Earth sits on a " + earth.getDegreesOfAxisTilt() + " degree tilt.");
        System.out.printf("As of 1/20/2014, there are %1$,.0f people on Earth!", + Earth.getInstance().getPopulation());
    }
}

The code you have is nicely formatted, and well documented, etc. ... but, as a singleton, it has a number of problems....

The two most glaring are:

It is not a singleton

Earth real = Earth.getInstance();
Earth.setEarth(null);
Earth alternate = Earth.getInstance();
if (real != alternate) {
   System.out.println("Oops...");
}

The synchronization.

You suggest in your comments that the getInstance() needs to be synchronized to avoid thread problems... but your other setter/getter methods are not synchronized.... as a result, threads all over the place can be getting stale, wrong, and otherwise incomplete populations, ages, etc.

As an example of a singleton 'best use case', this one has some problems... ;-)

But, that's sort of OK, since Earth has problems anyway!


Reading data from file This reads a list of points from a file with a certain format:

<number of points>
x1 y1
x2 y2

How I can make it better?

from collections import namedtuple
Point = namedtuple('Point ', ['x', 'y'])
def read():
    ins = open("PATH_TO_FILE", "r")
    array = []
    first = True
    expected_length = 0
    for line in ins:
        if first:
            expected_length = int(line.rstrip('\n'))
            first = False
        else:
            parsed = line.rstrip('\n').split ()
            array.append(Point(int(parsed[0]), int(parsed[1])))
    if expected_length != len(array):
        raise NameError("error on read")
    return  array

Another improvement is to use open as a context manager so that you don't have to remember to .close() the file object even if there are errors while reading.

def read():
    with open("FILE", "r") as f:
        array = []
        expected_length = int(f.next())
        for line in f:
            parsed = map(int, line.split())
            array.append(Point(*parsed))
        if expected_length != len(array):
            raise NameError('error on read')
        return array

See http://docs.python.org/2/library/stdtypes.html#file.close for more details.


Date range validation The following code is ran when the user presses a button to generate a log file based on the date selected. The DatePicker has a restrictive selected date range of the last 2 weeks including that same day. If the user leaves the page open for more than one day (very common), they will however be able to generate a log for a day that is too old. I've added this check to ensure that this isn't the case. I'm looking for a review on any part of this code.

[Bindable] private var mGeneratedLog:String;
[Bindable] private var mSelectedDate:Date;
[Bindable] private var mSelectableRange:Object;

private function getUploadMessages():void
{
    //validate range
    var now:Date = new Date();
    var tomorrow:Date = new Date(now.fullYear, now.month, now.date + 1, 0, 0, 0, 0);
    var twoWeeksAgo:Date = new Date(now.fullYear, now.month, now.date - 14, 0, 0, 0, 0);

    //refresh selectable range incase the page has been open too long.
    mSelectableRange = {rangeStart: twoWeeksAgo, rangeEnd: now};

    if (twoWeeksAgo.getTime() >= mSelectedDate.getTime())
    {
        mGeneratedLog = "Selected date is older than 2 weeks of age (Data has been purged).\nLog Not Generated.";
    }
    else if( mSelectedDate.getTime() >= tomorrow.getTime())
    {
        mGeneratedLog = "Selected date has not happened yet (log would be empty).\nLog Not Generated.";
    }
    else
    {
        mGeneratedLog = "Generating...";

        var formatter:DateFormatter = new DateFormatter();
        formatter.formatString = "YYYY-MM-DD JJ:NN:SS.QQQ";

        var lParameters:Object = {date:formatter.format(mSelectedDate)}
        mDatalayer.callStatement("GenerateLog", lParameters);
    }
}

I would store the result of mSelectedData.getTime() into a variable. It will save one method call and remove duplicate code.
The line that resets the data range seems a tad out of place; however, I am not sure about the rest of your implementation, so this might be the best place for it.
Also, I would check your first if-statement:

if (twoWeeksAgo.getTime() >= mSelectedDate.getTime())

Currently it will evaluate true (which is not expected) if the Dates are the same. From your description, it sounds like you want the date range to be inclusive not exclusive. Change the >= to simply > to get the result you expect:

if (twoWeeksAgo.getTime() > mSelectedDate.getTime())

Other than that, the code looks fine; though I personally would capitalize the first word of each comment and put a space between it and the double slashes. So, // Some comment instead of //some comment. Just a personal preference.


K-means function in Python I have written a k-means function in Python to understand the methodology. I am trying to use this on a more complex dataset with a larger value for k, but it is running super slow. Does anyone have any recommendations for how I can improve this? I have provided code below, along with loading in an example dataset and applying the algorithm.
def Euc(x,y):
    return math.sqrt(sum([(a - b) ** 2 for a,b in zip(x,y)]))

def K_means(TE,k):
    Iteration = 0
    R = []
    O_a = []
    Epoch = 0
    Tol = 1
    Old_Tol = 2
    Tol_r = []
    start_time = time.time()
    mean_cl = [[random.uniform(TE.iloc[i].min(),TE.iloc[i].max()) for i in range(len(TE.columns))] for c in range(0,k)]
    for n in range(len(TE)):
        D = [Euc(TE.iloc[n].tolist(),mean_cl[c]) for c in range(0,k)]
        O_a.append(D.index(min(D)))
    while(abs(Old_Tol - Tol) > 0.005):
        Old_Tol = Tol
        Epoch = Epoch + 1
        mean_cl = [TE.iloc[[j for j, x in enumerate(O_a) if x == i]].mean() for i in range(0,k)]
        N_a = []
        for n in range(len(TE)):
            Iteration = Iteration + 1
            D = [Euc(TE.iloc[n].tolist(),mean_cl[c]) for c in range(0,k)]
            N_a.append(D.index(min(D)))
       Tol = np.mean([x != y for x,y in zip(O_a,N_a)])
        Tol_r.append(Tol)
        O_a = N_a
    R.append(time.time() - start_time)
    R.append(Tol_r)
    R.append(N_a)
    R.append(Iteration)
    return R

def load_Pima():
    url = "http://www.stats.ox.ac.uk/pub/PRNN/pima.tr"
    Pima_training = pd.read_csv(url,sep = '\s+')
    url = "http://www.stats.ox.ac.uk/pub/PRNN/pima.te"
    Pima_testing = pd.read_csv(url,sep = '\s+')
    Pima_training = Pima_training.iloc[1:]
    Pima_testing = Pima_testing.iloc[1:]
    Pima_training.loc[:,"type"] = Pima_training.loc[:,"type"].apply(lambda x : 0 if x == 'Yes' else 1)
    Pima_testing.loc[:,"type"] = Pima_testing.loc[:,"type"].apply(lambda x : 0 if x == 'Yes' else 1)
    Features = Pima_training.loc[:,Pima_training.columns != "type"]
    Means = Features.mean()
    SDs = Features.std()
    for name in Features.columns:
        Pima_training[name] = (Pima_training[name]-Means[name])/SDs[name]
        Pima_testing[name] = (Pima_testing[name]-Means[name])/SDs[name]
    return Pima_training, Pima_testing

Pima_training, Pima_testing = load_Pima()

class_var = "type"
random.seed(2031)
k = 2
TE = Pima_testing
TE = TE.loc[:,TE.columns != class_var]
km = K_means(TE,k)

The function returns the runtime of the algorithm, the tolerance at each epoch (% of changes in cluster assignment), the final cluster assignments, and the total number of iterations. I have already removed four for loops, which has sped it up quite a bit. But I fear my lack of Python programming is holding me back from making this more efficient. Any help is appreciated!

You can vectorize this at various points to apply arithmetic to the whole dataframe rather than row-by-row.
def min_euclidean(df, options):
    """ Returns the index of the series in iterable options for which df - row has minimum
    Euclidean distance """
    return pd.DataFrame(((df - series) ** 2).sum(axis=1, skipna=False) for series in options).idxmin()

def k_means(TE, k):
    iteration = 0
    epoch = 0
    tol = 1
    old_tol = 2
    tols = []
    start_time = time.time()
    mean_cl = [random.uniform(TE.min(), TE.max()) for _ in range(k)]
    o_a = min_euclidean(TE, mean_cl)
    while abs(old_tol - tol) > 0.005:
        old_tol = tol
        epoch += 1
        mean_cl = [TE[o_a == i].mean() for i in range(k)]
        n_a = min_euclidean(TE, mean_cl)
        iteration += len(TE)
        tol = (o_a != n_a).mean()
        tols.append(tol)
        o_a = n_a
    return time.time() - start_time, tols, n_a, iteration

Note that:

wherever possible we work with Pandas series or dataframes instead of lists
I calculate mean_cl as a list of Pandas series instead of a list of lists. This way we avoid iterating through the column or row indices of TE, which is slower. There might be some way to optimize this further by storing mean_cl as a dataframe, but I can't see an obvious way of working with it that way.
there is no need to take the square root for the Euclidean distance - the indices associated with minimal distance will be the same working with the squared values
o_a and n_a are also stored as series. We can then do (o_a!= n_a).mean() to calculate the disparity between them.
The biggest optimization here is probably the min_euclidean function which calculates the square difference for the entire dataframe in an optimized way, rather than iterating through it.

This may be a helpful explanation of vectorization. Working with Pandas series and dataframes in an optimal often involves a slightly different way of thinking than in regular Python.
EDIT: Here is a version using numpy instead of pandas. This fully vectorizes all the operations and is substantially faster again. It uses an optimization from this StackOverflow answer.
def k_means(TE, k):
    epoch = 0
    tol = 1
    old_tol = 2
    tols = []
    start_time = time.time()
    te = np.array(TE)
    rows, columns = te.shape
    te3 = te[:, np.newaxis]  # 3d version of te for calculating euclidean more easily
    k_range = np.arange(k)[:, np.newaxis]
    mean_cl = np.random.uniform(te.min(axis=0), te.max(axis=0), size=(k, columns))
    o_a = np.nanargmin(((te3 - mean_cl) ** 2).sum(axis=2), axis=1)
    while abs(old_tol - tol) > 0.005:
        old_tol = tol
        epoch += 1
        m = o_a == k_range     # masks for each value in range 0 to k-1
        mean_cl = m.dot(te) / m.sum(1, keepdims=True)
        n_a = np.nanargmin(((te3 - mean_cl) ** 2).sum(axis=2), axis=1)
        tol = (o_a != n_a).mean()
        tols.append(tol)
        o_a = n_a
    return time.time() - start_time, tols, n_a, epoch * rows


XML parser + bs4 combo I just wrote a short function to parse SO jobs XML feed and return dicts containing information about each job entry.
Now, each job entry page is visited to grab info not present in the xml feed (company logo URL, salary info, etc.) through bs4 with couple functions in the get_so_extras module.

parse_feed.py:

from datetime import datetime as dt
from xml.etree import ElementTree as etree
from get_so_extras import get_company_logo, get_so_salary
import urllib3
import json
import sys

def get_so_listings(url):
    """
    Get remote job listings from stackoverflow.com xml feed
    """

    http = urllib3.PoolManager()

    try:
        so_file = http.request("GET", url).data
    except Exception as e:
        print(e.args)
        sys.exit()

    so_root = etree.fromstring(so_file)
    items = so_root.findall("channel/item")

    # Parse SO xml feed in dict
    so_listings = []
    for e in items:
        job_dict = {
            "so_id": e.findtext("guid"),
            "title": e.findtext("title"),
            "so_url": e.findtext("link"),
            "author": e.findtext(
                """{http://www.w3.org/2005/Atom}author/{http://www.w3.org/2005/Atom}name"""
            ),
            "description": e.findtext("description"),
            "published_at": str(
                dt.strptime(
                    e.findtext("pubDate").strip(), "%a, %d %b %Y %H:%M:%S Z"
                    )
            ),
            "updated_at": str(
                dt.strptime(
                    e.findtext("{http://www.w3.org/2005/Atom}updated"),
                    "%Y-%m-%dT%H:%M:%SZ",
                    )
            ),
            "company_logo_url": get_company_logo(e.findtext("link")),
            "categories": [c.text for c in e.findall("category")],
        }

        # @TODO: get_company_logo(job_dict["so_url"])
        so_listings.append(job_dict)

    print("Jobs imported: {}".format(len(so_listings)))

    # Helper - export to json, ideally pushed to db
    with open('output1.json', 'w', encoding='utf-8') as f:
        json.dump(so_listings, f, indent=4)

    return True

And here the helper function used to grab company logo URLs from get_so_extras module.

get_so_extras.py:

from bs4 import BeautifulSoup
import requests
import time

def get_company_logo(job_url):
    """
    Get company logo from stackoverflow.com job listing page
    """

    try:
        page = requests.get(job_url)
        soup = BeautifulSoup(page.text, 'html.parser')
        logo = soup.find("div", attrs={'class': 's-avatar s-avatar__lg mr8 bg-white fl-shrink0'}).\
            img["src"]
    except Exception as e:
        print(e)
        pass

    time.sleep(5) # Be kind

    return logo

It'd be great to understand whether I made any obvious mistake or bad choice along the way.
Obviously calling get_company_logo within the XML parsing loop slows things down, what would be the best approach to get those fields?
Probably checking if we're looking at a new company/listing from db before visiting the page to scrape the logo would be more efficient.

edit: also, given job listings have pretty much similar attributes, could it make sense to create a class listing with attribute and a method to push it to db (with de-duplication logic perhaps)?

Be ruthless, thanks in advance.

I've been experimenting with the best data structure for this. Here is what I have for now. It is definitely a work in progress, I hope to keep updating it constantly.

The CSV output was unexpected, ultimately a result of my decision to use a namedtuple. I chose namedtuples because, like you, I thought the data fit that tabular style quite well. You wrote given job listings have pretty much similar attributes, could it make sense to create a class listing with attribute and a method to push it to db, and I mostly agree, I just didn't feel that the data itself warranted a whole class.

import collections as colls
import csv
import datetime as dt

import requests
from lxml import etree

Job = colls.namedtuple('Job', ['guid', 'title', 'url', 'author', 'logo', 'description', 'pub_date', 'update_date',
                               'categories'])

html_parser = etree.HTMLParser()

req_session = requests.Session()
req = req_session.get(url_1)

root = etree.fromstring(req.content)
ns_map = root.nsmap

job_elems = root.xpath('/rss/channel/item')[:10]

def parse_job_item(job_item):
    guid = job_item.findtext('guid')
    title = job_item.findtext('title')
    link = job_item.findtext('link')
    author = job_item.findtext('a10:author/a10:name', namespaces=ns_map)
    description = job_item.findtext('description')
    pub_date = job_item.findtext('pubDate')
    if pub_date:
        pub_date = dt.datetime.strptime(pub_date, "%a, %d %b %Y %H:%M:%S Z")
    update_date = job_item.findtext('a10:updated', namespaces=ns_map)
    if update_date:
        update_date = dt.datetime.strptime(update_date, "%Y-%m-%dT%H:%M:%SZ")
    categories = [elem.text for elem in job_item.findall('category')]

    job_page_elem = etree.fromstring(req_session.get(link).content, parser=html_parser)
    # "//body/div[@class='container']/div[@id='content']/header/div/a/img/@src"
    # contains(concat(' ', normalize-space(@class), ' '), ' s-avatar ')
    company_logo = job_page_elem.xpath(
        "/html/body/div[@class='container']/div[@id='content']/header/div[contains(concat(' ', normalize-space(@class), ' '), ' s-avatar ')]//img/@src")
    if company_logo:
        company_logo = company_logo[0]
    res_item = Job(guid, title, link, author, company_logo, description, pub_date, update_date, categories)
    return res_item

job_data_list = (parse_job_item(curr_elem) for curr_elem in job_elems)

with open('../out/jobs_out.csv', 'w', newline='') as out_file:
    writer = csv.writer(out_file)
    writer.writerow(Job._fields)
    writer.writerows(job_data_list)


Style, simplification and modularization for unit converter Here is an exercise I completed today from Bjarne Stroustrup's Programming Principles and Practice in C++ book.  Any tips about coding style, simplification, or perhaps modularization by means of using functions for some of the data processing would be sincerely appreciated. FYI I have only been programming for 5 months, apologies in advance for any blatant mistakes.

// This program takes floating-point numbers and select units as input, and displays the sum,
// the amount of measurements entered, and the high and low measurements entered.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

// Globals
const double cm_to_m = 0.01;
const double m_to_cm = 100;
const double in_to_m = 2.54 * 0.01;
const double m_to_in = 100 * (1.0/2.54);
const double ft_to_m = 12 * 2.54 * 0.01;
const double m_to_ft = 100 * (1.0/2.54) * (1.0/12.0);

// Main Function
int main()
{
    // Declarations
    int count = 0;
    double num, conv, low, high, sum = 0;
    string unit, low_unit, high_unit;
    vector<double> input_array;

    // Input
    cout << "Enter a measurement in one of the following accepted units (cm, m, in,     ft): " << endl;
    while (cin >> num >> unit) {
        if (unit == "m" || unit == "cm" || unit == "in" || unit == "ft") {
            if (unit == "m") {
                input_array.push_back(num);
                if (count == 0) low = num, low_unit = unit, high = num, high_unit = unit;
                else if (num < low) low = num, low_unit = unit;
                else if (num > high) high = num, high_unit = unit;
                ++count;
            }
            else if (unit == "cm") {
                conv = num * cm_to_m;
                input_array.push_back(conv);
                if (count == 0) low = conv, low_unit = unit, high = conv, high_unit = unit;
                else if (conv < low) low = conv, low_unit = unit;
                else if (conv > high) high = conv, high_unit = unit;
                ++count;
            }
            else if (unit == "in") {
                conv = num * in_to_m;
                input_array.push_back(conv);
                if (count == 0) low = conv, low_unit = unit, high = conv, high_unit = unit;
                else if (conv < low) low = conv, low_unit = unit;
                else if (conv > high) high = conv, high_unit = unit;
                ++count;
            }
            else if (unit == "ft") {
                conv = num * ft_to_m;
                input_array.push_back(conv);
                if (count == 0) low = conv, low_unit = unit, high = conv, high_unit = unit;
                else if (conv < low) low = conv, low_unit = unit;
                else if (conv > high) high = conv, high_unit = unit;
                ++count;
            }
        }
        else
            cout << "Incorrect Unit Entered! Please try again..." << endl;
    }

    // Low/High Unit Re-Conversion
    if (low_unit == "cm")
        low *= m_to_cm;
    else if (low_unit == "in")
       low *= m_to_in;
    else if (low_unit == "ft")
       low *= m_to_ft;

    if (high_unit == "cm")
        high *= m_to_cm;
    else if (high_unit == "in")
        high *= m_to_in;
    else if (high_unit == "ft")
        high *= m_to_ft;

    // Sort
    sort(input_array.begin(), input_array.end());

    // Sum the contents of the array.
    for (int i = 0; i < input_array.size(); ++i)
        sum += input_array[i];

    // Output
    cout << endl;
    cout << count << " measurements were entered" << endl;
    cout << "The sum of measurements entered is " << sum << " m" << endl;
    cout << "The lowest measurement entered was " << low << " " << low_unit << endl;
    cout << "The highest measurement entered was " << high << " " << high_unit << endl;

    // Return
    return 0;
}

Do you think your code is optimal?  You should be the first reviewer (along with the compiler).

Did you notice that you had to copy the
same code four times, once for each unit type.  Duplication of code is
generally bad and you should spot it yourself.  Your four input cases, meters,
cm, inches and feet all do the same thing:

convert to meters
push into vector
set low/high variables

Here's what the loop might look without the duplication:

double low = DBL_MAX;
double high = DBL_MIN;
...

while (cin >> num >> unit) {
    if (unit == "m") {
        meters = num;
    } else if (unit == "cm") {
        meters = num * cm_to_m;
    } else if (unit == "in") {
        meters = num * in_to_m;
    } else if (unit == "ft") {
        meters = num * ft_to_m;
    } else {
        cout << "Incorrect Unit Entered! Please try again..." << endl;
        continue;
    }
    input.push_back(meters);

    if (meters < low) {
        low = meters;
        low_unit = unit;
    } else if (meters > high) {
        high = meters;
        high_unit = unit;
    }
}

This is a lot simpler than your original code, having removed all of the
duplication.  Your tests for count == 0 are unnecessary if you set the
low/high variables to the limits of the range for double (all double values
are going to be less than or equal to DBL_MAX etc).   This leaves a continue
which many people would consider bad form and some coding standards outlaw.
To avoid this we could put the conversion into a function:

static bool convert_to_meters(double num, double &meters, const string& unit)
{
    const double cm_to_m = 0.01;
    const double in_to_m = 2.54 * 0.01;
    const double ft_to_m = 12 * 2.54 * 0.01;
    if (unit == "m") {
        meters = num;
    } else if (unit == "cm") {
        meters = num * cm_to_m;
    } else if (unit == "in") {
        meters = num * in_to_m;
    } else if (unit == "ft") {
        meters = num * ft_to_m;
    } else {
        return false;
    }
    return true;
}

And call it from the main loop:

while (cin >> num >> unit) {
    if (!convert_to_meters(num, meters, unit)) {
        cout << "Incorrect Unit Entered! Please try again..." << endl;
    }
    else {
        input.push_back(meters);

        if (meters < low) {
            low = meters;
            low_unit = unit;
        } else if (meters > high) {
            high = meters;
            high_unit = unit;
        }
    }
}

You then have another set of unit conversions done twice which could be
extracted to a function:

static double convert_from_meters(double meters, const string& unit)
{
    const double m_to_cm = 100;
    const double m_to_in = 100 * (1.0/2.54);
    const double m_to_ft = 100 * (1.0/2.54) * (1.0/12.0);
    double num = meters;
    if (unit == "cm") {
        num *= m_to_cm;
    } else if (unit == "in") {
        num *= m_to_in;
    } else if (unit == "ft") {
        num *= m_to_ft;
    }
    return num;
}

and called with:

low  = convert_from_meters(low, low_unit);
high = convert_from_meters(high, high_unit);

You finish with a loop to add all of the values in the vector.  There is a standard
algorith for this:

double sum = std::accumulate(input.begin(), input.end(), 0.0);

Note that your sorting of the vector seems to be unnecessary. However you
could determine the low/high values (without units) by looking at the first
and last items in the vector after sorting.  And if you gave up the
requirement to print the low/high values in their original units you would
need neither to save low/high and low_unit/high_unit every time round the
loop, nor to convert from meters back to original units.  The code then becomes
much simpler.

This might seem like cheating and in an exercise where the
requirements are set for you, it is.  But in the real world, simplifying the
requirements (which can often be fairly arbitrary and many times are
determined by you) can make a huge difference to the complexity and cost of
code.  Clearly the customer has to agree to any changes that affect the end
product.


Julia RPN calculator algorithm ported from Python version I've just finished the Reverse Polish Notation task in Julia from rosettacode.com by porting the existing Python code.

There are only a few lines I don't get how to port:

maxcolwidths = [max(len(y) for y in x) for x in zip(*rp)]

and the subsequent lines that use maxcolwidths.

I managed to pretty print the test output anyway, but I'd really love to hear any opinions from you.

ops = [
    :^ => :op_pow,
    :* => :op_mul,
    :/ => :op_div,
    :+ => :op_add,
    :- => :op_sub
]

for (op, func) in ops
    @eval function ($func)(stack)
        b = pop!(stack)
        a = pop!(stack)
        push!(stack, ($op)(a, b))
    end
end

input(prompt::String="") = (print(prompt); inp = chomp(readline()))
get_input(inp::String=input("Expression: ")) = (tokens = split(inp, ' '))

function rpn_calc{T<:String}(tokens::Vector{T}=get_input())
    stack = {}
    table = ["TOKEN" "ACTION" "STACK"]
    for token in tokens
        sym = symbol(token)
        if sym in keys(ops)
            action = "Apply op to top of stack."
            @eval $(ops[sym])($stack)
        else
            action = "Push num onto top of stack."
            push!(stack, parse(token))
        end
        table = [table; token action  join([string(s) for s in stack], ' ')]
    end
    return table
end

function test_rpn(rpn::String="3 4 2 * 1 5 - 2 3 ^ ^ / +")
    println("For RPN expression: $rpn")
    table = rpn_calc(get_input(rpn))
    i = 1
    n_rows = length(table[:, 1])
    while i <= n_rows
        if i == 1
            println(join(table[i, 1:2], '\t'), "\t"^4, table[i, 3])
        else
            println(join(table[i, :], '\t'))
        end
        i += 1
    end
    println("\nThe final output value is: $(table[end, 3])")
end

test_rpn()

Output:

For RPN expression: 3 4 2 * 1 5 - 2 3 ^ ^ / +
TOKEN   ACTION                           STACK
3       Push num onto top of stack       3
4       Push num onto top of stack       3 4
2       Push num onto top of stack       3 4 2
*       Apply op to top of stack         3 8
1       Push num onto top of stack       3 8 1
5       Push num onto top of stack       3 8 1 5
-       Apply op to top of stack         3 8 -4
2       Push num onto top of stack       3 8 -4 2
3       Push num onto top of stack       3 8 -4 2 3
^       Apply op to top of stack         3 8 -4 8
^       Apply op to top of stack         3 8 65536
/       Apply op to top of stack         3 0.0001220703125
+       Apply op to top of stack         3.0001220703125

The final output value is: 3.0001220703125

In case you don't already know this ...

Here is what the line [max(len(y) for y in x) for x in zip(*rp)] is doing.

Say that

rp = [('a', 'b', 'c', 'd'), ('aa', 'bbb', 'cccc', 'ddddd')]
unzipped_rp = zip(*rp) # [('a', 'aa'), ('b', 'bbb'), ('c', 'cccc'), ('d', 'ddddd')]

This code does almost the same as what the line above does ...

max_lengths = []

for x in unzipped_rp:
    lengths = []
    for y in x:
        lengths.append(len(y))
    max_lengths.append(max(lengths))

print max_lengths

Output:
    [2, 3, 4, 5]


Getting the index (x,y) of a char in a "2D" list in Haskell I have this working function circuitFind that I really don't find nice because I feel there is a better and simpler way to accomplish what it does.

circuitFind :: Circuit -> Tile -> Maybe Position
circuitFind c t = unpack . find (\ p -> fst p /= Nothing) . enumerate . map findTile $ c
    where findTile = findIndex (==t)
          enumerate = flip zip [0..]
          unpack a = case a of
             Just (Just x, y) -> Just (x,y)
             _ -> Nothing

Basically, the function works like this: (ie: we search for the char '3')

["1stline", "2ndline", "3rdline"]
              |
        map findTile '3'
              |
              v

[Nothing, Nothing, Just 0]
              |
          enumerate
              |
              v

[(Nothing, 0), (Nothing, 1), (Just 0, 2)]
              |
       find (\ p -> fst p /= Nothing)
              |
              v

      Just (Just 0, 2)
              |
           unpack
              |
              v

     ––  Just (0,2) ––

Is there a better way to make this function more readable/shorter/... ?

All the relevant code here:

import Data.List

type Vec2D = (Int, Int)
type Position = Vec2D
type Circuit = [[Tile]]
type Tile = Char

basicCircuit :: Circuit
basicCircuit = ["------------",
                "-b        e-",
                "------------"]

circuitFind :: Circuit -> Tile -> Maybe Position
circuitFind c t = unpack . find (\ p -> fst p /= Nothing) . enumerate . map findTile $ c
    where findTile = findIndex (==t)
          enumerate = flip zip [0..]
          unpack a = case a of
             Just (Just x, y) -> Just (x,y)
             _ -> Nothing

Some tests to illustrate the usage:

Main> circuitFind basicCircuit 'e'
Just (10,1)
Main> circuitFind basicCircuit 'o'
Nothing

Disclaimer: I'm rusty with Haskell, there may be a cleaner way to do this.

Code review: your code looks fine to my eyes, it's just that circuitFind is overly complex, as you suspected. Also note that findIndex (==t) can be written as elemIndex t (source).

  "Let us see whether we could, by chance, conceive some other general
  problem that contains the original problem and is easier to solve." –
  Leibnitz.

We start by solving the more general problem of finding all indices of t in c.

Let's look at the skeleton of our solution.

[ (x,y) | ??? ]

We can get y using zip [0..] as you have done.

[ (x,y) | (y,line) <- zip [0..] c, ??? ]

Now we can find x using elemIndices.

[ (x,y) | (y,line) <- zip [0..] c, x <- elemIndices t line ]

Thanks to lazy evaluation, and Data.Maybe, we get our solution

circuitFind :: Circuit -> Tile -> Maybe Position
circuitFind c t = listToMaybe [ (x,y) | (y,line) <- zip [0..] c, x <- elemIndices t line ]


Multiplying a numeric string with the "vedic method" This is vedic method multiplication.  This code takes time on a very long numeric string, and I want to optimize it.  I also apply recursion on multIndices (this function is multiplying two given indices values).

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

char str1[10000],str2[10000],resultant[10000000];
int carry=0,n=0;
void mulIndices(int i, int j){
    int result=0;
    for(;i<=j;i++,j--){
    result = result + carry + (str1[i]-48)*(str2[j]-48);
        if(i!=j)
            result += (str2[i]-48)*(str1[j]-48);
    carry=0;
    }
    if(result > 9){
        carry = result/10;
        result %= 10;
    }
    resultant[n++] = result+48;
}
void reverseStr(char str[]){
    int tmp,i=0,j=0,length = strlen(str);
    for(i=0,j=length-1;i<length/2;i++,j--){
            tmp = str[i];
            str[i] = str[j];
            str[j] = tmp;
    }
}
int main()
{
    int value=-1, i=0,u,v,j=0,mulVal=0,length1 = 0,length2 = 0,diffOfLen=0,maxLength=0;
    printf("Enter the first numeric value: ");
    gets(str1);
    printf("Enter the second numeric value: ");
    gets(str2);

    length1 = strlen(str1);
    length2 = strlen(str2);

    if(length2<length1){
        diffOfLen= length1-length2;
        maxLength = length2;
    }else{
        diffOfLen= length2-length1;
        maxLength = length1;
    }

    i = diffOfLen;
/*
    if(length2<length1){
        i += length2;
    }else if(length2>length1){
        i += length1;
    }
*/
    reverseStr(str1);
    reverseStr(str2);

    while(diffOfLen--){
        //printf("%d\n",diffOfLen);
        if(length2<length1){
            str2[i++] = '0';
            str2[i] = '\0';
        }
        else if(length2>length1){
            str1[i++] = '0';
            str1[i] = '\0';
        }
    }
/*
    puts(str1);
    puts(str2);
*/

    for(i=0;i<maxLength;i++){
            mulIndices(0,i);
            //printf("0 %d\n",i);
    }
    for(i=1;i<maxLength;i++){
            mulIndices(i,maxLength-1);
            //printf("0 %d\n",i);
    }if(carry != 0){
        resultant[n++] = carry+48;
    }
    resultant[n] = '\0';
    reverseStr(resultant);
    puts(resultant);

    return 0;
}

Code organization: main does too much. Actual calculations, that is everything between gets and puts shall be a standalone function (multiply). Zero-filling loop shall be factored out into a function (see below). main declares many unused variables (value, u, v, j, mulVal - do you need them?).
Globals: globals are bad. Try to get rid of them.
Input: Don't use gets. Also, input shall be validated.
Magic number: 48 is ASCII for zero. Subtracting '0' would be much more clear. BTW, you do a lot of extra work: it is enough to convert just once as soon as the string lengths are calculated.

Other notes:

Don't be shy on spaces. Things like for(i=0,j=length-1;i<length/2;i++,j--){ are very hard to read.

An if (i != j) condition in mulIndices may only happen upon loop termination. There's no need to test it at every iteration. Similarly, in the length fitting loop, the condition is tested at every iteration. Swapping ifs and while results in better code:

if (length2 < length1) {
    while (diffOfLen--)
        str2[i++] = '0';
    str2[i] = 0;
} else {
    while (diffOfLen--)
        str1[i++] = '0';
    str1[i] = 0;
}

BTW, now it is obvious that the loops are functions. I'd prefer just memset.


JavaScript singleton with methods and properties I am diving deeper into JavaScript and starting to learn more about prototypes and simulating classes etc. I am used to working with the Module pattern and would like to try and combine this pattern along with working with prototyping into an own little framework (purely for learning purposes).

I have devised a little construct and I was hoping if some of you advanced users could give me some feedback on the particular construct.

What I am trying to achieve is to create a singleton with methods and properties one could access, I would like to extend/build this via the prototype as speed is something I care a lot about. The thing I still have doubts about is whether or not this would be a suitable construct for what I have in mind, whether or not this would be fast etc.

Much appreciated! Here's the code.

var Mui = (function (window, document, undefined) {

Mui = function () {
    this.Version = {
        Major  : '0',
        Minor  : '1',
        Bugfix : '0'
    };
};

Mui.prototype = {
    sayHi : function () {
        alert('hi');
    }
};

return new Mui;

}(window, this.document));

A singleton is an object which is the only instance of its type. Therefore, it makes most sense to define all non-function properties and methods directly on that singleton:

var singleton = {
    prop1: ...,
    prop2: ...,
    method1: function () { ... },
    method2: function () { ... }
};

Extending the singleton is easy:

singleton.prop3 = ...;
singleton.method3 = ...;


Function caller (to multiple receivers) interface This class is designed to call a similar function of multiple objects of multiple classes using a single interface (it is not for calling functions that return a value).

A potential usage will be sending same data to multiple writers (log writer, HTML generator and styled printer to console).

Tested with Python 3.4.2

I've also included a test/example in the below code:

"""
caller module:
Contains Caller class - call multiple other classes or modules with
similar function definitions, (it is not for calling functions that
returns a value)

Author : Bhathiya Perera
"""
class Caller():
    """call other classes or modules with
       similar function definitions"""
    def __init__(self, *receivers):
        """Initialize

        Parameters :
            receivers - va-arg receivers (can be objects, modules,
                        another caller , ....)
        """
        self._names = []
        self._receivers = receivers

    def __getattr__(self, name):
        """Get attribute of a given name
        This will return 'self' therefore it can be called later
        """
        self._names.append(name)
        return self

    def __call__(self, *args, **kw):
        """This class is callable with any arguments or key-value arguments
        It will then be posted to all receivers
        """
        if len(self._names) == 0:
            raise Exception("Cannot call")

        method_name = self._names.pop()
        for receiver in self._receivers:
            method = getattr(receiver, method_name)
            method(*args, **kw)

        return self

if __name__ == "__main__":
    # -------------------------------------------------
    # Test its usage
    class Receiver1():
        def a(self, arg):
            print ("Receiver1 - a", arg)

        def b(self, arg):
            print ("Receiver1 - b", arg)

    class Receiver2():
        def a(self, arg):
            print ("Receiver2 - a", arg)

        def b(self, arg):
            print ("Receiver2 - b", arg)

    class Receiver3():
        def a(self, arg):
            print ("Receiver3 - a", arg)

        def b(self, arg):
            print ("Receiver3 - b", arg)

    c = Caller(Receiver3())
    d = Caller(Receiver1(), Receiver2(), c)
    d.a("hello a")
    d.b("hello b")
    print ("-----")
    d.a.b.a.b.a.b.a("a")("b")("c")("d")("e")("f")("g")

If it was executed as a module it will print:

Receiver1 - a hello a
Receiver2 - a hello a
Receiver3 - a hello a
Receiver1 - b hello b
Receiver2 - b hello b
Receiver3 - b hello b
-----
Receiver1 - a a
Receiver2 - a a
Receiver3 - a a
Receiver1 - b b
Receiver2 - b b
Receiver3 - b b
Receiver1 - a c
Receiver2 - a c
Receiver3 - a c
Receiver1 - b d
Receiver2 - b d
Receiver3 - b d
Receiver1 - a e
Receiver2 - a e
Receiver3 - a e
Receiver1 - b f
Receiver2 - b f
Receiver3 - b f
Receiver1 - a g
Receiver2 - a g
Receiver3 - a g

Review for Python conventions and anything else.

If I understand correctly,
the purpose of Caller seems to be to call a function on multiple objects.
It works like this:

Construct a Caller x by passing 1 or more objects in the constructor
Call any method m on x, and it will be dispatched to method m of all objects

Right? The docstring doesn't explain this very well.
CallDispatcher might be a better name.

My impression is that you're discovering powerful features of Python,
and you're trying to use them because you can,
not because you have a concrete purpose.
Sort of like an exercise, not for real-life use.

It seems to me that __getattr__ is seriously abused.
I don't have experience overriding this method,
but I would guess it's designed to implement getters dynamically.
First of all,
adding getters dynamically seems like a hack that should be used with extreme care,
including a good justification that it's the best option.
Secondly,
instead of behaving as a getter,
this implementation mutates the object and returns self.
I see you did that to make chaining and currying possible,
it's interesting, but it seems a misuse of the language.

Another thing I don't like about the approach is the heavy dependence on duck typing.
The objects that can be used with Caller don't have to follow a well-defined interface,
they can be anything.
The user just has to make sure that when they call a .hello function on a Caller object,
all the objects inside have a .hello function defined.
It's great that Python let's us do this kind of thing,
but it doesn't mean that we should.
I prefer to have well-defined and well-documented interfaces,
with a list of legitimate methods that I'm allowed to call.

Python conventions

Instead of:

class Caller():

The class should be declared as:

class Caller:

Instead of:

    if len(self._names) == 0:

The Pythonic way:

    if not self._names:

Instead of:

        print ("Receiver3 - b", arg)

There should be no space before the opening paren:

        print("Receiver3 - b", arg)


Binary search in Rust I am a newbie to rust and wanted to know if this code is following idiomatic rust or can be improved.

use std::cmp::Ordering;

pub fn find(array: &[i32], key: i32) -> Option<usize> {
    if array.is_empty(){
        return None;
    }
    let mut start = 0;
    let mut end = array.len() - 1;
    let mut middle;

    loop {
        middle = (end - start) / 2;
        let middle_element = array[start + middle];
        match key.cmp(&middle_element){
            Ordering::Less => end -= middle,
            Ordering::Greater => start += middle,
            Ordering::Equal => {return Some(start+middle as usize);} ,
        }

        //The slicing syntax produces an unborrowed slice
        //(type: [i32]) which we must then borrow (to give a &[i32]),
        //even if we are slicing a borrowed slice.//More can be read at
        //https://github.com/nrc/r4cppp/blob/master/arrays.md
        if end - start <= 1 {
            break;
        };
    }

    if array[start] == key {
        return Some(start as usize);
    }

    if array[end] == key {
        return Some(end as usize);
    }

    None
}

It has passed all the tests listed on Exercism for binary_search problem.

Style

Spaces and punctuation

if array.is_empty(){

should be

if array.is_empty() {

(likewise match key.cmp(&middle_element){ → match key.cmp(&middle_element) {, etc.)

Ordering::Equal => {return Some(start+middle as usize);} ,

should be

Ordering::Equal => return Some(start + middle as usize),

although really, the comma at the end isn't necessary; you can remove that too.

And there should only be one new line below use std::cmp::Ordering and none above.

Scope

middle isn't used outside the loop, so you can replace:

let mut middle;

loop {
    middle = (end - start) / 2;

with:

loop {
    let middle = (end - start) / 2;

Note how the mut can go away, because the value of middle is only set once (per loop).

Unnecessary cast (as)

Ordering::Equal => {
    return Some(start + middle as usize);
},

The as usize is unnecessary; Rust already knows that you're returning Option<usize>. In fact, both start and middle are already usize, as is start + middle, so Rust isn't even doing anything fancy to get this to work. However, writing as usize makes it seem like those aren't usize, which could end up confusing your reader quite a lot.

(Same with start as usize → start and end as usize → end.)

Misleading comments

This comment:

//The slicing syntax produces an unborrowed slice
//(type: [i32]) which we must then borrow (to give a &[i32]),
//even if we are slicing a borrowed slice.//More can be read at
//https://github.com/nrc/r4cppp/blob/master/arrays.md
if end - start <= 1 {

is misleading, for two reasons:

It's right above (hence attached to) the wrong piece of code.
You don't use the slicing syntax (array[4..6]) anywhere in your code; you use the indexing syntax.

Just remove it; perhaps replace it with

let middle_element = array[start + middle];
// cmp requires a reference
match key.cmp(&middle_element) {

or something if you think it would be helpful. Though be aware that let middle_element = array[start + middle] makes a copy of middle_element, so the reference is to middle_element on the stack, not array[start + middle] wherever array is stored.

loop with if and break

if end - start <= 1 {
    break;
};

You're trying to make a do while loop here. However, if end - start <= 1 already, you don't need to enter this loop in the first place. This means you can just use a regular while:

while end - start > 1 {
    let middle = (end - start) / 2;
    let middle_element = array[start + middle];
    // cmp requires a reference
    match key.cmp(&middle_element) {
        Ordering::Less => end -= middle,
        Ordering::Greater => start += middle,
        Ordering::Equal => return Some(start + middle),
    }
}

And now cargo fmt doesn't change the code, and cargo clippy doesn't give any suggestions. Hooray!

Implementation

middle

In my mind, middle should be the index of the middle element – not the difference between start and the middle element. You might want to calculate this as (start + end) / 2 but that risks overflow; fortunately, start + (end - start) / 2 works fine.

So this:

let middle = (end - start) / 2;
let middle_element = array[start + middle];
// cmp requires a reference
match key.cmp(&middle_element) {
    Ordering::Less => end -= middle,
    Ordering::Greater => start += middle,
    Ordering::Equal => return Some(start + middle)
}

becomes:

while end - start > 1 {
    let middle = start + (end - start) / 2;
    let middle_element = array[middle];
    // cmp requires a reference
    match key.cmp(&middle_element) {
        Ordering::Less => end = middle,
        Ordering::Greater => start = middle,
        Ordering::Equal => return Some(middle)
    }
}

Unnecessary variable

Now we've made that change, I think array[middle] is obviously the middle element; so much so that we can remove middle_element entirely and get clearer code:

let middle = start + (end - start) / 2;
// cmp requires a reference
match key.cmp(&array[middle]) {

Ordering ordering

I actually think it'd be clearer if these were in Less, Equal, Greater order:

match key.cmp(&array[middle]) {
    Ordering::Less => end = middle,
    Ordering::Equal => return Some(middle),
    Ordering::Greater => start = middle
}

Implicit return

At the end, it might be clearer to use the implicit return form:

if array[start] == key {
    Some(start)
} else if array[end] == key {
    Some(end)
} else {
    None
}

Addendum: Tests

To make sure I didn't break your code while making these changes, I wrote a test. Tests are good to have (not that this is a particularly good test).

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_find() {
        assert_eq!(find(&[2, 4, 5, 7, 11, 12, 17], 5), Some(2));
        assert_eq!(find(&[], 5), None);
        assert_eq!(find(&[2, 4, 5, 7, 11, 12, 17], 6), None);
        assert_eq!(find(&[-63, -42, 1, 2, 4, 5, 7, 11, 12, 17, 17, 18], 12), Some(8));

        call_find(&[-10, -7, 0, 2, 4, 4, 5, 16, 27, 37, 38, 40, 40, 40, 40, 63, 628, 844, 10000000, 41230456]);
    }

    fn call_find(array: &[i32]) {
        for i in 0..array.len() {
            assert_eq!(array[find(array, array[i]).unwrap()], array[i]);
        }
    }
}


How can I make my decrypt method more efficient? I am making a simple transposition cipher.  I am testing the program with the word "computer" with the secret key "5,2,8,3,7,1,4,6", where the encrypt method will put the 5th letter 'u' in the first position, 2nd letter 'o' in 2nd position, 8th letter 'r' in 3rd position...

So the output would be:
original: computer
encrypted:uormecpt
decrypted:computer

Right now my decrypt method is of O(n^2). How can I make this faster?

Where char[] y would be uormecpt.  The z[j] - 1 is the offset as my iterator starts from 0, but my key starts at 1.

public static char[] decrypt(char[] y, int[] z)
{
    char[] decrypted = new char[y.length];

    for (int i = 0; i < y.length; i++)
    {
        for (int j = 0; j < y.length; j++)
        {
            if (i == z[j]-1)
                decrypted[i] = y[j];
        }
    }

    return decrypted;
}

If you can assume that every index in the encrypted message is included in the key, You can loop over the key and encrypted message together, placing each letter into the correct decrypted message slot directly:

public static char[] decrypt(char[] encrypted, int[] key)
{
    char[] decrypted = new char[encrypted.length];

    for (int i = 0; i < encrypted.length; i++)
    {
        decrypted[key[i]] = encrypted[i];
    }

    return decrypted;
}


If/else that contains HTML blocks, which contain additional PHP functions I have a form that posts (a,b) values into the following .php file, and displays an error message when the user tries to reach the .php file directly, instead via POST request.

This code is probably pretty messy, for example, I'm not sure I can post
 tags right away, instead of having them inside the  tags, but since it's an if/else function, I'm not sure how to build this in the most efficient way.

<?php
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
?>

You didn't come here through a Post.

<?php
    } else {

if(isset($_POST['a'])){

    switch ($_POST['a']) {

    case "1":
        $var1 = "word1";
        break;

    case "2":
        $var1 = "word2";
        break;

    default:
        $var1 = "other";
    }
}

if(isset($_POST['b'])){

    switch ($_POST['b']) {

    case "1":
        $var2 = "word3";
        break;

    case "2":
        $var2 = "word4";
        break;

    default:
        $var2 = "other";
    }
}

?>
<!doctype html>

<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

HTML-blocks that contain PHP such as <?php echo $var1; ?>, and <?php echo $var2; ?>.

<?php
    }
?>

A few suggestions.

Instead of writing styles in same file use an external style sheet
Also you can restructure it like:

 <!doctype html>

 <title>test</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

 <?php
     if ($_SERVER['REQUEST_METHOD'] !== 'POST')
     {
 ?>

You didn't come here through a Post.

<?php
     }
     else
     {
         if(isset($_POST['a']))
         {
            $status = "HTML-blocks that contain PHP such as ";
            switch ($_POST['a'])
            {
                case "1":
                  $status .= "word1";
                break;
                case "2":
                  $status .= "word2";
                break;
                default:
                  $status .= "other";
            }
        }

        if(isset($_POST['b']))
        {
            $status .= "and ";
            switch ($_POST['b'])
            {
                case "1":
                  $status .= "word3";
                break;
                case "2":
                  $status .= "word4";
                break;
                default:
                  $status .= "other";
            }
        }
        echo $status;
 ?>

 <?php
    }
 ?>


Optimizing code in codewars I was practicing python on codewars.com with this question:
Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
12 ==> 21
513 ==> 531
2017 ==> 2071
But when I attempted my solution it said it was not optimized enough
Can someone say why it said that?
from itertools import permutations
def next_bigger(n):
    per = list(permutations(str(n)))
    result = []
    for j in per:
        result.append(int("".join(j)))
    for i in sorted(result):
        if i > n:
            return i

Time & Memory Complexity
Your code uses a lot of time and memory.
With an \$d\$ digit number, you will get roughly \$d!\$ different permutations of digits.  list(permutations(str(n))) will cause all of these permutations to be realized in a list \$d!\$ elements long.
You take this list, and then repeatedly take one permutation from it, convert it into a number, add append it to the end of a result list, growing the list one element at a time.  This can be an \$O(k^2)\$ operation, and since \$k\$ in this case is \$d!\$, you have \$O({d!}^2)\$ time complexity.
Next, you take this list, and sort it, which is an \$O(k \log k)\$ operation, or in this case \$O(d! \log {d!})\$.
Finally, you take this sorted list, and loop through it until you find the first value larger than the starting value.
Space complexity: \$O(d!)\$.  Time complexity: \$O({d!}^2)\$.
Removing the \$O(k^2)\$
The simplest way to avoid the creation of list, and repeated append operation (which may cause a relocation & copy of all previous elements for each additional element added to it), is to allocate an array of the correct size ahead of time.
Since this is such a common operation, Python even gives us a shortcut: list comprehension.  Any code of the form:
destination = []
for value in source:
    destination.append(func(value))

can be rewritten as:
destination = [func(value) for value in source]

The Python interpreter can (via the__length_hint__ from PEP424) tell that it will be allocating a new list of len(container) elements, and may pre-allocate that storage, and then start populating the elements of that list.
(Note: CPython, IronPython, Anaconda, and other big snakes may implement things differently under the hood, possibly amortizing individual appends down to an \$O(1)\$ operation, and may or may not use __length_hint__, but the point still is using list comprehension will always be faster than allocating a list and repeatedly appending elements one at a time.)
We can re-write your function as:
def next_bigger(n):
    per = list(permutations(str(n)))
    result = [int("".join(j)) for j in per]
    for i in sorted(result):
        if i > n:
            return i

Space complexity: \$O(d!)\$.  Time complexity: \$O(d! \log {d!})\$.
Removing the \$O(k \log k)\$
Sorting is an expensive operation.  We don't want to do it if we don't have to.  And we definitely don't have to here; we only want one value as a result.
You are looking for the smallest value, from a list of values, that is larger than the input.  We can filter out all values which aren't larger than the input:
    candidates = [value for value in result if value > n]

And then return the minimum of all candidates:
    return min(candidates)

No sorting.  Space complexity: \$O(d!)\$.  Time complexity: \$O({d!})\$.
Removing the \$O(d!)\$ Space Complexity
There is no reason to store any intermediate results.  You could generate your list of permutations, and for each permutation, convert it back to a number, discard any value that isn't larger that the original, and remember the smallest value which passes.
def next_bigger(n):
    per = permutations(str(n))

    result = (int("".join(j)) for j in per)

    candidates = (i for i in result if i > n)

    return min(candidates)

permutations(...) is a generator function, so per is assigned a generator object.  We use that generator to construct our own generator that converts a digits of a permutation into an integer, and store that generator in result.  We take that generator and create another one which only produces values larger than the original, assigning the generator to candidates.
At this point, no permutations have been created yet.  No digits have been joined, and converted to an integer.  And no values have been tested for whether they are greater than the original.  Only generators for these actions have been created.
Then, we pass the last generator to min(...).  The min(...) function asks this generator for a value, and then for another value and save the smaller, and then another value and saves the smaller, and so on.  Only the smallest value is preserved at each step.
No list creation.  Space complexity: \$O(1)\$.  Time complexity: \$O({d!})\$.
Readability
I've used your variable names (n, per, result, j, and i) unmodified in my "improvements".  But someone reading the code has to inspect the code to determine that j is a tuple of digits, and i is the corresponding integer value.  Better variable names go a long way towards more understandable code.  Type hints and """docstrings""" are also extremely useful.
from itertools import permutations

def next_bigger(number: int) -> int:
    """
    For a positive integer, returns the next larger number that can
    be formed by rearranging its digits. For example:

    >>> next_bigger(12)
    21

    >>> next_bigger(513)
    531

    >>> next_bigger(2017)
    2071
    """

    permuted_values = (int("".join(permuted_digits))
                       for permuted_digits in permutations(str(number)))

    return min(value for value in permuted_values if value > number)

if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)

Of course, for a Code Wars submission, you'd strip out the docstrings, doctest, type hints in the pursuit of speed.
A Better Algorithm
The above are minor improvements on your existing algorithm.  As comments and other posts indicate, there is a better algorithm.


Python retry logic based on return code and output I am trying to write a function which execute the given command with given number of retry and delay. If the return code is 0 and output string have expected_output(partial) have to break the loop and return the return code and output. Is there any better to write this code?
cmd check_output_and_retry(cmd, expected_output, delay=1, retry=3):
    for i in range(retry):
        # Run the given command.
        # Return value will be return code with cmd output.
        ret, output = execute_cmd(cmd)
        if ret == 0 and expected_out in output:
            break
        else:
            time.sleep(delay)
    return ret, output

Without getting into a code golf'esque "shortest possible way to write this function", I'll just note a few alternatives to your particular implementation, and you can consider if you think they're simpler or not.

if ret == 0 is equivalent to if not ret. While that's probably not more legible in the if statement, it might be if you named this variable, e.g. program_failed = not ret.

expected_out in output is just one thing someone might want to do to evaluate if the output was what they wanted (e.g., maybe instead they want to do a regex check). You may want to replace this with a totally freeform function, then just call that function and use its result; e.g., if ret == 0 and output_ok(output):

Building on both of these, it might be prettier to name the conditions:
status_ok = ret == 0
output_ok = check_output(output)
if status_ok and output_ok:  # ...

Due to the nature of the if statement, the else condition is superfluous. It'd be equivalent to write:
if condition:
    break

time.sleep(delay)

You return ret, output whether or not the program succeeds, which may be confusing. Since your function's purpose is to check the output of the program and retry if it fails, it seems odd to return "successfully" if the program fails those checks just because it's run out of retries. Consider raising an exception instead.
for _ in range(retry):
    # ...
    if condition:
        break
    # ...
else:
    raise ValueError("Failed to run program successfully, <some useful information about ret, output, etc.>")
return output  # Only output, since ``ret`` is guaranteed to be 0

Pycharm and potentially other Python stylers might get upset at you for having a named variable you don't use: i. Consider replacing with _:
for _ in range(retry):  # ...

I'm just going to assume the cmd check_output... is just a typo, since Python uses def.

Write a docstring!

Again, you might not think all of the above are improvements, just alternatives. If you did follow them all, you might end up with the following:
def check_output_and_retry(cmd, check_output: lambda out: True, delay=1, retry=3):
    """Runs command until it succeeds. Raises a ValueError if it can't get the program to succeed.

    Args:
        cmd (str): The command to run
        check_output (callable): A function that takes the output string and returns whether or not it's ok
        delay (int|float): The number of seconds to wait between attempts
        retry (int): The number of times to try running the command before failing

    Returns:
        str: The program output. The program return code is guaranteed to be 0.
    """
    for _ in range(retry):
        # Run the given command.
        ret, output = execute_cmd(cmd)
        status_ok = ret == 0
        output_ok = check_output(output)
        if status_ok and output_ok:
            break

        time.sleep(delay)
    else:
        raise ValueError(f"Program failed to execute within {retry} attempts (status: {ret}: {output}")

    # Return value will be cmd output, since the return code is guaranteed to always be 0
    return output


Asymptotic complexity of multiple binary search Since binary search is \$O(log(n))\$.  Consider this example where I am searching for the existence of e and l and f in the word.

Is this \$O(n log(n))\$ or \$O(3 log(n))\$ and thereby still \$O(log(n))\$?

def search(array, item):

    if not array:
        return False

    if len(array) == 1:
        return array[0] == item

    mid = len(array) // 2
    left = array[:mid]
    right = array[mid:]

    return search(left, item) or search(right, item)

def elfish(word, letters):
    """
    >>> elfish('', 'efl')
    False

    >>> elfish('whiteleaf', 'elf')
    True

    >>> elfish('whiteleaf', 'elf')
    True

    >>> elfish('unfriendly', 'elf')
    True

    >>> elfish('waffles', 'elf')
    True

    >>> elfish('waffles', 'elf')
    True

    >>> elfish('sameh', 'elf')
    False

    >>> elfish('wolf', 'elf')
    False

    """
    result = True
    for letter in letters:
        result = result and search(word, letter)
    return result

elfish('waffles', 'elf')

The pure Python way of doing this is:

if 'e' in word and 'l' in word and 'f' in word:
    return True

Is Python doing a binary search in the background?

There are multiple problems in your approach - but they are more at the conceptual level, not in the style of the code, which is just fine. The unit tests are also commendable. But:

The algorithm you have coded is not the binary search algorithm.
The code implements a recursive search algorithm in an unsorted array. It has \$O(n)\$ time complexity and \$O(log(n))\$ space complexity - a clearly suboptimal for this task. The space complexity comes from the recursive function calls and the fact that Python does not optimize tail recursion. While you do demonstrate that solving the problem with recursion is possible, it is not the best option in terms of efficiency.
If you do implement binary search, sort the array first. To find the value I suggest using the functions from bisect module rather than reinventing the wheel, if this is a production code.
The Python in operator does not use binary search, as it has to avoid sorting the string, so binary search would not work; however, it does use some advanced string search algorithms, so is better than a naive version.

In this loop:

    for letter in letters:
        result = result and search(word, letter)

it is clear that the answer will be False as soon as the first search() call fails. Therefore you can if not search(word, letter): return False for better efficiency, and don't need the result variable.

This is an alternative version that:

Has \$O(max(||letters||, ||word||))\$ effective complexity (assuming
\$O(1)\$ for set insertion and lookup) due to the use of counting sort.
Increases the average efficiency by returning False immediately after the first missing character is encountered

def elfish(word, letters):
    present_characters = set()
    for c in word:
        present_characters.add(c)
    for letter in letters:
        if letter not in present_characters:
            return False
    return True


Graph adjacency list implementation in C++ I have been playing around with an adjacency list implementation of a graph class, on which I'd like to be able to run a build and test several graph algorithms. The code I have below works and I have been able to implement BFS, DFS, Dijkstra and Prim's algorithms, but I'm not very satisfied with it and would very much appreciate criticism.

One of the key problems that I can see is that the neighbours of a node are private and therefore to traverse them inside a function (i.e. Dijkstra) I need to make this function a friend of the node class.  I suspect that I should implement smart pointers to solve this but before I do this I'd like to consider other suggestions (maybe custom iterators?).

I also think there is a problem with how the nodes are being initialised, as I would prefer not having to call setKey in the graph::addNode function.

The node class:

class node{
 public:
  node() {}
  node(int k) : key(k){}
  void addNeighbour(int k, int weight = 1){
    if (this->key == k) return;
    neighbours.push_back(std::make_pair(k,weight));
  }
  inline int getKey() const {return key;}
  inline void setKey(const int k){key = k;}

  void display() const{
    for (std::list<std::pair<int,int> >::const_iterator it = neighbours.begin(); it != neighbours.end(); ++it){
      std::pair<int,int> entry = *it;
      std::cout << entry.first << " ";
    }
    std::cout << std::endl;
  }

  friend void bfs(graph &g, int src);
  friend graph prim(graph &g);
  friend void dijkstra(graph &lg, int src);
 private:
  std::list<std::pair<int, int> > neighbours;  //first element in pair corresponds to vertex key, second to the edge weight between them
  int key;
};

The graph class:

class graph{
 public:
  graph(const int sz) : size(sz),
                        nodes(sz, node()),
                        directed(false) {}
  void addNode(int key, const std::vector<std::pair<int,int> > &input);
  void display() const;
  node &operator[](const int i){return nodes[i];}
  inline int getSize() const {return size;}
 private:
  std::vector<node> nodes;
  int size;
  bool directed;
};

void graph::addNode(const int key, const std::vector<std::pair<int,int> > &input){

  nodes[key].setKey(key);
  for (std::vector<std::pair<int,int> >::const_iterator it = input.begin(); it != input.end(); ++it){
    std::pair<int,int> entry = *it;
    nodes[key].addNeighbour(entry.first, entry.second);
    if (!directed){
      nodes[entry.first].addNeighbour(key, entry.second);
    }
  }
}

Overall, it seems good. One problem that I find here though is the lack of vertical spacing at some places. This is very subjective, I agree, but adding a blank line to separate unrelated things can improved readability. I once read somewhere that code should be split into "paragraphs". That's an interesting thought to keep in mind. Giving an example, this is one possible way I would space the method graph::addNode():

void graph::addNode(const int key, const std::vector<std::pair<int,int> > &input) {

    nodes[key].setKey(key);

    for (std::vector<std::pair<int,int> >::const_iterator it = input.begin(); it != input.end(); ++it) {

        std::pair<int,int> entry = *it;
        nodes[key].addNeighbour(entry.first, entry.second);

        if (!directed) {
            nodes[entry.first].addNeighbour(key, entry.second);
        }
    }
}

Another minor point, but you don't need to add inline to a method when it is already defined directly inside the class body. In such case, adding the keyword is just unnecessary verbosity.

Huge lines like in those for loops:

for (std::list<std::pair<int,int> >::const_iterator it = neighbours.begin(); it != neighbours.end(); ++it)

Can be greatly simplified using auto or range-based for, if you have access to C++11. Failing that, I'd suggest that you typedef your list type to avoid having to replicate std::list<std::pair<int,int> > so many times (remember the DRY principle).

typedef std::list<std::pair<int, int> > ListType;

And as for the search algorithms, you didn't provide any implementation for them, but I don't see a reason why they shouldn't be members of graph. Personally, I don't see much purpose for a node to exist on its own without a graph, so I would make node a private inner class of graph and make all of its members public. Node seems like an implementation detail to me. Your interface apparently deals in terms of ints only.