process numerical input arguments of mixed ints, floats, and "array-like" things of same length>1 I'm trying to process numerical input arguments for a function. Users can mix ints, floats, and "array-like" things of ints and float, as long as they are all length=1 or the same length>1.

Now I convert them as follows:

convert to float                                convert to np.ndarray; dtype==float
----------------                                -----------------------------------
float
int
np.float64
range object resulting in len == 1              range object resulting in len > 1
len==1 list or tuple of int or float            len > 1 list or tuple of ints & floats
len==1 np.ndarray of dtype np.int or np.float   len > 1 np.ndarray of dtype np.int or np.float

then test all resulting arrays to make sure they are the same length. If so, I return a list containing floats and arrays. If not, return None.

I want to avoid up-conversion of booleans and small byte-length ints.

The script below appears to do what I want by brute force testing, but I wonder if there is a better way?

Desired behaviors:

fixem(some_bad_things) returns None
fixem(all_good_things) returns [42.0, 3.14, 3.141592653589793, 2.718281828459045, 3.0, 42.0, 3.0, 42.0, array([1. , 2.3, 2. ]), array([3.14, 1.  , 4.  ]), array([1., 2., 2.]), array([3., 1., 4.]), array([0., 1., 2.]), array([0, 1, 2])]
and sum(fixem(all_good_things)) returns array([149.13987448 149.29987448 156.99987448])

def fixit(x):
    result = None
    if type(x) in (int, float, np.float64):
        result = float(x)
    elif type(x) == range:
        y = list(x)
        if all([type(q) in (int, float) for q in y]):
            if len(y) == 1:
                result = float(y[0])
            elif len(y) > 1:
                result = np.array(y)
    elif type(x) in (tuple, list) and all([type(q) in (int, float) for q in x]):
        y = np.array(x)
        if y.dtype in (int, float):
            if len(y) == 1:
                result = float(y[0])
            elif len(y) > 1:
                result = y.astype(float)
    elif (type(x) == np.ndarray and len(x.shape) == 1 and
          x.dtype in (np.int, np.float)):
        if len(x) == 1:
            result = float(x[0])
        elif len(x) > 1:
            result = x.astype(float)
    return result

def fixem(things):
    final = None
    results = [fixit(thing) for thing in things]
    floats  = [r for r in results if type(r) is float]
    arrays  = [r for r in results if type(r) is np.ndarray]
    others  = [r for r in results if type(r) not in (float, np.ndarray)]
    if len(others) == 0:
        if len(arrays) == 0 or len(set([len(a) for a in arrays]))==1: # none or all same length
            final = floats + arrays
    return final

import numpy as np

some_bad_things = ('123', False, None, True, 42, 3.14, np.pi, np.exp(1),
                   [1, 2.3, 2], (3.14, 1, 4), [1, 2, 2], (3, 1, 4),
                   (3,), [42], (3.,), [42.], np.array([True, False]),
                   np.array([False]), np.array(False), np.array('xyz'),
                   np.array(42), np.array(42.), np.arange(3.), range(3))

all_good_things = (42, 3.14, np.pi, np.exp(1), [1, 2.3, 2], (3.14, 1, 4),
                   [1, 2, 2], (3, 1, 4), (3,), [42], (3.,), [42.],
                   np.arange(3.), range(3))

for i, things in enumerate((some_bad_things, all_good_things)):
    print(i, fixem(things))

print(sum(fixem(all_good_things))) # confirm

I suggest using isinstance instead of type to check the types of variables. You can read about it in details here: What are the differences between type() and isinstance()?
So, for example, instead of writing:

if type(x) in (int, float, np.float64):

you would write:

if isinstance(x, (int, float)):

You can check that it works for np.exp(1) which is of type np.float64.
When the x is of type range the following check is redundant:

if all([type(q) in (int, float) for q in y])

as the elements of y will be always integers. Also, there is no need to convert range to list. The following will also work:

result = float(x[0]) if len(x) == 1 else np.array(x)

To check if a list is empty in Python we usually write:

if not others:

instead of:

if len(others) == 0:

Imports should be at the top of the script. Move the import numpy as np line there.
In the future, when you have a function that can accept variables of different types and its behavior depends on which type it gets, you could try using singledispatch. I could come up with the following implementation:

from collections.abc import Iterable
from functools import singledispatch
from numbers import Real

import numpy as np

@singledispatch
def fixit(x):
    return None

@fixit.register
def _(x: Real):
    return float(x)

@fixit.register
def _(x: Iterable):
    y = np.array(x)
    if y.dtype in (np.int, np.float) and len(y.shape) == 1:
        return float(y[0]) if len(y) == 1 else y.astype(float)
    else:
        return None

I didn't check it thoroughly but for your test cases it works. (but looks a bit ugly)
A better way to solve your problem would be to convert immediately all the values to NumPy arrays of at least one dimension. We would require a np.atleast_1d function for that:

def to_normalized_data(values):
    arrays = list(map(np.atleast_1d, values))
    sizes = set(map(np.size, arrays))
    has_bad_types = any(array.dtype not in (np.int32, np.float64) for array in arrays)
    if len(sizes) > 2 or has_bad_types:
        return None
    max_size = max(sizes)
    singletons = [float(array[0]) for array in arrays if array.size == 1]
    iterables = [array.astype(float) for array in arrays if array.size == max_size]
    return singletons + iterables

>>> to_normalized_data(all_good_things)
[42.0,
 3.14,
 3.141592653589793,
 2.718281828459045,
 3.0,
 42.0,
 3.0,
 42.0,
 array([1. , 2.3, 2. ]),
 array([3.14, 1.  , 4.  ]),
 array([1., 2., 2.]),
 array([3., 1., 4.]),
 array([0., 1., 2.]),
 array([0., 1., 2.])]
>>> sum(to_normalized_data(all_good_things))
array([149.13987448, 149.29987448, 156.99987448])
>>> print(to_normalized_data(some_bad_things))
None

Answering your comments:

  For some reason my anaconda's numpy (1.17.3) returns int64 rather than
  int32 as you have in item 6

Looks like this behavior is OS-specific. Probably a better way to check the types of the obtained arrays would be by using np.can_cast. So, instead of writing:

has_bad_types = any(array.dtype not in (np.int32, np.float64) for array in arrays)

we could write:

has_bad_types = not all(np.can_cast(array.dtype, np.float64) for array in arrays)

  Item #6 doesn't reject two different lengths if no singletons are present. With ([1, 2, 3], [1, 2, 3, 4]) as input, the output is [array([1., 2., 3., 4.])] and [1, 2, 3] just falls through the cracks and disappears

Welp, I missed this case... We can add it back as:

if len(sizes) > 2 or 1 not in sizes or has_bad_types:

  also my original script tested if len(x.shape) == 1 in order to reject ndm > 1 arrays which item #6 doesn't, but that can be easily added back with something like testing for set(map(np.ndim, arrays)) == set((1,)). This is important because np.size won't distinguish between a length=4 1D array and a 2x2 array.

Yep, that's right. Taking all the above into account, the final code could look like this:

def to_normalized_data(values):
    arrays = list(map(np.atleast_1d, values))
    sizes = set(map(np.size, arrays))
    have_bad_types = not all(np.can_cast(array.dtype, np.float64) for array in arrays)
    have_several_dimensions = set(map(np.ndim, arrays)) > {1}
    if len(sizes) > 2 or 1 not in sizes or have_bad_types or have_several_dimensions:
        return None
    max_size = max(sizes)
    singletons = [float(array[0]) for array in arrays if array.size == 1]
    iterables = [array.astype(float) for array in arrays if array.size == max_size]
    return singletons + iterables


1024 bit key generation in php I want to use this function to store 1024 bit keys in my Mysql database. If you call generateKey(128), you'll get a 128 byte string, same as 1024 bit string. I want to know if there is something wrong with this code or if I should be worried about inter-operability issues with MySQL, Java, Android, File Read/Write, etc.

    public function generateKey($size){

    $randomString = "";
    $charUniverse = "";
    for($i=0;$i<256;$i++){
        $charUniverse .= chr($i);
    }
    for($i=0;$i<$size;$i++){
        $randInt=mt_rand(0, strlen($charUniverse)-1);
        $randChar=$charUniverse[$randInt];
        $randomString=$randomString.$randChar;
    }
    return $randomString;
}

Use chr($randInt) instead of $charUniverse[$randInt], and abandon the $charUniverse variable altogether.
Use the $str .= "str" dot-equals operator in PHP to append to your final string.

Thus your code becomes:

public function generateKey($size){

   $randomString = "";
   $charDomainSize = 256;
   for($i=0;$i<$size;$i++){
     $randInt=mt_rand(0, $charDomainSize-1);
     $randChar=chr($randInt);
     $randomString .= $randChar;
   }
   return $randomString;

}

If we compress your code further, it becomes:

public function generateKey($size){
   $randomString = "";
   for($i=0;$i<$size;$i++){
      $randomString .= chr(mt_rand(0, 255));
   }
   return $randomString;
}

I conducted a speed test, as well. The new code is faster (1000 runs, varied sizes between 1128 and 1148). The units are seconds.

Function 1 Average: 0.024438648223877
Function 2 Average: 0.015253195762634

Only using 256 as a size, 1000 runs:

Function 1 Average: 0.00031177306175232
Function 2 Average: 0.00017282342910767

This is a little overkill, but I was bored.

It should be very easy to port your random string generator to other platforms, although it may develop more or less dependable randomness based on the underlying generators. E.g. don't use Java's java.util.Random for security or scientific purposes (see Difference between java.util.Random and java.security.SecureRandom).

You might also want to consider PHP's openssl_random_pseudo_bytes, depending on your intent. That may not be as easily ported, though, as your current code.


Storing MySQL data in Memcache I have written a script that checks if data is known in memcached, and if not it queries it from the mysql db and stores it.

I would appreciate any inputs if i have done this the "correct" way, since i'm trying to optimize the code as much as possible.

  _query() & _rows() are simple mysqli functions

Save in memcache

// Store memcache data
function setCache($key,$value,$storage=18) {
    $memcache_obj = new Memcache;
    $memcache_obj = memcache_connect(memcache_host, 11211);

    if(is_array($key)) {
        $i = 0;
        foreach($key as $id => $storeName) {
            $memcache_obj->set($storeName, $value[$id], 0, $storage);
        }
    }else{
        $memcache_obj->set($key, $value, 0, $storage);
    }
}

Get from memcache

// Get memcache data
function getCache($key) {
    $memcache_obj = new Memcache;
    $memcache_obj = memcache_connect(memcache_host, 11211);
    $res = $memcache_obj->get($key);
    if(empty($res)) {
        $res = false;   // Expired
    }
    return $res;
}

Get data from memcache (or store in memcache if not present)

// Get data from either memcache or mysql
function _getData($userid,$table,$fields,$server) {

    $toSelect = explode(",",$fields);
    $toPush = array();
    foreach($toSelect AS &$value) {
        // Check if data is available from cache
        $key = $userid."_".$table."_".$value;
        $res[$value] = getCache($key);
        if(empty($res[$value])) {
            // Not cached, so must be pushed
            $toPush[] = $value;
        }
    }

    if($toPush) {
        // Some or all data missing from cache, so we fetch and cache it
        $fieldsToSelect = implode(",",$toPush);
        $q = _query("SELECT ".$fieldsToSelect." FROM ".$table." WHERE id = '".$userid."'",$server);
        $row = _rows($q);
        $key = array();
        $cValue = array();
        foreach($toPush AS &$value) {
            $key[] = $userid."_".$table."_".$value;
            $cValue[] = $row[$value];
            $res[$value] = $row[$value];
        }
        setCache($key,$cValue);
    }
    return $res;

}

The idea is to use the function as follows:

_getData($userid,"name_table","first_name,last_name",$dbConnection);

The above will return the data requested from memcahced first and if not present, then query it from mysql and store it in memcached.

The above works well, but how much does it hurt the eye?

Four things come to mind:

You're mixing object oriented programing with the more 'traditional' way PHP was written.  You don't need to use both.  If you will use the older memcache_connect, memcache_get and memcache_get functions, you don't need to instantiate an object with new Memcache.  Checkout the bottom of the connect page for the two side by side. Instantiating gives you more flexibility though (see point 3 below).  You tend to call memcache_connect even though the rest of your code is object-oriented; be consistent and use $memcache_obj->connect(...)
memcache_get returns FALSE when the object is not in the cache. So there is no need in your getCache function to do if(empty($res)){$res=false} because $res will already be false.
Consider closing the connection to the cache when you're done with it. Otherwise you may have a large number of active connections as you create a new instance and connect every time getCache and setCache are called. I would call Memcache::close before returning from either function.  Alternatively, if these functions are called often within one request-response cycle, you could have a Cache class that you instantiate; the Memcache instance would be a property of the class. Then in the class constructor, you can call new Memcache and Memcache::connect, and use the same connection for all operations. Then in the class destructor (the __destruct function, you can close the connection.
Your _getData indiscriminately uses caching. No matter what data is sought, it gets cached. You may have to be a bit more surgical because if you have fast changing DB data, _getData will soon start returning obsolete information (for instance, one would not seriously consider serving current stock prices or currency conversion rates from a cache). You may want to apply caching only to a subset of your DB, depending on the nature of your data


The only change I would make is in your two foreach loops. If you see below, I have made the change I would recommend making. This will make the loop a bit shorter and more accurate.

// Store occurrence of same days
$countDays  = array('Mon' => 0, 'Tue' => 0, 'Wed' => 0, 'Thu' => 0,
     'Fri' => 0, 'Sat' => 0, 'Sun' => 0);

// Store values
$output = array('Mon' => 0, 'Tue' => 0, 'Wed' => 0, 'Thu' => 0,
     'Fri' => 0,'Sat' => 0, 'Sun' => 0);

// Count days
foreach($data as $key => $value) {

    $dayName = date('D', strtotime($key));

    $countDays[$dayName]++;
    //add up all the qty when you go through the array the first time
   // IE all the Tuesdays in the array get added up.
    $output[$dayName] += $value;
}

// Calculate average
foreach($output as $key => $value) {
    //now take all the totals you just made in the other loop, and avg them
    $output[$key] = round($value / $countDays[$key]);
}

This is the only way I can see to improve the code. This way, you have a 'shorter' second foreach loop, which may improve the speed of your code a bit. You could also do the $value by reference and change it on the fly, but I think the way I have it now is clearer. This way you aren't doing the math more then once per array element, so you only do the avg for something like Tuesday once.

As Pinoniq stated you can drop the second foreach loop and add a function, and use array_map to do the rounding. Leave the first foreach loop the same and then add this, instead of the other foreach loop.

function average($a, $b){
    return round($a/$b);
}
$output = array_map("average",$output,$countDays);
//var_dump($output); //<-only if you want to test results.

Downside: You lose your index keys if you do it like this. However, you can easily fix that by just keeping the keys in an array, and then print them out at the same time, or use array_combine($keys,$values); to get your output array back.


Calculating range of ArrayLists I have written this method which calculates the range (max - min) of an ArrayList. I have two for loops each for a different ArrayList. The for loops do exactly the same thing except they each use a different list, so I was wondering if there was a way to just use one for loop (or any other way) that does the work but iterates through both ArrayLists so that I don't have nearly identical for loops.

public static void calcRange(ArrayList <Integer> list1, ArrayList<Integer> list2){
    int max = list1.get(0);
    int min = list1.get(0);
    int max2 = list2.get(0);
    int min2 = list2.get(0);

    for (int i : list1){
        if ( i > max){
            max = i;
        } else if (i < min){
            min = i;
        }
    }
    for (int i : list2){
        if ( i > max2){
            max2 = i;
        } else if (i < min2){
            min2 = i;
        }
    }
    System.out.println("List 1 Range: "+(max - min)+"\tList 2 Range: "+(max2 - min2));
}

One way you can remove duplicated code is to create a method:

public static int[] GetMaxMin (ArrayList <Integer> list)
{
    int max = list.get(0);
    int min = list.get(0);

    for (int i : list){
        if (i > max) {
            max = i;
        } else if (i < min) {
            min = i;
        }
    }
    int[] maxMin = {max, min};

    return maxMin;
}

This can then be called like this:

max = GetMaxMin(list)[0];
min = GetMaxMin(list)[1];

However, the above said, I would not recommend doing this because it has two purposes - to get the max value and the min value in the list.  What I would recommend is to implement two methods - one to get the max value and one to get the min value:

public static int GetMax (ArrayList <Integer> list)
{
    int max = list.get(0);

    for (int i : list){
        if (i > max) {
            max = i;
        }
    }

    return max;
}

GetMin would be similar.  Then, all you would need to do is this:

int max = GetMax(list1);
int min = GetMin(list1);
int max2 = GetMax(list2);
int min2 = GetMin(list2);

As you are calculating a range of values, though, you should just write a method to do that:

public static int CalculateRange (ArrayList <Integer> list)
{
    int max = list.get(0);
    int min = list.get(0);

    for (int i : list){
        if (i > max) {
            max = i;
        } else if (i < min) {
            min = i;
        }
    }

    return max - min;
}

As brought up in the comments, this will crash if there are 0 elements in the list.  To prevent this, you should probably check this before you try to get the range, like this:

if (list.size() != 0) {
    System.out.printf("List 1 Range: %d\tList 2 Range: %d\n", CalculateRange(list1), CalculateRange(list2));
} else {
    System.out.println("There are no elements in this array");
}


Enter year, date, and month in any order, I'll organize it I would like some advice on how I could make it less repetitive and use more functions and classes.

#include <iostream>
#include <string>

using namespace std;

class date
{
public:
    date() = default;
    date(istream &is) { is >> year >> month >> day; }

    bool organizeInfo();
    bool organize();
    ostream &outputInfo(std::ostream &os) { os << year << " " << month << " " << day; return os; }

private:

    bool checkValid();
    bool checkSwitch(unsigned &item1, unsigned &item2, unsigned &item3);
    void switchItems(unsigned &item1, unsigned &item2) { unsigned tempItem1 = item1; item1 = item2; item2 = tempItem1; }

    unsigned year = 0;
    unsigned month = 0;
    unsigned day = 0;
};

inline bool date::checkValid()
{
    if (month <= 12 && day <= 31)
        return 1;
    return 0;
}

inline bool date::checkSwitch(unsigned &item1, unsigned &item2, unsigned &item3)
{
    switchItems(item1, item2);
    if (checkValid())
        return 1;
    else
    {
        switchItems(item1, item2);
        switchItems(item2, item3);
        if (checkValid())
            return 1;
        else
        {
            switchItems(item2, item3);
            switchItems(item1, item3);
            if (checkValid())
                return 1;
            else
            {
                return 0;
            }
        }
    }
}

inline bool date::organize()
{
    if (checkValid())
        return 1;
    else
    {
        if (checkSwitch(day, month, year))
            return 1;
        else if (checkSwitch(year, month, day))
            return 1;
        else if (checkSwitch(day, year, month))
            return 1;
        return 0;
    }
}

bool date::organizeInfo()
{
    if (checkValid())
        return 1;
    else
    {
        if (organize())
            return 1;
        else
            return 0;
    }
    return 0;
}

int main()
{
    cout << "Enter year, month, date and ill try and organize it" << endl;
    date dawg(cin);
    if(dawg.organizeInfo())
        dawg.outputInfo(cout) << endl;
    return 0;
}

Besides the obvious points already mentioned in the other answers

Don't populate member variables in a constructor from streamed input

Passing std::istream to populate members in the constructor looks weird:

date(istream &is) { is >> year >> month >> day; }

The canonical way is to provide an input operator:

class date {
     friend std::istream& operator>>(std::istream& is, date& d) {
          is >> d.year >> d.month >> d.day;
          return is;
     }
     // ....
};

This allows to check the stream state for input errors after using it.

Don't promise things to users of your API, you cannot ever guarantee

As going for the logic you're trying to implement:

You are aware that it's not really possible to distinguish day, month and year inputs just by the bare numbers?

Some test cases in day, month, year order:

1 3 2
5 11 23
...

Well, month must be below or equal 12 and days below or equal 31, but what about days up to 12 or years input up to 12/31?

You actually have to require a specific date format for user input

Users won't be happy with wrong guesses from your code, and what you're promising isn't possible at all.

This is a major flaw in your code, and renders any other discussion merely useless.


JavaScript/jQuery carousel/slider I wrote this jQuery/JavaScript code for slideshow of my dynamic webapp. Is this too much jQuery code for carousel? It seems to work fine on my PC, but with bigger images it gets slower (7MB+) which is normal I suppose? Or am I doing whole thing wrong? I know I could do it with a JavaScript for loop or something, but I think it is easier with jQuery. Is jQuery less power-efficient than plain JavaScript? I wouldnt like to change it all as it has kind of "sentimental" value for me.

$(".prev-btn").on("click", function(){
  current = $(".li-placeholder").find("li.active");
  next = current.prev()
  if (current.index() == 0 ){
    next = $(".li-placeholder li").last();
    src = $(next).attr("src");
    $(".content").attr("src", src);
    $(".download-link").attr("href", src);
    $(next).addClass("active");
    $(current).removeClass("active");
  }
  else {
  src = next.attr("src");
  $(".content").attr("src", src);
  $(".download-link").attr("href", src);
  $(next).addClass("active");
  $(current).removeClass("active");
}
})

$(".next-btn").on("click", function(){
  current = $(".li-placeholder li.active");
  next = current.next()
  if (current.index() == $(".li-placeholder li").last().index()){
    next = $(".li-placeholder li:eq(0)");
    src = $(next).attr("src");
    $(".content").attr("src", src);
    $(".download-link").attr("href", src);
    $(next).addClass("active");
    $(current).removeClass("active");

  }
  else {
  src = next.attr("src");
  $(".content").attr("src", src);
  $(".download-link").attr("href", src);
  $(next).addClass("active");
  $(current).removeClass("active");
}

})

$(".exam-span-file").on("click", function(){
  wrapper = $(this).closest(".exam-span-wrapper");
  src = $(wrapper).find("li:eq(0)").attr("src");
  $(".content").attr("src", src);
  $(".download-link").attr("href", src);
  $(".imgmodal").show();
  exam_id = $(this).closest(".parent").attr("exam-id");
  $(".imgmodal").attr("exam-id", exam_id);
  $(wrapper).find("li:eq(0)").addClass("active");
  clone = $(wrapper).find(".exam-ul").clone();
  $(".li-placeholder").html(clone);

  if ($(".li-placeholder li").length == 1 ){
    $(".prev-btn").hide();
    $(".next-btn").hide();
  }
  else {
    $(".next-btn").show();
    $(".prev-btn").show();
  }

With something as lightweight as this, I don't think you are going to see any appreciable difference in javascript-based performance between plain Javascript and jQuery.  Now, downloading 7MB images is going to be relatively slow regardless as to whether you use javascript or jQUery, and my guess is that there is really no reason you should be loading images that size ever, unless you needed user to be able to zoom in on super high-quality images such that you need lots of pixels to support this.

The #1 thing you should do here, which could help performance to some extent, is to cache your jQuery collection results to variables.

There is no reason, for example that you should be querying $(".content"), $(".download-link"), etc. over and over again like you are doing.  This requires querying against the DOM (which is more expensive when querying by class than by ID because you must traverse the entire DOM) every single time.

Instead you should do something like this:

$(document).ready(function () {
    var $liPlaceholder = $('.li-placeholder');
    var $content = $('.content');
    var $downloadLink = $('.download-link');
    var $imgModal = $('.imgmodal');
    // and so on..

    // and then use these collections later on
    $('.prev-btn').on('click', function () {
        var current = $liPlaceholder.find("li.active");
        // etc.
    });
});

I think you have way too much code around traversing the collection for your prev/next buttons, along with a lot of repeated code for setting/removing active class and content/download link properties. I don't think you need to be looking for the active item at all.  Consider this code:

$(document).ready(function () {
    var $slides = $('.li-placeholder li');
    var $content = $('.content');
    var $downloadLink = $('.download-link');
    // default slide index to display on page load
    var slideIdx = 0;

    $('.prev-button').on('click', function() {
        slideIdx--;
        if(slideIdx < 0) {
            slideIdx = $slides.length - 1;
        }
        showSlide(slideIdx);
    });

    $('.next-button').on('click', function() {
        slideIdx++;
        if(slideIdx === $slides.length) {
            slideIdx = 0;
        }
        showSlide(slideIdx);
    });

    function showSlide(idx) {
        $slides.removeClass('active');
        var $current = $slides.eq(idx);
        var src = $current.attr('src');
        $current.addClass('active');
        $content.attr('src', src);
        $downloadLink.attr('href', src);
    }

   // set initial slide
   showSlide(slideIdx);
}

I am not exactly sure what the exam-file-span handler is doing without being able to see the code, but just looking at the way you are traversing the DOM and performing selectors here would make me think there is improvement to be had here as well.

$(".li-placeholder").html(clone);

You really should not be using html() method (which expects string) as means to inject a cloned DOM node into DOM.  You should really you append() here.

$liPlaceholder.append(clone);

You have some fundamental problems with your javascript that you should address:

If you are going to use semicolons to separate lines of code (as most writing javascript do, though it is optional), you need to be 100% consistent about it.  You have a few spots where you are missing the semicolon to terminate the line.
You are not properly initializing your variables using var (or let/const if in more modern versions of javascript).  You really need to get into this habit if you don't your code to work unexpectedly.
You are indenting your code inconsistently.
Every single one of your else statements in this code is avoidable.  You should get into the good habit of learning how to design else conditions away when possible.  The fewer parallel code paths you have in your code, the less complex (and therefore easier to test and easier to maintain) it will be.


Sorting a file with three-line blocks by the second word of the first line in each block I have a text file with the following three line pattern with blank lines in between. My script sorts alphabetically by each person's last name and preserves formatting. I would love to see other options to improve this in Bash. For example, the group command that redirects into final.txt repeats a lot. Also, it would be nice to have the content of output.txt in a variable instead of creating a file.

Sally Smith
UniqueStringSmith_1
UniqueStringSmith_2

Wally Wilson
UniqueStringWilson_1
UniqueStringWilson_2

Tod Taylor
UniqueStringTaylor_1
UniqueStringTaylor_2

Judy Johnson
UniqueStringJohnson_1
UniqueStringJohnson_2

The result looks like the following, sorted alphabetically by last name:

Judy Johnson
UniqueStringJohnson_1
UniqueStringJohnson_2

Sally Smith
UniqueStringSmith_1
UniqueStringSmith_2

Tod Taylor
UniqueStringTaylor_1
UniqueStringTaylor_2

Wally Wilson
UniqueStringWilson_1
UniqueStringWilson_2

Here is my script:

#!/bin/bash

# Get the number of lines in the document.
lines=$(cat my-file.txt | wc -l)

# This is the starting range and end range. Each section is three lines.
x=1
y=3

until [ "$x" -gt "$lines" ]; do
    # Store the three lines to one line.
    block=$(awk 'NR=="'"$x"'",NR=="'"$y"'"' my-file.txt)
    # Echo each instance into my file.
    # The $block variable is not double quotes so new lines are not honored.
    echo $block >> output.txt
    # Increment so it goes on to the next block.
    x=$((x+4))
    y=$((y+4))
done

# Sort the output file in place by the second column.
sort -k2 output.txt -o output.txt

# Put it back into original formatting.
while read i; do
    (echo "$i" | awk '{ print $1 " " $2 }'; echo "$i" | awk '{ print $3 }'; echo "$i" | awk '{ print $4 }'; echo "") >> final.txt
done < output.txt

# Remove the unnecessary file.
rm output.txt

Usability

Hardcoded input and output filenames are not easy to use.
This script only works with one specific input file name,
and it may inadvertently overwrite a file.
It would be better to take the input file as a command line argument,
and write the output to stdout,
letting the user to redirect to any file.

Error handling

If the input file doesn't exist, the script prints a bunch of error messages:

cat: my-file.txt: No such file or directory
sort: open failed: output.txt: No such file or directory
script.sh: line 29: output.txt: No such file or directory
rm: output.txt: No such file or directory

It would be better to check first that the file exists and fail early.

Keep in mind that after an error in one of the commands,
the script continues to run and execute the rest of the commands anyway.
I've seen cases when this cause real damage,
for example with rm -fr commands that assumed to be in a different directory, which was not the case due to earlier errors.
So it's important to look out for possible errors, check the exit code of commands and halt execution early.

You could do something like this:

input=$1

if ! test -f "$input"; then
    echo fatal: input file argument missing or not a file: $input
    echo usage: $0 input
    exit 1
fi

Bash arithmetic

The -gt operator in [ ... ] is obsolete, a better way is to use the modern ((...)). Instead of:

until [ "$x" -gt "$lines" ]; do

You can write like this:

until (( x > lines )); do

Simpler quoting

You can simplify the quoting here:

    block=$(awk 'NR=="'"$x"'",NR=="'"$y"'"' "$input")

Like this:

block=$(awk "NR==$x,NR==$y" "$input")

Initializing output.txt

In the until loop, you append to output.txt.
What if the file already existed before running the script?
You will get funny results.

To make sure the file is empty, you can do this:

> output.txt

But this is still not great. A file with that name may exist, and now its content will be destroyed.

Instead of using a temporary file in the current folder,
it would be better to use one in $TMP/output.txt.
And to avoid clashing with other scripts that might do the same,
you can add the process ID to the filename, for example $TMP/output-$$.txt.
But the best solution is to use the mktemp command:

tmpfile=$(mktemp)

Deleting temporary files at the end

One problem with deleting temporary files at the end of the script like you did with rm output.txt is that you might forget to do it.
Another problem is the end of the script might not be reached,
if the command gets interrupted due to an error or signals or the user pressing Control-C.
You can protect against these by using the trap builtin:

tmpfile=$(mktemp)
trap "rm -f '$tmpfile'; exit 1" 1 2 3 15

I copied again the line creating the temporary file,
because it's best to put the trap command right after that line,
so it won't be forgotten.

The first parameter of trap is a command to run,
typically more than one commands,
and it's important that the last one is exit.
The other parameters are signals that will be trapped.
1, 2, 3, 15 are typical signals to trap, for example 2 is SIGINT,
it is sent when the user presses Control-C while the script is running.

More Bash arithmetic

Instead of this:

    x=$((x+4))
    y=$((y+4))

You can simplify to:

((x+=4))
((y+=4))

Fewer variables

y is not really necessary. Instead of incrementing it by 4 in parallel with x, you can just increment x, and use x + 2 in awk:

Fewer redirections

Instead of redirecting output in every iteration of the until loop,
you could redirect the entire loop, just once:

until (( x > lines )); do
    block=$(awk "NR==$x,NR==$x+2" "$input")
    echo $block
    ((x+=4))
done > "$tmpfile"

Fewer processes

Instead of running an awk process for every block in the file in an until loop,
you could move the same logic inside awk itself,
and achieve the same using a single process:

awk '{printf "%s ", $0} NR % 4 == 0 {print ""}' "$input" > "$tmpfile"

In the while loop too, there is some waste.
Multiple commands are on one line separated by ;,
and enclosed within (...).
It's equivalent to this:

while read i; do
    echo "$i" | awk '{ print $1 " " $2 }'
    echo "$i" | awk '{ print $3 }'
    echo "$i" | awk '{ print $4 }'
    echo
done < "$tmpfile"

Note that i is a poor name for a variable that contains a line.

But the bigger issue is that a single line with awk could replace the 4 lines of echo:

echo $line | awk '{ print $1 " " $2; print $3; print $4; print ""; }'

Even better, a single awk process could replace the entire loop:

awk '{ print $1 " " $2; print $3; print $4; print ""; }' "$tmpfile"

Putting it together

At this point, we have:

An until loop that creates $tmpfile
A sort that sorts $tmpfile
An awk command that processes $tmpfile

We can chain them all into a pipeline, and get rid of $tmpfile altogether.

With the above changes and unnecessary elements removed,
the script becomes:

#!/bin/bash

input=$1

if ! test -f "$input"; then
    echo fatal: input file argument missing or not a file: $input
    echo usage: $0 input
    exit 1
fi

awk '{printf "%s ", $0} NR % 4 == 0 {print ""}' "$input" | \
sort -k2 | \
awk '{print $1 " " $2; print $3; print $4; print ""}'


Sorting an int[] array with an Insertion Sort I'm currently learning about different sorting algorithms and after reading on the concept of the insertion sort of how it's done I've tried to implement it by myself before seeing how it was implemented in the source from which I'm learning.

This was my implementation:

void insertionSort(int arr[])
{
    for(int i = 1; i < SIZE; i++)
    {
        for(int j = i; j > 0 && arr[j] < arr[j - 1]; j--)
        {
            int swap = arr[j];
            arr[j] = arr[j - 1];
            arr[j - 1] = swap;
        }
    }
}

Now I think I've implemented it correctly (not talking about efficient or anything just the algorithm itself), but when I saw the way it was implemented in the course I'm seeing I had a bit of concerns about my implementation because they're really different and I just wanted to make sure my implementation is really an insertion sort algorithm implementation and I didn't done anything else.

Here's the implementation by the source I'm learning from:

void insertionSort(int arr[])
{
  for(int i = 1;, i < SIZE; i++)
  {
      int value = arr[i];
      int j = i - 1;
      int done = 0;
      do
      {
          if (arr[j] > value)
          {
              arr[j + 1] = arr[j];
              j--;
              if (j < 0)
                  done = 1;
          }
          else
          {
              done = 1;
          }
      } while(!done)
      arr[j + 1] = value;
  }
}

Is my implementation of insertion sort correct ?

Also I would appreciate if you could compare my implementation to the one made by the source I'm learning from, any efficiency differences or any other thing you think would worth mentioning.

Your implementation is not quite correct. It is subtle, but what you have is a type of bubble sort in that you do not insert the new value, rather you 'slide' the value in to place.

An insertion sort can be thought of as a 'hole'. You shift all the 'bigger' values to the right by one space, and create a hole at the point where the value should be inserted. Then you insert the value in to the hole.

There should not be a concept of a 'swap' in an insertion sort.

You start at the first unsorted value, and then if the previous values are smaller, you move them up one, until you have the space at the right spot. Then you put the value there.

The example code makes this 'obvious' (but not really), in that it always compares against value and not arr[j+1]. It also has only a single 'assignment' to the array for each time in the loop. Your swap routine does two assignments on each loop.

So, No, your implementation of an insertion sort is not quite correct. It is a correct sort, but not a 'text-book' insertion sort since it slides, rather than inserts the value.


Large arrays make runtime very slow So I have the following code that takes the input of two arrays, and apply some queries to match elements from DBpediaClassesArray with elements from YagoClassesArray, then it returns the number of elements that are similar in the two ArrayLists.
    public static void get_ND_Matches() throws IOException{
    @SuppressWarnings("rawtypes")
    List<String> DBpediaClassesArray = new ArrayList<String>();
    List<String> YagoClassesArray = new ArrayList<String>();
    DBpediaClassesArray = new ArrayList<String>( ClassesRetrieval.getDBpediaClasses());
    YagoClassesArray = new ArrayList<String>( ClassesRetrieval.fileToArrayListYago());
    String YagoClassWithMaxMatches="";
    HashMap<String,Integer> mappingYagoLabelMaxValue = new HashMap<String,Integer>();
    int NumberOfCommonInstances;
    HashMap<String,ArrayList<String>> MappingYagoClassWithInstances = new HashMap<>();

    for(String yagoClass:YagoClassesArray){
        MappingYagoClassWithInstances.put(yagoClass, GetYagooClassInstances(yagoClass));
        System.out.println("Done for : "+yagoClass );
    }
    for(String dbClass:DBpediaClassesArray){
        ArrayList<String> DBpediaInstancesArray = GetDBpediaClassInstances(dbClass);
        for(Map.Entry<String, ArrayList<String>> YagoMapEntry : MappingYagoClassWithInstances.entrySet()){
            String yagoClass=YagoMapEntry.getKey();
            Set<String> IntersectionSet =Sets.intersection(Sets.newHashSet(DBpediaInstancesArray), Sets.newHashSet(YagoMapEntry.getValue()));
            //System.out.println(dbClass + " and "+ yagoClass+ " = "+ IntersectionSet.size());
            NumberOfCommonInstances = IntersectionSet.size();
            mappingYagoLabelMaxValue.put(yagoClass, NumberOfCommonInstances);
        }
        int MaximumValueOfIntersection=(Collections.max(mappingYagoLabelMaxValue.values()));
        for(Entry<String, Integer> YagoLabelToValueEntry:mappingYagoLabelMaxValue.entrySet()){
            if(YagoLabelToValueEntry.getValue()==MaximumValueOfIntersection && MaximumValueOfIntersection != 0){
                 YagoClassWithMaxMatches = YagoLabelToValueEntry.getKey();
            }
            if(MaximumValueOfIntersection==0){
                YagoClassWithMaxMatches = "Nothing in yago";
            }
        }
        System.out.println("-------------------------------");
        System.out.println(dbClass+" Corresponds to "+ YagoClassWithMaxMatches+" with : "+MaximumValueOfIntersection);
        System.out.println("-------------------------------");

    }
}

This code returns for example:

Actor from DBPEDIA Corresponds to Yago_Actor
Album from DBPEDIA Corresponds to Yago_Album
SomeClass from DBPEDIA Corresponds to nothing in Yago

Etc..
Behind the scenes, this code uses getDBpediaClasses and then applies GetDBpediaClassInstances method to get an ArrayList of results for each class. Each ArrayList resulted is then compared to another ArrayList generated by GetYagooClassInstances for each class of fileToArrayListYago().
Now, because of all the calculations made in the background (there are millions of elements in each array), this process takes hours to execute, because it runs each comparison after another, while it would be better to get them all done at once and then just get the YagoClassWithMaxMatches after all of them have been computed.
I was thinking of concurrency, but I first wanted to see if there is an easier way.
Are there any suggestions to make the code run faster?

First I must encourage you to follow java conventions. Local variables and methods should be typed in lowerCamelCase. You shouldn't also assign a variable twice if you can avoid it for example you shouldn't do this

List<String> DBpediaClassesArray = new ArrayList<String>();
DBpediaClassesArray = new ArrayList<String>( ClassesRetrieval.getDBpediaClasses());

You could also guive a better name to this variable, the array sufix isn't doing much there, I would prefer dbpediaClasses.
You should do this instead:

List<String> dbpediaClasses= new ArrayList<String>( ClassesRetrieval.getDBpediaClasses());

About your implementation:

You are in the wrong path! It seems to me that you aren't writing code in the simplest way to achieve the expected behaviour. You are creating way to many maps in order to simply find a max number of intersections.

I wouldn't put my hands on fire for it, because I can't test it, but I think that your code is equivalent to this:

public static void getNdMatches() throws IOException{
    List<String> dbpediaClasses = new ArrayList<String>( ClassesRetrieval.getdbpediaClasses());
    List<String> yagoClasses = new ArrayList<String>( ClassesRetrieval.fileToArrayListYago());
    HashMap<String, Set<String>> cachedYagos = new HashMap<String, Set<String>>();
    String yagoClassWithMaxMatches="";

    for(String dbClass:dbpediaClasses){
      int max = 0;
      Set<String> dbClassSet = Sets.newHashSet(GetDBpediaClassInstances(dbClass));
      for(String yagoClass:yagoClasses){
          Set<String> yagoSet = cachedYagos.get(yagoClass);
          if(yagoSet == null){
            yagoSet = Sets.newHashSet(GetYagooClassInstances(yagoClass);
            cachedYagos.put(yagoClass, yagoSet);
          }
          Set<String> IntersectionSet = Sets.intersection(dbClassSet, yagoSet);
          if(IntersectionSet.size() > max){
            max = IntersectionSet.size();
            yagoClassWithMaxMatches = yagoClass
          }
      }
      if(max == 0){
          System.out.println(dbClass+" Corresponds to nothing");
      }else{
          System.out.println(dbClass+" Corresponds to "+ yagoClassWithMaxMatches+" with : "+max);
      }
    }
}


Finding all simple (without internal cycles) paths in a directed graph with total >1.0 weight Assume directed graph with each edge being weighted by some positive float.

  Problem: find all simple paths (in other words, [0, 1, 2, 0] is
  simple while [0, 1, 0, 1, 2, 0] is not due to internal [0, 1, 0]
  cycle) with length <= cutoff and "push" them using pusher
  callback.

P.S. There exists some realtime engine (abstracted out by pusher) that does such traversal frequently and algorithm should be optimized to be as fast as possible.

from collections import deque
def algorithm(G, source_node, target_node, pusher, cutoff=5):
    queue = deque([[source_node]] if source_node in G else deque())
    while len(queue):
        path = queue.popleft()
        if len(path) == cutoff:  # no sense to keep this path, it not gonna fit the limit
            continue
        adjacency_nodes = G[path[-1]]  # all the neighbours from the latest node in this path
        if not len(adjacency_nodes):  # deadend reached: you can't get any further from this node and it doesn't fit the requirement, so just forgetting it
            continue
        for adjacency_node in adjacency_nodes:
            extended_path = path.copy() + [adjacency_node]  # might some smart linked list do any better here?
            if adjacency_node == target_node:
                pusher(extended_path)  # wow! found one! does not make sense to keep it, since any other path from here will introduce an internal cycle, right?
            else:
                queue.append(extended_path)  # stay calm and keep trying

An empty container like a list or deque is False, so it isn't necessary to use len() on them.  This is more "pythonic"

while queue:
    ...

    if not adjacency_nodes:
        ...

It seems wasteful to add a path to the queue only to discard it because it is too long.  It would be better to check the length before making a copy of the path and adding it to the queue.  Moreover, if len(path) == is cutoff - 1 the only possible solution is if target_node is in adjacency_nodes.  So, something like this might be faster:

from collections import deque

def algorithm(G, source_node, target_node, pusher, cutoff=5):

    if source_node not in G:
        return

    queue = deque([[source_node]])

    while queue:
        path = queue.popleft()

        adjacency_nodes = G[path[-1]]

        if not adjacency_nodes:
            continue

        if len(path) == cutoff - 1:
            if target_node in adjacency_nodes:
                pusher(path[:] + [target_node])

        elif len(path) < cutoff - 1:
            queue.extend(path[:] + [node] for node in adjacency_nodes)

If you are trying to optimize for speed, use the profiler in the standard library to see where the algorithm is spending time.

The algorithm is basically a breadth first search of the graph.  Because there is a depth cutoff, a depth first search might be faster because there isn't the overhead of copying the path and keeping the queue of paths to search.  But the only way to know is to implement it and see.

Lastly, the networkx library provides all_simple_paths(G, source, target, cutoff=None) which is a generator of all simple paths from source to target with a maximum length cuttoff. FYI, networkx uses a DFS search (source code).


Is it ok to use PHP's strpos and substr altogether in one statement? I am using PHP to build a REST API. I want to receive requests from the URL in the following format:

http://mydomain.com/api/format/method?app_id=value&call=encrypted_request

So, I have modified my .htaccess as:

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

Now, I receive the request URI and extract the name of the method and the parameters from it:

$params = explode('/',$_SERVER['REQUEST_URI']);
$format = $params[count($params)-2];
$method = substr($params[count($params)-1],0,strpos($params[count($params)-1],'?'));
$app_id = $_REQUEST['app_id'];
$enc_request = $_REQUEST['call'];

My question here is, whether it is ok to use substr and strpos on the array value, simultaneously ? Also, whether this approach of forming the URL and extracting the paramters from it is correct ?

Reference :
substr strpos

Instead of raw string manipulation, I would use parse_url and parse_str:

<?php

// Note: parse_url is not intended for relative URLs
// (in other words, bare $_SERVER['REQUEST_URI'] will not work -- you'll have to build a full URL)
$url = 'http://mydomain.com/api/format/method?app_id=value&call=encrypted_request';

$path = explode('/', ltrim(parse_url($url, PHP_URL_PATH), '/'));
parse_str(parse_url($url, PHP_URL_QUERY), $query);

$api = array_shift($path);
$format = array_shift($path);
$method = array_shift($path);

$app_id = (isset($query['app_id'])) ? $query['app_id'] : null;
$enc_request = (isset($query['call'])) ? $query['call'] : null;

Yes, this code is a bit longer, but it's more readable to me. Also, raw string manipulation is hazard to failing border cases. If you use a well tested parser, problems less likely.

And, as an added bonus, this routing isn't tied to any globals. Off the top of my head I can't think of a reason, but at some point, it might be useful to be able to route a fake request. It definitely makes unit testing easier.


Bash script to extract HTML comment into a Markdown file I learned Bash a million years ago. I just wrote this simple script used to get the first lot of HTML comments from a file, and spit it out in order to create a README.md file.

It is just. So. Ugly. I read bits and pieces over the years, and I am sure it can be improved so much...

Here we go:

#!/bin/bash

IFS=''
active='0';
cat  hot-form-validator.html | while read "line";do

  echo $line | grep '\-\->' > /dev/null
  if [ $active = '1' -a $? = '0' ];then
    exit 0;
  fi;

  suppress=0;
  echo $line | grep '^ *@' > /dev/null
  if [ $? = '0' ];then suppress='1'; fi;

  if [ $active = '1' -a $suppress = '0' ];then echo $line;fi;

  echo $line | grep "<!--" > /dev/null
  if [ $? = '0' ];then active='1'; fi;

done

Questions:

Is there a better way to do grep and then check $??  Back in the day it was the way to go, but...
Should active be a proper number rather than a string with a number? I  know, it could be anything... but having a string that can be 0 or 1 just feels wrong.
Is there a better way to preserve spaces, rather than zapping IFS?
Any more pearls of wisdom, other than quitting my (short lived) career of bash scripter?

A bug

If your html contains a backspace character e.g

The special character \n is a way to include read line

your code interprets it a

  The special character n is a way to include read line.

to avoid this, add "-r" switch to your read line

cat  hot-form-validator.html | while  read -r "line";do

You want to check if your file exists before reading it

if [ -f $filename ]; then
#do something
else
#do something
fi


Add one to integer represented as an array I am practicing interview questions and have written the following
 code for the given task.

Task : Given a non-negative number represented as an array of digits, add 1 to the number (increment the number represented by the digits). The digits are stored such that the most significant digit is at the head.

Code:

class Solution:
# @param A : list of integers
# @return a list of integers
    def plusOne(self, A):
        Rev_A = A[::-1]
        i = 0
        while i <= len(A)-1:
            if Rev_A[i] != 9:
                Rev_A[i] +=1
                carry = 0
                break
            else:
                Rev_A[i] = 0
                carry = 1
            i += 1
        if carry == 1:
            Rev_A.append(1)
        while True:
            if Rev_A[-1]==0:
                Rev_A.pop()
            else:
                break
        return Rev_A[::-1]

    def __init__(self):
        self.list = []

Test cases:

if __name__ == "__main__":

    A = Solution()
    ## Test Cases
    print A.plusOne([0])
    print A.plusOne([9,0,0])
    print A.plusOne([6,9,9])
    print A.plusOne([9,9,9])
    print A.plusOne([0,9,9,9])
    print A.plusOne([0,0,0,1,2,3])

How can this code be better?

Run the code through pycodestyle, then understand and apply all of the recommended changes. This is tedious the first couple times, but you'll learn to write much more idiomatic Python.
The class is pointless - you might as well just write a bare function instead. __init__ also creates a field which is then never used.
Names like A make the code harder to read. Naming your variables what they actually are makes the code much easier to read.
I would swap around your first if/else to avoid the negative comparison.
You use a number for carry, but it might as well be boolean because it can never be more than 1.
Personally I consider this code hard to understand. You reverse the list twice (making a copy both times), add and remove to it. This is my take on it:

def increment(digits):
    for index, digit in reversed(list(enumerate(digits))):
        if digit == 9:
            digits[index] = 0
        else:
            digits[index] += 1
            return digits
    digits.insert(0, 1)
    return digits

if __name__ == '__main__':
    print(increment([0]))
    print(increment([9,0,0]))
    print(increment([6,9,9]))
    print(increment([9,9,9]))
    print(increment([0,9,9,9]))
    print(increment([0,0,0,1,2,3]))

Reverse the list one element at a time
Set trailing nines to zero
If any number is not nine, increment it and we're done
If we get through the whole list, it must have been all nines, so we add a one to the start and return
This code treats an empty list as zero, which may or may not be allowed in the exercise.


Review of HTML and CSS for a newsfeed of posts Originally my wireframe was

But I ended up going with this in testing. The image is the result of my new code.

Keep in mind that the actual content is just filler content and will be dynamic. I just wanted to get the styling in place.

I created each article with the following code

HTML

[test] Title of the Discussion

Here we are talking about something. and this is the short brief about it.

     Posted on

       4/4/1984

     by

       Firstname Surname

     View &rarr;

CSS

.discusBox {
  border: #333 solid 1px;
  height: 120px;
  width: 720px;
  position: relative;
  background-color: #fff;
}

.discusTitle {
  line-height: 40px;
  padding-left: 6px;
  position: absolute;
  top: 0;
  left: 120px;
  width: 600px;
  vertical-align: middle;
}

.discusTitle h3 {
  font-size: 18px;
  font-weight: bold;
}

.discusBrief {
  height: 60px;
  width: 600px;
  position: absolute;
  top: 40px;
  left: 120px;
  overflow: hidden;
}
.discusBrief p { padding-left: 6px; }

.discusMeta {
  height: 20px;
  width: 600px;
  position: absolute;
  top: 100px;
  left: 120px;
  font-size: 11px;
  line-height: 20px;
  vertical-align: middle;
}

.discusMetaPostedOn, .discusBy {
  display: inline;
  float: left;
}

.discusMetaPostedOn {
  padding-left: 6px;
  margin-right: 24px;
}
.discusMetaPostedOn p { margin-bottom: 0;}

.discusBy { }

.discusLink {
  float: right;
  background-color: #2fb7e0;
  width: 120px;
  text-align: center;
}

.discusLink a{
  color: #fff;
  text-decoration: none;
  display: block;
}

this looks really good so far,

I don't see anything that I would change about this.  you are using span tags correctly and efficiently for what you are doing with them,  your div tags are also used to the best of their abilities.

your CSS also looks good, I don't think I would change anything there either.

I guess the only thing that I might change, and this depends on how you intend to use it, is probably the grouping of the discusBy and the discusMetaPostedOn, I might group those together because they look like they are going to be the same formatting aside from the things that you have given specific classes to.

you might want to give each <div class="discusBox"> it's own unique ID especially if you are going to work some Javascript magic or server-side magic on it.

otherwise it looks really good,  you probably won't make any of the changes I mentioned because of the way you want to go forward with the code.


Sorting Timestamped Messages (iOS) An app I'm building professionally includes rudimentary text messaging. It allows users to send from the phone, and it polls for new messages (I know, yikes. Push notifications are a future task) with variable frequency for new messages from other users.

Part of its functionality is of course keeping messages in date-sorted order, and each message has a timestamp on it. I came up with two sorting implementations and I was curious as to which one would be more efficient.

Implementation 1:

for (Message* message in messages) {
    [self.backingMessages addObject:message];
}
NSSortDescriptor* sortingDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"fullTimestamp" ascending:YES];
[self.backingMessages sortUsingDescriptors:@[sortingDescriptor]];

Implementation 2:

for (Message* message in messages) {
    NSInteger insertionPoint = [self.backingMessages indexOfObject:message inSortedRange:NSMakeRange(0, self.backingMessages.count) options:NSBinarySearchingInsertionIndex usingComparator:^NSComparisonResult(Message*  _Nonnull obj1, Message*  _Nonnull obj2) {
        return [obj1.fullTimestamp compare:obj2.fullTimestamp];
    }];
    self.backingMessages[insertionPoint] = message;
}

Some observations:

The new messages being added are known to be sorted
The messages being added to are initially sorted, and so will also be sorted every time new messages are added.

Doing some back-of-the-napkin analysis...

n = length of existing message array
m = length of new message array
implementation 1: O(m) + O((n+m)log(n+m))
implementation 2: O(mlog(n+m)) + O(m) <- for the shifting that I assume happens upon insertion

My gut says that implementation 2 would be faster by a hair, depending on how the shifting works. All of this being said, I'm assuming that Apple ends up doing some crazy polymorphic implementation for sorting depending on the data, so implementation 1 might end up being faster. I'm probably overthinking this since the amount of data I'm expecting is so small, but I'm still curious about what might theoretically be faster.

If both new and old messages are sorted it's basically a merge of two sorted arrays, similar to the merge step in merge sort. It can be done O(n + m) time. I'd suggest you to look into how that's implemented.


Extracting address information from non-formatted text I'm pretty new to large projects, and usually my code is neat and manageable. But now that I'm about a month deep, things are starting to seem sloppy (or at least not aesthetically pleasing).

Are there any good methods/things I should keep in mind when designing a function that is compact and neat?

Function is question: 'postal', 'streettypecheck', and 'namecheck' are regex

function addresscheck(serverpackage) {
    var i;
    var streetnumber = [];
    var postalcode = [];
    var potentialname = [];
    var streettype = [];
    var highlightdata = serverpackage.split(' ');
    for (i = 0; i <= highlightdata.length; i++) {
        if(!isNaN(highlightdata[i])) {
            streetnumber.push(highlightdata[i]);
        } else if (postalcheck.test(highlightdata[i])) {
            if (highlightdata[i].indexOf('-') !== -1 || highlightdata[i].indexOf(" ") !== -1 && highlightdata[i].length == 7) {
                postalcode.push(highlightdata[i]);
            } else if (highlightdata[i].indexOf('-') == 1 || highlightdata[i].indexOf(' ') && highlightdata[i].length == 6) {
                postalcode.push(highlightdata[i]);
            }
        } else if (streettypecheck.test(highlightdata[i])) {
            streettype.push(highlightdata[i]);
        } else if (namecheck.test(highlightdata[i])) {
            potentialname.push(highlightdata[i]);
        }
    }
    var addressinfo={
        postalcode: postalcode,
        streetnumber: streetnumber,
        streettype: streettype,
        potentialname: potentialname
    }
    return addressinfo;
}

Consider that all text is non formatted.

Sample data1: Street st jksh7dyasf B7Z-8U0 aaa

Sample data2: 166623gggdgdgdgdf 123 88f8f88d88dydydy B7Z-8U0 Street st 8888 aaaa

BUG
First you split by space and then you test if those chunks contain it. The answer will always be no. From the fact that you still test for it however, I guess that you actually expect them to be there, so some valid postal codes will not be detected.
Mistakes

You iterate one too many times,
In … || highlightdata[i].indexOf(' ') && … you probably forgot  == 1,
Due to precedence of && over || and lack of parentheses your logical statement works differently than you probably intended,

Remarks

Use of for…of would benefit readability and performance,

No need to define 4 array variables that will later end up in an object — create an object with 4 arrays right away and push there directly,

Use strict equality === operator — it performs no type conversion and you avoid potential pitfails,

Use const and let rather than var — they won't exist in the entire execution context and enable performance optimization,

highlightdata[i].indexOf('-') == 1 will at most go through the entire string — use highlightdata[i].charAt(1) === '-' instead,

!highlightdata[i].includes('-') is more idiomatic and concise than highlightdata[i].indexOf('-') !== -1,

No need to declare var i before the loop,

Naming convention: use camelCase,

2 space and line break after } are more popular formatting choices,

Be consistent with the kind of quotes you use.

Rewrite
Effectively it works like the original code. Therefore it is broken as well.
const checkAddress = serverPackage => {
  const info = {postal: [], streetNumber: [], streetType: [], potentialName: []};

  for (const token of serverPackage.split(' ')) {
    if(!isNaN(token)) {
      info.streetNumber.push(token);
    }
    else if (postalCheck.test(token)) {
      if (token.charAt(1) === '-' || token.length === 6) {
        info.postal.push(token);
      }
      else if (!token.includes('-') || token.length === 7) {
        info.postal.push(token);
      }
    }
    else if (streetTypeCheck.test(token)) {
      info.streetType.push(token);
    }
    else if (nameCheck.test(token)) {
      info.potentialName.push(token);
    }
  }

  return info;
};


Ding!!
I've got it!
So, I have been looking at this code for quite a while now, because I knew there had to be some ingenious way to do this. It seemed all to simple to need something of the opposite scale! And, after playing around, sure enough, I think I got it to it's best.
However! I'd hate to just give away the answer without a bit of some code critiquing beforehand. Shall we begin?...

I sure hope you didn't spend to long typing out those arrays. That'd would have been a bummer! Let's take advantage of a little resource, I like to call it the fill-numeric-array-o-matic. Switch that baby on, and bam, you get this beautiful babe:
$_5elements = range(1, 5);
$_10elements = range(1, 10);
$_14elements = range(1, 14);
$_40elements = range(1, 40);
$_140elements = range(1, 140);

Ain't she a beaut'?
Alright, next step! I see you countin' up the input array a couple times, good thing we know how to handle this! That's right, it needs to DRY out.
$array_length = count($array);

Feel free to replace all those nasty repetitions now!
After we've dried up that spill, let's knock off this arrow nonsense and whip up some clean lookin' code!
Watch ladies and gentlemen as we turn this snippet:

if ($array) {
    $array_length = count($array);
    if ($array_length > $target_array_length) {
        ...
        foreach (...) {
            if (...) {
                $return[] = $value;
            }
        }
        $return = array_reverse($return);
    } else {
        $return = $array;
    }
    return $return;
}
return false;

into this gorgeous girl piece of code!
$array_length = count($array);

if ($array_length == 0) {
    return false;
}

if ($array_length <= $target_array_length) {
    return $array;
}

*insert top secret algorithm here*

return array_reverse($output);

I hope we all got to see this amazing transformation, the original having layers and layers, ifs and elses all over! To now, a clean and concise workflow...
Up next! The end is near, I promise! Before though, let's have a look at these formats and styles. Your code's fashion is really last year... Everyone's shopping at using 2014 standards.
Seriously though, applying and sticking to a style will benefit everyone. I highly recommend something such as PHP-FIG or the Zend Standards.
It's mostly just your naming conventions in this code that are goofy, and I have made some changes in my code below.
Last but not least, the algorithm! No offense, but your loop plus the conditions made everything so hard to follow. Debugging it to figure out what it did what gave me a headache. Good thing I have aspirin.
I found your choice of krsort() unnecessary. Well, I've been able to completely remove this!
Now, here's a list of requirements that must be achieved when we do the work:

The amount of numbers returned MUST be equal to the number specified.
The interval between numbers MUST be as even as possible throughout the list.
The highest integer has priority in the output over the lowest numbers. (Assumed this one based on your output)

I'm going to use a funky lookin' for loop to go through the array. It's going to look confusing at parts, but I'll do my best to make it worse clear things up!
$output = [];
$ratio = round($array_length / $target_array_length);
for ($index = $array_length - 1; count($output) < $target_array_length; $index -= $ratio) {
    $output[] = $array[$index];
}

return array_reverse($output);

How ya like them apples! Alrighty, let's see what I've done here:

Make a new $output array to hold our output.
Find the $ratio at which we should go through the array at. This will cross off the evenly spaced requirement!
We're going to set $index to one less than the original array's length. We do this so we can reference the highest index and not have an out of bounds error.
Throughout the loop, check to make sure we have less in our output array than we want. If we have the right amount, break the loop. Cross off Req. #1!
For each iteration, reduced our index by that ratio we came up with earlier.

Inside the loop, add to our output the value from $array  with the index that has been decreasing in the loop.
Reverse it to get the desired direction, and there ya have it!
Here's the full code that I came up with. Naming and all! I call this one: Make-sorted-and-spread-out-array-inator.
$arrayLength5 = range(1, 5);
$arrayLength10 = range(1, 10);
$arrayLength14 = range(1, 14);
$arrayLength40 = range(1, 40);
$arrayLength140 = range(1, 140);

function spreadOutArray(array $array, $targetOutputLength = 10) {

    $originalArrayLength = count($array);

    if ($originalArrayLength == 0) {
        return false;
    }

    if ($originalArrayLength <= $targetOutputLength) {
        return $array;
    }

    $output = [];
    $interval = round($originalArrayLength / $targetOutputLength);
    for ($index = $originalArrayLength - 1; count($output) < $targetOutputLength; $index -= $interval) {
        $output[] = $array[$index];
    }

    return array_reverse($output);
}

I hope the galaxy is better now that this question has one hell of an answer. Live long and prosper. Writing these types of answers will help in your quest to living long and prospering much.
I'd be happy to clarify anything.


Finding the minimum number of moves to achieve equal array elements Long story short, the other day I discovered the site LeetCode and started solving some of its problems until I stumbled onto this one.

I'll paste the description here:

  Given a non-empty integer array of size n, find the minimum number of
  moves required to make all array elements equal, where a move is
  incrementing n - 1 elements by 1.

  Input:

[1,2,3]

  Output:

3

  Explanation:

  Only three moves are needed (remember each move increments two
  elements): [1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

The problem is, the solution I am trying to submit always exceeds the allowed processing time limit and I feel like I've reached a dead end. Can anyone suggest a way to improve my code?

 static void Main()
    {
        int res = MinMoves(new int[] { 1, 2, 3 });
    }
    public static int MinMoves(int[] nums)
    {
        if (nums.Length < 2)
            return 0;

        int moves = 0;
        int diff = 0;
        int min = 0;
        int max = 0;
        int maxIX = 0;
        do
        {
            min = nums.Min();
            max = nums.Max();
            maxIX = Array.IndexOf(nums, max);
            diff = Math.Abs(max - min);
            moves += diff;
            for (int i = 0; i < nums.Length; i++)
                if (i != maxIX)
                    nums[i] += diff;

        } while (min != max);

        return moves;
    }

The problem can be re-formulated into a much easier-to-conceptualize form.

Instead of

  Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.

say instead

  where a move is decrementing a single element by 1

Do you see why these are the same?  Suppose we start with 1, 2, 3.  Adding 1, 1, 0 produces 2, 3, 3.  Adding 0, 0, -1 produces 1, 2, 2, which is effectively the same thing. However many moves it takes to make 2, 3, 3 all equal is surely the same number of moves as it takes to make 1, 2, 2, all equal, or 0, 1, 1, or 1000, 1001, 1001, or whatever. Where you start is irrelevant.

Once you know that the problem is actually "how many single decrements does it take to get all the elements equal?" the answer is easily seen. There is never any point in decrementing the smallest element, and every element will have to eventually equal the smallest element. Therefore the answer is: it's the sum of the differences of every element from the minimal element.

That's a trivial program in C#:

var min = nums.Min();
return nums.Select(x => x - min).Sum();

Or alternatively, in a single line:

return nums.Sum() - nums.Length * nums.Min();

(Though as noted in the comments, this second version can overflow. Consider doing all the math in longs or BigIntegers if you're worried about overflow cases.)


Efficient way of flat mapping a range of a multidimensional random access collection I've recently answered a question about reading elements from an array of arrays. A way it could be interpreted is that the OP wanted to read a range that could span over multiple subarrays of the 2D array like so :

let a = [["5", "3", ".", ".", "7", "."],
         ["6", ".", ".", "1", "9", "5"]]

a.lazy.flatMap{$0}[1..<7] ["3", ".", ".", "7", ".", "6"]

This way of reading a range would need to at least flatMap all the previous arrays to the lower bound of the range. Which would be wasteful.

A more natural way would be to only read the needed elements from the original array:

func get<T>(_ range: Range<Int>, from array2d: [[T]]) -> [T]? {
    var result: [T] = []
    result.reserveCapacity(range.upperBound - range.lowerBound)

    var count1 = 0

    //Get the index of the first element
    guard var low = array2d
            .firstIndex(where: {
                 count1 += $0.count
                 return range.lowerBound < count1 }),
          count1 != 0
    else { return nil }

    let before = count1 - array2d[low].count
    var count2 = before

    //Get the index of the last element in the range
    guard let high = array2d[low..<array2d.endIndex]
            .firstIndex(where: {
                 count2 += $0.count
                 return range.upperBound <= count2
            }),
          count2 != 0
    else { return nil }

    //Append the elements in the array with the low index
    for i in (range.lowerBound - before)..<min(range.upperBound - before, array2d[low].count) {
        result.append(array2d[low][i])
    }

    //If the range spans over multiple arrays
    if count1 < count2 {
        low += 1

        //Append the elements in the arrays with an index between low and high
        while low < high {
            result.append(contentsOf: array2d[low])
            low += 1
        }

        //Append the elements in the array with the high index
        for i in 0..<(range.upperBound - count2 + array2d[high].count) {
            result.append(array2d[high][i])
        }
    }

    return result
}

Which could be used like so :

let a = [["0", "1", "2", "3", "4", "5"], ["6", "7"], [], ["8","9","10","11", "12"], ["13","14", "15"]]

get(5..<11, from: a) //Optional(["5", "6", "7", "8", "9", "10"])
get(7..<9, from: a) //Optional(["7", "8"])

To me, the above code feels.. on the border of sanity/maintainability...

What I'd like to do is to make it more generic, maybe as an extension to RandomAccessCollection, and making the flattening process recursive for arrays/collections of arbitrary dimensions. I'm stuck here and not sure if this is the appropriate network to ask such a question.

Feedback on all aspects of the code is welcome, such as (but not limited to):

Efficiency,
Readability,
Naming.

I gather that your intent was to write a method that iterates through an array of arrays (but avoiding functional patterns), flattening the results in the process such that given...

let a = [["0", "1", "2", "3", "4", "5"], ["6", "7"], [], ["8","9","10","11", "12"], ["13","14", "15"]]

... that result for 5..<10 would be ["5", "6", "7", "8", "9"]

Assuming that’s what you were trying to do, I think you can simplify it:

extension Array {
    func flattened<T>(range: Range<Int>) -> [T]? where Element == Array<T> {
        var result: [T] = []

        var offset = range.startIndex
        var length = range.upperBound - range.lowerBound

        result.reserveCapacity(length)

        for subarray in self {
            let subarrayCount = subarray.count
            if offset < subarrayCount {
                if length > subarrayCount - offset {
                    result += subarray[offset...]
                    length -= subarrayCount - offset
                } else {
                    return result + subarray[offset..<offset + length]
                }
            }
            offset = Swift.max(0, offset - subarrayCount)
        }

        return nil
    }
}

In terms of observations on your code:

I wouldn’t advise get method name. It’s not very meaningful name and only conjures up confusion with getters. I’d go with something that captured the “flattening” nature of the routine.
As a general rule, we should avoid closures with side-effects in functional programming patterns. Even though you’ve written an “iterative” rendition of the OP’s code, you’re using a functional method, firstIndex, and you are updating variables outside the closure. It’s technically allowed but is contrary to the spirit of functional programming patterns and is dependent upon the implementation details of firstIndex.


Helper extension to release Windsor component; not sure if it's over-kill One of the tenets of Windsor IoC (probably applies to all IoC containers too) is to "release what you explicitly resolve", which admittedly should occur rarely.  But we have a fair few UsingFactoryMethod setups in our installers, which are resolving directly (which appears to be a valid case for explicit resolution).

However, remembering to call Dispose() on those resolved things is something I doubt a lot of people will remember, so I came up with a helper method in order to be able to wrap that logic away (always a good thing, right?).  However, I'm not sure if it's just a bit overkill in this case.

namespace Castle.Windsor {
    using System;
    using Castle.MicroKernel;

    public static class KernelExtensions {

        public static ResolvedResult<TInstance> ResolveDispose<TInstance>(this IKernel kernel) {
            return new ResolvedKernelResult<TInstance>(kernel);
        }

        public static ResolvedResult<TInstance> ResolveDispose<TInstance>(this IWindsorContainer container) {
            return new ResolvedContainerResult<TInstance>(container);
        }

        public abstract class ResolvedResult<T> : IDisposable {

            public T Instance { get; private set; }

            protected ResolvedResult(Func<T> resolver, Action<object> releaser) {
                this.Instance = resolver();
                this._Releaser = releaser;
            }

            #region IDisposable Members

            public void Dispose() {
                if (null == _Releaser) {
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                //Dis-associate the resolved instance, can't null assign as T isn't typed
                Instance = default(T);

                _Releaser(Instance);
                _Releaser = null;
            }

            #endregion

            private Action<object> _Releaser;

            public static implicit operator T(ResolvedResult<T> res) {
                return res.Instance;
            }
        }

        private sealed class ResolvedKernelResult<T> : ResolvedResult<T> {
            internal ResolvedKernelResult(IKernel kernel) : base(kernel.Resolve<T>, kernel.ReleaseComponent) { }
        }

        private sealed class ResolvedContainerResult<T> : ResolvedResult<T> {
            internal ResolvedContainerResult(IWindsorContainer container) : base(container.Resolve<T>, container.Release) { }
        }
    }
}

Usage

Before:

container.Register(
    //...

    Component.For<MyComponentType>()
        .UsingFactoryMethod(k => {
            var altComponent = k.Resolve<SomeAlternativeComponent>();

            var component = new ImplementingComponentType(altComponent.RandomProperty);

            k.ReleaseComponent(altComponent);

            return component;
        })
)

After:

container.Register(
    //...

    Component.For<MyComponentType>()
        .UsingFactoryMethod(k => {
            using(var altComponent = k.ResolveDispose<SomeAlternativeComponent>()) {
                return new ImplementingComponentType(altComponent.Instance.RandomProperty);
            }
        })
)

Style-wise everything looks good. The only note I'd make is that in C#, generally the convention is to start brackets on a new line rather than in-line, although obviously this is ultimately up to personal or team preference. XML comments on public members may be a good idea too, as it's not trivially obvious what the purpose of this class is unless you're very familiar with the container.

As to the actual usefulness of the helper, though, I'm doubtful:

It doesn't significantly reduce the amount of code you have to write
It is just as reliant on people remembering to use it
It does not improve readability, and if anything, slightly degrades it.

One alternative would be instead of providing a helper method to use inside UsingFactoryMethod, you provide an alternative version of that method. You'd probably need to tweak it, but a rough version might look like:

public static ComponentRegistration<TService> UsingFactoryMethod<TService, TResource, TImpl>(
        this ComponentRegistration<TService> component, Func<IKernel, TResource> resourceResolver,
        Func<IKernel, TResource, TImpl> factoryMethod)
        where TService : class
        where TImpl : TService
    {
        return component.UsingFactoryMethod(
            (kernel) =>
            {
                var resource = resourceResolver(kernel);
                var result = factoryMethod(kernel, resource);
                kernel.ReleaseComponent(resource);
                return result;
            });
    }

A bit of a mouthful, but then using it would look like:

Component.For<MyComponentType>()
    .UsingFactoryMethod(
         k => k.Resolve<SomeAlternativeComponent>(),
        (k, alt) => (new ImplementingComponentType(alt.RandomProperty)));

This reduces the amount of code to write a bit more, and it helps remind people to use it by being on their intellisense. I'd say it's somewhat a matter of judgement whether this is more or less readable than the helper method version. It is also less flexible if, for example, you need multiple different explicitly resolved resources inside a single factory method. But, as far as I can think, this kind of approach is likely to be the only fruitful way to achieve what you want.

UPDATE

Another alternative using the decorator pattern, which allows you to deal with multiple explictly resolved services by decorating the kernel:

public static ComponentRegistration<TService> UsingReleasingFactoryMethod<TService, TImpl>(
    this ComponentRegistration<TService> component, Func<IKernel, TImpl> factoryMethod)
    where TService : class
    where TImpl : TService
{
    Converter<IKernel, TImpl> safeMethod = (kernel) =>
    {
        var releasingKernel = new ReleasingKernel(kernel);
        var result = factoryMethod(kernel);
        releasingKernel.ReleaseAll();
        return result;
    };
    return component.UsingFactoryMethod(safeMethod);
}

Here ReleasingKernel is a decorator for Kernel which keeps track of all services resolved, and otherwise passes all calls through to the kernel. It also has a method which I'm calling ReleaseAll which calls to the contained kernel to release all services it has recorded.

This doesn't actually have to be a decorator, you could create your own class which only has a subset of the interface of IKernel available, if not all methods are needed.

So using this, your example would look like:

Component.For<MyComponentType>()
    .UsingReleasingFactoryMethod(k => {
        var altComponent = k.Resolve<SomeAlternativeComponent>();
        return new ImplementingComponentType(altComponent.RandomProperty);
    })

Definitely shorter and more readable. In terms of people remembering to use it, it will appear on the intellisense, but with a different name to UsingFactoryMethod.


Password protected Joomla administrator folder with Python I am trying to make a basic auth password protected folder for Joomla. This script will simply ask for username and password to secure administrator folder in Joomla and creates .htaccess and .pass_file.

I want you to review it and offer suggestions so that I can do it more efficiently and learn to manage code.

#!/usr/bin/env python
import os
import pwd
import sys

def ok():
    os.chdir("/home/" + username);
    os.system('htpasswd -c .pass_file '+ user);
    os.chdir("/home/" + username + "/public_html/administrator/");
    os.system('echo AuthUserFile /home/' + username + '/.pass_file > .htaccess');
    os.system('echo AuthName Restricted >> .htaccess');
    os.system('echo AuthType Basic >> .htaccess');
    os.system('echo require valid-user >> .htaccess');
    print "=" *40;
    quit();

username = raw_input("Enter your cpanel username: ");
try:
    pwd.getpwnam(username);
except KeyError:
    print "User not found.";
    quit();
print "=" * 40;
user = raw_input("Enter the username you want to create for authentication: ");
print "=" * 40;
print "Your username will be "+ user +" for authentication";
print "=" * 40;
filename="/home/"+username+"/public_html/administrator/.htaccess";
if os.path.isfile(filename):
    yes = set(['yes','y', 'ye', ''])
    no = set(['no','n'])
    response = raw_input("Filename exists. Overwrite??");
    ans = response.lower();
    if ans in no:
        print "Sorry we didn't secure the administrator folder. :(";
        quit();
    elif ans in yes:
        ok();
    else:
        sys.stdout.write("Please respond with 'yes' or 'no'. Quiting...");
quit();

My suggestions would be:

Rewrite ok() using python I/O rather than running echo in a subprocess. We're passing in arguments because they are no longer going to be global variables after some of the edits below.

def ok(passfile, htaccess, user):
    os.system("htpasswd -c %s %s" % (passfile, user))
    with open(htaccess, 'w') as f:
        f.write('AuthUserFile %s\n' % (passfile))
        f.write('AuthName Restricted\n')
        f.write('AuthType Basic\n')
        f.write('require valid-user\n')
    print "=" *40
    quit()

Consider using the python module https://pypi.python.org/pypi/htpasswd instead of calling htpasswd in a subprocess. For example:

import htpasswd

with htpasswd.Basic("/path/to/user.db") as userdb:
try:
    userdb.add("bob", "password")
except htpasswd.basic.UserExists, e:
    print e

Take all the top level lines outside any function and put them in a main() routine at the top of the file (after the imports). Like so (I'm also doing some tweaks here to make things more portable and pythonic):

#!/usr/bin/env python
import os
import pwd
import sys

def main(args):
    username = raw_input("Enter your cpanel username: ");
    try:
        pwd.getpwnam(username);
    except KeyError:
        print "User not found.";
        quit();
    print "=" * 40;
    user = raw_input("Enter the username you want to create for authentication: ");
    print "=" * 40;
    print "Your username will be "+ user +" for authentication";
    print "=" * 40;

    # Note we're building up our file paths without ever using '/' or
    # '\'. By letting python build our paths for us, they'll be portable
    homedir = os.getenv("HOME")
    passfile = os.path.join(homedir, ".pass_file")
    htaccess = os.path.join(homedir, "public_html", "administrator", ".htaccess")

    # If htaccess already exists, we ask user whether to overwrite.
    # If the user says "no", we say sorry and call quit().
    # If the user says "yes", we break out of the loop and call ok().
    # Otherwise, we keep telling the user to answer 'yes' or 'no'
    # until they do.
    #
    # If htaccess does not exist, I think we want to create it. The
    # original code did not address this case.
    if os.path.isfile(htaccess):
        while True
            ans = raw_input("File %s exists. Overwrite??" % htaccess);
            # re.findall() will return a list of regexp matches. If there
            # are no matches, the list is empty and the if evaluates to
            # False. Note the regexp handles mixed case and abbreviations.
            if re.findall('[Nn][Oo]?', ans):
                print "Sorry we didn't secure the administrator folder. :(";
                quit();
            elif re.findall('[Yy]?[Ee]?[Ss]?', ans):
                break
            else:
                sys.stdout.write("Please respond with 'yes' or 'no'.");
    ok(passfile, htaccess, user)
    quit();

Then at the bottom of the file,

if __name__ == '__main__':
    main(sys.argv)

By using a main() routine and calling it from the bottom of the file if __name__ contains the string '__main__', you can import this file into other files and reuse the code by calling the functions. With lines at the top level of the file, outside functions, those lines would get run if you ever imported the file. Following this convention consistently makes debugging and code reuse much easier.


Can I shorten this assembly code to test if a number is even? Here is MIPS code to return 1 if a number is even, 0 otherwise:
isEven:
  andi $t0, $a0, 1
  li   $t1, 1
  sub  $v0, $t1, $t0
  jr   $ra

My question is whether this can be done in fewer instructions. I could implement isOdd in two instructions (by eliminating the li and sub), but I don't see a single-instruction way to invert just the bottom bit of $t0 into $v0.

As was helpfully pointed out by G. Sliepen in a comment, you can flip the bottom bit using xor.
That enables the above code to be rewritten in one fewer instruction:
isEven:
  andi $t0, $a0, 1
  xori $v0, $t0, 1
  jr   $ra

This takes advantages of the properties:
A xor 1 = !A
A xor 0 = A


Calculate inputs average I'm creating an online calculator to get the average grade of different tests my students take. I wonder if you see any problems in the following code or any way to improve it:

document.getElementById('calculator').addEventListener('click', function() {
  var physicsTests = document.getElementById('physics').getElementsByTagName('input'),
    historyTests = document.getElementById('history').getElementsByTagName('input'),
    physicsTestsCount = 0,
    historyTestsCount = 0,
    physicsAverage = document.getElementById('physicsAverage'),
    historyAverage = document.getElementById('historyAverage'),
    i;
  for (i = 0; i < physicsTests.length; i++) {
    if (physicsTests[i].value) {
      physicsTestsCount++;
    }
    if (!physicsTestsCount) {
      physicsAverage.value = 'No assessment made!';
    } else {
      physicsAverage.value = (Number(physicsTests[0].value) + Number(physicsTests[1].value) + Number(physicsTests[2].value)) / physicsTestsCount;
    }
  }
  for (i = 0; i < historyTests.length; i++) {
    if (historyTests[i].value) {
      historyTestsCount++;
    }
    if (!historyTestsCount) {
      historyAverage.value = 'No assessment made!';
    } else {
      historyAverage.value = (Number(historyTests[0].value) + Number(historyTests[1].value) + Number(historyTests[2].value)) / historyTestsCount;
    }
  }
});
<form>

    Physics:
    <input type="number">
    <input type="number">
    <input type="number">
    <output id="physicsAverage"></output>

    History:
    <input type="number">
    <input type="number">
    <input type="number">
    <output id="historyAverage"></output>

  <button type="button" id="calculator">Calculate</button>
</form>

type=number inputs can be error-prone because it's easy to mistakenly adjust a value with the mouse wheel.  Unless you specifically intend to enter grades with a mouse wheel, or have some other use for that interface, go with regular text fields.

You're testing the truth of element.value as a string and then adding it as a number.  It's good practice to be explicit about these kinds of conversions.

It would be nice to generalize the code to handle any subject, without the use of hard-coding or copy-and-paste.

We only need the subject name to put a label next to the inputs; the code doesn't need to know it at all.   The code snippet below uses the name=... attribute to label the inputs (via CSS) and class=subject to denote an average-eligible set of inputs.  The number of inputs is determined solely by the HTML.

document.getElementById('calculator').addEventListener('click', function() {
    Array.from( document.getElementsByClassName('subject') ).forEach(subject => {
        const scores=Array.from( subject.getElementsByTagName('input') ).map( e => ""+e.value.trim() ).filter( s => s.length ).map( n => parseFloat(n) ),
          output=subject.getElementsByTagName('output'),
          sum=scores.length ? scores.reduce((partial_sum, a) => partial_sum + a) : 0,
          average=scores.length ? ( sum / scores.length ).toFixed(2) : "No assessment made!"
      if (output.length) output[0].textContent = average;
  })
});

.subject::before {  text-transform: capitalize; content: attr(name) ": " }
.subject > input { width:3em }
<form>

   <input> <input> <input> <output/>

   <input> <input> <input> <output/>

 <input> <input> <input> <input> <output/>

   <input> <output/>

  <button type=button id=calculator>Calculate</button>
</form>


Custom event handler in Javascript In my web projects I often need a simple way to trigger callbacks defined somewhere else. Leaving jQuery finally behind me, I was missing their simple event system and tried to create my own. I'd like to know if this is a good implementation since I am not that proficient with Javascript yet.

function Events ()
{
    /**
     * handlers for an event
     *
     * @var {object}
     */
    this.stack = {}

    /**
     * on function.
     * adds a callback to an event stack
     *
     * @param {string} event       the event to subscribe to
     * @param {function} callback  the event callback to subscribe
     *
     * @return void
     */
    this.on = function (event, callback)
    {
        // if there is no callback registered for this event yet,
        // create an array for this event
        if (! this.stack.hasOwnProperty(event)) {
            this.stack[event] = []
        }

        // push the event callback to the handler stack
        this.stack[event].push(callback)
    }

    /**
     * off function.
     * removes a callback from an event stack
     *
     * @param {string} event       the event to unsubscribe from
     * @param {function} callback  the event callback to unsubscribe
     *
     * @return {bool}              whether the callback was removed or not
     */
    this.off = function (event, callback)
    {
        // if the event does not exist, return false
        if (! event in this.stack) return false

        // iterate over handlers, remove the callback in question
        this.stack[event] = this.stack[event].filter(
            function(item) {
                if (item !== callback) {
                    return item
                }
            }
        )

        return true
    }

    /**
     * trigger function.
     * calls all registered callbacks for an event
     *
     * @param {string} eventName  the event to trigger callbacks for
     * @param {mixed} data        optional data to hand over to the callbacks
     *
     * @return {bool}             whether the event has been fired
     */
    this.trigger = function (event, data)
    {
        // use an empty object if no data given
        var data = (typeof data === 'undefined') ? {} : data;

        // the event does not exist.
        if (! this.stack.hasOwnProperty(event)) return false

        // iterate over all callbacks, run them as expected
        for (var i = 0; i < this.stack[event].length; i++) {

            // @TODO: the scope should maybe be modifyable, even though
            //        this would require to specify a scope parameter
            //        for every event trigger...
            this.stack[event][i].call(window, event, data)
        }

        return true
    }
}

The Events class can later be instantiated and used in other objects like so:

// ...

this.eventHandler = new Events

this.eventHandler.on('testEvent', function(event, data) {
    console.log(event + ' fired! Data: ' + data)
})

this.eventHandler.trigger('testEvent', 'test data') // testEvent fired! Data: test data

// ...

Overall it looks pretty good. There are a couple of improvements.

Stylistically, JavaScript doesn't place the { character on a new line. You'll see it start on the same line separated by one space:

function Events() {
    // ...
}

if (condition) {
    // ...
} else if (condition) {
    // ...
} else {
    // ...
}

Since you are not using any function closure variables, there is no need to recreate the on and trigger methods each time the Events constructor function is called. Use the prototype property instead:

function Events() {
    this.stack = [];
}

Events.prototype = {
    stack: null,

    constructor: Event,

    on: function (event, callback) {
        // ...
    },

    off: function (event, callback) {
        // ...
    },

    trigger: function (event, data) {
        // ...
    }
};

You could remove the need for the new operator with a little constructor function trickery:

function Events() {
    if (!(this instanceof Events)) {
        return new Events();
    }

    this.stack = [];
}

This would allow you to generate a new Events object by calling Events():

Events().on("foo", function(event) {
    // ...
});

The word Events makes this seem like a collection of existing events. Really you've created an event dispatcher, and EventDispatcher feels like a better name.


A Blum Blum Shub pseudorandom RNG implementation in JavaScript I made a Blum Blum Shub pseudorandom number generator implementation in JavaScript.

  Blum Blum Shub (B.B.S.) is a pseudorandom number generator proposed in
  1986 by Lenore Blum, Manuel Blum and Michael Shub that is derived
  from Michael O. Rabin's oblivious transfer mapping.

  Blum Blum Shub takes the form

  \$x_{n+1}=x_{n}^{2}{\bmod {M}}\$

  where M = pq is the product of two large primes p and q. At each step
  of the algorithm, some output is derived from \$x_{n+1}\$; the output is
  commonly either the bit parity of \$x_{n+1}\$ or one or more of the least
  significant bits of \$x_{n+1}\$.

  The seed \$x_0\$ should be an integer that is co-prime to M (i.e. p and q
  are not factors of \$x_0\$) and not 1 or 0.

  The two primes, p and q, should both be congruent to 3 (mod 4) (this
  guarantees that each quadratic residue has one square root which is
  also a quadratic residue) and gcd(φ(p − 1), φ(q − 1)) should be small
  (this makes the cycle length large).

-- from Wikipedia

var p = 5651;
var q = 5623;
var M = p * q;

var x = undefined;

/** Get the gcd of two numbers, A and B. */
function gcd(a, b) {
    while(a != b) {
        if(a > b) {
            a = a - b;
        } else {
            b = b - a;
        }
    }
    return a;
}

/** Seed the random number generator. */
function seed(s) {
    if(s == 0) {
        throw new Error("The seed x[0] cannot be 0");
    } else if(s == 1) {
        throw new Error("The seed x[0] cannot be 1");
    } else if(gcd(s, M) != 1) {
        throw new Error("The seed x[0] must be co-prime to " + M.toString());
    } else {
        x = s;
        return s;
    }
}

/** Get next item from the random number generator. */
function next() {
    var cachedx = x;
    cachedx = cachedx * x;
    cachedx = cachedx % M;
    x = cachedx;
    return x;
}

The code might be able to be refactored to an object and a factory generating such objects, for independent states and functions of the generator. I'm interested if there are any more problems with this code.

You haven't declared cachedx, so it's implicitly global. Turn on strict mode (put 'use strict'; at the top of your script) to prevent this in the future. I'm not sure why cachedx would be necessary anyway, though:

/** Get next item from the random number generator. */
function next() {
    x = x * x % M;
    return x;
}

Also, there's no point in initializing things to undefined. That's the default. The chance that something might be uninitialized when you attempt to use it is a bad sign, though, and you're probably right that it would be better to be able to create instances of the generator:

function Random(p, q, seed) {
    var m = p * q;

    if (seed == 0) {
        throw new Error("The seed x[0] cannot be 0");
    } else if (seed == 1) {
        throw new Error("The seed x[0] cannot be 1");
    } else if (gcd(seed, m) != 1) {
        throw new Error("The seed x[0] must be co-prime to " + m);
    }

    this.m = m;
    this.state = seed;
}

Random.prototype.next = function () {
    var x = this.state;
    var next = x * x % this.m;

    this.state = next;
    return next;
};

noting that you don't need to call toString to concatenate a string and a number.