Μηνιαία αρχεία: Μάιος 2016


WordPress: Google AdSense Plugin 3

Recently, we were trying to changing the position of the Google Ads that are shown on a website using the Google AdSense plugin for WordPress.

After clicking on the Manage Ads button at the configuration page (http://example.com/wp-admin/options-general.php?page=GooglePublisherPlugin) we would get an error that another theme had set the active ads and that the plugin cannot proceed to modify them unless they are disabled from the other theme (Specifically we would get the following error: Due to a theme change, ads are not being shown. Please reconfigure your ads or restore the previous theme.).

(a) Disabling the plugin, (b) Uninstalling the plugin (c) Reconnecting with another AdSense account did not help at all.

What we did at the end was to remove the GooglePublisherPlugin entry from the wp_option database of our installation.

DELETE FROM `MyDatabase`.`wp_options` WHERE `option_name` = "GooglePublisherPlugin";

Next time we visited the configuration page, we were disconnected from the previous account and we had to reconnect.

GetStarted-AdSense
After reconnecting, we followed the configuration procedure, we pressed the Manage Ads button, the website was analyzed, we got the confirmation message and we clicked on the Save & Activate button to store the changes.

For a few hours, no ads were shown on the site. We did not take any action and on the next day that ads started appearing as expected.

Advertisements

Java: Create a lookup table for an Enum 4

Simple Enum

Assuming the user has a simple enum that does not have any member variable as follows:

public enum Grades {
    A, B, C, D, E, F
}

In this case, we do not need to create a map to get an enum value from an input string. We can use the enum build-in method valueOf which returns the enum constant of the specified enum type with the specified name.

Please note that the input string must match exactly an identifier used to declare an enum constant in this type. Extraneous white-space characters or wrong letter case are not permitted.

An Enum that has a member variable

Switching to a more interesting example, we assume the user has an enum type that each enum constant has a member variable. In the following example each constant has an int value as member.

public enum Weekday {

    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3),
    THURSDAY(4),
    FRIDAY(5),
    SATURDAY(6),
    SUNDAY(7);

    public int getCode() {

        return mCode;
    }

    Weekday(final int code) {

        mCode = code;
    }

    private final int mCode;
}

In this example, getting the matching enum constant for an input integer number is not as straight forward as before. We could iterate over all constants check their code and return the one that matches but that would not be efficient, especially for enum types that have many constants.

What we propose is to create a static map of elements that will have on the key part the value of the enum constant and on the value part the actual enum constant.

public enum Weekday {

    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3),
    THURSDAY(4),
    FRIDAY(5),
    SATURDAY(6),
    SUNDAY(7);

    public int getCode() {

        return mCode;
    }

    public static Weekday fromCode(final int code) {

        final Weekday element = sMap.get(code);
        if (element != null) {

            return element;
        }
        throw new IllegalArgumentException(String.format("Unknown code: <%d> for %s", code, Weekday.class.toString()));
    }

    Weekday(final int code) {

        mCode = code;
    }

    private static final Map<Integer, Weekday> sMap = new HashMap<>();

    static {
        for (final Weekday d : Weekday.values()) {

            sMap.put(d.getCode(), d);
        }
    }
    private final int mCode;
}

What we did in the above code, was to statically create the map we described. Which is, a map from the value that each enum constant holds to the constant. Then using the fromCode method we defined, we check the map for the input value, if the value is not part of the keys set of the map, it will throw an Illegal Argument Exception.

Doing Even better

An improvement we could do in the above code, would be to extract the part of the code that iterates over the fields and creates the map to reuse it. To do that, we need to use Functional Interface. Meaning we will create a function that takes as input another function that expects some input (if any) and produces as output an element of the type of the key.

Our function that can be used for all enums that their constants hold an int value is the following:

//ToIntFunction represents a function that produces an int-valued result. This is the int-producing primitive specialization for Function. This is a functional interface whose functional method is applyAsInt(Object).
public static <E extends Enum<E>> Map<Integer, E> createMap(final ToIntFunction<E> converter, final Class<E> enumClass) {

    final Map<Integer, E> map = new HashMap<>();
    for (final E s : enumClass.getEnumConstants()) {

        map.put(converter.applyAsInt(s), s);
    }
    return map;
}

The code of the enum could change to the following:

public enum Weekday {

    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3),
    THURSDAY(4),
    FRIDAY(5),
    SATURDAY(6),
    SUNDAY(7);

    public int getCode() {

        return mCode;
    }

    public static Weekday fromCode(final int code) {

        final Weekday element = sMap.get(code);
        if (element != null) {

            return element;
        }
        throw new IllegalArgumentException(String.format("Unknown code: <%d> for %s", code, Weekday.class.toString()));
    }

    Weekday(final int code) {

        mCode = code;
    }

    private static final Map<Integer, Weekday> sMap = Collections.unmodifiableMap(createMap(Weekday::getCode, Weekday.class));

    private final int mCode;
}

The function that we used as input to the new function is the getCode we defined in the enum. As you can see, it is a function that produces an int-valued result just as the requirement of the ToIntFunction parameter asks for.


Java: Breakdown a long number to the powers of two it is composed from 1

The following function will accept a long number as input and will produce an LongStream, which is a sequence of primitive long-valued elements that supports sequential and parallel aggregate operations.

public static LongStream splitToPowersOfTwo(final long input) {

    long temp = input;
    final LongStream.Builder builder = LongStream.builder();

    while (temp != 0) {

        //Long.lowestOneBit: Finds the lowest-order ("rightmost") one-bit in the specified long value and returns a long number that has only the bit in the previously matched position set as 1. This value is a power of two that is one of the components of the number. If the number is zero, the function returns zero.
        final long powerOfTwo = Long.lowestOneBit(temp);
        builder.add(powerOfTwo);
        //We update our temp by subtracting the number we got, our goal is to remove the previously matched bit and get the next one on the next iteration.
        temp = temp & ~ powerOfTwo;
    }

    return builder.build();
}

We used Long.lowestOneBit as it makes it easy for us to breakdown the number to its power of two components by matching for us only one bit at time.

Example of usage:

Scenario: We want to breakdown a long number to the powers of two that their sum produces the number and create a String with those values. Using our function, we can do the following:

final String output = splitToPowersOfTwo(flags).mapToObj(Long::toString).collect(Collectors.joining(", "));

Note: an LongStream is not the same as a Stream<Long>, we used .mapToObj(Long::toString) which calls the static method Long.toString(long). This is different to calling .map(Long::toString) on a Stream<Long> as the latter won’t compile because it is ambiguous.


Java: Breakdown an integer to the powers of two it is composed from 1

The following function will accept an integer number as input and will produce an IntStream, which is a sequence of primitive int-valued elements that supports sequential and parallel aggregate operations.

public static IntStream splitToPowersOfTwo(final int input) {

    int temp = input;
    final IntStream.Builder builder = IntStream.builder();

    while (temp != 0) {

        //Integer.lowestOneBit: Finds the lowest-order ("rightmost") one-bit in the specified int value and returns an int number that has only the bit in the previously matched position set as 1. This value is a power of two that is one of the components of the number. If the number is zero, the function returns zero.
        final int powerOfTwo = Integer.lowestOneBit(temp);
        builder.add(powerOfTwo);
        //We update our temp by subtracting the number we got, our goal is to remove the previously matched bit and get the next one on the next iteration.
        temp = temp & ~ powerOfTwo;
    }

    return builder.build();
}

We used Integer.lowestOneBit as it makes it easy for us to breakdown the number to its power of two components by matching for us only one bit at time.

Example of usage:

Scenario: We want to breakdown an integer to the powers of two that their sum produces the number and create a String with those values. Using our function, we can do the following:

final String output = splitToPowersOfTwo(flags).mapToObj(Integer::toString).collect(Collectors.joining(", "));

Note: an IntStream is not the same as a Stream<Integer>, we used .mapToObj(Integer::toString) which calls the static method Integer.toString(int). This is different to calling .map(Integer::toString) on a Stream<Integer> as the latter won’t compile because it is ambiguous.


Setting up the contest’s environment

The contest environment of the Balkan Olympiad in Informatics 2016 (BOI 2016) that will be hosted in Cyprus will have the following configuration.

For the contestants:

The operating system of the competition will be Ubuntu 16.04 LTS (XenialXerus) Desktop edition x64 bit architecture.

On the system we have two accounts:

  • contestant – this is the account the contestants will use. It is set to auto-login, to not have a password and be a normal account.
  • maintenance – this is the account the administrators will use. It is an administrative account.

Using the administrative account:

Before proceeding with any changes, we updated the whole system.

sudo apt-get -y update; 
sudo apt-get -y upgrade;

Later, some applications that are not needed for the competition, were removed from the installation environment in an attempt to keep the installation less than 5.5GB.

sudo apt-get remove transmission-* thunderbird* shotwell* rhythmbox* gnome-mines gnome-sudoku simple-scan remmina* gnome-mahjongg cheese* aisleriot libreoffice-*;

After that, we installed the additional software that is needed for the competition from the Ubuntu repositories.

sudo apt-get -y install build-essential codeblocks codeblocks-contrib ddd emacs geany gedit nano scite vim mc stl-manual valgrind fpc fp-docs lazarus terminator;

Some cleanup on the disk was needed at this point which we did with the commands below.

#Please note that the following commands will remove applications and services, be sure to read what it is about to be removed.
#You might want to keep some of the stuff that are being deleted.
sudo apt autoremove;
sudo apt-get autoclean;
sudo apt-get clean;

Using the contestant’s account:

Following, we created the desktop shortcuts of the applications that should be used by the contestants, making it easier for them to find.

for name in codeblocks ddd emacs firefox geany gedit gnome-calculator gnome-terminal lazarus mc python SciTE  terminator vim; do
	cp /usr/share/applications/$name*.desktop ~/contestant/Desktop;
done

One last step that we had to take to finish the setup on what a contestant needs, we started Firefox and set the homepages to be http://alpha:8888/|file:///usr/share/doc/stl-manual/html/index.html|http://alpha:8890/. alpha is the hostname of our grading environment.

For maintainers:

On the contestant’s machine:

The machines have ssh servers enabled to allow administrating personnel to perform maintenance operations.

#The following command installs and enables ssh server on an Ubuntu 16.04 desktop installation.
sudo apt-get install openssh-server;
#We will create a read only copy of the original configuration.
#Everybody should do this to make sure if they do not manage to configure properly their sshd to be able to restore the default configuration.
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.factory-defaults;
sudo chmod a-w /etc/ssh/sshd_config.factory-defaults;

On the administration machine:

We created a new public/private rsa key pair using the command ssh-keygen, which we uploaded to the contestant’s machine using ssh-copy-id [email protected]. We will use this key to connect to the contestant’s machine without using a password.

On the contestant’s machine:

Using a text editor (like gedit, nano, vi etc) we edited the /etc/ssh/sshd_config configuration file to reflect some security changes.

  • We changed the #PasswordAuthentication yes to PasswordAuthentication no to disable logins using password. Only users holding our private ssh key will be able to login.
  • At the end of the file we added AllowTcpForwarding no and X11Forwarding no to disable forwarding.
  • At the end of the file we added AllowUsers maintenance, to whitelist maintenance on the ssh service, while at the same time blocking everyone else from using it. In other words, only user maintenance will be able to use the ssh service.

When we are done with the changes, we saved the file and issued the following command to restart the ssh service.

sudo systemctl restart ssh

Next, we had to block any network activity the contestants should not have.

To do so, we installed squid on the contestant’s machine and configured it to allow access only to the STL documentation, the contest environment and the results page.

sudo apt-get install squid;
#We will create a read only copy of the original configuration.
#Everybody should do this to make sure if they do not manage to configure properly their squid to be able to restore the default configuration.
#We used move instead of copy here, the reason is that the original file is HUGE (~8K lines).
#We moved the file to create a new one that will contain only what we need.
sudo mv /etc/squid/squid.conf /etc/squid/squid.conf.factory-defaults;
sudo chmod a-w /etc/squid/squid.conf.factory-defaults;

Afterwards, we created a new configuration file /etc/squid/squid.conf and used the following as content.

acl Safe_ports port 8888	# competition
acl Safe_ports port 8890	# ranking

acl CONNECT method CONNECT
http_access deny !Safe_ports
http_access deny CONNECT all
http_access allow localhost manager
http_access deny manager
http_access allow localhost
acl whitelist dstdomain .alpha .beta
http_access allow whitelist
http_access deny all

http_port 3128 transparent

coredump_dir /var/spool/squid
refresh_pattern ^ftp:		1440	20%	10080
refresh_pattern ^gopher:	1440	0%	1440
refresh_pattern -i (/cgi-bin/|\?) 0	0%	0
refresh_pattern (Release|Packages(.gz)*)$      0       20%     2880
refresh_pattern .		0	20%	4320

cache deny all

To redirect all outgoing traffic to our squid proxy server and complete the procedure we used the following iptables command.

sudo squid -k reconfigure;
sudo iptables -t nat -A OUTPUT -p tcp -m owner ! --uid-owner proxy --dport 1:65535 -j REDIRECT --to-port 3128;
#The simplest method to make the change permanent is to use iptables-save and iptables-restore to save the currently-defined iptables rules to a file and (re)load them (e.g., upon reboot).
sudo sh -c "iptables-save > /etc/iptables.conf";
#Then modify file /etc/rc.local and add right above the 'exit 0' command the following:
# Load iptables rules from this file
iptables-restore < /etc/iptables.conf

Following, we disabled the guest account as it would cause trouble if used since it does not have permanent storage, so on restart all files of the contestant would be deleted.

Everybody should do this to make sure if they do not manage to configure properly their lightdm to be able to restore the default configuration.
sudo cp /etc/lightdm/lightdm.conf /etc/lightdm/lightdm.conf.factory-defaults;
sudo chmod a-w /etc/lightdm/lightdm.conf.factory-defaults;

To disable guest session edit the file /etc/lightdm/lightdm.conf using a text editor and add at the end of the file the following allow-guest=false. Save the file and close it.
To make the change become active you either have to restart the machine or lightdm itself, in any case all all open graphical programs will close and you’ll lose unsaved work in all of them.

sudo restart lightdm;

 

Pending

disable mounting other disks

disable usb

back up data

block any connection outside the specific labs

To copy the flash drive

sudo dd if=/dev/sdd of=/dev/sdc bs=64K conv=noerror,sync