text:
package com.android.development;

import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkUtils;
import android.net.RouteInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.RemoteException;
import android.os.Handler;
import android.os.Message;
import android.os.IBinder;
import android.os.INetworkManagementService;
import android.os.Parcel;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.ServiceManager;
import android.os.ServiceManagerNative;
import android.os.SystemClock;
import android.provider.Settings;
import android.os.Bundle;
import android.util.Log;
import android.view.IWindowManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.android.internal.telephony.Phone;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;

public class Connectivity extends Activity {
    private static final String TAG = "DevTools - Connectivity";
    private static final String GET_SCAN_RES = "Get Results";
    private static final String START_SCAN = "Start Scan";
    private static final String PROGRESS_SCAN = "In Progress";

    private static final long SCAN_CYCLES = 15;

    private static final int EVENT_TOGGLE_WIFI = 1;
    private static final int EVENT_TOGGLE_SCREEN = 2;

    private EditText mDCOnDurationEdit;
    private EditText mDCOffDurationEdit;
    private TextView mDCCycleCountView;
    private long mDCOnDuration = 120000;
    private long mDCOffDuration = 120000;
    private int mDCCycleCount = 0;

    private EditText mSCOnDurationEdit;
    private EditText mSCOffDurationEdit;
    private TextView mSCCycleCountView;
    private long mSCOnDuration = 120000;
    private long mSCOffDuration = 12000;
    private int mSCCycleCount = 0;

    private boolean mDelayedCycleStarted = false;

    private Button mScanButton;
    private TextView mScanResults;
    private EditText mScanCyclesEdit;
    private CheckBox mScanDisconnect;
    private long mScanCycles = SCAN_CYCLES;
    private long mScanCur = -1;
    private long mStartTime = -1;
    private long mStopTime;
    private long mTotalScanTime = 0;
    private long mTotalScanCount = 0;

    private String mTdlsAddr = null;

    private WifiManager mWm;
    private PowerManager mPm;
    private ConnectivityManager mCm;
    private INetworkManagementService mNetd;

    private WifiScanReceiver mScanRecv;
    IntentFilter mIntentFilter;

    private WakeLock mWakeLock = null;
    private WakeLock mScreenonWakeLock = null;

    private boolean mScreenOffToggleRunning = false;
    private boolean mScreenOff = false;

    private static final String CONNECTIVITY_TEST_ALARM =
            "com.android.development.CONNECTIVITY_TEST_ALARM";
    private static final String TEST_ALARM_EXTRA = "CONNECTIVITY_TEST_EXTRA";
    private static final String TEST_ALARM_ON_EXTRA = "CONNECTIVITY_TEST_ON_EXTRA";
    private static final String TEST_ALARM_OFF_EXTRA = "CONNECTIVITY_TEST_OFF_EXTRA";
    private static final String TEST_ALARM_CYCLE_EXTRA = "CONNECTIVITY_TEST_CYCLE_EXTRA";
    private static final String SCREEN_ON = "SCREEN_ON";
    private static final String SCREEN_OFF = "SCREEN_OFF";
    public BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(CONNECTIVITY_TEST_ALARM)) {
                String extra = (String)intent.getExtra(TEST_ALARM_EXTRA);
                PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
                Long on = new Long(120000);
                Long off = new Long(120000);
                int cycle = 0;
                try {
                    on = Long.parseLong((String)intent.getExtra(TEST_ALARM_ON_EXTRA));
                    off = Long.parseLong((String)intent.getExtra(TEST_ALARM_OFF_EXTRA));
                    cycle = Integer.parseInt((String)intent.getExtra(TEST_ALARM_CYCLE_EXTRA));
                } catch (Exception e) {}

                if (extra.equals(SCREEN_ON)) {
                    mScreenonWakeLock = mPm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
                            PowerManager.ACQUIRE_CAUSES_WAKEUP,
                            "ConnectivityTest");
                    mScreenonWakeLock.acquire();

                    mSCCycleCount = cycle+1;
                    mSCOnDuration = on;
                    mSCOffDuration = off;
                    mSCCycleCountView.setText(Integer.toString(mSCCycleCount));

                    scheduleAlarm(mSCOnDuration, SCREEN_OFF);
                } else if (extra.equals(SCREEN_OFF)) {

                    mSCCycleCount = cycle;
                    mSCOnDuration = on;
                    mSCOffDuration = off;

                    mScreenonWakeLock.release();
                    mScreenonWakeLock = null;
                    scheduleAlarm(mSCOffDuration, SCREEN_ON);
                    pm.goToSleep(SystemClock.uptimeMillis());
                }
            }
        }
    };

    public Handler mHandler2 = new Handler() {
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case EVENT_TOGGLE_WIFI:
                    Log.e(TAG, "EVENT_TOGGLE_WIFI");
                    if (mDelayedCycleStarted && mWm != null) {
                        long delay;
                        switch (mWm.getWifiState()) {
                            case WifiManager.WIFI_STATE_ENABLED:
                            case WifiManager.WIFI_STATE_ENABLING:
                                mWm.setWifiEnabled(false);
                                delay = mDCOffDuration;
                                break;
                            default:
                                mWm.setWifiEnabled(true);
                                delay = mDCOnDuration;
                                mDCCycleCount++;
                                mDCCycleCountView.setText(Integer.toString(mDCCycleCount));
                        }
                        sendMessageDelayed(obtainMessage(EVENT_TOGGLE_WIFI),
                                delay);
                    }
                    break;
            }
        }
    };

   /**
     * Wifi Scan Listener
     */
    private class WifiScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                mStopTime = SystemClock.elapsedRealtime();
                if (mStartTime != -1) {
                    mTotalScanTime += (mStopTime - mStartTime);
                    mStartTime = -1;
                }
                Log.d(TAG, "Scan: READY " + mScanCur);

                List<ScanResult> wifiScanResults = mWm.getScanResults();
                if (wifiScanResults != null) {
                    mTotalScanCount += wifiScanResults.size();
                    Log.d(TAG, "Scan: Results = " + wifiScanResults.size());
                }

                mScanCur--;
                mScanCyclesEdit.setText(Long.toString(mScanCur));
                if (mScanCur == 0) {
                    unregisterReceiver(mScanRecv);
                    mScanButton.setText(GET_SCAN_RES);
                } else {
                    Log.d(TAG, "Scan: START " + mScanCur);
                    mStartTime = SystemClock.elapsedRealtime();
                    mWm.startScan();
                }
            }
        }
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.connectivity);

        mWm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        mPm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        mCm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
        mNetd = INetworkManagementService.Stub.asInterface(b);

        findViewById(R.id.enableWifi).setOnClickListener(mClickListener);
        findViewById(R.id.disableWifi).setOnClickListener(mClickListener);

        findViewById(R.id.startDelayedCycle).setOnClickListener(mClickListener);
        findViewById(R.id.stopDelayedCycle).setOnClickListener(mClickListener);
        mDCOnDurationEdit = (EditText)findViewById(R.id.dc_wifi_on_duration);
        mDCOnDurationEdit.setText(Long.toString(mDCOnDuration));
        mDCOffDurationEdit = (EditText)findViewById(R.id.dc_wifi_off_duration);
        mDCOffDurationEdit.setText(Long.toString(mDCOffDuration));
        mDCCycleCountView = (TextView)findViewById(R.id.dc_wifi_cycles_done);
        mDCCycleCountView.setText(Integer.toString(mDCCycleCount));

        findViewById(R.id.startScreenCycle).setOnClickListener(mClickListener);
        findViewById(R.id.stopScreenCycle).setOnClickListener(mClickListener);
        mSCOnDurationEdit = (EditText)findViewById(R.id.sc_wifi_on_duration);
        mSCOnDurationEdit.setText(Long.toString(mSCOnDuration));
        mSCOffDurationEdit = (EditText)findViewById(R.id.sc_wifi_off_duration);
        mSCOffDurationEdit.setText(Long.toString(mSCOffDuration));
        mSCCycleCountView = (TextView)findViewById(R.id.sc_wifi_cycles_done);
        mSCCycleCountView.setText(Integer.toString(mSCCycleCount));

        mScanButton = (Button)findViewById(R.id.startScan);
        mScanButton.setOnClickListener(mClickListener);
        mScanCyclesEdit = (EditText)findViewById(R.id.sc_scan_cycles);
        mScanCyclesEdit.setText(Long.toString(mScanCycles));
        mScanDisconnect = (CheckBox)findViewById(R.id.scanDisconnect);
        mScanDisconnect.setChecked(true);
        mScanResults = (TextView)findViewById(R.id.sc_scan_results);
        mScanResults.setVisibility(View.INVISIBLE);

        mScanRecv = new WifiScanReceiver();
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);

        findViewById(R.id.startTdls).setOnClickListener(mClickListener);
        findViewById(R.id.stopTdls).setOnClickListener(mClickListener);

        findViewById(R.id.start_mms).setOnClickListener(mClickListener);
        findViewById(R.id.stop_mms).setOnClickListener(mClickListener);
        findViewById(R.id.start_hipri).setOnClickListener(mClickListener);
        findViewById(R.id.stop_hipri).setOnClickListener(mClickListener);
        findViewById(R.id.crash).setOnClickListener(mClickListener);

        findViewById(R.id.add_default_route).setOnClickListener(mClickListener);
        findViewById(R.id.remove_default_route).setOnClickListener(mClickListener);
        findViewById(R.id.bound_http_request).setOnClickListener(mClickListener);
        findViewById(R.id.bound_socket_request).setOnClickListener(mClickListener);
        findViewById(R.id.routed_http_request).setOnClickListener(mClickListener);
        findViewById(R.id.routed_socket_request).setOnClickListener(mClickListener);
        findViewById(R.id.default_request).setOnClickListener(mClickListener);
        findViewById(R.id.default_socket).setOnClickListener(mClickListener);

        registerReceiver(mReceiver, new IntentFilter(CONNECTIVITY_TEST_ALARM));
    }

    @Override
    public void onResume() {
        super.onResume();
        findViewById(R.id.connectivity_layout).requestFocus();
    }

    private View.OnClickListener mClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.enableWifi:
                    mWm.setWifiEnabled(true);
                    break;
                case R.id.disableWifi:
                    mWm.setWifiEnabled(false);
                    break;
                case R.id.startDelayedCycle:
                    onStartDelayedCycle();
                    break;
                case R.id.stopDelayedCycle:
                    onStopDelayedCycle();
                    break;
                case R.id.startScreenCycle:
                    onStartScreenCycle();
                    break;
                case R.id.stopScreenCycle:
                    onStopScreenCycle();
                    break;
                case R.id.startScan:
                    onStartScanCycle();
                    break;
                case R.id.startTdls:
                    onStartTdls();
                    break;
                case R.id.stopTdls:
                    onStopTdls();
                    break;
                case R.id.start_mms:
                    mCm.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
                            Phone.FEATURE_ENABLE_MMS);
                    break;
                case R.id.stop_mms:
                    mCm.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
                            Phone.FEATURE_ENABLE_MMS);
                    break;
                case R.id.default_socket:
                    onDefaultSocket();
                    break;
                case R.id.default_request:
                    onDefaultRequest();
                    break;
                case R.id.routed_socket_request:
                    onRoutedSocketRequest();
                    break;
                case R.id.routed_http_request:
                    onRoutedHttpRequest();
                    break;
                case R.id.bound_socket_request:
                    onBoundSocketRequest();
                    break;
                case R.id.bound_http_request:
                    onBoundHttpRequest();
                    break;
                case R.id.remove_default_route:
                    onRemoveDefaultRoute();
                    break;
                case R.id.add_default_route:
                    onAddDefaultRoute();
                    break;
                case R.id.crash:
                    onCrash();
                    break;
                case R.id.start_hipri:
                    mCm.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
                            Phone.FEATURE_ENABLE_HIPRI);
                    break;
                case R.id.stop_hipri:
                    mCm.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
                            Phone.FEATURE_ENABLE_HIPRI);
                    break;
            }
        }
    };

    private void onStartDelayedCycle() {
        if (!mDelayedCycleStarted) {
            mDelayedCycleStarted = true;
            try {
                mDCOnDuration = Long.parseLong(mDCOnDurationEdit.getText().toString());
                mDCOffDuration = Long.parseLong(mDCOffDurationEdit.getText().toString());
            } catch (Exception e) { };
            mDCCycleCount = 0;

            mWakeLock = mPm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ConnectivityTest");
            mWakeLock.acquire();
            mHandler2.sendMessage(mHandler2.obtainMessage(EVENT_TOGGLE_WIFI));
        }
    }

    private void onStopDelayedCycle() {
        if (mDelayedCycleStarted) {
            mDelayedCycleStarted = false;
            mWakeLock.release();
            mWakeLock = null;
            if(mHandler2.hasMessages(EVENT_TOGGLE_WIFI)) {
                mHandler2.removeMessages(EVENT_TOGGLE_WIFI);
            }
        }
    }

    private void onStartScreenCycle() {
        try {
            mSCOnDuration = Long.parseLong(mSCOnDurationEdit.getText().toString());
            mSCOffDuration = Long.parseLong(mSCOffDurationEdit.getText().toString());
        } catch (Exception e) { };
        mSCCycleCount = 0;

        mScreenonWakeLock = mPm.newWakeLock(PowerManager.FULL_WAKE_LOCK,
                "ConnectivityTest");
        mScreenonWakeLock.acquire();

        scheduleAlarm(10, SCREEN_OFF);
    }

    private void scheduleAlarm(long delayMs, String eventType) {
        AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(CONNECTIVITY_TEST_ALARM);

        i.putExtra(TEST_ALARM_EXTRA, eventType);
        i.putExtra(TEST_ALARM_ON_EXTRA, Long.toString(mSCOnDuration));
        i.putExtra(TEST_ALARM_OFF_EXTRA, Long.toString(mSCOffDuration));
        i.putExtra(TEST_ALARM_CYCLE_EXTRA, Integer.toString(mSCCycleCount));

        PendingIntent p = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delayMs, p);
    }

    private void onStopScreenCycle() {
    }

    private void onCrash() {
        ConnectivityManager foo = null;
        foo.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
                Phone.FEATURE_ENABLE_MMS);
    }

    private void onStartScanCycle() {
        if (mScanCur == -1) {
            try {
                mScanCur = Long.parseLong(mScanCyclesEdit.getText().toString());
                mScanCycles = mScanCur;
            } catch (Exception e) { };
            if (mScanCur <= 0) {
                mScanCur = -1;
                mScanCycles = SCAN_CYCLES;
                return;
            }
        }
        if (mScanCur > 0) {
            registerReceiver(mScanRecv, mIntentFilter);
            mScanButton.setText(PROGRESS_SCAN);
            mScanResults.setVisibility(View.INVISIBLE);
            if (mScanDisconnect.isChecked())
                mWm.disconnect();
            mTotalScanTime = 0;
            mTotalScanCount = 0;
            Log.d(TAG, "Scan: START " + mScanCur);
            mStartTime = SystemClock.elapsedRealtime();
            mWm.startScan();
        } else {
            // Show results
            mScanResults.setText("Average Scan Time = " +
                Long.toString(mTotalScanTime / mScanCycles) + " ms ; Average Scan Amount = " +
                Long.toString(mTotalScanCount / mScanCycles));
            mScanResults.setVisibility(View.VISIBLE);
            mScanButton.setText(START_SCAN);
            mScanCur = -1;
            mScanCyclesEdit.setText(Long.toString(mScanCycles));
            if (mScanDisconnect.isChecked())
                mWm.reassociate();
        }
    }

    private void onStartTdls() {
        mTdlsAddr = ((EditText)findViewById(R.id.sc_ip_mac)).getText().toString();
        Log.d(TAG, "TDLS: START " + mTdlsAddr);
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getByName(mTdlsAddr);
            mWm.setTdlsEnabled(inetAddress, true);
        } catch (Exception e) {
            mWm.setTdlsEnabledWithMacAddress(mTdlsAddr, true);
        }
    }

    private void onStopTdls() {
        if (mTdlsAddr == null) return;
        Log.d(TAG, "TDLS: STOP " + mTdlsAddr);
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getByName(mTdlsAddr);
            mWm.setTdlsEnabled(inetAddress, false);
        } catch (Exception e) {
            mWm.setTdlsEnabledWithMacAddress(mTdlsAddr, false);
        }
    }

    private void onAddDefaultRoute() {
        try {
            mNetd.addRoute("eth0", new RouteInfo(null,
                    NetworkUtils.numericToInetAddress("8.8.8.8")));
        } catch (Exception e) {
            Log.e(TAG, "onAddDefaultRoute got exception: " + e.toString());
        }
    }

    private void onRemoveDefaultRoute() {
        try {
            mNetd.removeRoute("eth0", new RouteInfo(null,
                    NetworkUtils.numericToInetAddress("8.8.8.8")));
        } catch (Exception e) {
            Log.e(TAG, "onRemoveDefaultRoute got exception: " + e.toString());
        }
    }

    private void onRoutedHttpRequest() {
        onRoutedRequest(HTTP);
    }

    private void onRoutedSocketRequest() {
        onRoutedRequest(SOCKET);
    }

    private final static int SOCKET = 1;
    private final static int HTTP   = 2;

    private void onRoutedRequest(int type) {
        String url = "www.google.com";

        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getByName(url);
        } catch (Exception e) {
            Log.e(TAG, "error fetching address for " + url);
            return;
        }

        mCm.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI, inetAddress);

        switch (type) {
            case SOCKET:
                onBoundSocketRequest();
                break;
            case HTTP:
                HttpGet get = new HttpGet("http://" + url);
                HttpClient client = new DefaultHttpClient();
                try {
                    HttpResponse httpResponse = client.execute(get);
                    Log.d(TAG, "routed http request gives " + httpResponse.getStatusLine());
                } catch (Exception e) {
                    Log.e(TAG, "routed http request exception = " + e);
                }
        }

    }

    private void onBoundHttpRequest() {
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("rmnet0");
            Log.d(TAG, "networkInterface is " + networkInterface);
        } catch (Exception e) {
            Log.e(TAG, " exception getByName: " + e);
            return;
        }
        if (networkInterface != null) {
            Enumeration inetAddressess = networkInterface.getInetAddresses();
            while(inetAddressess.hasMoreElements()) {
                Log.d(TAG, " inetAddress:" + ((InetAddress)inetAddressess.nextElement()));
            }
        }

        HttpParams httpParams = new BasicHttpParams();
        if (networkInterface != null) {
            ConnRouteParams.setLocalAddress(httpParams,
                    networkInterface.getInetAddresses().nextElement());
        }
        HttpGet get = new HttpGet("http://www.bbc.com");
        HttpClient client = new DefaultHttpClient(httpParams);
        try {
            HttpResponse response = client.execute(get);
            Log.d(TAG, "response code = " + response.getStatusLine());
        } catch (Exception e) {
            Log.e(TAG, "Exception = "+ e );
        }
    }

    private void onBoundSocketRequest() {
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("rmnet0");
        } catch (Exception e) {
            Log.e(TAG, "exception getByName: " + e);
            return;
        }
        if (networkInterface == null) {
            try {
                Log.d(TAG, "getting any networkInterface");
                networkInterface = NetworkInterface.getNetworkInterfaces().nextElement();
            } catch (Exception e) {
                Log.e(TAG, "exception getting any networkInterface: " + e);
                return;
            }
        }
        if (networkInterface == null) {
            Log.e(TAG, "couldn't find a local interface");
            return;
        }
        Enumeration inetAddressess = networkInterface.getInetAddresses();
        while(inetAddressess.hasMoreElements()) {
            Log.d(TAG, " addr:" + ((InetAddress)inetAddressess.nextElement()));
        }
        InetAddress local = null;
        InetAddress remote = null;
        try {
            local = networkInterface.getInetAddresses().nextElement();
        } catch (Exception e) {
            Log.e(TAG, "exception getting local InetAddress: " + e);
            return;
        }
        try {
            remote = InetAddress.getByName("www.flickr.com");
        } catch (Exception e) {
            Log.e(TAG, "exception getting remote InetAddress: " + e);
            return;
        }
        Log.d(TAG, "remote addr ="+remote);
        Log.d(TAG, "local addr ="+local);
        Socket socket = null;
        try {
            socket = new Socket(remote, 80, local, 6000);
        } catch (Exception e) {
            Log.e(TAG, "Exception creating socket: " + e);
            return;
        }
        try {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println("Hi flickr");
        } catch (Exception e) {
            Log.e(TAG, "Exception writing to socket: " + e);
            return;
        }
    }

    private void onDefaultRequest() {
        HttpParams params = new BasicHttpParams();
        HttpGet get = new HttpGet("http://www.cnn.com");
        HttpClient client = new DefaultHttpClient(params);
        try {
            HttpResponse response = client.execute(get);
            Log.e(TAG, "response code = " + response.getStatusLine());
        } catch (Exception e) {
            Log.e(TAG, "Exception = " + e);
        }
    }

    private void onDefaultSocket() {
        InetAddress remote = null;
        try {
            remote = InetAddress.getByName("www.flickr.com");
        } catch (Exception e) {
            Log.e(TAG, "exception getting remote InetAddress: " + e);
            return;
        }
        Log.e(TAG, "remote addr =" + remote);
        Socket socket = null;
        try {
            socket = new Socket(remote, 80);
        } catch (Exception e) {
            Log.e(TAG, "Exception creating socket: " + e);
            return;
        }
        try {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println("Hi flickr");
            Log.e(TAG, "written");
        } catch (Exception e) {
            Log.e(TAG, "Exception writing to socket: " + e);
            return;
        }
    }
}


text:
using namespace std;

namespace vr
{

  class ItemInfo : public wxTreeItemData
  {
  public:
    ItemInfo(const string& fullPath, bool isDirectory)
      : fullPath(fullPath), isDirectory(isDirectory)
    {

    }

    std::string fullPath;
    bool isDirectory = false;
  };

  FileSelectorWidget::FileSelectorWidget(
    wxWindow* parent,
    wxWindowID id,
    const std::string& rootPath,
    const std::string& filter,
    const wxPoint& pos,
    const wxSize& size)
    : wxTreeCtrl(parent, id, pos, size), rootPath(rootPath), filter(filter)
  {

    Bind(wxEVT_TREE_ITEM_EXPANDING, &FileSelectorWidget::onItemExpanding, this, id);
    Bind(wxEVT_TREE_ITEM_COLLAPSING, &FileSelectorWidget::onItemCollapsing, this, id);
    Bind(wxEVT_TREE_ITEM_ACTIVATED, &FileSelectorWidget::onItemActivated, this, id);

    auto data = make_unique<ItemInfo>(rootPath, true);
    auto rootItem = AddRoot("Root", -1, -1, data.get());
    data.release();

    addDummyItem(rootItem);

    Expand(rootItem);

  }

  void FileSelectorWidget::onItemExpanding(wxTreeEvent& event)
  {
    auto itemInfo = dynamic_cast<const ItemInfo*>(GetItemData(event.GetItem()));
    if (itemInfo->isDirectory)
    {
      populateDirectoryItem(itemInfo->fullPath, event.GetItem());
    }
  }

  void FileSelectorWidget::onItemCollapsing(wxTreeEvent& event)
  {
    DeleteChildren(event.GetItem());

    auto itemInfo = dynamic_cast<const ItemInfo*>(GetItemData(event.GetItem()));
    if (itemInfo->isDirectory)
      addDummyItem(event.GetItem());
  }

  void FileSelectorWidget::onItemActivated(wxTreeEvent& event)
  {
    auto itemInfo = dynamic_cast<const ItemInfo*>(GetItemData(event.GetItem()));
    if (itemInfo->isDirectory)
      return;

    FileSelectedEvent fileSelectedEvent(TS_FILE_SELECTED, GetId(), itemInfo->fullPath);
    fileSelectedEvent.SetEventObject(this);
    ProcessWindowEvent(fileSelectedEvent);
  }

  void FileSelectorWidget::populateDirectoryItem(const std::string& path, const wxTreeItemId& parent)
  {
    DeleteChildren(parent);
    wxDir dir(path);

    if (dir.IsOpened())
    {
      wxString fileName;
      for (auto keepGoing = dir.GetFirst(&fileName, wxString(), wxDIR_DIRS | wxDIR_FILES); keepGoing; keepGoing = dir.GetNext(&fileName))
      {
        auto childPath = path + "/" + fileName.ToStdString();
        addItem(parent, fileName.ToStdString(), childPath);
      }
    }
  }

  void FileSelectorWidget::addDummyItem(const wxTreeItemId& parent)
  {
    auto rootItem = AppendItem(parent, "Dummy");
  }

  void FileSelectorWidget::addItem(const wxTreeItemId& parent, const string& name, const string& fullPath)
  {
    auto data = make_unique<ItemInfo>(fullPath, wxDirExists(fullPath.c_str()));
    auto item = AppendItem(parent, name, -1, -1, data.get());
    if (data->isDirectory)
      addDummyItem(item);

    data.release();
  }

}

redpajama_set_name: RedPajamaGithub


text:
module JFlow.Acyclic where

import Jinja.Program as P

import JFlow.Data

import Data.Maybe (fromMaybe)
import Text.PrettyPrint.ANSI.Leijen
import qualified Data.Set as S

--import Debug.Trace

newtype AcyclicFact = AcFact AC  deriving (Eq,Ord)
data AC = AcTop | Ac (S.Set Var) deriving (Eq,Ord)

instance Pretty AcyclicFact where
  pretty (AcFact AcTop)   = string "AcFact" <$> string "AcTop"
  pretty (AcFact (Ac ac)) =
    string "AcFact"
    <$> list (map ((char '^' <>). pretty) $ S.elems ac)

instance Show AcyclicFact where
  show = show . pretty

acFlow :: Flow AcyclicFact
acFlow = Flow acLattice acTransfer acQueryV

acLattice :: SemiLattice AcyclicFact
acLattice = SemiLattice acName acBot acJoin
  where
    acName = "Acyclic"
    acBot  = AcFact AcTop

    acJoin _ (AcFact AcTop) (AcFact ac)          = AcFact ac
    acJoin _ (AcFact ac) (AcFact AcTop)          = AcFact ac
    acJoin _ (AcFact (Ac ac1)) (AcFact (Ac ac2)) = AcFact (Ac ac3)
      where ac3 = ac1 `S.intersection` ac2

acTransfer :: Transfer AcyclicFact
acTransfer = Transfer acTransferf acSetup acProject acExtend
  where
    assign x y ac
      | y `S.member` ac = x `S.insert` ac
      | otherwise       = x `S.delete` ac

    acTransferf _ _ _   (AcFact  AcTop)  = undefined
    acTransferf p q ins (AcFact (Ac ac)) =
      let (i,j) = hasIndexQ q in acTransferf' p q ins ac i j
    acTransferf' p q ins ac i j = AcFact . Ac $ case ins of
      Load n       -> (StkVar i j `assign` LocVar i n) ac
      Store n      -> let (x,y) = (LocVar i n, StkVar i (j+1)) in S.delete y $ (x `assign` y) ac
      Push _       -> StkVar i j `S.insert` ac
      New _        -> StkVar i j `S.insert` ac
      CheckCast _  -> ac
      Pop          -> StkVar i (j+1) `S.delete` ac
      IAdd         -> StkVar i (j+1) `S.delete` ac
      ISub         -> StkVar i (j+1) `S.delete` ac
      Goto _       -> ac
      IfFalse _    -> StkVar i (j+1) `S.delete` ac
      CmpEq        -> S.insert (StkVar i j) $ S.delete (StkVar i (j+1)) ac
      CmpNeq       -> S.insert (StkVar i j) $ S.delete (StkVar i (j+1)) ac
      ICmpGeq      -> StkVar i (j+1) `S.delete` ac
      BNot         -> ac
      BOr          -> StkVar i (j+1) `S.delete` ac
      BAnd         -> StkVar i (j+1) `S.delete` ac
      Return       -> undefined
      Invoke _ _   -> undefined

      GetField fn cn  -> if isAcyclic' p cn fn then StkVar i j `S.insert` ac else ac
      -- x.f = y; either y is already cyclic or there is a cycle with x
      -- TODO: check if normalising is necessary
      PutField fn cn -> S.delete val . S.delete ref $
        if isAcyclic' p cn fn
          {-|| (val `S.member` ac && not (shares val ref))-}
          {-|| (val `S.member` ac && (maybe False ((cn `S.notMember`) . reachableClasses p) valty))-}
        then ac
        else ac `S.difference` sharesWith ref (S.elems ac) q
        where
          (val,ref) = (StkVar i (j+2), StkVar i (j+1))
          shares    = mayShareQ q
          valty = case snd $ field p cn fn of
            RefType cn' -> Just cn'
            _           -> Nothing

    isAcyclic' p cn fn = P.isAcyclicType' p ty
      where ty = snd $ field p cn fn

    sharesWith x es q = S.fromList $ foldl k [] es
      where  k xs y = if  mayShareQ q x y then y:xs else xs

    acSetup p cn mn = AcFact (Ac $ S.fromList [LocVar 0 i | i <- [0..mx]])
      where
        md = theMethod p cn mn
        mx = maxLoc md + length (methodParams md)

    acProject _ q _ _ nparams (AcFact (Ac ac)) = AcFact (Ac $ S.map rename ac)
      where
        (i,j)  = hasIndexQ q
        rename z = z `fromMaybe` lookup z (zip [StkVar i k | k <- [j,j-1..]] [LocVar (i+1) k | k <- [nparams,nparams-1..0]])
    acProject _ _ _ _ _ acf = acf

    acExtend _ q _ nparams _ (AcFact (Ac ac)) =
      AcFact . Ac . S.filter k $ (rl `assign` rs) ac
      where
        (i,j) = hasIndexQ q
        (rs,rl) = (StkVar (i+1) 0, StkVar i (j -nparams))
        k (StkVar i2 _) = i2 <= i
        k (LocVar i2 _) = i2 <= i
    acExtend _ _ _ _ _ acf = acf

acQueryV :: QueryV AcyclicFact
acQueryV = defaultQueryV{ isAcyclic = acIsAcyclic }
  where
    acIsAcyclic (AcFact AcTop) _   = Just True
    acIsAcyclic (AcFact (Ac ac)) x = Just $ x `S.member` ac


text:
int main(){
    printf("Haha, world.");
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface net.sourceforge.pmd.lang.DataFlowHandler (PMD 5.0.4 API)</title>
<meta name="date" content="2013-05-01">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
net.sourceforge.pmd.lang.DataFlowHandler

Packages that use DataFlowHandler

Package
Description

net.sourceforge.pmd.lang

net.sourceforge.pmd.lang.dfa

net.sourceforge.pmd.lang.java

net.sourceforge.pmd.lang.java.dfa

Uses of DataFlowHandler in net.sourceforge.pmd.lang

Fields in net.sourceforge.pmd.lang declared as DataFlowHandler

Modifier and Type
Field and Description

static DataFlowHandler
DataFlowHandler.DUMMY

Methods in net.sourceforge.pmd.lang that return DataFlowHandler

Modifier and Type
Method and Description

DataFlowHandler
AbstractLanguageVersionHandler.getDataFlowHandler()

DataFlowHandler
LanguageVersionHandler.getDataFlowHandler()

Get the DataFlowHandler.

Uses of DataFlowHandler in net.sourceforge.pmd.lang.dfa

Constructors in net.sourceforge.pmd.lang.dfa with parameters of type DataFlowHandler

Constructor and Description

Linker(DataFlowHandler dataFlowHandler,
      List<StackObject> braceStack,
      List<StackObject> continueBreakReturnStack)

Structure(DataFlowHandler dataFlowHandler)

Uses of DataFlowHandler in net.sourceforge.pmd.lang.java

Classes in net.sourceforge.pmd.lang.java that implement DataFlowHandler

Modifier and Type
Class and Description

class
JavaDataFlowHandler

Methods in net.sourceforge.pmd.lang.java that return DataFlowHandler

Modifier and Type
Method and Description

DataFlowHandler
AbstractJavaHandler.getDataFlowHandler()

Uses of DataFlowHandler in net.sourceforge.pmd.lang.java.dfa

Methods in net.sourceforge.pmd.lang.java.dfa with parameters of type DataFlowHandler

Modifier and Type
Method and Description

void
DataFlowFacade.initializeWith(DataFlowHandler dataFlowHandler,
              ASTCompilationUnit node)

Constructors in net.sourceforge.pmd.lang.java.dfa with parameters of type DataFlowHandler

Constructor and Description

StatementAndBraceFinder(DataFlowHandler dataFlowHandler)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2002-2013 InfoEther. All Rights Reserved.


text:
package main

import (
	"database/sql"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/intervention-engine/fhir/models"
	_ "github.com/lib/pq"
	"github.com/synthetichealth/bulkfhirloader/bulkloader"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

var debug *bool

func main() {
	// required command line flags
	fhirBundlePath := flag.String("path", "", "Path to fhir bundles to upload")
	mongoServer := flag.String("mongo", "localhost:27017", "MongoDB server url, format: host:27017")
	mongoDBName := flag.String("dbname", "fhir", "MongoDB database name, e.g. 'fhir'")
	pgurl := flag.String("pgurl", "", "Postgres connection string, format: postgresql://username:password@host/dbname?sslmode=disable")

	// optional flags (with sensible defaults)
	numWorkers := flag.Int("workers", 8, "Number of concurrent workers to use")
	reset := flag.Bool("reset", false, "Reset the FHIR collections in Mongo and reset the synth_ma statistics")
	debug = flag.Bool("debug", false, "Display additional debug output")

	flag.Parse()

	if *fhirBundlePath == "" {
		fmt.Println("You must specify a path to the fhir bundles to upload")
		os.Exit(1)
	}

	if *pgurl == "" {
		fmt.Println("You must specify a Postgres connection string")
		os.Exit(1)
	}

	var err error

	// setup the MongoDB connection
	mongoSession, err := mgo.Dial(*mongoServer)
	if err != nil {
		log.Fatal(err)
	}
	defer mongoSession.Close()

	// setup the Postgres connection
	pgDB, err := sql.Open("postgres", *pgurl)
	if err != nil {
		log.Fatal("Failed to connect to Postgres")
	}

	// ping the Postgres db to ensure we connected successfully
	if err = pgDB.Ping(); err != nil {
		log.Fatal(err)
	}
	defer pgDB.Close()

	// GQ: always reset postgres fact tables. reset flag will only clear mongo now
	bulkloader.ClearFactTables(pgDB)

	// optionally reset the data in mongo (if starting a clean upload)
	if *reset {
		bulkloader.ClearMongoCollections(mongoSession, *mongoDBName)
	}

	// query Postgres for a list of the current subdivisions and diseases we track
	log.Println("Getting latest subdivision and disease information from Postgres...")

	cousubs, err := getCousubs(pgDB)
	if err != nil {
		logDebug(err)
		log.Fatal("Failed to get subdivision list from Postgres")
	}

	diseases, err := getDiseases(pgDB)
	if err != nil {
		logDebug(err)
		log.Fatal("Failed to get disease list from Postgres")
	}

	// create a new WorkerChannel to coordinate workers
	log.Printf("Reading FHIR bundles in %s\n", *fhirBundlePath)

	start := time.Now()
	workerChannel := new(WorkerChannel)
	workerChannel.bundleChannel = make(chan string, 256)

	var wg sync.WaitGroup
	var counter uint64 // total number of FHIR bundles processed

	// spawn workers
	for i := 0; i < *numWorkers; i++ {
		wg.Add(1)
		go worker(&wg, workerChannel.bundleChannel, mongoSession, *mongoDBName, cousubs, diseases, &counter)
	}

	err = filepath.Walk(*fhirBundlePath, workerChannel.visit)
	if err != nil {
		log.Println("An error occured while reading-in FHIR bundles:")
		log.Fatal(err)
	}

	// close the channel when done
	close(workerChannel.bundleChannel)

	// wait for all workers to shut down properly
	wg.Wait()
	log.Printf("%d FHIR bundles read in %f seconds\n", counter, getSecondsSince(start))

	// process the statistics for the uploaded bundles
	bulkloader.CalculatePopulationFacts(mongoSession, *mongoDBName, pgDB)
	log.Printf("Time elapsed: %f seconds\n", getSecondsSince(start))

	bulkloader.CalculateDiseaseFacts(mongoSession, *mongoDBName, pgDB)
	log.Printf("Time elapsed: %f seconds\n", getSecondsSince(start))

	bulkloader.CalculateConditionFacts(mongoSession, *mongoDBName, pgDB)
	log.Printf("Time elapsed: %f seconds\n", getSecondsSince(start))
}

// getCousubs queries the Postgres database for the latest list of subdivision in the
// synth_ma.synth_cousub_dim table.
func getCousubs(db *sql.DB) (*bulkloader.CousubMap, error) {

	rows, err := db.Query(`
		SELECT case when right(cd.cs_name, 5) = ' Town' then substring(cd.cs_name, 1, length(cd.cs_name)-5)
			else cs_name
			end
			, cd.ct_fips
			, cd.cs_fips
		FROM synth_ma.synth_cousub_dim cd`)

	if err != nil {
		return nil, err
	}
	defer rows.Close()

	cousubs := make(bulkloader.CousubMap)

	for rows.Next() {
		var csName, ctFips, csFips string
		var cousub bulkloader.Cousub

		err := rows.Scan(&csName, &ctFips, &csFips)
		if err != nil {
			return nil, err
		}
		cousub.CountyIDFips = ctFips
		cousub.SubCountyIDFips = csFips
		cousubs[csName] = cousub
	}
	return &cousubs, nil
}

// getDiseases queries the Postgres database for the latest list of diseases in the
// synth_ma.synth_condition_dim table.
func getDiseases(db *sql.DB) (*bulkloader.DiseaseMap, error) {

	rows, err := db.Query(`
		SELECT cd.condition_id, coalesce(cd.disease_id, -999), cd.code_system, cd.code
		FROM synth_ma.synth_condition_dim cd`)

	if err != nil {
		return nil, err
	}
	defer rows.Close()

	diseases := make(bulkloader.DiseaseMap)

	for rows.Next() {
		var conditionID, diseaseID int
		var system, code string
		var disease bulkloader.Disease

		err := rows.Scan(&conditionID, &diseaseID, &system, &code)
		if err != nil {
			return nil, err
		}
		disease.ConditionID = conditionID
		disease.DiseaseID = diseaseID
		key := bulkloader.DiseaseKey{
			CodeSystem:  system,
			CodeSysCode: code,
		}
		diseases[key] = disease
	}
	return &diseases, nil
}

// WorkerChannel coordinates the processing of FHIR bundles between several workers.
type WorkerChannel struct {
	bundleChannel chan (string)
}

// visit visits all the FHIR bundles in a specified path, adding each bundle to the
// bundleChannel that feeds the workers.
func (wc *WorkerChannel) visit(path string, f os.FileInfo, err error) error {

	if err != nil {
		return err
	}

	logDebug("Visited: %s\n", path)

	if !f.IsDir() && strings.HasSuffix(path, ".json") {

		// push bundle onto channel
		wc.bundleChannel <- path
		return nil
	}

	logDebug("Processed directory path or non-json file....")
	return nil
}

// worker uses a WorkerChannel to process all of the resources in a single FHIR bundle, specified by the path to that bundle's JSON file.
func worker(wg *sync.WaitGroup, bundles <-chan string, mongoSession *mgo.Session, dbName string, cousubs *bulkloader.CousubMap, diseases *bulkloader.DiseaseMap, counter *uint64) {
	defer wg.Done()

	for {
		select {
		case path, ok := <-bundles:
			if !ok {
				return
			}

			jsonFile, err := os.Open(path)
			if err != nil {
				logDebug("Error opening JSON file:\n", err)
				continue
			}

			jsonData, err := ioutil.ReadAll(jsonFile)
			jsonFile.Close()
			if err != nil {
				logDebug("Error reading JSON data:\n", err)
				continue
			}

			var bundle models.Bundle
			json.Unmarshal(jsonData, &bundle)

			refMap := make(map[string]models.Reference)

			entries := make([]*models.BundleEntryComponent, len(bundle.Entry))
			for i := range bundle.Entry {
				entries[i] = &bundle.Entry[i]
			}

			for _, entry := range entries {
				// Create a new BSON ID and add it to the reference map
				id := bson.NewObjectId().Hex()
				refMap[entry.FullUrl] = models.Reference{
					Reference:    reflect.TypeOf(entry.Resource).Elem().Name() + "/" + id,
					Type:         reflect.TypeOf(entry.Resource).Elem().Name(),
					ReferencedID: id,
					External:     new(bool),
				}
				// Update the resource's UUID to the new BSON ID that was just generated
				bulkloader.SetID(entry.Resource, id)
			}

			// Update all the references to the entries (to reflect newly assigned IDs)
			bulkloader.UpdateAllReferences(entries, refMap)

			resources := make([]interface{}, len(entries))
			for i := range entries {
				resources[i] = entries[i].Resource
			}

			atomic.AddUint64(counter, 1)
			bulkloader.UploadResources(resources, mongoSession, dbName, *cousubs, *diseases)
		} // close the select
	} // close the for
}

func getSecondsSince(start time.Time) float64 {
	return time.Now().Sub(start).Seconds()
}

func logDebug(v ...interface{}) {
	if *debug {
		log.Println(v...)
	}
}


text:
namespace System.CodeDom {

    using System.Diagnostics;
    using System;
    using System.Collections;
    using System.Runtime.InteropServices;
    using System.Globalization;

    /// <devdoc>
    ///    <para>
    ///       Manages a collection of <see cref='System.CodeDom.CodeNamespaceImport'/> objects.
    ///    </para>
    /// </devdoc>
    [
        ClassInterface(ClassInterfaceType.AutoDispatch),
        ComVisible(true),
        Serializable,
    ]
    public class CodeNamespaceImportCollection : IList {
        private ArrayList data = new ArrayList();
        private Hashtable keys = new Hashtable(StringComparer.OrdinalIgnoreCase);

        /// <devdoc>
        ///    <para>
        ///       Indexer method that provides collection access.
        ///    </para>
        /// </devdoc>
        public CodeNamespaceImport this[int index] {
            get {
                return ((CodeNamespaceImport)data[index]);
            }
            set {
                data[index] = value;
                SyncKeys();
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the number of namespaces in the collection.
        ///    </para>
        /// </devdoc>
        public int Count {
            get {
                return data.Count;
            }
        }

		/// <internalonly/>
		bool IList.IsReadOnly
		{
			get
			{
				return false;
			}
		}

		/// <internalonly/>
		bool IList.IsFixedSize
		{
			get
			{
				return false;
			}
		}

        /// <devdoc>
        ///    <para>
        ///       Adds a namespace import to the collection.
        ///    </para>
        /// </devdoc>
        public void Add(CodeNamespaceImport value) {
            if (!keys.ContainsKey(value.Namespace)) {
                keys[value.Namespace] = value;
                data.Add(value);
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Adds a set of <see cref='System.CodeDom.CodeNamespaceImport'/> objects to the collection.
        ///    </para>
        /// </devdoc>
        public void AddRange(CodeNamespaceImport[] value) {
            if (value == null) {
                throw new ArgumentNullException("value");
            }
            foreach (CodeNamespaceImport c in value) {
                Add(c);
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Clears the collection of members.
        ///    </para>
        /// </devdoc>
        public void Clear() {
            data.Clear();
            keys.Clear();
        }

        /// <devdoc>
        ///    <para>
        ///    Makes the collection of keys synchronised with the data.
        ///    </para>
        /// </devdoc>
        private void SyncKeys() {
            keys = new Hashtable(StringComparer.OrdinalIgnoreCase);
            foreach(CodeNamespaceImport c in this) {
                keys[c.Namespace] = c;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets an enumerator that enumerates the collection members.
        ///    </para>
        /// </devdoc>
        public IEnumerator GetEnumerator() {
            return data.GetEnumerator();
        }

        /// <internalonly/>
        object IList.this[int index] {
            get {
                return this[index];
            }
            set {
                this[index] = (CodeNamespaceImport)value;
                SyncKeys();
            }
        }

        /// <internalonly/>
        int ICollection.Count {
            get {
                return Count;
            }
        }

        /// <internalonly/>
        bool ICollection.IsSynchronized {
            get {
                return false;
            }
        }

        /// <internalonly/>
        object ICollection.SyncRoot {
            get {
                return null;
            }
        }

        /// <internalonly/>
        void ICollection.CopyTo(Array array, int index) {
            data.CopyTo(array, index);
        }

        /// <internalonly/>
        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        /// <internalonly/>
        int IList.Add(object value) {
            return data.Add((CodeNamespaceImport)value);
        }

        /// <internalonly/>
        void IList.Clear() {
            Clear();
        }

        /// <internalonly/>
        bool IList.Contains(object value) {
            return data.Contains(value);
        }

        /// <internalonly/>
        int IList.IndexOf(object value) {
            return data.IndexOf((CodeNamespaceImport)value);
        }

        /// <internalonly/>
        void IList.Insert(int index, object value) {
            data.Insert(index, (CodeNamespaceImport)value);
            SyncKeys();
        }

        /// <internalonly/>
        void IList.Remove(object value) {
            data.Remove((CodeNamespaceImport)value);
            SyncKeys();
        }

        /// <internalonly/>
        void IList.RemoveAt(int index) {
            data.RemoveAt(index);
            SyncKeys();
        }
    }
}


text:
#include "builtin.h"
#include "cache.h"
#include "config.h"
#include "dir.h"
#include "quote.h"
#include "pathspec.h"
#include "parse-options.h"
#include "submodule.h"

static int quiet, verbose, stdin_paths, show_non_matching, no_index;
static const char * const check_ignore_usage[] = {
"git check-ignore [<options>] <pathname>...",
"git check-ignore [<options>] --stdin",
NULL
};

static int nul_term_line;

static const struct option check_ignore_options[] = {
	OPT__QUIET(&quiet, N_("suppress progress reporting")),
	OPT__VERBOSE(&verbose, N_("be verbose")),
	OPT_GROUP(""),
	OPT_BOOL(0, "stdin", &stdin_paths,
		 N_("read file names from stdin")),
	OPT_BOOL('z', NULL, &nul_term_line,
		 N_("terminate input and output records by a NUL character")),
	OPT_BOOL('n', "non-matching", &show_non_matching,
		 N_("show non-matching input paths")),
	OPT_BOOL(0, "no-index", &no_index,
		 N_("ignore index when checking")),
	OPT_END()
};

static void output_exclude(const char *path, struct exclude *exclude)
{
	char *bang  = (exclude && exclude->flags & EXC_FLAG_NEGATIVE)  ? "!" : "";
	char *slash = (exclude && exclude->flags & EXC_FLAG_MUSTBEDIR) ? "/" : "";
	if (!nul_term_line) {
		if (!verbose) {
			write_name_quoted(path, stdout, '\n');
		} else {
			if (exclude) {
				quote_c_style(exclude->el->src, NULL, stdout, 0);
				printf(":%d:%s%s%s\t",
				       exclude->srcpos,
				       bang, exclude->pattern, slash);
			}
			else {
				printf("::\t");
			}
			quote_c_style(path, NULL, stdout, 0);
			fputc('\n', stdout);
		}
	} else {
		if (!verbose) {
			printf("%s%c", path, '\0');
		} else {
			if (exclude)
				printf("%s%c%d%c%s%s%s%c%s%c",
				       exclude->el->src, '\0',
				       exclude->srcpos, '\0',
				       bang, exclude->pattern, slash, '\0',
				       path, '\0');
			else
				printf("%c%c%c%s%c", '\0', '\0', '\0', path, '\0');
		}
	}
}

static int check_ignore(struct dir_struct *dir,
			const char *prefix, int argc, const char **argv)
{
	const char *full_path;
	char *seen;
	int num_ignored = 0, dtype = DT_UNKNOWN, i;
	struct exclude *exclude;
	struct pathspec pathspec;

	if (!argc) {
		if (!quiet)
			fprintf(stderr, "no pathspec given.\n");
		return 0;
	}

	/*
	 * check-ignore just needs paths. Magic beyond :/ is really
	 * irrelevant.
	 */
	parse_pathspec(&pathspec,
		       PATHSPEC_ALL_MAGIC & ~PATHSPEC_FROMTOP,
		       PATHSPEC_SYMLINK_LEADING_PATH |
		       PATHSPEC_KEEP_ORDER,
		       prefix, argv);

	die_path_inside_submodule(&the_index, &pathspec);

	/*
	 * look for pathspecs matching entries in the index, since these
	 * should not be ignored, in order to be consistent with
	 * 'git status', 'git add' etc.
	 */
	seen = find_pathspecs_matching_against_index(&pathspec, &the_index);
	for (i = 0; i < pathspec.nr; i++) {
		full_path = pathspec.items[i].match;
		exclude = NULL;
		if (!seen[i]) {
			exclude = last_exclude_matching(dir, &the_index,
							full_path, &dtype);
		}
		if (!quiet && (exclude || show_non_matching))
			output_exclude(pathspec.items[i].original, exclude);
		if (exclude)
			num_ignored++;
	}
	free(seen);

	return num_ignored;
}

static int check_ignore_stdin_paths(struct dir_struct *dir, const char *prefix)
{
	struct strbuf buf = STRBUF_INIT;
	struct strbuf unquoted = STRBUF_INIT;
	char *pathspec[2] = { NULL, NULL };
	strbuf_getline_fn getline_fn;
	int num_ignored = 0;

	getline_fn = nul_term_line ? strbuf_getline_nul : strbuf_getline_lf;
	while (getline_fn(&buf, stdin) != EOF) {
		if (!nul_term_line && buf.buf[0] == '"') {
			strbuf_reset(&unquoted);
			if (unquote_c_style(&unquoted, buf.buf, NULL))
				die("line is badly quoted");
			strbuf_swap(&buf, &unquoted);
		}
		pathspec[0] = buf.buf;
		num_ignored += check_ignore(dir, prefix,
					    1, (const char **)pathspec);
		maybe_flush_or_die(stdout, "check-ignore to stdout");
	}
	strbuf_release(&buf);
	strbuf_release(&unquoted);
	return num_ignored;
}

int cmd_check_ignore(int argc, const char **argv, const char *prefix)
{
	int num_ignored;
	struct dir_struct dir;

	git_config(git_default_config, NULL);

	argc = parse_options(argc, argv, prefix, check_ignore_options,
			     check_ignore_usage, 0);

	if (stdin_paths) {
		if (argc > 0)
			die(_("cannot specify pathnames with --stdin"));
	} else {
		if (nul_term_line)
			die(_("-z only makes sense with --stdin"));
		if (argc == 0)
			die(_("no path specified"));
	}
	if (quiet) {
		if (argc > 1)
			die(_("--quiet is only valid with a single pathname"));
		if (verbose)
			die(_("cannot have both --quiet and --verbose"));
	}
	if (show_non_matching && !verbose)
		die(_("--non-matching is only valid with --verbose"));

	/* read_cache() is only necessary so we can watch out for submodules. */
	if (!no_index && read_cache() < 0)
		die(_("index file corrupt"));

	memset(&dir, 0, sizeof(dir));
	setup_standard_excludes(&dir);

	if (stdin_paths) {
		num_ignored = check_ignore_stdin_paths(&dir, prefix);
	} else {
		num_ignored = check_ignore(&dir, prefix, argc, argv);
		maybe_flush_or_die(stdout, "ignore to stdout");
	}

	clear_directory(&dir);

	return !num_ignored;
}


text:
<%
    from pylons.i18n.translation import _
%>
<%inherit file="/base/admin.html"/>
<%namespace file="fields.html" name="fields" import="*"/>
<%namespace file="/component/admin.html" name="admin" import="*"/>
<%namespace file="/component/editor.html" name="editor" import="*"/>

<%def name="title()">
    ${parent.title()} > ${_('Edit Comment')}
</%def>

<%def name="js()">
    ${editor.admin_editor()}
</%def>

    ${h.link_to(
        h.literal(''),
        h.url_for(controller='comment', action='list'),
        class_='ui-state-default ui-corner-all',
        title=_('Cancel')
    )}

${h.form(h.url_for(action='save', controller='comment', id=request.urlvars['id']), method='post')}
    ${fields.body()}
    ${h.submit('edit', _('Edit Comment'))} ${_('or')}
    ${h.link_to(_('Cancel'), h.url_for(controller='comment', action='list'))}
${h.end_form()}


text:
div.zoom-selected
{
  position: relative;
  width: 64px;
  height: 64px;
  background: url('images/viewer-icons.png') 0px -64px no-repeat;
  background-clip: content-box;
}

div.zoom
{
  position: relative;
  width: 64px;
  height: 64px;
  background: url('images/viewer-icons.png') 0px -128px no-repeat;
  background-clip: content-box;
}

div.pan-selected
{
  position: relative;
  width: 64px;
  height: 64px;
  background: url('images/viewer-icons.png') -64px -64px no-repeat;
  background-clip: content-box;
}

div.pan
{
  position: relative;
  width: 64px;
  height: 64px;
  background: url('images/viewer-icons.png') -64px -128px no-repeat;
  background-clip: content-box;
}

div.track-selected
{
  position: relative;
  width: 64px;
  height: 64px;
  background: url('images/viewer-icons.png') -128px -64px no-repeat;
  background-clip: content-box;
}

div.track
{
  position: relative;
  width: 64px;
  height: 64px;
  background: url('images/viewer-icons.png') -128px -128px no-repeat;
  background-clip: content-box;
}

div.camera-selected
{
  position: relative;
  width: 32px;
  height: 32px;
  background: url('images/viewer-icons.png') 0px 0px no-repeat;
  background-clip: content-box;
}

div.camera
{
  position: relative;
  width: 32px;
  height: 32px;
  background: url('images/viewer-icons.png') 0px -32px no-repeat;
  background-clip: content-box;
}


text:
@extends('layouts.public',['layoutMode' => 'blank', 'title' => 'complete sso', 'selectedTab'=>'login'])

@section('content')

					 siggy account required

					 'account/login']) !!}

						@if($errors->any())

						{{$errors->first()}}

						@endif

										{{ Form::text('username',null, ['class' => 'form-control', 'placeholder' => 'Username', 'autofocus' => 'autofocus']) }}

										{{ Form::password('password',['class' => 'form-control', 'placeholder' => 'Password']) }}

										{{ Form::checkbox('remember', '1', true) }} Remember me?

									<input type="submit" class="btn btn-lg btn-primary btn-block" value="Sign in">

					{!! Form::close() !!}

					Lost or forgot password? Click here

							or

						Create a siggy account

@endsection


text:
.handsontable {
  position: relative;
  font-family: Arial, Helvetica, sans-serif;
  line-height: 1.3em;
  font-size: 13px;
}

.handsontable * {
  box-sizing: content-box;
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
}

.handsontable table {
  border-collapse: separate;
  position: relative;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  -ms-user-select: none;
  /*user-select: none; /*no browser supports unprefixed version*/
  border-spacing: 0;
  margin: 0;
  border-width: 0;
}

.handsontable col {
  width: 50px;
}

.handsontable th,
.handsontable td {
  border-right: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  height: 22px;
  line-height: 21px;
  padding: 0 4px 0 4px; /* top, bottom padding different than 0 is handled poorly by FF with HTML5 doctype */
  background-color: #FFF;
  font-size: 12px;
  vertical-align: top;
}

.handsontable th:last-child {
  /*Foundation framework fix*/
  border-right: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
}

.handsontable tr:first-child th.htNoFrame,
.handsontable th:first-child.htNoFrame,
.handsontable th.htNoFrame {
  border-left-width: 0;
  background-color: white;
  border-color: #FFF;
}

.handsontable th:first-child,
.handsontable td:first-child,
.handsontable .htNoFrame + th,
.handsontable .htNoFrame + td {
  border-left: 1px solid #CCC;
}

.handsontable tr:first-child th,
.handsontable tr:first-child td {
  border-top: 1px solid #CCC;
}

.handsontable thead tr:last-child th {
  border-bottom-width: 0;
}

.handsontable thead tr.lastChild th {
  border-bottom-width: 0;
}

.handsontable th {
  background-color: #EEE;
  color: #222;
  text-align: center;
  font-weight: normal;
  white-space: nowrap;
}

.handsontable th .small {
  font-size: 12px;
}

.handsontable thead th {
  padding: 2px 4px;
}

.handsontable th.active {
  background-color: #CCC;
}

/* border line */
.handsontable .wtBorder {
  position: absolute;
  font-size: 0;
}

.handsontable td.area {
  background-color: #EEF4FF;
}

/* fill handle */
.handsontable .wtBorder.corner {
  font-size: 0;
  cursor: crosshair;
}

.handsontable .htBorder.htFillBorder {
  background: red;
  width: 1px;
  height: 1px;
}

/* textarea border color */
textarea.handsontableInput {
  border: 2px solid #5292F7;
  outline-width: 0;
  margin: 0;
  padding: 1px 4px 0 2px;
  font-family: Arial, Helvetica, sans-serif; /*repeat from .handsontable (inherit doesn't work with IE<8) */
  line-height: 1.3em;
  font-size: 13px;
  box-shadow: 1px 2px 5px rgba(0, 0, 0, 0.4);
  resize: none;
}

.handsontableInputHolder.htHidden textarea.handsontableInput {
  border-color: #5292F7;
  background: #5292F7;
  color: #5292F7;
}

.handsontableInputHolder {
  position: absolute;
  top: 0;
  left: 0;
  width: 1px;
  height: 1px;
  overflow: hidden;
}

/*
AutocompleteRenderer down arrow
*/
.handsontable .htAutocomplete {
  position: relative;
  padding-right: 20px;
}

.handsontable .htAutocompleteArrow {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 10px;
  color: #EEE;
  cursor: default;
  width: 16px;
  text-align: center;
}

.handsontable td .htAutocompleteArrow:hover {
  color: #777;
}

/* typeahead rules. Needed only if you are using the autocomplete feature */
.typeahead {
  position: absolute;
  font-family: Arial, Helvetica, sans-serif;
  line-height: 1.3em;
  font-size: 13px;
  z-index: 10;
  top: 100%;
  left: 0;
  float: left;
  display: none;
  min-width: 160px;
  padding: 4px 0;
  margin: 0;
  list-style: none;
  background-color: white;
  border-color: #CCC;
  border-color: rgba(0, 0, 0, 0.2);
  border-style: solid;
  border-width: 1px;
  -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
  -webkit-background-clip: padding-box;
  -moz-background-clip: padding;
  background-clip: padding-box;
  margin-top: 2px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}

.typeahead li {
  line-height: 18px;
  display: list-item;
}

.typeahead a {
  display: block;
  padding: 3px 15px;
  clear: both;
  font-weight: normal;
  line-height: 18px;
  color: #333;
  white-space: nowrap;
}

.typeahead li > a:hover, .typeahead .active > a, .typeahead .active > a:hover {
  color: white;
  text-decoration: none;
  background-color: #08C;
}

.typeahead a {
  color: #08C;
  text-decoration: none;
}

/*context menu rules*/
ul.context-menu-list {
  color: black;
}

ul.context-menu-list li {
  margin-bottom: 0; /*Foundation framework fix*/
}

/**
 * dragdealer
 */

.handsontable .dragdealer {
  position: relative;
  width: 9px;
  height: 9px;
  background: #F8F8F8;
  border: 1px solid #DDD;
}

.handsontable .dragdealer .handle {
  position: absolute;
  width: 9px;
  height: 9px;
  background: #C5C5C5;
}

.handsontable .dragdealer .disabled {
  background: #898989;
}


text:
import {Component, OnDestroy, OnInit} from '@angular/core';
import {Account} from '../../services/accounting/domain/account.model';
import {ActivatedRoute} from '@angular/router';
import * as fromAccounting from '../store';
import * as fromRoot from '../../store';
import {Subscription} from 'rxjs/Subscription';
import {AccountingStore} from '../store/index';
import {DELETE, SelectAction} from '../store/account/account.actions';
import {Observable} from 'rxjs/Observable';
import {FimsPermission} from '../../services/security/authz/fims-permission.model';
import {TranslateService} from '@ngx-translate/core';
import {TdDialogService} from '@covalent/core';

@Component({
  templateUrl: './account.detail.component.html'
})
export class AccountDetailComponent implements OnInit, OnDestroy {

  private actionsSubscription: Subscription;

  private accountSubscription: Subscription;

  canDelete$: Observable<boolean>;

  account: Account;

  constructor(private route: ActivatedRoute, private dialogService: TdDialogService, private translate: TranslateService,
              private store: AccountingStore) {
  }

  ngOnInit(): void {
    this.actionsSubscription = this.route.params
      .map(params => new SelectAction(params['id']))
      .subscribe(this.store);

    const account$: Observable<Account> = this.store.select(fromAccounting.getSelectedAccount)
      .filter(account => !!account);

    this.canDelete$ = Observable.combineLatest(
      this.store.select(fromRoot.getPermissions),
      account$,
      (permissions, account: Account) => ({
        hasPermission: this.hasDeletePermission(permissions),
        isAccountClosed: account.state === 'CLOSED'
      }))
      .map(result => result.hasPermission && result.isAccountClosed);

    this.accountSubscription = account$
      .subscribe(account => this.account = account);
  }

  private hasDeletePermission(permissions: FimsPermission[]): boolean {
    return permissions.filter(permission =>
      permission.id === 'accounting_accounts' &&
      permission.accessLevel === 'DELETE'
    ).length > 0;
  }

  ngOnDestroy(): void {
    this.actionsSubscription.unsubscribe();
    this.accountSubscription.unsubscribe();
  }

  confirmDeletion(): Observable<boolean> {
    const message = 'Do you want to delete this account?';
    const title = 'Confirm deletion';
    const button = 'DELETE ACCOUNT';

    return this.translate.get([title, message, button])
      .flatMap(result =>
        this.dialogService.openConfirm({
          message: result[message],
          title: result[title],
          acceptButton: result[button]
        }).afterClosed()
      );
  }

  deleteAccount(): void {
    this.confirmDeletion()
      .filter(accept => accept)
      .subscribe(() => {
        this.store.dispatch({
          type: DELETE, payload: {
            account: this.account,
            activatedRoute: this.route
          }
        });
      });
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dicom {
	internal static class StringExtensions {
		public static bool IsDigits(this string s) {
			foreach (char c in s)
				if (!Char.IsDigit(c))
					return false;
			return true;
		}

		public static bool ListContains(this string s, char separator, string value) {
			var parts = s.Split(separator);
			foreach (string part in parts) {
				if (part.Trim() == value)
					return true;
			}
			return false;
		}

		/// <summary>
		/// Array of valid wildcards
		/// </summary>
		private static char[] Wildcards = new char[] { '*', '?' };

		/// <summary>
		/// Returns true if the string matches the pattern which may contain * and ? wildcards.
		/// Matching is done without regard to case.
		/// </summary>
		/// <param name="pattern"></param>
		/// <param name="s"></param>
		/// <returns></returns>
		public static bool Wildcard(this string s, string pattern) {
			return Wildcard(s, pattern, false);
		}

		/// <summary>
		/// Returns true if the string matches the pattern which may contain * and ? wildcards.
		/// </summary>
		/// <param name="pattern"></param>
		/// <param name="s"></param>
		/// <param name="caseSensitive"></param>
		/// <returns></returns>
		public static bool Wildcard(this string s, string pattern, bool caseSensitive) {
			// if not concerned about case, convert both string and pattern
			// to lower case for comparison
			if (!caseSensitive) {
				pattern = pattern.ToLower();
				s = s.ToLower();
			}

			// if pattern doesn't actually contain any wildcards, use simple equality
			if (pattern.IndexOfAny(Wildcards) == -1)
				return (s == pattern);

			// otherwise do pattern matching
			int i = 0;
			int j = 0;
			while (i < s.Length && j < pattern.Length && pattern[j] != '*') {
				if ((pattern[j] != s[i]) && (pattern[j] != '?')) {
					return false;
				}
				i++;
				j++;
			}

			// if we have reached the end of the pattern without finding a * wildcard,
			// the match must fail if the string is longer or shorter than the pattern
			if (j == pattern.Length)
				return s.Length == pattern.Length;

			int cp = 0;
			int mp = 0;
			while (i < s.Length) {
				if (j < pattern.Length && pattern[j] == '*') {
					if ((j++) >= pattern.Length) {
						return true;
					}
					mp = j;
					cp = i + 1;
				} else if (j < pattern.Length && (pattern[j] == s[i] || pattern[j] == '?')) {
					j++;
					i++;
				} else {
					j = mp;
					i = cp++;
				}
			}

			while (j < pattern.Length && pattern[j] == '*') {
				j++;
			}

			return j >= pattern.Length;
		}
	}
}


text:
var $ = require('jquery'),
    Mn = require('backbone.marionette');

var LocaleItem = Mn.ItemView.extend({
  template: '#locale_tmpl',
  tagName: 'li',
  events: {
    'click a': 'highlight'
  },

  highlight: function(e){
    e.preventDefault();
    this.model.trigger('highlight');
  }
});

var LocaleCollection = Mn.CompositeView.extend({
  childView: LocaleItem,
  childViewContainer: 'ul',
  template: '#locales_tmpl',
  collectionEvents: {
    highlight: 'onHighlight'
  },

  initialize: function(){
    this.model = this.collection.findWhere({current: true});
  },

  onHighlight: function(){
    this.model = this.collection.findWhere({current: true});
    this.render();
  },

  onRender: function(){
    $('.dropdown-toggle', this.el).dropdown()
  }
});

module.exports = LocaleCollection;


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Networking.Connectivity;
using Windows.UI.Core;

namespace SecuritySystemUWP
{
    /// <summary>
    /// Main page of the app
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private CoreDispatcher _MainPageDispatcher = null;

        public MainPage()
        {
            this.InitializeComponent();

            _MainPageDispatcher = Window.Current.Dispatcher;

            // network status change event
            NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;

            // get static device environment info and display it in UI
            appVersionValueTextBlock.Text = EnvironmentSettings.GetAppVersion();
            OSVersionValueTextBlock.Text = EnvironmentSettings.GetOSVersion();

            UpdateNetworkInfo();

        }

        /// <summary>
        /// On network status change update network info and display on main page
        /// </summary>
        /// <param name="sender"></param>
        private async void NetworkInformation_NetworkStatusChanged(object sender)
        {
            await _MainPageDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                UpdateNetworkInfo();
            });
        }

        /// <summary>
        /// Get dynamic network information about the device and display it
        /// </summary>
        private void UpdateNetworkInfo()
        {
            string ipAddress = EnvironmentSettings.GetIPAddress();
            string instructions = "";
            // check if ip address is valid
            if (ipAddress == "0.0.0.0")
            {
                ipAddress = "Invalid IP Address: 0.0.0.0";
                instructions = "Setup Instructions: Please ensure your device has a valid ip address first.";
            }
            else {
                instructions = "Setup Instructions: To configure this security system please go to URL http://" + ipAddress + ":8000 on a browser.";
            }

            // update UI
            deviceNameValueTextBlock.Text = EnvironmentSettings.GetDeviceName();
            ipAddressValueTextBlock.Text = ipAddress;
            instructionsTextBlock.Text = instructions;
        }
    }
}


text:
<?php

namespace RelayPoint\MondialRelay\Test;

use RelayPoint\MondialRelay\OpeningHoursParser;

class OpeningHoursParserTest extends \PHPUnit_Framework_TestCase
{
	/**
	 * Parser object.
	 *
	 * @var OpeningHoursParser
	 */
	protected $openingHoursParser;

	public function setUp()
	{
		parent::setUp();
		$this->openingHoursParser = new OpeningHoursParser();
	}

	public function testParse()
	{
		$relayPoint = new \stdClass();
		$relayPoint->Horaires_Lundi = new \stdClass();
		$relayPoint->Horaires_Lundi->string = array('0800', '1900');

		$relayPoint->Horaires_Mardi = new \stdClass();
		$relayPoint->Horaires_Mardi->string = array('0800', '1900');

		$relayPoint->Horaires_Mercredi = new \stdClass();
		$relayPoint->Horaires_Mercredi->string = array('0800', '1900');

		$relayPoint->Horaires_Jeudi = new \stdClass();
		$relayPoint->Horaires_Jeudi->string = array('0800', '1900');

		$relayPoint->Horaires_Vendredi = new \stdClass();
		$relayPoint->Horaires_Vendredi->string = array('0800', '1200', '1400', '1900');

		$relayPoint->Horaires_Samedi = new \stdClass();
		$relayPoint->Horaires_Samedi->string = array('0800', '1400');

		$relayPoint->Horaires_Dimanche = new \stdClass();
		$relayPoint->Horaires_Dimanche->string = array('0000', '0000', '0000', '0000');

		$actual = $this->openingHoursParser->parse($relayPoint);

		$expected = array(
			'Lundi' => '08:00 - 19:00',
			'Mardi' => '08:00 - 19:00',
			'Mercredi' => '08:00 - 19:00',
			'Jeudi' => '08:00 - 19:00',
			'Vendredi' => '08:00 - 12:00 14:00 - 19:00',
			'Samedi' => '08:00 - 14:00',
			'Dimanche' => 'Fermé',
		);

		$this->assertEquals($expected, $actual);
	}
}


text:
import { Fab, makeStyles, Toolbar } from '@material-ui/core';
import Container from '@material-ui/core/Container';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import AddIcon from '@material-ui/icons/Add';
import { GetServerSideProps, NextPage } from 'next';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { InviteUserModal } from '../../../components/organizations/invite-user-modal';
import { OrganizationDetails } from '../../../components/organizations/organization-details';
import { UserList } from '../../../components/organizations/user-list';
import { useAuthenticatedUser } from '../../../src/use-authenticated-user.hook';
import { listVisible } from '../../../store/common/list-state.models';
import { loadOrganization, loadOrganizationUsers } from '../../../store/organizations/organizations.actions';
import { RootState } from '../../../store/store';

interface OrganizationProps {
  organizationId: string;
}

const useStyles = makeStyles((theme) => ({
  container: {
    paddingTop: theme.spacing(4),
    paddingBottom: theme.spacing(4),
  },
  paper: {
    padding: theme.spacing(2),
  },
  organizationUsersList: {
    minHeight: theme.spacing(30),
    maxHeight: theme.spacing(60),
    overflow: 'auto',
  },
  organizationUsersListTitle: {
    flex: '1 1 100%',
  },
  organizationUsersListToolbar: {
    paddingLeft: theme.spacing(2),
    paddingRight: theme.spacing(2),
  },
}));

const OrganizationPage: NextPage<OrganizationProps> = ({ organizationId }) => {
  const classes = useStyles();
  const dispatch = useDispatch();

  const { user } = useAuthenticatedUser(['https://swetuggtixdev.onmicrosoft.com/tix-api/access_as_backoffice']);

  useEffect(() => {
    if (user.current?.userId) {
      dispatch(loadOrganization(organizationId));
      dispatch(loadOrganizationUsers(organizationId));
    }
  }, [user.current, organizationId]);

  const [inviteUserModalOpen, setInviteUserModalOpen] = useState(false);

  const onInviteUserButtonClick = () => {
    setInviteUserModalOpen(true);
  };

  const organizations = useSelector((r: RootState) => r.organizations);

  const organization = organizations.organizations.models[organizationId];
  const users = listVisible(organizations.organizationUsers);

  return (
    <React.Fragment>
      {organization && (
        <Container maxWidth={false} className={classes.container}>
          <Typography variant="h4" component="h1" gutterBottom>
            {organization.name}
          </Typography>
          <Grid container spacing={3}>
            <Grid item xs={12} md={5}>
              <Grid container spacing={2}>
                <Grid item xs={12}>
                  <Paper className={classes.paper}>
                    <OrganizationDetails organization={organization} />
                  </Paper>
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Paper className={classes.paper}>
                <Toolbar className={classes.organizationUsersListToolbar}>
                  <Typography className={classes.organizationUsersListTitle} variant="h6" component="div">
                    Users
                  </Typography>
                  <Fab size="small" color="primary" onClick={onInviteUserButtonClick}>
                    <AddIcon />
                  </Fab>
                  <InviteUserModal
                    organizations={organizations}
                    organizationId={organizationId}
                    open={inviteUserModalOpen}
                    setOpen={setInviteUserModalOpen}
                  />
                </Toolbar>
                <UserList organization={organization} users={users} />
              </Paper>
            </Grid>
          </Grid>
        </Container>
      )}
    </React.Fragment>
  );
};

export default OrganizationPage;

export const getServerSideProps: GetServerSideProps = async ({ params, query }) => {
  const organizationId = params?.organizationId;

  return {
    props: {
      organizationId: organizationId,
    },
  };
};


text:
layout: staff-member
name: Candy Pang
website: "https://www.linkedin.com/in/candypang"
profile_photo_path_staff: "image/girl.png"
position: Researcher
status: current
title: phd
---


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:icon="@mipmap/ic_launcher"
            android:title="test" />

        <item
            android:icon="@mipmap/ic_launcher"
            android:title="test" />

        <item
            android:icon="@mipmap/ic_launcher"
            android:title="test" />

        <item
            android:icon="@mipmap/ic_launcher"
            android:title="test" />
    </group>

</menu>


text:
'use strict';

defineParticle(({SimpleParticle, html, log}) => {

  return class extends SimpleParticle {
    get template() {
      return `<span>{{json}}<span>`;
    }
    render(props, state) {
      if (state.count === undefined) {
        state.count = 10;
      }
      if (!state.async && state.count--) {
        // TODO(lindner): Convert to use Random service
        const dur = Math.floor(Math.random()*10);
        log(`will update in ${dur}s`);
        state.async = setTimeout(() => {
          const json = JSON.stringify(`The time is now ${new Date().toLocaleTimeString()}`);
          this.set('output', {json});
          log(`set output to`, json);
          this.setState({async: null, json});
        }, dur*1000) + 1;
      }
      return state;
    }
  };

});


text:
package org.redisson.spring.support;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.Assert;
import org.w3c.dom.Element;

/**
 *
 * @author Rui Gu (https://github.com/jackygurui)
 */
public class RedissonLiveObjectDefinitionParser
    extends AbstractRedissonNamespaceDefinitionParser {

    public RedissonLiveObjectDefinitionParser(RedissonNamespaceParserSupport helper) {
        super(helper, RedissonNamespaceParserSupport.LIVE_OBJECT_SERVICE_REF_ATTRIBUTE);
    }

    @Override
    protected void parseNested(Element element, ParserContext parserContext, BeanDefinitionBuilder builder, BeanDefinition bd) {
        Class<?> apiClass;
        try {
            apiClass = Class.forName(helper.getAttribute(element,
                    RedissonNamespaceParserSupport.CLASS_ATTRIBUTE));
        } catch (ClassNotFoundException ex) {
            throw new IllegalArgumentException(
                    "The class [" + helper.getAttribute(element,
                            RedissonNamespaceParserSupport.CLASS_ATTRIBUTE)
                    + "] specified in \"api-class\" attribute has not "
                    + "found. Please check the class path.", ex);
        }
        Assert.state(helper.hasAttribute(element,
                RedissonNamespaceParserSupport.OBJECT_ID_ATTRIBUTE)
                || helper.hasAttribute(element,
                        RedissonNamespaceParserSupport.OBJECT_ID_REF_ATTRIBUTE),
                "One of \""
                + RedissonNamespaceParserSupport.OBJECT_ID_ATTRIBUTE
                + "\" or \""
                + RedissonNamespaceParserSupport.OBJECT_ID_REF_ATTRIBUTE
                + "\" attribute is required in the \""
                + RedissonNamespaceParserSupport.LIVE_OBJECT_ELEMENT
                + "\" element.");
        builder.addPropertyValue("targetObject", new RuntimeBeanReference(
                helper.getAttribute(element,
                        RedissonNamespaceParserSupport.LIVE_OBJECT_SERVICE_REF_ATTRIBUTE)));
        builder.addPropertyValue("targetMethod", "get");
        ManagedList args = new ManagedList();
        args.add(apiClass);
        if (helper.hasAttribute(element,
                RedissonNamespaceParserSupport.OBJECT_ID_ATTRIBUTE)) {
            args.add(helper.getAttribute(element,
                    RedissonNamespaceParserSupport.OBJECT_ID_ATTRIBUTE));
        }
        if (helper.hasAttribute(element,
                RedissonNamespaceParserSupport.OBJECT_ID_REF_ATTRIBUTE)) {
            args.add(new RuntimeBeanReference(
                    helper.getAttribute(element,
                            RedissonNamespaceParserSupport.OBJECT_ID_REF_ATTRIBUTE)));
        }
        builder.addPropertyValue("arguments", args);
    }

    @Override
    protected Class<?> getBeanClass(Element element) {
        return MethodInvokingFactoryBean.class;
    }

}


text:
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#ifndef _RAO_FONTMAP_H_
#define _RAO_FONTMAP_H_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

class CPDFSDK_Annot;

class CBA_FontMap : public CPWL_FontMap
{
public:
	CBA_FontMap(CPDFSDK_Annot* pAnnot, IFX_SystemHandler* pSystemHandler);
	CBA_FontMap(CPDF_Document* pDocument, CPDF_Dictionary* pAnnotDict, IFX_SystemHandler* pSystemHandler);

	virtual ~CBA_FontMap();

	virtual void				Initial(FX_LPCSTR fontname = NULL);

public:
	void						SetDefaultFont(CPDF_Font * pFont, const CFX_ByteString & sFontName);

	void						Reset();
	void						SetAPType(const CFX_ByteString& sAPType);

protected:
	virtual CPDF_Font*			FindFontSameCharset(CFX_ByteString& sFontAlias, FX_INT32 nCharset);
	virtual void				AddedFont(CPDF_Font* pFont, const CFX_ByteString& sFontAlias);
	virtual CPDF_Document*		GetDocument();
private:
	CPDF_Font*					FindResFontSameCharset(CPDF_Dictionary* pResDict, CFX_ByteString& sFontAlias,
									FX_INT32 nCharset);
	CPDF_Font*					GetAnnotDefaultFont(CFX_ByteString &csNameTag);
	void						AddFontToAnnotDict(CPDF_Font* pFont, const CFX_ByteString& sAlias);

private:
	CPDF_Document*				m_pDocument;
	CPDF_Dictionary*			m_pAnnotDict;
	CPDF_Font*					m_pDefaultFont;
	CFX_ByteString				m_sDefaultFontName;

	CFX_ByteString				m_sAPType;
};

#endif // _RAO_FONTMAP_H_


text:
load(libdir + "parallelarray-helpers.js");

function testFilterNone() {
  // Test filtering (removing everything)
  var p = new ParallelArray([0,1,2,3,4]);
  var none = p.map(function () { return false; });
  var r = p.filter(none);
  assertEqParallelArray(r, new ParallelArray);
  var p = new ParallelArray([5,2], function(i,j) { return i+j; });
  var r = p.filter(none);
  assertEqParallelArray(r, new ParallelArray);
}

testFilterNone();


text:
function Controller() {
    function signChange(e) {
        var imageView;
        Ti.API.info(e);
        imageView = Ti.UI.createImageView({
            image: e.data
        });
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "index";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    var __defers = {};
    $.__views.index = Ti.UI.createWindow({
        backgroundColor: "white",
        id: "index"
    });
    $.__views.index && $.addTopLevelView($.__views.index);
    $.__views.signView = Alloy.createWidget("jp.co.mountposition.signview", "widget", {
        id: "signView",
        __parentSymbol: $.__views.index
    });
    $.__views.signView.setParent($.__views.index);
    signChange ? $.__views.signView.on("change", signChange) : __defers["$.__views.signView!change!signChange"] = true;
    exports.destroy = function() {};
    _.extend($, $.__views);
    exports.destroy = function() {
        $.signView.destroy();
    };
    $.index.open();
    __defers["$.__views.signView!change!signChange"] && $.__views.signView.on("change", signChange);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
import { Definition } from 'ember-fsm';
import { module, test } from 'qunit';

function create(args) {
  return new Definition(args);
}

function build(transitions) {
  return create({
    states: { initialState: 'a' },
    events: { run: { transitions: transitions } }
  }).transitionsFor('run');
}

module('Unit: ember-fsm/-definition', function() {
  test('Instantiation', function(assert) {
    assert.throws(function() {
      Definition({ events: {} }); // jshint ignore:line
    }, TypeError, 'requires new operator be used');

    assert.throws(function() {
      create({ states: { }});
    }, TypeError, 'requires an "events" property');

    assert.throws(function() {
      create({ events: true });
    }, TypeError, 'requires "events" property to be an object');

    assert.throws(function() {
      create({ events: {}, states: true });
    }, TypeError, 'requires "states" property to be an object (if passed)');

    assert.strictEqual(create({
      events: {
        poke: {
          transitions: [
            { initialized: 'annoyed' }
          ]
        }
      }
    }).initialState, 'initialized', 'initial state is set to default if not provided');

    assert.throws(function() {
      create({ events: {} });
    }, /at least one/, 'requires at least one event');
  });

  test('Explicitly defined states', function(assert) {
    assert.throws(function() {
      create({
        states: {
          knownStates: ['initialized', 'farting']
        },
        events: {
          fart: {
            transitions: { initialized: 'farting' }
          },
          shart: {
            transitions: { farting: 'soiled' }
          }
        }
      });
    }, /not a defined state/, 'does not allow transitions to specify unlisted states');

    assert.throws(function() {
      create({
        states: {
          initialState: 'wiggling',
          explicitStates: ['wiggling', 'wobbling', 'farting']
        },
        events: {
          wiggle: {
            transitions: [
              { wiggling: 'wobbling' }
            ]
          }
        }
      });
    }, /is not used/, 'does not allow specified states to be unused');
  });
});

module('Unit: ember-fsm/-definition - compilation', function() {
  test('state callbacks', function(assert) {
    let def = create({
      states: {
        initialized: {
          willEnter: 'barkLikeDog',
          willExit:  ['sadface', 'eatMemory']
        }
      },
      events: {
        run: {
          transitions: { initialized: 'hihihi' }
        }
      }
    });

    let s = def.lookupState('initialized');

    assert.deepEqual(s.willEnter, ['barkLikeDog'], 'tracks callbacks');
    assert.deepEqual(s.willExit, ['sadface', 'eatMemory'], 'tracks callbacks');
  });

  test('aliases "transition" to "transitions"', function(assert) {
    let def = create({
      events: {
        amaze: {
          transition: { initialized: 'x' }
        }
      }
    });

    assert.strictEqual(def.stateNames.length, 2);
    assert.deepEqual(def.stateNames, ['x', 'initialized']);
  });
});

module('Unit: ember-fsm/-definition - Unwinding transitions', function() {
  test('$all macro', function(assert) {
    let def = create({
      states: {
        initialState: 'a'
      },
      events: {
        reset: { transitions: { $all: 'a' } },
        fobble: { transitions: { a: 'x' } },
        doggle: { transitions: { a: 'y' } },
        wobble: { transitions: { a: 'z' } }
      }
    });

    ['a', 'x', 'y', 'z'].forEach((fromState) => {
      let t = def.transitionsFor('reset', fromState);
      assert.strictEqual(t.length, 1, 'expands $all to all other known states');
      assert.strictEqual(t[0].fromState, fromState, 'expands $all to all other known states');
    });
  });

  test('$same macro', function(assert) {
    let def = create({
      events: {
        toA: {
          transitions: [
            { initialized: 'a' },
            { a: '$same' }
          ]
        }
      }
    });

    let t = def.transitionsFor('toA', 'a');

    assert.strictEqual(t.length, 1, 'replaces $same with the state specified in fromState');
    assert.strictEqual(t[0].toState, 'a', 'replaces $same with the state specified in fromState');
  });

  test('$initial macro (replaces $initial with initial state)', function(assert) {
    let def = create({
      states: {
        $initial: {
          willEnter: 'sayHello'
        }
      },
      events: {
        one: { transition: { $initial: 'a' } },
        two: { transition: { a: '$initial', willEnter: 'waveHello' } }
      }
    });

    let t0 = def.transitionsFor('one', '$initial');
    let t1 = def.transitionsFor('two', 'a');
    let s  = def.lookupState('$initial');

    assert.strictEqual(t0.length, 1);
    assert.strictEqual(t0[0].toState, 'a');
    assert.strictEqual(t1.length, 1);
    assert.strictEqual(t1[0].toState, 'initialized');
    assert.deepEqual(t1[0].willEnter, ['waveHello']);
    assert.strictEqual(s.willEnter.length, 1);
    assert.strictEqual(s.willEnter[0], 'sayHello');
  });

  test('allows multiple guarded transitions with the same from state', function(assert) {
    let def = create({
      states: { initialState: 'off' },
      events: {
        run: {
          transitions: [
            { on: '$same' },
            { off: 'on', unless: 'isWarm' },
            { off: 'on', guard: 'hasPower' },
            { off: 'off' }
          ]
        }
      }
    });

    let t = def.transitionsFor('run', 'off');

    assert.strictEqual(t.length, 3);
    assert.strictEqual(t[0].isGuarded, true);
    assert.strictEqual(t[0].doUnless, 'isWarm');
    assert.strictEqual(t[1].isGuarded, true);
    assert.strictEqual(t[1].doIf, 'hasPower');
    assert.strictEqual(t[2].isGuarded, false);
  });

  test('validations', function(assert) {
    assert.throws(function() {
      create({
        states: { initialState: 'off' },
        events: {
          run: {
            transitions: [
              { on: '$same' },
              { off: 'on', unless: 'isWarm' },
              { off: 'on', guard: 'hasPower' },
              { off: 'off' },
              { off: 'fail' }
            ]
          }
        }
      });
    }, /more than one/, 'allows no more than one guarded transition with the same from state');

    assert.throws(function() {
      create({
        events: {
          pedal: {
            transitions: {
              'initialized':    'mounting',
              'mounting':       'moving.slowly',
              'moving.slowly':  'moving.quickly',
              'moving.quickly': '$same'
            }
          }
        }
      });
      // The reason why is that the order of object properties isn't guarenteed
      // and it's vital that transition order is maintained
    }, /only one .+ per object/, 'does not allow multiple transitions per transition definition');

    assert.throws(function() {
      create({
        states: { initialState: 'off' },
        events: {
          run: {
            transitions: [
              { on: '$same' },
              { off: 'on' },
              { off: 'on' }
            ]
          }
        }
      });
    }, /more than one/, 'does not allow unguarded transitions with the same from state');
  });

  test('Unwinding transitions - tracks potential exit transitions for each state', function(assert) {
    let def = create({
      states: { initialState: 'a' },
      events: {
        one: {
          transition: { a: 'b' }
        },

        two: {
          transition: { a: 'b' }
        }
      }
    });

    let a = def.lookupState('a');

    assert.strictEqual(a.exitTransitions.length, 2);
    assert.strictEqual(a.exitTransitions[0].toState, 'b');
    assert.strictEqual(a.exitTransitions[0].event, 'one');
    assert.strictEqual(a.exitTransitions[1].toState, 'b');
    assert.strictEqual(a.exitTransitions[1].event, 'two');
  });

  test('tracks potential entry transitions for each state', function(assert) {
    let def = create({
      states: { initialState: 'a' },
      events: {
        one: {
          transition: { b: 'a' }
        },

        two: {
          transition: { c: 'a' }
        }
      }
    });

    let a = def.lookupState('a');
    let b = def.lookupState('b');

    assert.strictEqual(a.enterTransitions.length, 2);
    assert.strictEqual(a.enterTransitions[0].fromState, 'b');
    assert.strictEqual(a.enterTransitions[0].event, 'one');
    assert.strictEqual(a.enterTransitions[1].fromState, 'c');
    assert.strictEqual(a.enterTransitions[1].event, 'two');
    assert.strictEqual(b.exitTransitions[0].toState, 'a');
    assert.strictEqual(b.enterTransitions.length, 0);
  });
});

module('Unit: ember-fsm/-definition - Unwound transitions', function() {
  test('sets array properties to be arrays', function(assert) {
    let t = build([
      { a: 'b', before: 'doTing' },
      { d: 'e', willEnter: 'doTing' },
      { f: 'g', didEnter: 'doTing' },
      { h: 'i', willExit: 'doTing' },
      { j: 'k', didExit: 'doTing' },
      { b: 'c', after: 'doTing' }
    ]);

    assert.deepEqual(t[0].beforeEvent, ['doTing']);
    assert.deepEqual(t[1].willEnter, ['doTing']);
    assert.deepEqual(t[2].didEnter, ['doTing']);
    assert.deepEqual(t[3].willExit, ['doTing']);
    assert.deepEqual(t[4].didExit, ['doTing']);
    assert.deepEqual(t[5].afterEvent, ['doTing']);
  });

  test('passes through non-array properties', function(assert) {
    let t = build([
      { a: 'b', guard: 'hasTing' },
      { b: 'c', unless: 'hasTing' }
    ]);

    assert.strictEqual(t[0].doIf, 'hasTing');
    assert.strictEqual(t[1].doUnless, 'hasTing');
  });

  test('allows fromStates and toState to be passed as named properties', function(assert) {
    let t = build({ from: 'a', to: 'b' });

    assert.strictEqual(t[0].fromState, 'a');
    assert.strictEqual(t[0].toState, 'b');
  });

  test('allows multiple fromStates to be specified in one transition', function(assert) {
    let t = build({ from: ['a', 'b'], to: 'c' });

    assert.strictEqual(t.length, 2);
    assert.strictEqual(t[0].fromState, 'a');
    assert.strictEqual(t[0].toState, 'c');
    assert.strictEqual(t[1].fromState, 'b');
    assert.strictEqual(t[1].toState, 'c');
  });
});

module('Unit: ember-fsm/-definition - Public API', function() {
  let fsmDef = create({
    events: {
      one: {
        transitions: { initialized: 'a' }
      },

      two: {
        transitions: { a: 'b' }
      },

      three: {
        transitions: [
          { b: 's1' },
          { s1: 's1.sub1' },
          { 's1.sub1': 's1.sub2' },
          { 's1.sub2': 's1.sub2.sub1' },
          { 'ns.s1': 'ns.s2' }
        ]
      }
    }
  });

  test('provides eventNames', function(assert) {
    assert.strictEqual(fsmDef.eventNames.length, 3);
    assert.deepEqual(fsmDef.eventNames, ['one', 'two', 'three']);
  });

  test('provides events', function(assert) {
    assert.strictEqual(fsmDef.events.length, 3);
    assert.deepEqual(fsmDef.events.map((e) => e.name), ['one', 'two', 'three']);
  });

  test('provides stateNames', function(assert) {
    assert.strictEqual(fsmDef.stateNames.length, 9);
    assert.deepEqual(fsmDef.stateNames, [
      'a', 'initialized', 'b', 's1', 's1.sub1', 's1.sub2',
      's1.sub2.sub1', 'ns.s2', 'ns.s1'
    ]);
  });

  test('provides states', function(assert) {
    assert.strictEqual(fsmDef.states.length, 9);
    assert.deepEqual(fsmDef.states.map((s) => s.name), [
      'a', 'initialized', 'b', 's1', 's1.sub1', 's1.sub2',
      's1.sub2.sub1', 'ns.s2', 'ns.s1'
    ]);
  });

  test('can look up a state by name', function(assert) {
    assert.deepEqual(fsmDef.lookupState('a').name, 'a');
  });

  test('throws an error if requested to look up a state that doesn\'t exist', function(assert) {
    assert.throws(function() {
      fsmDef.lookupState('herp');
    }, /is not defined/);
  });

  test('can look up states by prefix', function(assert) {
    assert.strictEqual(fsmDef.lookupStates('s1').length, 4);
  });

  test('can look up states by namespace', function(assert) {
    assert.strictEqual(fsmDef.lookupStates('ns').length, 2);
  });

  test('throws an error if requested to lookup a state or prefix with no result', function(assert) {
    assert.throws(function() {
      fsmDef.lookupStates('herp');
    }, /no states or substates defined/);
  });

  test('knows that namespaces are not states', function(assert) {
    assert.throws(function() {
      fsmDef.lookupState('ns');
    }, /is not defined/);
  });

  test('provides a list of state prefixes', function(assert) {
    assert.deepEqual(fsmDef.stateNamespaces, ['s1', 's1.sub2', 'ns']);
  });

  test('can look up events by name', function(assert) {
    assert.strictEqual(fsmDef.lookupEvent('one').name, 'one');
  });

  test('can look up transitions by event', function(assert) {
    assert.strictEqual(fsmDef.transitionsFor('one').length, 1);
  });

  test('can look up transitions by event and starting state', function(assert) {
    assert.strictEqual(fsmDef.transitionsFor('one', 'initialized').length, 1);
    assert.strictEqual(fsmDef.transitionsFor('one', 'b').length, 0);
  });
});


text:
package com.azavea.androidvalidatedforms;

import android.content.Intent;

/**
 * Created by kathrynkillebrew on 2/1/16.
 */
public interface IntentResultListener {
    void gotIntentResult(int requestCode, int resultCode, Intent resultData);
}