text:
use DBI;
use strict;
use utf8;

# Master DB params
my $MASTER_DB_DATASOURCE = 'database=vhffs;host=localhost;port=5432';
my $MASTER_DB_USER = 'vhffs';
my $MASTER_DB_PASS = 'vhffs';

# Slave DB params
my $SLAVE_DB_DATASOURCE = 'database=vhffs;host=localhost;port=5432';
my $SLAVE_DB_USER = 'vhffs';
my $SLAVE_DB_PASS = 'vhffs';

# We've to connect to the master DB, fetch
# mx, boxes, forward & ml
# tables and reinject them in slave DB
# We just fetch necessary fields for address verification

my $master_dbh = DBI->connect('DBI:Pg:'.$MASTER_DB_DATASOURCE, $MASTER_DB_USER, $MASTER_DB_PASS)
	or die('Unable to open master connection'."\n");

my $slave_dbh = DBI->connect('DBI:Pg:'.$SLAVE_DB_DATASOURCE, $SLAVE_DB_USER, $SLAVE_DB_PASS)
	or die('Unable to open slave connection'."\n");

# Create temporary tables
$slave_dbh->do('CREATE TEMPORARY TABLE tmp_mx2(LIKE vhffs_mx2)')
	or die('Unable to create temporary MX domain table'."\n");
$slave_dbh->do('CREATE TEMPORARY TABLE tmp_mx2_localpart(LIKE vhffs_mx2_localpart)')
	or die('Unable to create temporary boxes table'."\n");

$master_dbh->{AutoCommit} = 0;
$slave_dbh->{AutoCommit} = 0;

# We need to set transaction isolation level to serializable to avoid
# foreign key issues
$master_dbh->do('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE')
	or die('Unable to set transaction level on master DB'."\n");

# Replicate vhffs_mx table
my $msth = $master_dbh->prepare(q{SELECT d.mx_id, d.domain
	FROM vhffs_mx d
	INNER JOIN vhffs_object o ON o.object_id = d.object_id
	WHERE o.state = 6})
	or die('Unable to prepare SELECT query for vhffs_mx'."\n");
my $ssth = $slave_dbh->prepare(q{INSERT INTO tmp_mx2(mx_id, domain, catchall)
	VALUES(?, ?, false)})
	or die('Unable to prepare INSERT query for tmp_mx2'."\n");

$msth->execute()
	or die('Unable to execute SELECT query for vhffs_mx'."\n");

while(my $r = $msth->fetchrow_hashref) {
	$ssth->execute( $r->{mx_id}, $r->{domain} )
	or die('Unable to insert mx #'.$r->{mx_id}."\n");
}

$ssth->finish();
$msth->finish();

# Replicate vhffs_mx_catchall table
my $msth = $master_dbh->prepare(q{SELECT mx.mx_id FROM vhffs_mx mx
	INNER JOIN vhffs_object o ON o.object_id=mx.object_id
	INNER JOIN vhffs_mx_catchall ca ON mx.mx_id=ca.mx_id
	INNER JOIN vhffs_mx_box box ON box.box_id=ca.box_id
	WHERE box.state=6 AND o.state=6 GROUP BY mx.mx_id})
	or die('Unable to prepare SELECT query for vhffs_mx_catchall'."\n");
my $ssth = $slave_dbh->prepare(q{UPDATE tmp_mx2 SET catchall=true WHERE mx_id=?})
	or die('Unable to prepare UPDATE query for tmp_mx2'."\n");

$msth->execute()
	or die('Unable to execute SELECT query for vhffs_mx_catchall'."\n");

while(my $r = $msth->fetchrow_hashref) {
	$ssth->execute( $r->{mx_id} )
	or die('Unable to set catchall for mx #'.$r->{mx_id}."\n");
}

$ssth->finish();
$msth->finish();

# Replicate all localparts
$ssth = $slave_dbh->prepare(q{INSERT INTO tmp_mx2_localpart(mx_id, localpart)
	VALUES(?, ?)})
	or die('Unable to prepare INSERT query for tmp_mx2_localpart'."\n");
my $distinct = {};

# Replicate boxes localparts
$msth = $master_dbh->prepare(q{SELECT d.mx_id, lp.localpart
	FROM vhffs_mx_localpart lp
	INNER JOIN vhffs_mx d ON d.mx_id = lp.mx_id
	INNER JOIN vhffs_object o ON o.object_id = d.object_id
	INNER JOIN vhffs_mx_box b ON b.localpart_id = lp.localpart_id
	WHERE o.state = 6 AND b.state = 6})
	or die('Unable to prepare SELECT query for vhffs_mx_box'."\n");
$msth->execute()
	or die('Unable to execute SELECT query for vhffs_mx_box'."\n");
while(my $r = $msth->fetchrow_hashref) {
	unless( exists $distinct->{$r->{mx_id}}->{$r->{localpart}} ) {
		$ssth->execute( $r->{mx_id}, $r->{localpart} )
		or die('Unable to insert localpart #'.$r->{localpart_id}."\n");
		$distinct->{$r->{mx_id}}->{$r->{localpart}} = undef;
	}
}
$msth->finish();

# Replicate redirects localparts
$msth = $master_dbh->prepare(q{SELECT d.mx_id, lp.localpart
	FROM vhffs_mx_localpart lp
	INNER JOIN vhffs_mx d ON d.mx_id = lp.mx_id
	INNER JOIN vhffs_object o ON o.object_id = d.object_id
	INNER JOIN vhffs_mx_redirect r ON r.localpart_id = lp.localpart_id
	WHERE o.state = 6})
	or die('Unable to prepare SELECT query for vhffs_mx_redirect'."\n");
$msth->execute()
	or die('Unable to execute SELECT query for vhffs_mx_redirect'."\n");
while(my $r = $msth->fetchrow_hashref) {
	unless( exists $distinct->{$r->{mx_id}}->{$r->{localpart}} ) {
		$ssth->execute( $r->{mx_id}, $r->{localpart} )
		or die('Unable to insert localpart #'.$r->{localpart_id}."\n");
		$distinct->{$r->{mx_id}}->{$r->{localpart}} = undef;
	}
}
$msth->finish();

# Replicate mailing lists localparts
$msth = $master_dbh->prepare(q{SELECT d.mx_id, lp.localpart
	FROM vhffs_mx_localpart lp
	INNER JOIN vhffs_mx d ON d.mx_id = lp.mx_id
	INNER JOIN vhffs_object o ON o.object_id = d.object_id
	INNER JOIN vhffs_mx_ml ml ON ml.localpart_id = lp.localpart_id
	INNER JOIN vhffs_object mlo ON mlo.object_id = ml.object_id
	WHERE o.state = 6 AND mlo.state = 6})
	or die('Unable to prepare SELECT query for vhffs_mx_ml'."\n");
$msth->execute()
	or die('Unable to execute SELECT query for vhffs_mx_ml'."\n");
while(my $r = $msth->fetchrow_hashref) {
	unless( exists $distinct->{$r->{mx_id}}->{$r->{localpart}} ) {
		$ssth->execute( $r->{mx_id}, $r->{localpart} )
		or die('Unable to insert localpart #'.$r->{localpart_id}.."\n");
		$distinct->{$r->{mx_id}}->{$r->{localpart}} = undef;
	}
	# -request localpart for mailing lists
	$ssth->execute($r->{mx_id}, $r->{localpart}.'-request')
	or die('Unable to insert ml request address for localpart #'.$r->{localpart_id}."\n");
}
$msth->finish();

$distinct = {};
$ssth->finish();

# We're done fetching data
$master_dbh->disconnect();

my $count;

# Delete old localparts/domains
($count = $slave_dbh->do(q{DELETE FROM vhffs_mx2_localpart WHERE
	NOT EXISTS(SELECT * FROM tmp_mx2_localpart t
	WHERE t.mx_id = vhffs_mx2_localpart.mx_id
	AND t.localpart = vhffs_mx2_localpart.localpart)}))
	or die('Unable to delete no more existing localparts'."\n");
print int($count).' localparts deleted'."\n";

($count = $slave_dbh->do(q{DELETE from vhffs_mx2
	WHERE mx_id NOT IN(SELECT mx_id FROM tmp_mx2)}))
	or die('Unable to delete o more existing domains'."\n");
print int($count).' domains deleted'."\n";

# Insert new localparts/domains
($count = $slave_dbh->do(q{INSERT INTO vhffs_mx2(mx_id, domain, catchall)
	SELECT mx_id, domain, catchall FROM tmp_mx2 WHERE mx_id NOT
	IN(SELECT mx_id FROM vhffs_mx2)}))
	or die('Unable to insert new mail domains'."\n");
print int($count).' domains added'."\n";

($count = $slave_dbh->do(q{INSERT INTO vhffs_mx2_localpart(mx_id, localpart)
	SELECT mx_id, localpart FROM tmp_mx2_localpart tmp WHERE NOT EXISTS(
	SELECT * FROM vhffs_mx2_localpart a WHERE a.mx_id = tmp.mx_id AND
	a.localpart = tmp.localpart)}))
	or die('Unable to insert new localparts'."\n");
print int($count).' localparts added'."\n";

# Update catchall field
$slave_dbh->do(q{UPDATE vhffs_mx2 SET catchall = tmp.catchall
	FROM tmp_mx2 tmp WHERE tmp.mx_id = vhffs_mx2.mx_id})
	or die('Unable to update mx data'."\n");

$slave_dbh->commit();
$slave_dbh->disconnect();

redpajama_set_name: RedPajamaGithub


text:
package com.android.server;

import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
import static android.Manifest.permission.DUMP;
import static android.Manifest.permission.SHUTDOWN;
import static android.net.NetworkStats.SET_DEFAULT;
import static android.net.NetworkStats.TAG_NONE;
import static android.net.NetworkStats.UID_ALL;
import static android.net.TrafficStats.UID_TETHERING;
import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceGetCfgResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceListResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceRxThrottleResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceTxThrottleResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.IpFwdStatusResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.TetherDnsFwdTgtListResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.TetherInterfaceListResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.TetherStatusResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.TetheringStatsResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.TtyListResult;
import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;

import android.bluetooth.BluetoothTetheringDataTracker;
import android.content.Context;
import android.net.INetworkManagementEventObserver;
import android.net.InterfaceConfiguration;
import android.net.LinkAddress;
import android.net.NetworkStats;
import android.net.NetworkUtils;
import android.net.RouteInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.os.Binder;
import android.os.Handler;
import android.os.INetworkManagementService;
import android.os.Process;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.util.Log;
import android.util.Slog;
import android.util.SparseBooleanArray;

import com.android.internal.net.NetworkStatsFactory;
import com.android.internal.util.Preconditions;
import com.android.server.NativeDaemonConnector.Command;
import com.android.server.net.LockdownVpnTracker;
import com.google.android.collect.Maps;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.concurrent.CountDownLatch;

/**
 * @hide
 */
public class NetworkManagementService extends INetworkManagementService.Stub
        implements Watchdog.Monitor {
    private static final String TAG = "NetworkManagementService";
    private static final boolean DBG = false;
    private static final String NETD_TAG = "NetdConnector";

    private static final String ADD = "add";
    private static final String REMOVE = "remove";

    private static final String ALLOW = "allow";
    private static final String DENY = "deny";

    private static final String DEFAULT = "default";
    private static final String SECONDARY = "secondary";

    /**
     * Name representing {@link #setGlobalAlert(long)} limit when delivered to
     * {@link INetworkManagementEventObserver#limitReached(String, String)}.
     */
    public static final String LIMIT_GLOBAL_ALERT = "globalAlert";

    class NetdResponseCode {
        /* Keep in sync with system/netd/ResponseCode.h */
        public static final int InterfaceListResult       = 110;
        public static final int TetherInterfaceListResult = 111;
        public static final int TetherDnsFwdTgtListResult = 112;
        public static final int TtyListResult             = 113;

        public static final int TetherStatusResult        = 210;
        public static final int IpFwdStatusResult         = 211;
        public static final int InterfaceGetCfgResult     = 213;
        public static final int SoftapStatusResult        = 214;
        public static final int InterfaceRxCounterResult  = 216;
        public static final int InterfaceTxCounterResult  = 217;
        public static final int InterfaceRxThrottleResult = 218;
        public static final int InterfaceTxThrottleResult = 219;
        public static final int QuotaCounterResult        = 220;
        public static final int TetheringStatsResult      = 221;
        public static final int DnsProxyQueryResult       = 222;

        public static final int InterfaceChange           = 600;
        public static final int BandwidthControl          = 601;
        public static final int InterfaceClassActivity    = 613;
    }

    /**
     * Binder context for this service
     */
    private Context mContext;

    /**
     * connector object for communicating with netd
     */
    private NativeDaemonConnector mConnector;

    private final Handler mMainHandler = new Handler();

    private Thread mThread;
    private CountDownLatch mConnectedSignal = new CountDownLatch(1);

    private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
            new RemoteCallbackList<INetworkManagementEventObserver>();

    private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();

    private Object mQuotaLock = new Object();
    /** Set of interfaces with active quotas. */
    private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
    /** Set of interfaces with active alerts. */
    private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
    /** Set of UIDs with active reject rules. */
    private SparseBooleanArray mUidRejectOnQuota = new SparseBooleanArray();

    private Object mIdleTimerLock = new Object();
    /** Set of interfaces with active idle timers. */
    private static class IdleTimerParams {
        public final int timeout;
        public final String label;
        public int networkCount;

        IdleTimerParams(int timeout, String label) {
            this.timeout = timeout;
            this.label = label;
            this.networkCount = 1;
        }
    }
    private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();

    private volatile boolean mBandwidthControlEnabled;
    private volatile boolean mFirewallEnabled;

    /**
     * Constructs a new NetworkManagementService instance
     *
     * @param context  Binder context for this service
     */
    private NetworkManagementService(Context context) {
        mContext = context;

        if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
            return;
        }

        mConnector = new NativeDaemonConnector(
                new NetdCallbackReceiver(), "netd", 10, NETD_TAG, 160);
        mThread = new Thread(mConnector, NETD_TAG);

        // Add ourself to the Watchdog monitors.
        Watchdog.getInstance().addMonitor(this);
    }

    public static NetworkManagementService create(Context context) throws InterruptedException {
        final NetworkManagementService service = new NetworkManagementService(context);
        final CountDownLatch connectedSignal = service.mConnectedSignal;
        if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
        service.mThread.start();
        if (DBG) Slog.d(TAG, "Awaiting socket connection");
        connectedSignal.await();
        if (DBG) Slog.d(TAG, "Connected");
        return service;
    }

    public void systemReady() {
        prepareNativeDaemon();
        if (DBG) Slog.d(TAG, "Prepared");
    }

    @Override
    public void registerObserver(INetworkManagementEventObserver observer) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        mObservers.register(observer);
    }

    @Override
    public void unregisterObserver(INetworkManagementEventObserver observer) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        mObservers.unregister(observer);
    }

    /**
     * Notify our observers of an interface status change
     */
    private void notifyInterfaceStatusChanged(String iface, boolean up) {
        final int length = mObservers.beginBroadcast();
        for (int i = 0; i < length; i++) {
            try {
                mObservers.getBroadcastItem(i).interfaceStatusChanged(iface, up);
            } catch (RemoteException e) {
            }
        }
        mObservers.finishBroadcast();
    }

    /**
     * Notify our observers of an interface link state change
     * (typically, an Ethernet cable has been plugged-in or unplugged).
     */
    private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
        final int length = mObservers.beginBroadcast();
        for (int i = 0; i < length; i++) {
            try {
                mObservers.getBroadcastItem(i).interfaceLinkStateChanged(iface, up);
            } catch (RemoteException e) {
            }
        }
        mObservers.finishBroadcast();
    }

    /**
     * Notify our observers of an interface addition.
     */
    private void notifyInterfaceAdded(String iface) {
        final int length = mObservers.beginBroadcast();
        for (int i = 0; i < length; i++) {
            try {
                mObservers.getBroadcastItem(i).interfaceAdded(iface);
            } catch (RemoteException e) {
            }
        }
        mObservers.finishBroadcast();
    }

    /**
     * Notify our observers of an interface removal.
     */
    private void notifyInterfaceRemoved(String iface) {
        // netd already clears out quota and alerts for removed ifaces; update
        // our sanity-checking state.
        mActiveAlerts.remove(iface);
        mActiveQuotas.remove(iface);

        final int length = mObservers.beginBroadcast();
        for (int i = 0; i < length; i++) {
            try {
                mObservers.getBroadcastItem(i).interfaceRemoved(iface);
            } catch (RemoteException e) {
            }
        }
        mObservers.finishBroadcast();
    }

    /**
     * Notify our observers of a limit reached.
     */
    private void notifyLimitReached(String limitName, String iface) {
        final int length = mObservers.beginBroadcast();
        for (int i = 0; i < length; i++) {
            try {
                mObservers.getBroadcastItem(i).limitReached(limitName, iface);
            } catch (RemoteException e) {
            }
        }
        mObservers.finishBroadcast();
    }

    /**
     * Notify our observers of a change in the data activity state of the interface
     */
    private void notifyInterfaceClassActivity(String label, boolean active) {
        final int length = mObservers.beginBroadcast();
        for (int i = 0; i < length; i++) {
            try {
                mObservers.getBroadcastItem(i).interfaceClassDataActivityChanged(label, active);
            } catch (RemoteException e) {
            }
        }
        mObservers.finishBroadcast();
    }

    /**
     * Prepare native daemon once connected, enabling modules and pushing any
     * existing in-memory rules.
     */
    private void prepareNativeDaemon() {
        mBandwidthControlEnabled = false;

        // only enable bandwidth control when support exists
        final boolean hasKernelSupport = new File("/proc/net/xt_qtaguid/ctrl").exists();
        if (hasKernelSupport) {
            Slog.d(TAG, "enabling bandwidth control");
            try {
                mConnector.execute("bandwidth", "enable");
                mBandwidthControlEnabled = true;
            } catch (NativeDaemonConnectorException e) {
                Log.wtf(TAG, "problem enabling bandwidth controls", e);
            }
        } else {
            Slog.d(TAG, "not enabling bandwidth control");
        }

        SystemProperties.set(PROP_QTAGUID_ENABLED, mBandwidthControlEnabled ? "1" : "0");

        // push any existing quota or UID rules
        synchronized (mQuotaLock) {
            int size = mActiveQuotas.size();
            if (size > 0) {
                Slog.d(TAG, "pushing " + size + " active quota rules");
                final HashMap<String, Long> activeQuotas = mActiveQuotas;
                mActiveQuotas = Maps.newHashMap();
                for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
                    setInterfaceQuota(entry.getKey(), entry.getValue());
                }
            }

            size = mActiveAlerts.size();
            if (size > 0) {
                Slog.d(TAG, "pushing " + size + " active alert rules");
                final HashMap<String, Long> activeAlerts = mActiveAlerts;
                mActiveAlerts = Maps.newHashMap();
                for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
                    setInterfaceAlert(entry.getKey(), entry.getValue());
                }
            }

            size = mUidRejectOnQuota.size();
            if (size > 0) {
                Slog.d(TAG, "pushing " + size + " active uid rules");
                final SparseBooleanArray uidRejectOnQuota = mUidRejectOnQuota;
                mUidRejectOnQuota = new SparseBooleanArray();
                for (int i = 0; i < uidRejectOnQuota.size(); i++) {
                    setUidNetworkRules(uidRejectOnQuota.keyAt(i), uidRejectOnQuota.valueAt(i));
                }
            }
        }

        // TODO: Push any existing firewall state
        setFirewallEnabled(mFirewallEnabled || LockdownVpnTracker.isEnabled());
    }

    //
    // Netd Callback handling
    //

    private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
        @Override
        public void onDaemonConnected() {
            // event is dispatched from internal NDC thread, so we prepare the
            // daemon back on main thread.
            if (mConnectedSignal != null) {
                mConnectedSignal.countDown();
                mConnectedSignal = null;
            } else {
                mMainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        prepareNativeDaemon();
                    }
                });
            }
        }

        @Override
        public boolean onEvent(int code, String raw, String[] cooked) {
            switch (code) {
            case NetdResponseCode.InterfaceChange:
                    /*
                     * a network interface change occured
                     * Format: "NNN Iface added <name>"
                     *         "NNN Iface removed <name>"
                     *         "NNN Iface changed <name> <up/down>"
                     *         "NNN Iface linkstatus <name> <up/down>"
                     */
                    if (cooked.length < 4 || !cooked[1].equals("Iface")) {
                        throw new IllegalStateException(
                                String.format("Invalid event from daemon (%s)", raw));
                    }
                    if (cooked[2].equals("added")) {
                        notifyInterfaceAdded(cooked[3]);
                        return true;
                    } else if (cooked[2].equals("removed")) {
                        notifyInterfaceRemoved(cooked[3]);
                        return true;
                    } else if (cooked[2].equals("changed") && cooked.length == 5) {
                        notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
                        return true;
                    } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
                        notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
                        return true;
                    }
                    throw new IllegalStateException(
                            String.format("Invalid event from daemon (%s)", raw));
                    // break;
            case NetdResponseCode.BandwidthControl:
                    /*
                     * Bandwidth control needs some attention
                     * Format: "NNN limit alert <alertName> <ifaceName>"
                     */
                    if (cooked.length < 5 || !cooked[1].equals("limit")) {
                        throw new IllegalStateException(
                                String.format("Invalid event from daemon (%s)", raw));
                    }
                    if (cooked[2].equals("alert")) {
                        notifyLimitReached(cooked[3], cooked[4]);
                        return true;
                    }
                    throw new IllegalStateException(
                            String.format("Invalid event from daemon (%s)", raw));
                    // break;
            case NetdResponseCode.InterfaceClassActivity:
                    /*
                     * An network interface class state changed (active/idle)
                     * Format: "NNN IfaceClass <active/idle> <label>"
                     */
                    if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
                        throw new IllegalStateException(
                                String.format("Invalid event from daemon (%s)", raw));
                    }
                    boolean isActive = cooked[2].equals("active");
                    notifyInterfaceClassActivity(cooked[3], isActive);
                    return true;
                    // break;
            default: break;
            }
            return false;
        }
    }

    //
    // INetworkManagementService members
    //

    @Override
    public String[] listInterfaces() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            return NativeDaemonEvent.filterMessageList(
                    mConnector.executeForList("interface", "list"), InterfaceListResult);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public InterfaceConfiguration getInterfaceConfig(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        final NativeDaemonEvent event;
        try {
            event = mConnector.execute("interface", "getcfg", iface);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }

        event.checkCode(InterfaceGetCfgResult);

        // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz flag1 flag2 flag3
        final StringTokenizer st = new StringTokenizer(event.getMessage());

        InterfaceConfiguration cfg;
        try {
            cfg = new InterfaceConfiguration();
            cfg.setHardwareAddress(st.nextToken(" "));
            InetAddress addr = null;
            int prefixLength = 0;
            try {
                addr = NetworkUtils.numericToInetAddress(st.nextToken());
            } catch (IllegalArgumentException iae) {
                Slog.e(TAG, "Failed to parse ipaddr", iae);
            }

            try {
                prefixLength = Integer.parseInt(st.nextToken());
            } catch (NumberFormatException nfe) {
                Slog.e(TAG, "Failed to parse prefixLength", nfe);
            }

            cfg.setLinkAddress(new LinkAddress(addr, prefixLength));
            while (st.hasMoreTokens()) {
                cfg.setFlag(st.nextToken());
            }
        } catch (NoSuchElementException nsee) {
            throw new IllegalStateException("Invalid response from daemon: " + event);
        }
        return cfg;
    }

    @Override
    public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        LinkAddress linkAddr = cfg.getLinkAddress();
        if (linkAddr == null || linkAddr.getAddress() == null) {
            throw new IllegalStateException("Null LinkAddress given");
        }

        final Command cmd = new Command("interface", "setcfg", iface,
                linkAddr.getAddress().getHostAddress(),
                linkAddr.getNetworkPrefixLength());
        for (String flag : cfg.getFlags()) {
            cmd.appendArg(flag);
        }

        try {
            mConnector.execute(cmd);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void setInterfaceDown(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
        ifcg.setInterfaceDown();
        setInterfaceConfig(iface, ifcg);
    }

    @Override
    public void setInterfaceUp(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
        ifcg.setInterfaceUp();
        setInterfaceConfig(iface, ifcg);
    }

    @Override
    public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute(
                    "interface", "ipv6privacyextensions", iface, enable ? "enable" : "disable");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
       IPv6 addresses on interface down, but we need to do full clean up here */
    @Override
    public void clearInterfaceAddresses(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("interface", "clearaddrs", iface);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void enableIpv6(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("interface", "ipv6", iface, "enable");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void disableIpv6(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("interface", "ipv6", iface, "disable");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void addRoute(String interfaceName, RouteInfo route) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        modifyRoute(interfaceName, ADD, route, DEFAULT);
    }

    @Override
    public void removeRoute(String interfaceName, RouteInfo route) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        modifyRoute(interfaceName, REMOVE, route, DEFAULT);
    }

    @Override
    public void addSecondaryRoute(String interfaceName, RouteInfo route) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        modifyRoute(interfaceName, ADD, route, SECONDARY);
    }

    @Override
    public void removeSecondaryRoute(String interfaceName, RouteInfo route) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        modifyRoute(interfaceName, REMOVE, route, SECONDARY);
    }

    private void modifyRoute(String interfaceName, String action, RouteInfo route, String type) {
        final Command cmd = new Command("interface", "route", action, interfaceName, type);

        // create triplet: dest-ip-addr prefixlength gateway-ip-addr
        final LinkAddress la = route.getDestination();
        cmd.appendArg(la.getAddress().getHostAddress());
        cmd.appendArg(la.getNetworkPrefixLength());

        if (route.getGateway() == null) {
            if (la.getAddress() instanceof Inet4Address) {
                cmd.appendArg("0.0.0.0");
            } else {
                cmd.appendArg("::0");
            }
        } else {
            cmd.appendArg(route.getGateway().getHostAddress());
        }

        try {
            mConnector.execute(cmd);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    private ArrayList<String> readRouteList(String filename) {
        FileInputStream fstream = null;
        ArrayList<String> list = new ArrayList<String>();

        try {
            fstream = new FileInputStream(filename);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String s;

            // throw away the title line

            while (((s = br.readLine()) != null) && (s.length() != 0)) {
                list.add(s);
            }
        } catch (IOException ex) {
            // return current list, possibly empty
        } finally {
            if (fstream != null) {
                try {
                    fstream.close();
                } catch (IOException ex) {}
            }
        }

        return list;
    }

    @Override
    public RouteInfo[] getRoutes(String interfaceName) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();

        // v4 routes listed as:
        // iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT
        for (String s : readRouteList("/proc/net/route")) {
            String[] fields = s.split("\t");

            if (fields.length > 7) {
                String iface = fields[0];

                if (interfaceName.equals(iface)) {
                    String dest = fields[1];
                    String gate = fields[2];
                    String flags = fields[3]; // future use?
                    String mask = fields[7];
                    try {
                        // address stored as a hex string, ex: 0014A8C0
                        InetAddress destAddr =
                                NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16));
                        int prefixLength =
                                NetworkUtils.netmaskIntToPrefixLength(
                                (int)Long.parseLong(mask, 16));
                        LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);

                        // address stored as a hex string, ex 0014A8C0
                        InetAddress gatewayAddr =
                                NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16));

                        RouteInfo route = new RouteInfo(linkAddress, gatewayAddr);
                        routes.add(route);
                    } catch (Exception e) {
                        Log.e(TAG, "Error parsing route " + s + " : " + e);
                        continue;
                    }
                }
            }
        }

        // v6 routes listed as:
        // dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface
        for (String s : readRouteList("/proc/net/ipv6_route")) {
            String[]fields = s.split("\\s+");
            if (fields.length > 9) {
                String iface = fields[9].trim();
                if (interfaceName.equals(iface)) {
                    String dest = fields[0];
                    String prefix = fields[1];
                    String gate = fields[4];

                    try {
                        // prefix length stored as a hex string, ex 40
                        int prefixLength = Integer.parseInt(prefix, 16);

                        // address stored as a 32 char hex string
                        // ex fe800000000000000000000000000000
                        InetAddress destAddr = NetworkUtils.hexToInet6Address(dest);
                        LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);

                        InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate);

                        RouteInfo route = new RouteInfo(linkAddress, gateAddr);
                        routes.add(route);
                    } catch (Exception e) {
                        Log.e(TAG, "Error parsing route " + s + " : " + e);
                        continue;
                    }
                }
            }
        }
        return routes.toArray(new RouteInfo[routes.size()]);
    }

    @Override
    public void shutdown() {
        // TODO: remove from aidl if nobody calls externally
        mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);

        Slog.d(TAG, "Shutting down");
    }

    @Override
    public boolean getIpForwardingEnabled() throws IllegalStateException{
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        final NativeDaemonEvent event;
        try {
            event = mConnector.execute("ipfwd", "status");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }

        // 211 Forwarding enabled
        event.checkCode(IpFwdStatusResult);
        return event.getMessage().endsWith("enabled");
    }

    @Override
    public void setIpForwardingEnabled(boolean enable) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("ipfwd", enable ? "enable" : "disable");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void startTethering(String[] dhcpRange) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        // cmd is "tether start first_start first_stop second_start second_stop ..."
        // an odd number of addrs will fail

        final Command cmd = new Command("tether", "start");
        for (String d : dhcpRange) {
            cmd.appendArg(d);
        }

        try {
            mConnector.execute(cmd);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void stopTethering() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("tether", "stop");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public boolean isTetheringStarted() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        final NativeDaemonEvent event;
        try {
            event = mConnector.execute("tether", "status");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }

        // 210 Tethering services started
        event.checkCode(TetherStatusResult);
        return event.getMessage().endsWith("started");
    }

    // TODO(BT) Remove
    public void startReverseTethering(String iface)
             throws IllegalStateException {
        if (DBG) Slog.d(TAG, "startReverseTethering in");
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        // cmd is "tether start first_start first_stop second_start second_stop ..."
        // an odd number of addrs will fail
        String cmd = "tether start-reverse";
        cmd += " " + iface;
        if (DBG) Slog.d(TAG, "startReverseTethering cmd: " + cmd);
        try {
            mConnector.doCommand(cmd);
        } catch (NativeDaemonConnectorException e) {
            throw new IllegalStateException("Unable to communicate to native daemon");
        }
        BluetoothTetheringDataTracker.getInstance().startReverseTether(iface);

    }

    // TODO(BT) Remove
    public void stopReverseTethering() throws IllegalStateException {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.doCommand("tether stop-reverse");
        } catch (NativeDaemonConnectorException e) {
            throw new IllegalStateException("Unable to communicate to native daemon to stop tether");
        }
        BluetoothTetheringDataTracker.getInstance().stopReverseTether();
    }

    @Override
    public void tetherInterface(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("tether", "interface", "add", iface);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void untetherInterface(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("tether", "interface", "remove", iface);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public String[] listTetheredInterfaces() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            return NativeDaemonEvent.filterMessageList(
                    mConnector.executeForList("tether", "interface", "list"),
                    TetherInterfaceListResult);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void setDnsForwarders(String[] dns) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        final Command cmd = new Command("tether", "dns", "set");
        for (String s : dns) {
            cmd.appendArg(NetworkUtils.numericToInetAddress(s).getHostAddress());
        }

        try {
            mConnector.execute(cmd);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public String[] getDnsForwarders() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            return NativeDaemonEvent.filterMessageList(
                    mConnector.executeForList("tether", "dns", "list"), TetherDnsFwdTgtListResult);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    private void modifyNat(String action, String internalInterface, String externalInterface)
            throws SocketException {
        final Command cmd = new Command("nat", action, internalInterface, externalInterface);

        final NetworkInterface internalNetworkInterface = NetworkInterface.getByName(
                internalInterface);
        if (internalNetworkInterface == null) {
            cmd.appendArg("0");
        } else {
            Collection<InterfaceAddress> interfaceAddresses = internalNetworkInterface
                    .getInterfaceAddresses();
            cmd.appendArg(interfaceAddresses.size());
            for (InterfaceAddress ia : interfaceAddresses) {
                InetAddress addr = NetworkUtils.getNetworkPart(
                        ia.getAddress(), ia.getNetworkPrefixLength());
                cmd.appendArg(addr.getHostAddress() + "/" + ia.getNetworkPrefixLength());
            }
        }

        try {
            mConnector.execute(cmd);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void enableNat(String internalInterface, String externalInterface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            modifyNat("enable", internalInterface, externalInterface);
        } catch (SocketException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void disableNat(String internalInterface, String externalInterface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            modifyNat("disable", internalInterface, externalInterface);
        } catch (SocketException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public String[] listTtys() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            return NativeDaemonEvent.filterMessageList(
                    mConnector.executeForList("list_ttys"), TtyListResult);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void attachPppd(
            String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("pppd", "attach", tty,
                    NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
                    NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
                    NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
                    NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void detachPppd(String tty) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("pppd", "detach", tty);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void startAccessPoint(
            WifiConfiguration wifiConfig, String wlanIface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            wifiFirmwareReload(wlanIface, "AP");
            if (wifiConfig == null) {
                mConnector.execute("softap", "set", wlanIface);
            } else {
                mConnector.execute("softap", "set", wlanIface, wifiConfig.SSID,
                        getSecurityType(wifiConfig), wifiConfig.preSharedKey);
            }
            mConnector.execute("softap", "startap");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    private static String getSecurityType(WifiConfiguration wifiConfig) {
        switch (wifiConfig.getAuthType()) {
            case KeyMgmt.WPA_PSK:
                return "wpa-psk";
            case KeyMgmt.WPA2_PSK:
                return "wpa2-psk";
            default:
                return "open";
        }
    }

    /* @param mode can be "AP", "STA" or "P2P" */
    @Override
    public void wifiFirmwareReload(String wlanIface, String mode) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("softap", "fwreload", wlanIface, mode);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void stopAccessPoint(String wlanIface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("softap", "stopap");
            wifiFirmwareReload(wlanIface, "STA");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            if (wifiConfig == null) {
                mConnector.execute("softap", "set", wlanIface);
            } else {
                mConnector.execute("softap", "set", wlanIface, wifiConfig.SSID,
                        getSecurityType(wifiConfig), wifiConfig.preSharedKey);
            }
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void addIdleTimer(String iface, int timeout, String label) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        if (DBG) Slog.d(TAG, "Adding idletimer");

        synchronized (mIdleTimerLock) {
            IdleTimerParams params = mActiveIdleTimers.get(iface);
            if (params != null) {
                // the interface already has idletimer, update network count
                params.networkCount++;
                return;
            }

            try {
                mConnector.execute("idletimer", "add", iface, Integer.toString(timeout), label);
            } catch (NativeDaemonConnectorException e) {
                throw e.rethrowAsParcelableException();
            }
            mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, label));
        }
    }

    @Override
    public void removeIdleTimer(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        if (DBG) Slog.d(TAG, "Removing idletimer");

        synchronized (mIdleTimerLock) {
            IdleTimerParams params = mActiveIdleTimers.get(iface);
            if (params == null || --(params.networkCount) > 0) {
                return;
            }

            try {
                mConnector.execute("idletimer", "remove", iface,
                        Integer.toString(params.timeout), params.label);
            } catch (NativeDaemonConnectorException e) {
                throw e.rethrowAsParcelableException();
            }
            mActiveIdleTimers.remove(iface);
        }
    }

    @Override
    public NetworkStats getNetworkStatsSummaryDev() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        return mStatsFactory.readNetworkStatsSummaryDev();
    }

    @Override
    public NetworkStats getNetworkStatsSummaryXt() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        return mStatsFactory.readNetworkStatsSummaryXt();
    }

    @Override
    public NetworkStats getNetworkStatsDetail() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        return mStatsFactory.readNetworkStatsDetail(UID_ALL);
    }

    @Override
    public void setInterfaceQuota(String iface, long quotaBytes) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        // silently discard when control disabled
        // TODO: eventually migrate to be always enabled
        if (!mBandwidthControlEnabled) return;

        synchronized (mQuotaLock) {
            if (mActiveQuotas.containsKey(iface)) {
                throw new IllegalStateException("iface " + iface + " already has quota");
            }

            try {
                // TODO: support quota shared across interfaces
                mConnector.execute("bandwidth", "setiquota", iface, quotaBytes);
                mActiveQuotas.put(iface, quotaBytes);
            } catch (NativeDaemonConnectorException e) {
                throw e.rethrowAsParcelableException();
            }
        }
    }

    @Override
    public void removeInterfaceQuota(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        // silently discard when control disabled
        // TODO: eventually migrate to be always enabled
        if (!mBandwidthControlEnabled) return;

        synchronized (mQuotaLock) {
            if (!mActiveQuotas.containsKey(iface)) {
                // TODO: eventually consider throwing
                return;
            }

            mActiveQuotas.remove(iface);
            mActiveAlerts.remove(iface);

            try {
                // TODO: support quota shared across interfaces
                mConnector.execute("bandwidth", "removeiquota", iface);
            } catch (NativeDaemonConnectorException e) {
                throw e.rethrowAsParcelableException();
            }
        }
    }

    @Override
    public void setInterfaceAlert(String iface, long alertBytes) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        // silently discard when control disabled
        // TODO: eventually migrate to be always enabled
        if (!mBandwidthControlEnabled) return;

        // quick sanity check
        if (!mActiveQuotas.containsKey(iface)) {
            throw new IllegalStateException("setting alert requires existing quota on iface");
        }

        synchronized (mQuotaLock) {
            if (mActiveAlerts.containsKey(iface)) {
                throw new IllegalStateException("iface " + iface + " already has alert");
            }

            try {
                // TODO: support alert shared across interfaces
                mConnector.execute("bandwidth", "setinterfacealert", iface, alertBytes);
                mActiveAlerts.put(iface, alertBytes);
            } catch (NativeDaemonConnectorException e) {
                throw e.rethrowAsParcelableException();
            }
        }
    }

    @Override
    public void removeInterfaceAlert(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        // silently discard when control disabled
        // TODO: eventually migrate to be always enabled
        if (!mBandwidthControlEnabled) return;

        synchronized (mQuotaLock) {
            if (!mActiveAlerts.containsKey(iface)) {
                // TODO: eventually consider throwing
                return;
            }

            try {
                // TODO: support alert shared across interfaces
                mConnector.execute("bandwidth", "removeinterfacealert", iface);
                mActiveAlerts.remove(iface);
            } catch (NativeDaemonConnectorException e) {
                throw e.rethrowAsParcelableException();
            }
        }
    }

    @Override
    public void setGlobalAlert(long alertBytes) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        // silently discard when control disabled
        // TODO: eventually migrate to be always enabled
        if (!mBandwidthControlEnabled) return;

        try {
            mConnector.execute("bandwidth", "setglobalalert", alertBytes);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        // silently discard when control disabled
        // TODO: eventually migrate to be always enabled
        if (!mBandwidthControlEnabled) return;

        synchronized (mQuotaLock) {
            final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false);
            if (oldRejectOnQuota == rejectOnQuotaInterfaces) {
                // TODO: eventually consider throwing
                return;
            }

            try {
                mConnector.execute("bandwidth",
                        rejectOnQuotaInterfaces ? "addnaughtyapps" : "removenaughtyapps", uid);
                if (rejectOnQuotaInterfaces) {
                    mUidRejectOnQuota.put(uid, true);
                } else {
                    mUidRejectOnQuota.delete(uid);
                }
            } catch (NativeDaemonConnectorException e) {
                throw e.rethrowAsParcelableException();
            }
        }
    }

    @Override
    public boolean isBandwidthControlEnabled() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        return mBandwidthControlEnabled;
    }

    @Override
    public NetworkStats getNetworkStatsUidDetail(int uid) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        return mStatsFactory.readNetworkStatsDetail(uid);
    }

    @Override
    public NetworkStats getNetworkStatsTethering(String[] ifacePairs) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        if (ifacePairs.length % 2 != 0) {
            throw new IllegalArgumentException(
                    "unexpected ifacePairs; length=" + ifacePairs.length);
        }

        final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
        for (int i = 0; i < ifacePairs.length; i += 2) {
            final String ifaceIn = ifacePairs[i];
            final String ifaceOut = ifacePairs[i + 1];
            if (ifaceIn != null && ifaceOut != null) {
                stats.combineValues(getNetworkStatsTethering(ifaceIn, ifaceOut));
            }
        }
        return stats;
    }

    private NetworkStats.Entry getNetworkStatsTethering(String ifaceIn, String ifaceOut) {
        final NativeDaemonEvent event;
        try {
            event = mConnector.execute("bandwidth", "gettetherstats", ifaceIn, ifaceOut);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }

        event.checkCode(TetheringStatsResult);

        // 221 ifaceIn ifaceOut rx_bytes rx_packets tx_bytes tx_packets
        final StringTokenizer tok = new StringTokenizer(event.getMessage());
        tok.nextToken();
        tok.nextToken();

        try {
            final NetworkStats.Entry entry = new NetworkStats.Entry();
            entry.iface = ifaceIn;
            entry.uid = UID_TETHERING;
            entry.set = SET_DEFAULT;
            entry.tag = TAG_NONE;
            entry.rxBytes = Long.parseLong(tok.nextToken());
            entry.rxPackets = Long.parseLong(tok.nextToken());
            entry.txBytes = Long.parseLong(tok.nextToken());
            entry.txPackets = Long.parseLong(tok.nextToken());
            return entry;
        } catch (NumberFormatException e) {
            throw new IllegalStateException(
                    "problem parsing tethering stats for " + ifaceIn + " " + ifaceOut + ": " + e);
        }
    }

    @Override
    public void setInterfaceThrottle(String iface, int rxKbps, int txKbps) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("interface", "setthrottle", iface, rxKbps, txKbps);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    private int getInterfaceThrottle(String iface, boolean rx) {
        final NativeDaemonEvent event;
        try {
            event = mConnector.execute("interface", "getthrottle", iface, rx ? "rx" : "tx");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }

        if (rx) {
            event.checkCode(InterfaceRxThrottleResult);
        } else {
            event.checkCode(InterfaceTxThrottleResult);
        }

        try {
            return Integer.parseInt(event.getMessage());
        } catch (NumberFormatException e) {
            throw new IllegalStateException("unexpected response:" + event);
        }
    }

    @Override
    public int getInterfaceRxThrottle(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        return getInterfaceThrottle(iface, true);
    }

    @Override
    public int getInterfaceTxThrottle(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        return getInterfaceThrottle(iface, false);
    }

    @Override
    public void setDefaultInterfaceForDns(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("resolver", "setdefaultif", iface);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void setDnsServersForInterface(String iface, String[] servers) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);

        final Command cmd = new Command("resolver", "setifdns", iface);
        for (String s : servers) {
            InetAddress a = NetworkUtils.numericToInetAddress(s);
            if (a.isAnyLocalAddress() == false) {
                cmd.appendArg(a.getHostAddress());
            }
        }

        try {
            mConnector.execute(cmd);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void flushDefaultDnsCache() {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("resolver", "flushdefaultif");
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void flushInterfaceDnsCache(String iface) {
        mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
        try {
            mConnector.execute("resolver", "flushif", iface);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void setFirewallEnabled(boolean enabled) {
        enforceSystemUid();
        try {
            mConnector.execute("firewall", enabled ? "enable" : "disable");
            mFirewallEnabled = enabled;
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public boolean isFirewallEnabled() {
        enforceSystemUid();
        return mFirewallEnabled;
    }

    @Override
    public void setFirewallInterfaceRule(String iface, boolean allow) {
        enforceSystemUid();
        Preconditions.checkState(mFirewallEnabled);
        final String rule = allow ? ALLOW : DENY;
        try {
            mConnector.execute("firewall", "set_interface_rule", iface, rule);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void setFirewallEgressSourceRule(String addr, boolean allow) {
        enforceSystemUid();
        Preconditions.checkState(mFirewallEnabled);
        final String rule = allow ? ALLOW : DENY;
        try {
            mConnector.execute("firewall", "set_egress_source_rule", addr, rule);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void setFirewallEgressDestRule(String addr, int port, boolean allow) {
        enforceSystemUid();
        Preconditions.checkState(mFirewallEnabled);
        final String rule = allow ? ALLOW : DENY;
        try {
            mConnector.execute("firewall", "set_egress_dest_rule", addr, port, rule);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    @Override
    public void setFirewallUidRule(int uid, boolean allow) {
        enforceSystemUid();
        Preconditions.checkState(mFirewallEnabled);
        final String rule = allow ? ALLOW : DENY;
        try {
            mConnector.execute("firewall", "set_uid_rule", uid, rule);
        } catch (NativeDaemonConnectorException e) {
            throw e.rethrowAsParcelableException();
        }
    }

    private static void enforceSystemUid() {
        final int uid = Binder.getCallingUid();
        if (uid != Process.SYSTEM_UID) {
            throw new SecurityException("Only available to AID_SYSTEM");
        }
    }

    @Override
    public void monitor() {
        if (mConnector != null) {
            mConnector.monitor();
        }
    }

    @Override
    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        mContext.enforceCallingOrSelfPermission(DUMP, TAG);

        pw.println("NetworkManagementService NativeDaemonConnector Log:");
        mConnector.dump(fd, pw, args);
        pw.println();

        pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);

        synchronized (mQuotaLock) {
            pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
            pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
        }

        synchronized (mUidRejectOnQuota) {
            pw.print("UID reject on quota ifaces: [");
            final int size = mUidRejectOnQuota.size();
            for (int i = 0; i < size; i++) {
                pw.print(mUidRejectOnQuota.keyAt(i));
                if (i < size - 1) pw.print(",");
            }
            pw.println("]");
        }

        pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
    }
}


text:
var Cassandra = require('express-cassandra');
var logger = require('./logger');
// These variables are local to this module
var db;
var models;
var context;
var settings;

module.exports = db = {
  // Initialize the module. Invokes callback when ready (or on error)
  init: function(contextArg, callback) {
    context = contextArg;
    settings = context.settings;
    logger.info(" S2 :: Started :: Setting up cassandra Db connection ");

    models = Cassandra.createClient({
        clientOptions: {
            contactPoints: [settings.db.host],
            protocolOptions: { port: settings.db.port },
            keyspace: settings.db.keyspace,
            queryOptions: {consistency: Cassandra.consistencies.one}
        },
        ormOptions: {
            defaultReplicationStrategy : {
                class: 'SimpleStrategy',
                replication_factor: 1
            },
            migration: 'safe',
            createKeyspace: true
        }
      });
      models.connect(function (err) {
        if (err) throw err;
        else {
          logger.info(" S2 :: Complete :: Cassandra myka_keyspace connection established. DB ALL SET ");
        }
    });
    callback();
    // ends here
  },
  getModelRoot: () => models,
};


text:
<?php

namespace App\Events\Sites;

use App\Models\Site;
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

/**
 * Class SiteCreated
 *
 * @package App\Events
 */
class Created
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    /**
     * @var $user User object
     */
    public $user;
    /**
     * @var $site Site object
     */
    public $site;

    /**
     * Create a new event instance.
     *
     * @param User $user object
     * @param Site $site object
     */
    public function __construct(User $user, Site $site)
    {
        $this->user = $user;
        $this->site = $site;
    }
}


text:
layout: page
title: Solemn White Aerospace Dinner
date: 2016-05-24
author: Nathan Duncan
tags: weekly links, java
status: published
summary: Sed vel congue lectus, in dapibus augue. Sed ut.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 07/06/2017
  endDate: 07/11/2017
  ctyhocn: CSBHHHX
  groupCode: SWAD
published: true
---
Phasellus in volutpat tortor, nec convallis magna. Duis eget eros nisl. Aliquam pellentesque rutrum congue. Donec pretium sem erat, non convallis elit dapibus sed. Vivamus posuere faucibus sem sit amet finibus. Cras sagittis fringilla eros. Nunc in dapibus est. Mauris nisi nibh, rutrum ac accumsan non, gravida a ipsum. Donec pellentesque sollicitudin diam, non egestas urna. Proin ullamcorper malesuada fringilla. Aenean id luctus mauris, et consectetur mauris. Nam varius tellus a eros ullamcorper, interdum iaculis purus faucibus. Ut ligula leo, rutrum sed tortor eu, tempus mattis neque. Nam at ultricies metus. Nullam ut porttitor diam.
Integer a neque mattis, facilisis nulla ac, hendrerit turpis. Donec auctor lectus eget nulla faucibus congue. Maecenas tempus dolor vel ex pretium, in hendrerit nunc iaculis. Morbi in sodales tortor. Cras et ultrices libero. Aenean odio diam, facilisis eu lectus ac, pharetra ultricies tortor. Curabitur a lorem sem. Sed ullamcorper blandit ipsum sit amet maximus. Quisque scelerisque nunc quis lacus gravida, at hendrerit quam convallis. Morbi ornare tellus nec mattis varius. Pellentesque finibus nisl metus, in molestie ligula iaculis in. Aliquam rutrum lacinia porttitor. Vestibulum et maximus neque. Nunc eu leo augue. Aenean lacinia purus sed arcu commodo, id luctus purus cursus.

* Donec ac urna in arcu interdum efficitur nec vitae metus
* Nam non felis gravida, elementum ex eget, consequat elit
* Vestibulum feugiat elit finibus auctor tincidunt
* Phasellus rutrum sem vel elit pretium, a efficitur sapien maximus
* In vel nisl id purus dictum hendrerit sed sit amet metus.

Sed facilisis ante ac fermentum tincidunt. Pellentesque eu tempor sapien. Nunc et interdum dui. Sed ornare neque augue, a viverra nisl fringilla sed. Maecenas blandit odio ac libero iaculis placerat. Phasellus cursus aliquam mi, non luctus lorem consequat id. Vivamus mattis est turpis, id volutpat sem auctor in. Nullam dictum, elit ac efficitur gravida, nulla justo faucibus ante, ut dapibus massa erat in sapien. Aenean imperdiet diam convallis ligula volutpat iaculis.


text:
using namespace Tizen::Base;
using namespace Tizen::App;
using namespace Tizen::Base::Utility;
using namespace Tizen::Graphics;
using namespace Tizen::Locales;
using namespace Tizen::System;
using namespace Tizen::App;
using namespace Tizen::Ui;
using namespace Tizen::Ui::Controls;
using namespace Tizen::Web::Controls;
using namespace Tizen::Locations;
using namespace Tizen::Base::Collection;
using namespace Tizen::Web::Json;

PathFinder::PathFinder(void)
	: WEB_URL_PREFIX_HTTP(L"http://")
	, __pMainForm(null)
	, __pWeb(null)
{
}

PathFinder::~PathFinder(void)
{
}

Application*
PathFinder::CreateInstance(void)
{
	// You can create the instance through another constructor.
	return new PathFinder();
}

bool
PathFinder::OnAppInitializing(AppRegistry& appRegistry)
{
	Frame* pAppFrame = new Frame();
	pAppFrame->Construct();
	AddFrame(*pAppFrame);

	result r = E_SUCCESS;

	r = CreateWebForm();
	TryCatch(r == E_SUCCESS, , "CreateWebForm() has failed.\n");
	CreateLocationManager();
	return true;

CATCH:
	return false;
}

bool
PathFinder::OnAppTerminating(AppRegistry& appRegistry, bool forcedTermination)
{
	delete __pLocProvider;
	return true;
}

void
PathFinder::OnForeground(void)
{
	__pWeb->Resume();
}

void
PathFinder::OnBackground(void)
{
	__pWeb->Pause();
}

void
PathFinder::OnLowMemory(void)
{
}

void
PathFinder::OnBatteryLevelChanged(BatteryLevel batteryLevel)
{
}

result
PathFinder::CreateWebForm(void)
{
	result r = E_SUCCESS;
	Rectangle bound;
	WebSetting setting;

	Header* pHeader;

	FooterItem footerItem1;
	FooterItem footerItemCal;
	FooterItem footerItemClr;
	IAppFrame* pAppFrame = GetAppFrame();

	Tizen::Base::String url = App::GetInstance()->GetAppRootPath() + L"data/index.html";

	TryReturn(pAppFrame != null, E_SYSTEM, "GetAppFrame() has failed.\n");

	//form
	__pMainForm = new (std::nothrow) Form();
	r = __pMainForm->Construct(FORM_STYLE_NORMAL | FORM_STYLE_INDICATOR | FORM_STYLE_HEADER | FORM_STYLE_FOOTER);
	TryReturn(r == E_SUCCESS, r, "Form Construct() has failed. \n ");

	__pMainForm->AddOrientationEventListener(*this);
	__pMainForm->SetOrientation(ORIENTATION_AUTOMATIC_FOUR_DIRECTION);

	bound = __pMainForm->GetClientAreaBounds();

	pAppFrame->GetFrame()->AddControl(__pMainForm);
	pAppFrame->GetFrame()->SetCurrentForm(__pMainForm);

	//header
	pHeader = __pMainForm->GetHeader();
	pHeader->SetStyle(HEADER_STYLE_TITLE);
	pHeader->SetTitleText(L"Path Finder");

	//footer
	pFooter = __pMainForm->GetFooter();
	pFooter->SetStyle(FOOTER_STYLE_BUTTON_TEXT);
	pFooter->SetBackButton();
	pFooter->AddActionEventListener(*this);
	__pMainForm->SetFormBackEventListener(this);

	//footer item

	footerItemCal.Construct(AC_BUTTON_CALC);
	footerItemCal.SetText(L"Navigate");
	footerItemClr.Construct(AC_BUTTON_CLR);
	footerItemClr.SetText(L"Clear");
	footerItem1.Construct(AC_BUTTON_WEB_BACK);
	footerItem1.SetText(L"Back");
	pFooter->AddItem(footerItemCal);
	pFooter->AddItem(footerItemClr);
	pFooter->AddItem(footerItem1);

    __pMainForm->SetBackgroundColor(pFooter->GetColor());

	//Web
	__pWeb = new (std::nothrow) Web();

	bound = __pMainForm->GetClientAreaBounds();
	r = __pWeb->Construct(Rectangle(0, 0, bound.width, bound.height));
	TryReturn(r == E_SUCCESS, r, "Web Construct() has failed.\n ");

	r = __pMainForm->AddControl(__pWeb);
	TryReturn(r == E_SUCCESS, r, "Addcontrol() has failed.\n ");

	setting.SetInputStyle(INPUT_STYLE_OVERLAY);
	r = __pWeb->SetSetting(setting);
	TryReturn(r == E_SUCCESS, r, "SetSetting() has failed.\n ");

	__pWeb->SetLoadingListener(this);
	__pWeb->SetWebKeypadEventListener(this);
	__pWeb->SetWebUiEventListener(this);
	__pWeb->AddJavaScriptBridge(*this);
	__pWeb->SetFocus();

	__pWeb->LoadUrl(L"file://" + url);
	__pMainForm->RequestRedraw(true);
	return r;
}
result  PathFinder::CreateLocationManager(void)
{
	result r = E_SUCCESS;
	LocationCriteria criteria;

	criteria.SetAccuracy(LOC_ACCURACY_HUNDRED_METERS);
	__pLocProvider = new (std::nothrow) LocationProvider();
	r = __pLocProvider->Construct(criteria, *this);
	r = __pLocProvider->StartLocationUpdatesByDistance(100);
	if (r == E_USER_NOT_CONSENTED)
	 {
		// Check if either the GPS or network settings is enabled on the device Settings > Location menu
		bool isSettingEnabled = CheckLocationSetting();

		if (!isSettingEnabled)
		{
		   LaunchLocationSettings();
		}
		else
		{
		   ShowMessageBox(L"Privacy protection",
						  L"Allow the application to use your location by changing the Settings > Privacy setting.");
		}
	 }
	return r;
}

bool
PathFinder::CheckLocationSetting(void)
{
   bool hasPrivilege = false;
   bool gpsEnabled = true;
   bool wpsEnabled = true;

   result gps = Tizen::System::SettingInfo::GetValue(L"http://tizen.org/setting/location.gps", gpsEnabled);
   result wps = Tizen::System::SettingInfo::GetValue(L"http://tizen.org/setting/location.wps", wpsEnabled);

   hasPrivilege = gpsEnabled | wpsEnabled;
   if (gps != E_SUCCESS || wps != E_SUCCESS || hasPrivilege == false)
   {
      return false;
   }

   return true;
}
void
PathFinder::ShowMessageBox(const String& title, const String& message)
{
	MessageBox messageBox;

	messageBox.Construct(title, message, MSGBOX_STYLE_OK);

	int ModalResult;
	messageBox.ShowAndWait(ModalResult);
}

void
PathFinder::LaunchLocationSettings(void)
{
	int res;

	MessageBox messageBox;
	messageBox.Construct(L"Information", L"Location services are disabled. Enable them in location settings?", MSGBOX_STYLE_YESNO);
	messageBox.ShowAndWait(res);

	if (res == MSGBOX_RESULT_YES)
	{
		HashMap extraData;
		extraData.Construct();
		String categoryKey = L"category";
		String categoryVal = L"Location";
		extraData.Add(&categoryKey, &categoryVal);

		AppControl* pAc = AppManager::FindAppControlN(L"tizen.settings", L"http://tizen.org/appcontrol/operation/configure/location");

		if (pAc)
		{
			pAc->Start(null,null,&extraData, this);
			delete pAc;
		}
	}
	return;
}

void
PathFinder::OnActionPerformed(const Control& source, int actionId)
{
	String url;
	switch (actionId)
	{
	case AC_BUTTON_WEB_BACK:
	{
		Terminate();
	}
	break;
	case AC_BUTTON_CALC:
		{
			String str;
			wchar_t* testStr = L"calcRoute()";
			str.Format(50, L" %ls; ", testStr);
			__pWeb->EvaluateJavascriptN(str);
		}
		break;
	case AC_BUTTON_CLR:
		{
			String str;
			wchar_t* testStr = L"clearRoute()";
			str.Format(50, L" %ls; ", testStr);
			__pWeb->EvaluateJavascriptN(str);
		}
		break;

	default:
		break;
	}

	return;

}

void
PathFinder::OnOrientationChanged(const Control& source, OrientationStatus orientationStatus)
{
	Rectangle bound = __pMainForm->GetClientAreaBounds();

	if (__pWeb->IsVisible())
	{
		__pWeb->SetBounds(Rectangle(0, 0, bound.width, bound.height));
	}

	__pMainForm->Invalidate(true);
}

void
PathFinder::OnTextValueChangeCanceled(const Tizen::Ui::Control& source)
{
	__pMainForm->SetFocus();
}

void
PathFinder::OnTextValueChanged(const Tizen::Ui::Control& source)
{
	__pMainForm->SetFocus();
}

void
PathFinder::OnScreenOn(void)
{
}

void
PathFinder::OnScreenOff(void)
{
}

String
PathFinder::GetValidUrl(Tizen::Base::String& url)
{
	String absoluteUrl = url;
	Uri uri;

	uri.SetUri(url);
	if (uri.GetScheme() == L"")
	{
		absoluteUrl.Insert(WEB_URL_PREFIX_HTTP, 0);
	}
	return absoluteUrl;
}

bool
PathFinder::OnHttpAuthenticationRequestedN(const Tizen::Base::String& host, const Tizen::Base::String& realm, const Tizen::Web::Controls::AuthenticationChallenge& authentication)
{
	return false;
}

void
PathFinder::OnHttpAuthenticationCanceled(void)
{
}

void
PathFinder::OnLoadingStarted(void)
{
	//SetButtonCancelImage();
}

void
PathFinder::OnLoadingCanceled(void)
{
	//SetButtonGotoImage();
}

void
PathFinder::OnLoadingErrorOccurred(LoadingErrorType error, const String& reason)
{
	Tizen::Ui::Controls::MessageBox msgBox;
	int modalresult = 0;
	Tizen::Base::String errReason;

	switch (error)
	{
	case WEB_REQUEST_TIMEOUT:
	{
		errReason = Tizen::Base::String(L"Request timeout");
	}
	break;

	case WEB_NO_CONNECTION:
	{
		errReason = Tizen::Base::String(L"Network is not in service");
	}
	break;

	case WEB_MIME_NOT_SUPPORTED:
	{
		errReason = Tizen::Base::String(L"The content type is not supported");
	}
	break;

	case WEB_BAD_URL:
	{
		errReason = Tizen::Base::String(L"The url is invalid");
	}
	break;

	case WEB_HTTP_RESPONSE:
	{
		errReason = Tizen::Base::String(L"HTTP response");
	}
	break;

	case WEB_OUT_OF_MEMORY:
	{
		errReason = Tizen::Base::String(L"Page Too Large");
	}
	break;

	case WEB_REQUEST_MAX_EXCEEDED:
	{
		errReason = Tizen::Base::String(L"Request Max Exceeded");
	}
	break;

	case WEB_ERROR_UNKNOWN:
	default:
	{
		errReason = Tizen::Base::String(L"An Unknown error");
	}
	break;
	}

	msgBox.Construct(L"LOADING ERROR TYPE", errReason, MSGBOX_STYLE_NONE, 3000);
	msgBox.ShowAndWait(modalresult);
}

void
PathFinder::OnLoadingCompleted(void)
{
	SetUrl(__pWeb->GetUrl());
	//SetButtonGotoImage();
}

void
PathFinder::OnEstimatedProgress(int progress)
{
}

void
PathFinder::OnPageTitleReceived(const Tizen::Base::String& title)
{
}

bool
PathFinder::OnLoadingRequested(const Tizen::Base::String& url, WebNavigationType type)
{
	AppLog("%S",url.GetPointer());
	SetUrl(url);
	return false;
}

void
PathFinder::SetUrl(const Tizen::Base::String& url)
{
	result r = E_SUCCESS;
	if (url.GetLength() )
	{
		TryReturnVoid(r == E_SUCCESS, "Fail to update URL in the EditField.");
		__pMainForm->RequestRedraw (true);
	}
	else
	{
		AppLog("The length of the URL exceeds the limit of the length of text in this EditField.");
	}
}

DecisionPolicy
PathFinder::OnWebDataReceived(const Tizen::Base::String& mime, const Tizen::Net::Http::HttpHeader& header)
{
	return WEB_DECISION_CONTINUE;
}

void
PathFinder::OnFormBackRequested(Tizen::Ui::Controls::Form& source)
{
	AppLog("OnFormBackRequested.");
	Terminate();
}

void
PathFinder::OnWebKeypadWillOpen(Tizen::Web::Controls::Web& source)
{
	Rectangle bound = __pMainForm->GetClientAreaBounds();
	AppLog("OnWebKeypadWillOpen.");

	if (source.IsVisible())
	{
		source.SetSize(bound.width, bound.height );
	}
}

void
PathFinder::OnWebKeypadOpened(Tizen::Web::Controls::Web& source)
{
	AppLog("OnWebKeypadOpened.");
}

void
PathFinder::OnWebKeypadClosed(Tizen::Web::Controls::Web& source)
{
	AppLog("OnWebKeypadClosed.");
	Rectangle bound = __pMainForm->GetClientAreaBounds();
	source.SetSize(bound.width, bound.height );
}

void
PathFinder::OnWebPageBlockSelected(Tizen::Web::Controls::Web &source, Tizen::Graphics::Point &startPoint, Tizen::Graphics::Point &endPoint)
{
}

void
PathFinder::OnWebPageShowRequested(Tizen::Web::Controls::Web &source)
{
}

void
PathFinder::OnWebWindowCloseRequested(Tizen::Web::Controls::Web &source)
{
}

Tizen::Web::Controls::Web*
PathFinder::OnWebWindowCreateRequested(void)
{
	MessageBox messageBox;
	messageBox.Construct(L"", L"PathFinder doesn't include new window creation.", MSGBOX_STYLE_NONE, 3000);

	int modalResult = 0;
	messageBox.ShowAndWait(modalResult);

	return null;
}

void PathFinder:: OnLocationUpdated(const Tizen::Locations::Location& location)
{
	AppLog("PathFinder:: OnLocationUpdated");
	Coordinates coord = location.GetCoordinates();
	AppLog("Location Information: Latitude = %lf, Longitude = %lf, Altitude = %lf", coord.GetLatitude(), coord.GetLongitude(), coord.GetAltitude());

	String str;
	double lat = (coord.GetLatitude());
	double lon = (coord.GetLongitude());
	wchar_t* testStr = L"setposition";
	str.Format(50, L" %ls(%lf,%lf); ", testStr,lat,lon);

	__pWeb->EvaluateJavascriptN(str);
}
void PathFinder::OnLocationUpdateStatusChanged(Tizen::Locations::LocationServiceStatus status)
{
	AppLog("PathFinder:: OnLocationUpdateStatusChanged");
}
void PathFinder::OnAccuracyChanged(Tizen::Locations::LocationAccuracy accuracy)
{
	AppLog("PathFinder:: OnAccuracyChanged");
}
void PathFinder::OnRegionEntered(Tizen::Locations::RegionId regionId)
{
	AppLog("PathFinder:: OnRegionEntered");
}
void PathFinder::OnRegionLeft(Tizen::Locations::RegionId regionId)
{
	AppLog("PathFinder:: OnRegionLeft");
}
void PathFinder::OnRegionMonitoringStatusChanged(Tizen::Locations::LocationServiceStatus status)
{
	AppLog("PathFinder:: OnRegionMonitoringStatusChanged");
}

void PathFinder::HandleJavaScriptRequestN(Tizen::Web::Json::IJsonValue* pArg)
{
   AppLog("PathFinder:: HandleJavaScriptRequestN");
   result r = E_SUCCESS;
   JsonObject* pJsonObject = static_cast< JsonObject* >(pArg);
   IJsonValue* pValue = null;
   JsonString* pJsonStringValue = null;
   String key(L"data");

   r = pJsonObject->GetValue(&key, pValue);
   pJsonStringValue = static_cast< JsonString* >(pValue);

   AppLog("data: %ls\n", pJsonStringValue->GetPointer());

}
Tizen::Base::String PathFinder::GetName(void)
{
	AppLog("PathFinder:: GetName");
	return String(L"MyJsBridge");
}


text:
@interface HCIsSame ()
@property (nonatomic, strong, readonly) id object;
@end

@implementation HCIsSame

+ (instancetype)isSameAs:(id)object
{
    return [[self alloc] initSameAs:object];
}

- (instancetype)initSameAs:(id)object
{
    self = [super init];
    if (self)
        _object = object;
    return self;
}

- (BOOL)matches:(id)item
{
    return item == self.object;
}

- (void)describeMismatchOf:(id)item to:(id<HCDescription>)mismatchDescription
{
    [mismatchDescription appendText:@"was "];
    if (item)
        [mismatchDescription appendText:[NSString stringWithFormat:@"%p ", (__bridge void *)item]];
    [mismatchDescription appendDescriptionOf:item];
}

- (void)describeTo:(id<HCDescription>)description
{
    [[description appendText:[NSString stringWithFormat:@"same instance as %p ", (__bridge void *)self.object]]
                  appendDescriptionOf:self.object];
}

@end

id HC_sameInstance(id object)
{
    return [HCIsSame isSameAs:object];
}


text:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.elasticsearch</groupId>
  <artifactId>elasticsearch-dev-tools</artifactId>
  <version>2.1.0-SNAPSHOT</version>
  <name>Elasticsearch Build Resources</name>
  <description>Tools to assist in building and developing in the Elasticsearch project</description>
  <parent>
      <groupId>org.sonatype.oss</groupId>
      <artifactId>oss-parent</artifactId>
      <version>7</version>
      <relativePath></relativePath>
  </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <elasticsearch.s3.repository>s3://download.elasticsearch.org/elasticsearch/staging/</elasticsearch.s3.repository>
  </properties>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-remote-resources-plugin</artifactId>
        <version>1.5</version>
        <executions>
          <execution>
            <goals>
              <goal>bundle</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <includes>
            <include>**/*</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
    <extensions>
      <extension>
        <groupId>org.springframework.build</groupId>
        <artifactId>aws-maven</artifactId>
        <version>5.0.0.RELEASE</version>
      </extension>
    </extensions>
  </build>
  <profiles>
    <profile>
      <id>release</id>
      <build>
        <!-- sign the artifacts with GPG -->
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-gpg-plugin</artifactId>
            <version>1.6</version>
            <executions>
              <execution>
                <id>sign-artifacts</id>
                <phase>verify</phase>
                <goals>
                  <goal>sign</goal>
                </goals>
                <configuration>
                  <keyname>${gpg.keyname}</keyname>
                  <passphrase>${gpg.passphrase}</passphrase>
                  <defaultKeyring>${gpg.keyring}</defaultKeyring>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
      <distributionManagement>
        <repository>
          <id>aws-release</id>
          <name>AWS Release Repository</name>
          <url>${elasticsearch.s3.repository}</url>
        </repository>
      </distributionManagement>
    </profile>
  </profiles>
</project>


text:
{% extends "admin/base_site.html" %}
{% load staticfiles %}
{% block  navbar-fixed %} navbar-fixed{% endblock %}
{% block extrastyle %}
    <link rel="stylesheet" type="text/css" href="{% static "admin/css/prism.css" %}"/>
{% endblock %}
{% block extrajs %}
    <script src="{% static "admin/js/prism.js" %}" type="text/javascript"></script>
{% endblock %}


text:
<?php
/**
 * Template Name: Division - Solution (D7)
 */
?>

<?php while (have_posts()) : the_post(); ?>
  <?php get_template_part('templates/page', 'header'); ?>

  <?php // Defines a division class to add to sections
  // Also defines the link column division for related links
  $division = get_the_terms( get_the_ID(), 'division' );

  $divisionName = $division[0]->name;
    if( $divisionName == 'FAAC Commercial' ){
      $divisionClass = 'faac-commercial';
      $linkColumn_division = 'faacCommercial';
    } elseif( $divisionName == 'FAAC Military' ){
      $divisionClass = 'faac-military';
      $linkColumn_division = 'faacMilitary';
    } elseif( $divisionName == 'MILO Range' ){
      $divisionClass = 'milo-range';
      $linkColumn_division = 'miloRange';
    } elseif( $divisionName == 'Realtime Technologies' ){
      $divisionClass = 'rti';
      $linkColumn_division = 'rti';
    } else {
      $divisionClass = '';
      $linkColumn_division = '';
    }
  ?>

  <?php // Slider area
    if( get_field('solutionsChild_slider') != '' ):
      $slider = get_field('solutionsChild_slider');
        $slider_gallery = $slider['slider_gallery'];
        $slider_category = $slider['slider_category'];
        $slider_upperText = $slider['slider_upperText'];
        $slider_lowerText = $slider['slider_lowerText'];
  ?>
    <section class="slider slider--solutions-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/10-sliders/100-basic-slider.php', false, false ));
      ?>

  <?php endif; ?>

  <?php // Breadcrumbs & Flags ?>
  <div class="breadcrumbs-flags breadcrumbs-flags--solution-child <?php echo $divisionClass; ?>">

    <?php // Breadcrumbs ?>
    <section class="breadcrumbs breadcrumbs--solution-child <?php echo $divisionClass; ?>">
      <div class="breadcrumbs <?php echo $divisionClass; ?>" typeof="BreadcrumbList" vocab="https://schema.org/">
          <?php if(function_exists('bcn_display'))
          {
              bcn_display();
          }?>

    <?php //Sector Flag ?>
    <section class="sector-flag sector-flag--simulator-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/20-general/280-sector-flag.php', false, false ));
      ?>

    <?php //Division Flag ?>
    <section class="division-flag division-flag--solutions-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/40-divisions/430-division-flag.php', false, false ));
      ?>

  <?php // Lead Content
    if( get_field('solutionsChild_lead') != '' ):
      $introContent = get_field('solutionsChild_lead');
        $mediaBlock_direction = $introContent['mediaBlock_direction'];
        $mediaBlock_image = $introContent['mediaBlock_image'];
        $mediaBlock_headline = $introContent['mediaBlock_headline'];
        $mediaBlock_subImage = $introContent['mediaBlock_subImage'];
        $mediaBlock_content = $introContent['mediaBlock_content'];
  ?>
    <section class="intro-content intro-content--simulator-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/20-general/250-media-block.php', false, false ));
      ?>

  <?php endif; ?>

  <?php // Video Playlist
    if( get_field('solutionsChild_videos') != '' ):
      $solutionsChild_videos = 'solutionsChild_videos';
        $videoPlaylist = $solutionsChild_videos . '_videoPlaylist';
  ?>
    <section class="video-playlist video-playlist--solutions-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/50-promotions/540-video-playlist.php', false, false ));
      ?>

  <?php endif; ?>

  <?php // Solutions Features area
    if( get_field('solutionsChild_features') != '' ):
      $solutionsFeatures = get_field('solutionsChild_features');
        $centeredContent_headline = $solutionsFeatures['centeredContent_headline'];
        $centeredContent_body = $solutionsFeatures['centeredContent_body'];
  ?>
    <section class="centered-content centered--content--solutions-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/20-general/200-centered-content.php', false, false ));
      ?>

  <?php endif; ?>

  <?php // Feature Block
    if( get_field('solutionsChild_featureBlocks') != '' ):
      $featureBlocks = 'solutionsChild_featureBlocks';
        $featureBlock = $featureBlocks . '_featureBlock';
  ?>
    <section class="feature-blocks feature-blocks--solutions-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/20-general/230-feature-block.php', false, false ));
      ?>

  <?php endif; ?>

  <?php // Secondary Content
    $secondaryContent = get_field('solutionsChild_secondaryContent');
      $article_headline = $secondaryContent['article_headline'];
      $article_body = $secondaryContent['article_body'];

    if( $article_headline != '' ):
  ?>
    <section class="secondary-content secondary-content--solutions-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/20-general/240-article.php', false, false ));
      ?>

  <?php endif; ?>

  <?php //Documentation Links
      $solutionsChild_documentation = get_field('solutionsChild_documentation');
        $linkBlock_icon = $solutionsChild_documentation['linkBlock_icon'];
        $linkBlock_title = $solutionsChild_documentation['linkBlock_title'];
        $linkBlock_list = $solutionsChild_documentation['linkBlock_list'];
    if( $linkBlock_title != '' ):
  ?>
    <section class="documentation-links documentation-links--solutions-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/20-general/260-link-block-feature.php', false, false ));
      ?>

  <?php endif; ?>

  <?php // Main Simulator
    if( get_field('solutionsChild_simulator') != '' ):
      $mainSimulator = get_field('solutionsChild_simulator');
        $mainSimulator_page = $mainSimulator['mainSimulator_page'];
        $mainSimulator_headline = $mainSimulator['mainSimulator_headline'];
        $mainSimulator_buttonText = $mainSimulator['mainSimulator_buttonText'];
  ?>
    <section class="main-simulator main-simulator--solutions-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/30-options/341-main-simulator.php', false, false ));
      ?>

  <?php endif; ?>

  <?php //Related Links
    if( get_field('solutionsChild_relatedLinks') != '' ):
      $relatedLinks = 'solutionsChild_relatedLinks';
        $linkColumn = $relatedLinks . '_linkColumn';
  ?>
    <section class="related-links related-links--solutions-child <?php echo $divisionClass; ?>">
    <?php
        if( $divisionClass != ''):
          include (locate_template( 'templates/30-options/361-division-related-links.php', false, false ));
        else:
          include ( locate_template( 'templates/30-options/360-related-links-block.php', false, false ));
        endif;
      ?>

  <?php endif; ?>

  <?php //Category headings area
    if( 'solutionsChild_categoryHeadings' != '' ):
      $categoryHeading = 'solutionsChild_categoryHeadings';
        $categoryLinks_categories = $categoryHeading . '_categoryLinks_categories';
  ?>
    <section class="category-heading category-heading--solution-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/30-options/370-category-links-block.php', false, false ));
      ?>

  <?php endif; ?>

  <?php //Division promotion
    if( get_field('solutionsChild_divisionPromo') != '' ):
      $divisionPromo = get_field('solutionsChild_divisionPromo');
        $divisionPromo_select = $divisionPromo['divisionPromo_select'];
  ?>
    <section class="division-promotion division-promotion--solution-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/50-promotions/510-division-promotion.php', false, false ));
      ?>

  <?php endif; ?>

  <?php //Testimonial
    if( get_field('solutionsChild_testimonial') != '' ):
      $testimonial = get_field('solutionsChild_testimonial');
        $testimonial_link = $testimonial['testimonial_link'];
  ?>
    <section class="testimonial testimonial--solution-child <?php echo $divisionClass; ?>">
      <?php
        include ( locate_template( 'templates/50-promotions/530-testimonial.php', false, false ));
      ?>

  <?php endif; ?>

<?php endwhile; ?>


text:
        <form class="ui form" [formGroup]="form" (ngSubmit)="createUser()"
            [class.error]="form.invalid"
            [class.success]="form.valid"
        >

                First Name
                <input type="text" name="name" placeholder="First Name" autocomplete="off" formControlName="name" [(ngModel)]="user.name">

                Last Name
                <input type="text" name="lastName" placeholder="Last Name" autocomplete="off" formControlName="lastName" [(ngModel)]="user.lastName">

            <button class="ui button basic" type="button" (click)="previousPage()">Cancel</button>
            <button class="ui button primary" type="submit" [disabled]="form.invalid">Create user</button>
        </form>


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Framed Bramble</title>