text:
|Build Status| |Coverage Status| |PyPI Version| |PyPI Downloads| |Wheel Status|

python-envcfg
=============

Accessing environment variables with a magic module.

::

    >>> import os
    >>> from envcfg.raw.python import CONFIGURE_OPTS
    >>>
    >>> CONFIGURE_OPTS
    '--enable-shared --enable-universalsdk=/ --with-universal-archs=intel'
    >>> CONFIGURE_OPTS == os.environ['PYTHON_CONFIGURE_OPTS']
    True

It works with many frameworks such as Django and Flask. Then you can store your
config in the environment variables instead of framework-specific config files.
It is recommended by 12-Factor_.

Installation
------------

::

    $ pip install python-envcfg

Supported Formats
-----------------

- ``import envcfg.raw.foo as config``:
  Import each ``FOO_*`` environment variable as string.
- ``import envcfg.json.foo as config``:
  Import each ``FOO_*`` environment variable as JSON body.
- ``import envcfg.smart.foo as config``:
  Try to import each ``FOO_*`` environment variable as JSON body, if fail then import it as string.

There is an example:

+-------------------+------------------------+-------------------------+--------------------------+
|                   | ``envcfg.raw.foo.VAL`` | ``envcfg.json.foo.VAL`` | ``envcfg.smart.foo.VAL`` |
+===================+========================+=========================+==========================+
| ``FOO_VAL=foo``   | ``'foo'``              | ``ImportError``         | ``'foo'``                |
+-------------------+------------------------+-------------------------+--------------------------+
| ``FOO_VAL="foo"`` | ``'"foo"'``            | ``'foo'``               | ``'foo'``                |
+-------------------+------------------------+-------------------------+--------------------------+
| ``FOO_VAL=42``    | ``'42'``               | ``42``                  | ``42``                   |
+-------------------+------------------------+-------------------------+--------------------------+
| ``FOO_VAL="42"``  | ``'"42"'``             | ``'42'``                | ``'42'``                 |
+-------------------+------------------------+-------------------------+--------------------------+

Framework Integration
---------------------

Flask
~~~~~

1. Defines environment variables with a prefix::

    $ cat .env  # should not checked into VCS
    # values are valid JSON expressions
    MYAPP_DEBUG=true
    MYAPP_SECRET_KEY='"7950ad141c7e4b3990631fcdf9a1d909"'
    MYAPP_SQLALCHEMY_DATABASE_URI='"sqlite:///tmp/myapp.sqlite3"'

2. Creates Flask app and loads config from python-envcfg::

    $ cat myapp.py
    ...
    app = Flask(__name__)
    app.config.from_object('envcfg.json.myapp')  # MYAPP_ -> .myapp
    ...

3. Enters your app with those environment variables::

    $ env $(cat .env | xargs) python myapp.py

Django
~~~~~~

1. Creates a django project and moves all sensitive config items into the
   environment variables::

    $ cat djapp/settings.py  # codebase-scope config
    ...
    INSTALLED_APPS = (
        'django.contrib.admin',
    )
    ...

    $ cat .env  # environment-scope config, should not checked into VCS
    # values are valid JSON expressions
    DJAPP_SECRET_KEY='"wo9g2o#jws=u"'
    DJAPP_DEBUG=true
    DJAPP_TEMPLATE_DEBUG=true

2. Adds importing statements in the end of ``settings.py`` module::

    $ tail -n 2 djapp/settings.py
    # importing all config items stored in the environment variables
    from envcfg.json.djapp import *  # noqa

3. Runs your Django app with environment variables::

    $ env $(cat .env | xargs) python manage.py runserver

Tornado
~~~~~~~

1. Defines environment variables with a prefix::

    $ cat .env
    export TORAPP_PORT='8888'
    export TORAPP_MYSQL_HOST='"127.0.0.1"'
    export TORAPP_MYSQL_DATABASE='"database"'

2. Creates a Tornado project and loads config::

    $ cat torapp/server.py

    from tornado.web import Application, RequestHandler
    from tornado.ioloop import IOLoop
    from tornado.options import define, options
    from tordb import Connection

    def options_from_object(*args, **kwargs):
        module = __import__(*args, **kwargs)
        for name, value in vars(module).items():
            name = name.lower()
            if name in options._options:
                options._options[name].set(value)

    class IndexHandler(RequestHandler):
        def initialize(self):
            self.db = Connection(options.mysql_host, options.mysql_database)

        def get(self):
            pass  # some database operations with ``self.db``

    application = Application([
        (r'/', IndexHandler),
    ])

    define('port', type=int)
    define('mysql_host', type=unicode)
    define('mysql_database', type=unicode)
    options_from_object('envcfg.json.torapp', fromlist=['torapp'])

    if __name__ == '__main__':
        application.listen(options.port)
        IOLoop.instance().start()

3. Runs your Tornado app::

   $ env $(cat .env | xargs) python server.py

Works on Projects
-----------------

In development, we can work with per-project environments but no more typing
``source foo/bar``.

I recommend to put your project-specified environment variables in
``{PROJECT_ROOT}/.env`` and mark the ``.env`` as ignored in your VCS. For
example, you can write ``/.env`` in ``.gitignore`` if you are using Git, and
put a ``.env.example`` as a copying template for new-cloned projects.

And then, you can use some utility such as `honcho`_ or `autoenv`_ to apply
the ``.env`` automatically.

For honcho::

    $ echo 'MYPROJECT_DEBUG=true' >> .env
    $ echo 'web: python manage.py runserver' >> Procfile
    $ honcho run python manage.py check-debug
    True
    $ honcho start web
    Starting development server at http://127.0.0.1:5000/
    ...

For autoenv::

    $ echo 'MYPROJECT_DEBUG=true' >> myproject/.env
    $ cd myproject
    $ python manage.py check-debug
    True
    $ python manage.py runserver
    Starting development server at http://127.0.0.1:5000/
    ...

Issues
------

If you want to report bugs or request features, please create issues on
`GitHub Issues <https://github.com/tonyseek/python-envcfg/issues>`_.

Alternatives
------------

- https://github.com/henriquebastos/python-decouple
- https://github.com/pallets/click

.. _12-Factor: http://12factor.net
.. _honcho: https://github.com/nickstenning/honcho
.. _autoenv: https://github.com/kennethreitz/autoenv

.. |Build Status| image:: https://travis-ci.org/tonyseek/python-envcfg.svg?branch=master,develop
   :target: https://travis-ci.org/tonyseek/python-envcfg
   :alt: Build Status
.. |Coverage Status| image:: https://img.shields.io/coveralls/tonyseek/python-envcfg/develop.svg
   :target: https://coveralls.io/r/tonyseek/python-envcfg
   :alt: Coverage Status
.. |Wheel Status| image:: https://img.shields.io/pypi/wheel/python-envcfg.svg
   :target: https://warehouse.python.org/project/python-envcfg
   :alt: Wheel Status
.. |PyPI Version| image:: https://img.shields.io/pypi/v/python-envcfg.svg
   :target: https://pypi.python.org/pypi/python-envcfg
   :alt: PyPI Version
.. |PyPI Downloads| image:: https://img.shields.io/pypi/dm/python-envcfg.svg
   :target: https://pypi.python.org/pypi/python-envcfg
   :alt: Downloads


text:
package com.android.settings;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.SwitchPreference;
import android.provider.Settings;
import android.provider.Telephony;
import android.telephony.ServiceState;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.android.internal.logging.MetricsLogger;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.telephony.TelephonyProperties;
import com.mediatek.apn.ApnTypePreference;
import com.mediatek.apn.ApnUtils;
import com.mediatek.internal.telephony.ITelephonyEx;
import com.mediatek.settings.FeatureOption;
import com.mediatek.settings.UtilsExt;
import com.mediatek.settings.cdma.CdmaApnSetting;
import com.mediatek.settings.cdma.CdmaUtils;
import com.mediatek.settings.ext.IApnSettingsExt;
import com.mediatek.settings.sim.SimHotSwapHandler;
import com.mediatek.settings.sim.SimHotSwapHandler.OnSimHotSwapListener;
import com.mediatek.telephony.TelephonyManagerEx;

import java.util.HashSet;
import java.util.Set;

public class ApnEditor extends InstrumentedPreferenceActivity
        implements SharedPreferences.OnSharedPreferenceChangeListener,
                    Preference.OnPreferenceChangeListener {

    private final static String TAG = ApnEditor.class.getSimpleName();

    private final static String SAVED_POS = "pos";
    private final static String KEY_AUTH_TYPE = "auth_type";
    private final static String KEY_PROTOCOL = "apn_protocol";
    private final static String KEY_ROAMING_PROTOCOL = "apn_roaming_protocol";
    private final static String KEY_CARRIER_ENABLED = "carrier_enabled";
    private final static String KEY_BEARER_MULTI = "bearer_multi";
    private final static String KEY_MVNO_TYPE = "mvno_type";

    private static final int MENU_DELETE = Menu.FIRST;
    private static final int MENU_SAVE = Menu.FIRST + 1;
    private static final int MENU_CANCEL = Menu.FIRST + 2;
    private static final int ERROR_DIALOG_ID = 0;
    /// M: show dialog when change default APN
    private static final int CONFIRM_CHANGE_DIALOG_ID = 1;

    private static String sNotSet;
    private EditTextPreference mName;
    private EditTextPreference mApn;
    private EditTextPreference mProxy;
    private EditTextPreference mPort;
    private EditTextPreference mUser;
    private EditTextPreference mServer;
    private EditTextPreference mPassword;
    private EditTextPreference mMmsc;
    private EditTextPreference mMcc;
    private EditTextPreference mMnc;
    private EditTextPreference mMmsProxy;
    private EditTextPreference mMmsPort;
    private ListPreference mAuthType;
    private EditTextPreference mApnType;
    private ListPreference mProtocol;
    private ListPreference mRoamingProtocol;
    private SwitchPreference mCarrierEnabled;
    private MultiSelectListPreference mBearerMulti;
    private ListPreference mMvnoType;
    private EditTextPreference mMvnoMatchData;

    private String mCurMnc;
    private String mCurMcc;

    private Uri mUri;
    private Cursor mCursor;
    private boolean mNewApn;
    private boolean mFirstTime;
    private int mSubId;
    private Resources mRes;
    private TelephonyManager mTelephonyManager;
    private int mBearerInitialVal = 0;
    private String mMvnoTypeStr;
    private String mMvnoMatchDataStr;

    /**
     * Standard projection for the interesting columns of a normal note.
     */
    private static String[] sProjection = new String[] {
            Telephony.Carriers._ID,     // 0
            Telephony.Carriers.NAME,    // 1
            Telephony.Carriers.APN,     // 2
            Telephony.Carriers.PROXY,   // 3
            Telephony.Carriers.PORT,    // 4
            Telephony.Carriers.USER,    // 5
            Telephony.Carriers.SERVER,  // 6
            Telephony.Carriers.PASSWORD, // 7
            Telephony.Carriers.MMSC, // 8
            Telephony.Carriers.MCC, // 9
            Telephony.Carriers.MNC, // 10
            Telephony.Carriers.NUMERIC, // 11
            Telephony.Carriers.MMSPROXY,// 12
            Telephony.Carriers.MMSPORT, // 13
            Telephony.Carriers.AUTH_TYPE, // 14
            Telephony.Carriers.TYPE, // 15
            Telephony.Carriers.PROTOCOL, // 16
            Telephony.Carriers.CARRIER_ENABLED, // 17
            Telephony.Carriers.BEARER, // 18
            Telephony.Carriers.BEARER_BITMASK, // 19
            Telephony.Carriers.ROAMING_PROTOCOL, // 20
            Telephony.Carriers.MVNO_TYPE,   // 21
            Telephony.Carriers.MVNO_MATCH_DATA,  // 22
            Telephony.Carriers.SOURCE_TYPE, //23, M: [APN Source Type]
    };

    private static final int ID_INDEX = 0;
    private static final int NAME_INDEX = 1;
    private static final int APN_INDEX = 2;
    private static final int PROXY_INDEX = 3;
    private static final int PORT_INDEX = 4;
    private static final int USER_INDEX = 5;
    private static final int SERVER_INDEX = 6;
    private static final int PASSWORD_INDEX = 7;
    private static final int MMSC_INDEX = 8;
    private static final int MCC_INDEX = 9;
    private static final int MNC_INDEX = 10;
    private static final int MMSPROXY_INDEX = 12;
    private static final int MMSPORT_INDEX = 13;
    private static final int AUTH_TYPE_INDEX = 14;
    private static final int TYPE_INDEX = 15;
    private static final int PROTOCOL_INDEX = 16;
    private static final int CARRIER_ENABLED_INDEX = 17;
    private static final int BEARER_INDEX = 18;
    private static final int BEARER_BITMASK_INDEX = 19;
    private static final int ROAMING_PROTOCOL_INDEX = 20;
    private static final int MVNO_TYPE_INDEX = 21;
    private static final int MVNO_MATCH_DATA_INDEX = 22;
    /// M: [APN Source Type]
    private static final int SOURCE_TYPE_INDEX = 23;

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

        addPreferencesFromResource(R.xml.apn_editor);

        sNotSet = getResources().getString(R.string.apn_not_set);
        mName = (EditTextPreference) findPreference("apn_name");
        mApn = (EditTextPreference) findPreference("apn_apn");
        mProxy = (EditTextPreference) findPreference("apn_http_proxy");
        mPort = (EditTextPreference) findPreference("apn_http_port");
        mUser = (EditTextPreference) findPreference("apn_user");
        mServer = (EditTextPreference) findPreference("apn_server");
        mPassword = (EditTextPreference) findPreference("apn_password");
        mMmsProxy = (EditTextPreference) findPreference("apn_mms_proxy");
        mMmsPort = (EditTextPreference) findPreference("apn_mms_port");
        mMmsc = (EditTextPreference) findPreference("apn_mmsc");
        mMcc = (EditTextPreference) findPreference("apn_mcc");
        mMnc = (EditTextPreference) findPreference("apn_mnc");
        /// M: change the type preference to list preference @{
        // mApnType = (EditTextPreference) findPreference("apn_type");
        mApnTypeList = (ApnTypePreference) findPreference("apn_type_list");
        mApnTypeList.setOnPreferenceChangeListener(this);
        /// @}

        mAuthType = (ListPreference) findPreference(KEY_AUTH_TYPE);
        mAuthType.setOnPreferenceChangeListener(this);

        mProtocol = (ListPreference) findPreference(KEY_PROTOCOL);
        mProtocol.setOnPreferenceChangeListener(this);

        mRoamingProtocol = (ListPreference) findPreference(KEY_ROAMING_PROTOCOL);
        mRoamingProtocol.setOnPreferenceChangeListener(this);

        mCarrierEnabled = (SwitchPreference) findPreference(KEY_CARRIER_ENABLED);

        mBearerMulti = (MultiSelectListPreference) findPreference(KEY_BEARER_MULTI);
        mBearerMulti.setOnPreferenceChangeListener(this);

        mMvnoType = (ListPreference) findPreference(KEY_MVNO_TYPE);
        mMvnoType.setOnPreferenceChangeListener(this);
        mMvnoMatchData = (EditTextPreference) findPreference("mvno_match_data");

        mRes = getResources();

        final Intent intent = getIntent();
        final String action = intent.getAction();
        mSubId = intent.getIntExtra(ApnSettings.SUB_ID,
                SubscriptionManager.INVALID_SUBSCRIPTION_ID);

        mFirstTime = icicle == null;

        /// M: for plug-in @{
        mApnExt = UtilsExt.getApnSettingsPlugin(this);
        /// @}

        if (action.equals(Intent.ACTION_EDIT)) {
            mUri = intent.getData();
            /// M: for [Read Only APN], some APN can not be edited
            mReadOnlyMode = intent.getBooleanExtra("readOnly", false);
            Log.d(TAG, "Read only mode : " + mReadOnlyMode);
        } else if (action.equals(Intent.ACTION_INSERT)) {
            if (mFirstTime || icicle.getInt(SAVED_POS) == 0) {
                mUri = getContentResolver().insert(intent.getData(), new ContentValues());
                /// M: for plug-in
                mUri = mApnExt.getUriFromIntent(mUri, getApplicationContext(), intent);
            } else {
                mUri = ContentUris.withAppendedId(Telephony.Carriers.CONTENT_URI,
                        icicle.getInt(SAVED_POS));
            }
            mNewApn = true;
            /// M: if insert a new APN, get MVNO type from SIM @{
            /*
            mMvnoTypeStr = intent.getStringExtra(ApnSettings.MVNO_TYPE);
            mMvnoMatchDataStr = intent.getStringExtra(ApnSettings.MVNO_MATCH_DATA);
            */
            try {
                ITelephonyEx telephony = ITelephonyEx.Stub.asInterface(ServiceManager
                        .getService(Context.TELEPHONY_SERVICE_EX));
                mMvnoTypeStr = telephony.getMvnoMatchType(mSubId);
                mMvnoMatchDataStr = telephony.getMvnoPattern(mSubId, mMvnoTypeStr);
            } catch (android.os.RemoteException e) {
                Log.d(TAG, "RemoteException " + e);
            }
            /// @}
            // If we were unable to create a new note, then just finish
            // this activity.  A RESULT_CANCELED will be sent back to the
            // original activity if they requested a result.
            if (mUri == null) {
                Log.w(TAG, "Failed to insert new telephony provider into "
                        + getIntent().getData());
                finish();
                return;
            }

            // The new entry was created, so assume all will end well and
            // set the result to be returned.
            setResult(RESULT_OK, (new Intent()).setAction(mUri.toString()));

        } else {
            finish();
            return;
        }

        /// M: for plug-in @{
        sProjection = mApnExt.customizeApnProjection(sProjection);
        mApnExt.customizePreference(mSubId, getPreferenceScreen());
        /// @}

        mCursor = managedQuery(mUri, sProjection, null, null);
        mCursor.moveToFirst();

        mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

        fillUi();

        /// M: for [SIM Hot Swap] @{
        mSimHotSwapHandler = new SimHotSwapHandler(getApplicationContext());
        mSimHotSwapHandler.registerOnSimHotSwap(new OnSimHotSwapListener() {
            @Override
            public void onSimHotSwap() {
                Log.d(TAG, "onSimHotSwap, finish Activity~~");
                finish();
            }
        });
        /// @}

        /// M: @{
        if (!mNewApn) {
            getContentResolver().registerContentObserver(mUri, true, mContentObserver);
        }
        /// @}
    }

    @Override
    protected int getMetricsCategory() {
        return MetricsLogger.APN_EDITOR;
    }

    @Override
    public void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);

        /// M: listen for Airplane mode && data state @{
        IntentFilter filter = new IntentFilter(
                TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
        filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
        registerReceiver(mReceiver, filter);
        /// @}

        /// M: update screen to proper state
        updateScreenEnableState();
    }

    @Override
    public void onPause() {
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
        /// M: unlisten for airplane mode & data state change
        unregisterReceiver(mReceiver);
        super.onPause();
    }

    private void fillUi() {
        /// M: @{
        if (mCursor.getCount() == 0) {
            Log.w(TAG, "fillUi(), cursor count is 0, finish~~");
            finish();
            return;
        }
        /// @}

        if (mFirstTime) {
            mFirstTime = false;
            // Fill in all the values from the db in both text editor and summary
            mName.setText(mCursor.getString(NAME_INDEX));
            mApn.setText(mCursor.getString(APN_INDEX));
            mProxy.setText(mCursor.getString(PROXY_INDEX));
            mPort.setText(mCursor.getString(PORT_INDEX));
            mUser.setText(mCursor.getString(USER_INDEX));
            mServer.setText(mCursor.getString(SERVER_INDEX));
            mPassword.setText(mCursor.getString(PASSWORD_INDEX));
            mMmsProxy.setText(mCursor.getString(MMSPROXY_INDEX));
            mMmsPort.setText(mCursor.getString(MMSPORT_INDEX));
            mMmsc.setText(mCursor.getString(MMSC_INDEX));
            mMcc.setText(mCursor.getString(MCC_INDEX));
            mMnc.setText(mCursor.getString(MNC_INDEX));
            /// M: for [APN Type List] @{
            // mApnType.setText(mCursor.getString(TYPE_INDEX));
            String strType = mCursor.getString(TYPE_INDEX);
            mApnTypeList.setSummary(checkNull(strType));
            mApnTypeList.initCheckedState(strType);
            /// @}

            /// M: [APN Source Type]
            mSourceType = mCursor.getInt(SOURCE_TYPE_INDEX);

            if (mNewApn) {
                String numeric = mTelephonyManager.getSimOperator(mSubId);
                /// M: for SVLTE project to create APN using current operator numeric
                numeric = updateMccMncForSvlte(mSubId, numeric);

                // MCC is first 3 chars and then in 2 - 3 chars of MNC
                if (numeric != null && numeric.length() > 4) {
                    // Country code
                    String mcc = numeric.substring(0, 3);
                    // Network code
                    String mnc = numeric.substring(3);
                    // Auto populate MNC and MCC for new entries, based on what SIM reports
                    mMcc.setText(mcc);
                    mMnc.setText(mnc);
                    mCurMnc = mnc;
                    mCurMcc = mcc;
                }
                /// M: if APN type is Tether , need re-set APN type preference {@
                String apnType = getIntent().getStringExtra(ApnUtils.APN_TYPE);
                if (ApnUtils.TETHER_TYPE.equals(apnType)) {
                    mApnTypeList.setSummary("tethering");
                    mApnTypeList.initCheckedState("tethering");
                } else {
                    mApnTypeList.setSummary("default");
                    mApnTypeList.initCheckedState("default");
                }
                /// @}
                /// M: [APN Source Type]
                mSourceType = ApnUtils.SOURCE_TYPE_USER_EDIT;
            }
            int authVal = mCursor.getInt(AUTH_TYPE_INDEX);
            if (authVal != -1) {
                mAuthType.setValueIndex(authVal);
            } else {
                mAuthType.setValue(null);
            }

            mProtocol.setValue(mCursor.getString(PROTOCOL_INDEX));
            mRoamingProtocol.setValue(mCursor.getString(ROAMING_PROTOCOL_INDEX));
            mCarrierEnabled.setChecked(mCursor.getInt(CARRIER_ENABLED_INDEX)==1);
            mBearerInitialVal = mCursor.getInt(BEARER_INDEX);

            HashSet<String> bearers = new HashSet<String>();
            int bearerBitmask = mCursor.getInt(BEARER_BITMASK_INDEX);
            if (bearerBitmask == 0) {
                if (mBearerInitialVal == 0) {
                    bearers.add("" + 0);
                }
            } else {
                int i = 1;
                while (bearerBitmask != 0) {
                    if ((bearerBitmask & 1) == 1) {
                        bearers.add("" + i);
                    }
                    bearerBitmask >>= 1;
                    i++;
                }
            }

            if (mBearerInitialVal != 0 && bearers.contains("" + mBearerInitialVal) == false) {
                // add mBearerInitialVal to bearers
                bearers.add("" + mBearerInitialVal);
            }
            mBearerMulti.setValues(bearers);

            mMvnoType.setValue(mCursor.getString(MVNO_TYPE_INDEX));
            mMvnoMatchData.setEnabled(false);
            mMvnoMatchData.setText(mCursor.getString(MVNO_MATCH_DATA_INDEX));
            if (mNewApn && mMvnoTypeStr != null && mMvnoMatchDataStr != null) {
                mMvnoType.setValue(mMvnoTypeStr);
                mMvnoMatchData.setText(mMvnoMatchDataStr);
            }

            /// M: for plug-in
            mApnExt.setPreferenceTextAndSummary(
                    mSubId, mCursor.getString(sProjection.length - 1));
        }

        mName.setSummary(checkNull(mName.getText()));
        mApn.setSummary(checkNull(mApn.getText()));
        mProxy.setSummary(checkNull(mProxy.getText()));
        mPort.setSummary(checkNull(mPort.getText()));
        mUser.setSummary(checkNull(mUser.getText()));
        mServer.setSummary(checkNull(mServer.getText()));
        mPassword.setSummary(starify(mPassword.getText()));
        mMmsProxy.setSummary(checkNull(mMmsProxy.getText()));
        mMmsPort.setSummary(checkNull(mMmsPort.getText()));
        mMmsc.setSummary(checkNull(mMmsc.getText()));
        mMcc.setSummary(checkNull(mMcc.getText()));
        mMnc.setSummary(checkNull(mMnc.getText()));
        /// M: for [APN Type List]
        // mApnType.setSummary(checkNull(mApnType.getText()));

        String authVal = mAuthType.getValue();
        if (authVal != null) {
            int authValIndex = Integer.parseInt(authVal);
            mAuthType.setValueIndex(authValIndex);

            String []values = mRes.getStringArray(R.array.apn_auth_entries);
            mAuthType.setSummary(values[authValIndex]);
        } else {
            mAuthType.setSummary(sNotSet);
        }

        mProtocol.setSummary(
                checkNull(protocolDescription(mProtocol.getValue(), mProtocol)));
        mRoamingProtocol.setSummary(
                checkNull(protocolDescription(mRoamingProtocol.getValue(), mRoamingProtocol)));
        mBearerMulti.setSummary(
                checkNull(bearerMultiDescription(mBearerMulti.getValues())));
        mMvnoType.setSummary(
                checkNull(mvnoDescription(mMvnoType.getValue())));
        mMvnoMatchData.setSummary(checkNull(mMvnoMatchData.getText()));
        // allow user to edit carrier_enabled for some APN
        boolean ceEditable = getResources().getBoolean(R.bool.config_allow_edit_carrier_enabled);
        if (ceEditable) {
            mCarrierEnabled.setEnabled(true);
        } else {
            mCarrierEnabled.setEnabled(false);
        }
    }

    /**
     * Returns the UI choice (e.g., "IPv4/IPv6") corresponding to the given
     * raw value of the protocol preference (e.g., "IPV4V6"). If unknown,
     * return null.
     */
    private String protocolDescription(String raw, ListPreference protocol) {
        int protocolIndex = protocol.findIndexOfValue(raw);
        if (protocolIndex == -1) {
            return null;
        } else {
            String[] values = mRes.getStringArray(R.array.apn_protocol_entries);
            try {
                return values[protocolIndex];
            } catch (ArrayIndexOutOfBoundsException e) {
                return null;
            }
        }
    }

    private String bearerDescription(String raw) {
        int mBearerIndex = mBearerMulti.findIndexOfValue(raw);
        if (mBearerIndex == -1) {
            return null;
        } else {
            String[] values = mRes.getStringArray(R.array.bearer_entries);
            try {
                return values[mBearerIndex];
            } catch (ArrayIndexOutOfBoundsException e) {
                return null;
            }
        }
    }

    private String bearerMultiDescription(Set<String> raw) {
        String[] values = mRes.getStringArray(R.array.bearer_entries);
        StringBuilder retVal = new StringBuilder();
        boolean first = true;
        for (String bearer : raw) {
            int bearerIndex = mBearerMulti.findIndexOfValue(bearer);
            try {
                if (first) {
                    retVal.append(values[bearerIndex]);
                    first = false;
                } else {
                    retVal.append(", " + values[bearerIndex]);
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                // ignore
            }
        }
        String val = retVal.toString();
        if (!TextUtils.isEmpty(val)) {
            return val;
        }
        return null;
    }

    private String mvnoDescription(String newValue) {
        int mvnoIndex = mMvnoType.findIndexOfValue(newValue);
        String oldValue = mMvnoType.getValue();

        if (mvnoIndex == -1) {
            return null;
        } else {
            /// M: add PNN type
            // String[] values = mRes.getStringArray(R.array.mvno_type_entries);
            String[] values = mRes.getStringArray(R.array.ext_mvno_type_entries);
            if (values[mvnoIndex].equals("None")) {
                mMvnoMatchData.setEnabled(false);
            } else {
                mMvnoMatchData.setEnabled(true);
            }
            if (newValue != null && newValue.equals(oldValue) == false) {
                if (values[mvnoIndex].equals("SPN")) {
                    mMvnoMatchData.setText(mTelephonyManager.getSimOperatorName());
                } else if (values[mvnoIndex].equals("IMSI")) {
                    String numeric = mTelephonyManager.getSimOperator(mSubId);
                    mMvnoMatchData.setText(numeric + "x");
                } else if (values[mvnoIndex].equals("GID")) {
                    mMvnoMatchData.setText(mTelephonyManager.getGroupIdLevel1());
                }
            }

            try {
                return values[mvnoIndex];
            } catch (ArrayIndexOutOfBoundsException e) {
                return null;
            }
        }
    }

    public boolean onPreferenceChange(Preference preference, Object newValue) {
        String key = preference.getKey();
        if (KEY_AUTH_TYPE.equals(key)) {
            try {
                int index = Integer.parseInt((String) newValue);
                mAuthType.setValueIndex(index);

                String []values = mRes.getStringArray(R.array.apn_auth_entries);
                mAuthType.setSummary(values[index]);
            } catch (NumberFormatException e) {
                return false;
            }
        } else if (KEY_PROTOCOL.equals(key)) {
            String protocol = protocolDescription((String) newValue, mProtocol);
            if (protocol == null) {
                return false;
            }
            mProtocol.setSummary(protocol);
            mProtocol.setValue((String) newValue);
        } else if (KEY_ROAMING_PROTOCOL.equals(key)) {
            String protocol = protocolDescription((String) newValue, mRoamingProtocol);
            if (protocol == null) {
                return false;
            }
            mRoamingProtocol.setSummary(protocol);
            mRoamingProtocol.setValue((String) newValue);
        } else if (KEY_BEARER_MULTI.equals(key)) {
            String bearer = bearerMultiDescription((Set<String>) newValue);
            if (bearer == null) {
                return false;
            }
            mBearerMulti.setValues((Set<String>) newValue);
            mBearerMulti.setSummary(bearer);
        } else if (KEY_MVNO_TYPE.equals(key)) {
            String mvno = mvnoDescription((String) newValue);
            if (mvno == null) {
                return false;
            }
            mMvnoType.setValue((String) newValue);
            mMvnoType.setSummary(mvno);
            /// M: for [APN Type List] @{
        } else if (KEY_APN_TYPE_LIST.equals(key)) {
            mApnTypeList.setSummary(checkNull(mApnTypeList.getTypeString()));
            /// @}
        }

        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        /// M: for [Read Only APN] @{
        if (mReadOnlyMode) {
            return true;
        }
        /// @}
        // If it's a new APN, then cancel will delete the new entry in onPause
        /// M: [APN Source Type]not show delete for default APN type
        // if (!mNewApn) {
        if (!mNewApn && mSourceType != ApnUtils.SOURCE_TYPE_DEFAULT) {
            menu.add(0, MENU_DELETE, 0, R.string.menu_delete)
                .setIcon(R.drawable.ic_menu_delete);
        }
        menu.add(0, MENU_SAVE, 0, R.string.menu_save)
            .setIcon(android.R.drawable.ic_menu_save);
        menu.add(0, MENU_CANCEL, 0, R.string.menu_cancel)
            .setIcon(android.R.drawable.ic_menu_close_clear_cancel);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_DELETE:
            deleteApn();
            return true;
        case MENU_SAVE:
            /// M: [APN Source Type]show the confirm dialog when save the default APN {@
            if (mSourceType == ApnUtils.SOURCE_TYPE_DEFAULT) {
                showDialog(CONFIRM_CHANGE_DIALOG_ID);
            /// @}
            } else if (validateAndSave(false)) {
                finish();
            }
            return true;
        case MENU_CANCEL:
            if (mNewApn && mUri != null) {
                getContentResolver().delete(mUri, null, null);
            }
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK: {
                if (validateAndSave(false)) {
                    finish();
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onSaveInstanceState(Bundle icicle) {
        super.onSaveInstanceState(icicle);
        if (validateAndSave(true) && mCursor != null && mCursor.getCount() != 0) {
            icicle.putInt(SAVED_POS, mCursor.getInt(ID_INDEX));
        }
    }

    /**
     * Check the key fields' validity and save if valid.
     * @param force save even if the fields are not valid, if the app is
     *        being suspended
     * @return true if the data was saved
     */
    private boolean validateAndSave(boolean force) {
        String name = checkNotSet(mName.getText());
        String apn = checkNotSet(mApn.getText());
        String mcc = checkNotSet(mMcc.getText());
        String mnc = checkNotSet(mMnc.getText());

        if (getErrorMsg() != null && !force) {
            showDialog(ERROR_DIALOG_ID);
            return false;
        }

        if (!mCursor.moveToFirst() && !mNewApn) {
            Log.w(TAG,
                    "Could not go to the first row in the Cursor when saving data.");
            return false;
        }

        // If it's a new APN and a name or apn haven't been entered, then erase the entry
        if (force && mNewApn && name.length() < 1 && apn.length() < 1 && mUri != null) {
            getContentResolver().delete(mUri, null, null);
            /// M:
            mUri = null;
            return false;
        }

        ContentValues values = new ContentValues();

        // Add a dummy name "Untitled", if the user exits the screen without adding a name but
        // entered other information worth keeping.
        values.put(Telephony.Carriers.NAME,
                name.length() < 1 ? getResources().getString(R.string.untitled_apn) : name);
        values.put(Telephony.Carriers.APN, apn);
        values.put(Telephony.Carriers.PROXY, checkNotSet(mProxy.getText()));
        values.put(Telephony.Carriers.PORT, checkNotSet(mPort.getText()));
        values.put(Telephony.Carriers.MMSPROXY, checkNotSet(mMmsProxy.getText()));
        values.put(Telephony.Carriers.MMSPORT, checkNotSet(mMmsPort.getText()));
        values.put(Telephony.Carriers.USER, checkNotSet(mUser.getText()));
        values.put(Telephony.Carriers.SERVER, checkNotSet(mServer.getText()));
        values.put(Telephony.Carriers.PASSWORD, checkNotSet(mPassword.getText()));
        values.put(Telephony.Carriers.MMSC, checkNotSet(mMmsc.getText()));

        String authVal = mAuthType.getValue();
        if (authVal != null) {
            values.put(Telephony.Carriers.AUTH_TYPE, Integer.parseInt(authVal));
        }

        values.put(Telephony.Carriers.PROTOCOL, checkNotSet(mProtocol.getValue()));
        values.put(Telephony.Carriers.ROAMING_PROTOCOL, checkNotSet(mRoamingProtocol.getValue()));

        /// M: for [APN Type List] @{
        // values.put(Telephony.Carriers.TYPE, checkNotSet(mApnType.getText()));
        values.put(Telephony.Carriers.TYPE, checkNotSet(mApnTypeList.getTypeString()));
        /// @}

        values.put(Telephony.Carriers.MCC, mcc);
        values.put(Telephony.Carriers.MNC, mnc);

        values.put(Telephony.Carriers.NUMERIC, mcc + mnc);

        if (mCurMnc != null && mCurMcc != null) {
            if (mCurMnc.equals(mnc) && mCurMcc.equals(mcc)) {
                values.put(Telephony.Carriers.CURRENT, 1);
            }
        }

        Set<String> bearerSet = mBearerMulti.getValues();
        int bearerBitmask = 0;
        for (String bearer : bearerSet) {
            if (Integer.parseInt(bearer) == 0) {
                bearerBitmask = 0;
                break;
            } else {
                bearerBitmask |= ServiceState.getBitmaskForTech(Integer.parseInt(bearer));
            }
        }
        values.put(Telephony.Carriers.BEARER_BITMASK, bearerBitmask);

        int bearerVal;
        if (bearerBitmask == 0 || mBearerInitialVal == 0) {
            bearerVal = 0;
        } else if (ServiceState.bitmaskHasTech(bearerBitmask, mBearerInitialVal)) {
            bearerVal = mBearerInitialVal;
        } else {
            // bearer field was being used but bitmask has changed now and does not include the
            // initial bearer value -- setting bearer to 0 but maybe better behavior is to choose a
            // random tech from the new bitmask??
            bearerVal = 0;
        }
        values.put(Telephony.Carriers.BEARER, bearerVal);

        values.put(Telephony.Carriers.MVNO_TYPE, checkNotSet(mMvnoType.getValue()));
        values.put(Telephony.Carriers.MVNO_MATCH_DATA, checkNotSet(mMvnoMatchData.getText()));

        values.put(Telephony.Carriers.CARRIER_ENABLED, mCarrierEnabled.isChecked() ? 1 : 0);
        /// M: [APN Source Type]
        values.put(Telephony.Carriers.SOURCE_TYPE, mSourceType);

        /// M: for plug-in
        mApnExt.saveApnValues(values);

        /// M: firstly insert ,then update if need {@
        if (mUri == null) {
            Log.i(TAG, "former inserted URI was already deleted, insert a new one");
            mUri = getContentResolver().insert(getIntent().getData(), new ContentValues());
        } else {
        /// @}
            getContentResolver().update(mUri, values, null, null);
        }

        return true;
    }

    private String getErrorMsg() {
        String errorMsg = null;

        String name = checkNotSet(mName.getText());
        String apn = checkNotSet(mApn.getText());
        String mcc = checkNotSet(mMcc.getText());
        String mnc = checkNotSet(mMnc.getText());
        /// M: for [APN Type List]
        String apnType = mApnTypeList.getTypeString();

        if (name.length() < 1) {
            errorMsg = mRes.getString(R.string.error_name_empty);
        /// M: not check apn length if type is "ia",
        /// as default ia type, the apn item maybe null
        } else if ((apnType == null || !apnType.contains("ia")) && apn.length() < 1) {
            errorMsg = mRes.getString(R.string.error_apn_empty);
        } else if (mcc.length() != 3) {
            errorMsg = mRes.getString(R.string.error_mcc_not3);
        } else if ((mnc.length() & 0xFFFE) != 2) {
            errorMsg = mRes.getString(R.string.error_mnc_not23);
        }

        return errorMsg;
    }

    @Override
    protected Dialog onCreateDialog(int id) {

        if (id == ERROR_DIALOG_ID) {
            String msg = getErrorMsg();

            return new AlertDialog.Builder(this)
                    .setTitle(R.string.error_title)
                    .setPositiveButton(android.R.string.ok, null)
                    .setMessage(msg)
                    .create();
             /// M: add confirm dialog
        } else if (id == CONFIRM_CHANGE_DIALOG_ID) {
            return  new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle(R.string.error_title)
            .setMessage(getString(R.string.apn_predefine_change_dialog_notice))
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    if (validateAndSave(false)) {
                        finish();
                    }
                }
            })
            .setNegativeButton(R.string.cancel, null)
            .create();
        }

        return super.onCreateDialog(id);
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);

        if (id == ERROR_DIALOG_ID) {
            String msg = getErrorMsg();

            if (msg != null) {
                ((AlertDialog)dialog).setMessage(msg);
            }
        }
    }

    private void deleteApn() {
        if (mUri != null) {
            getContentResolver().delete(mUri, null, null);
        }
        finish();
    }

    private String starify(String value) {
        if (value == null || value.length() == 0) {
            return sNotSet;
        } else {
            char[] password = new char[value.length()];
            for (int i = 0; i < password.length; i++) {
                password[i] = '*';
            }
            return new String(password);
        }
    }

    private String checkNull(String value) {
        if (value == null || value.length() == 0) {
            return sNotSet;
        } else {
            return value;
        }
    }

    private String checkNotSet(String value) {
        if (value == null || value.equals(sNotSet)) {
            return "";
        } else {
            return value;
        }
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        Preference pref = findPreference(key);
        if (pref != null) {
            if (pref.equals(mPassword)){
                pref.setSummary(starify(sharedPreferences.getString(key, "")));
            /// M: @{
            } else if (pref.equals(mCarrierEnabled)) {
                pref.setSummary(
                        checkNull(String.valueOf(sharedPreferences.getBoolean(key, true))));
            /// @}
            /// M: check  port value , it must be 1-65535 @{
            } else if (pref.equals(mPort)) {
                String portStr = sharedPreferences.getString(key, "");
                if (!portStr.equals("")) {
                    try {
                        int portNum = Integer.parseInt(portStr);
                        if (portNum > 65535 || portNum <= 0) {
                            Toast.makeText(this, getString(R.string.apn_port_warning),
                                    Toast.LENGTH_LONG).show();
                            ((EditTextPreference) pref).setText("");
                        }
                    } catch (NumberFormatException e) {
                        Toast.makeText(this, getString(R.string.apn_port_warning),
                                Toast.LENGTH_LONG).show();
                        ((EditTextPreference) pref).setText("");
                    }
                }
                pref.setSummary(checkNull(sharedPreferences.getString(key, "")));
            /// @}
            } else if (pref.equals(mCarrierEnabled) || pref.equals(mBearerMulti)) {
                // do nothing
            } else {
                pref.setSummary(checkNull(sharedPreferences.getString(key, "")));
            }
        }
    }

    ///----------------------------------------MTK------------------------------------------------
    /// M: for [SIM Hot Swap]
    private SimHotSwapHandler mSimHotSwapHandler;

    /// M: [APN Source Type]
    private int mSourceType = ApnUtils.SOURCE_TYPE_DEFAULT;
    private boolean mReadOnlyMode = false;

    /// M: for plug-in
    private IApnSettingsExt mApnExt;

    /// M: for [APN Type List] @{
    private static final String KEY_APN_TYPE_LIST = "apn_type_list";
    private ApnTypePreference mApnTypeList;
    /// @}

    @Override
    public void onDestroy() {
        /// M: @{
        if (!mNewApn) {
            getContentResolver().unregisterContentObserver(mContentObserver);
        }
        /// @}
        /// M: for [SIM Hot Swap]
        mSimHotSwapHandler.unregisterOnSimHotSwap();
        super.onDestroy();

        /// M: for plug-in
        mApnExt.onDestroy();
    }

    /// M: add the receiver and observer to update UI {@
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
                boolean airplaneModeEnabled = intent.getBooleanExtra("state", false);
                if (airplaneModeEnabled) {
                    Log.d(TAG, "receiver: ACTION_AIRPLANE_MODE_CHANGED in ApnEditor");
                    exitWithoutSave();
                }
            } else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
                String apnType = intent.getStringExtra(PhoneConstants.DATA_APN_TYPE_KEY);
                Log.d(TAG, "Receiver,send MMS status, get type = " + apnType);
                if (PhoneConstants.APN_TYPE_MMS.equals(apnType)) {
                    updateScreenEnableState();
                }
            } else if (action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) {
                Log.d(TAG, "receiver: ACTION_SIM_STATE_CHANGED");
                updateScreenEnableState();
            }
        }
    };

    private void exitWithoutSave() {
        if (mNewApn && (mUri != null)) {
            getContentResolver().delete(mUri, null, null);
        }
        finish();
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        super.onMenuOpened(featureId, menu);
        // if the airplane is enable or call state not idle, then disable the
        // Menu.
        if (menu != null) {
            menu.setGroupEnabled(0, isSimReadyAndRadioOn() && !mReadOnlyMode
                    && mApnExt.getScreenEnableState(mSubId, this));
        }
        return true;
    }

    /**
     * update screen enable state
     */
    private void updateScreenEnableState() {
        boolean enable = isSimReadyAndRadioOn();
        getPreferenceScreen().setEnabled(enable &&
                !mReadOnlyMode && mApnExt.getScreenEnableState(mSubId, ApnEditor.this));

        /// M: for plug-in @{
        mApnExt.setApnTypePreferenceState(mApnTypeList, mApnTypeList.getTypeString());
        mApnExt.updateFieldsStatus(mSubId, mSourceType, getPreferenceScreen());
        mApnExt.setMvnoPreferenceState(mMvnoType, mMvnoMatchData);
        /// @}
    }

    private boolean isSimReadyAndRadioOn() {
        boolean simReady = TelephonyManager.SIM_STATE_READY == TelephonyManager.getDefault()
                .getSimState(SubscriptionManager.getSlotId(mSubId));
        boolean airplaneModeEnabled = android.provider.Settings.System.getInt(getContentResolver(),
                android.provider.Settings.System.AIRPLANE_MODE_ON, -1) == 1;

        boolean isMultiSimMode = Settings.System.getInt(getContentResolver(),
                Settings.System.MSIM_MODE_SETTING, -1) != 0;
        boolean enable = !airplaneModeEnabled && simReady && isMultiSimMode;
        Log.d(TAG, "updateScreenEnableState(), subId = " + mSubId + " ,airplaneModeEnabled = "
                + airplaneModeEnabled + " ,simReady = " + simReady + " , isMultiSimMode = "
                + isMultiSimMode);
        return enable;
    }

    private ContentObserver mContentObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            Log.d(TAG, "background changed apn ");
            mFirstTime = true;
            try {
                stopManagingCursor(mCursor);
            } finally {
                if (mCursor != null) {
                    mCursor.close();
                }
            }
            mCursor = managedQuery(mUri, sProjection, null, null);
            mCursor.moveToFirst();
            fillUi();
        }
    };

    /**
     * M: SVLTE phone maintains two icc numeric(CDMA 46003/LTE 46011) for CT 4G UICC card,
     * when adding new APN, default numeric should set to current operator numeric
     * (CDMA 46003/LTE 46011).
     */
    private String updateMccMncForSvlte(int subId, String iccNumeric) {
        String apnNumeric = iccNumeric;
        if (!FeatureOption.MTK_SVLTE_SUPPORT) {
            return apnNumeric;
        }
        int c2kSlot = CdmaUtils.getExternalModemSlot();
        int svlteRatMode = Settings.Global.getInt(getContentResolver(),
                TelephonyManagerEx.getDefault().getCdmaRatModeKey(subId),
                TelephonyManagerEx.SVLTE_RAT_MODE_4G);
        // In 4G data only mode, only LteDcPhone is active, do not need to update preferred
        // apn sub id
        if (SubscriptionManager.getSlotId(subId) == c2kSlot &&
                svlteRatMode != TelephonyManagerEx.SVLTE_RAT_MODE_4G_DATA_ONLY) {
            // If this is CT card, need to update APN default numeric according to operator numeric
            if (iccNumeric != null
                    && (iccNumeric.equals(CdmaApnSetting.CT_NUMERIC_CDMA) || iccNumeric
                            .equals(CdmaApnSetting.CT_NUMERIC_LTE))) {
                String operatorNumeric = SystemProperties
                        .get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC);
                /**
                 * Operator numeric system prop may be the following format for Dual SIM project
                 * 46003,46000,46011 means both SIM inserted and SIM1 register to both CDMA and LTE
                 * 46003,,46011 for SIM 2 not inserted and SIM1 register to both CDMA and LTE
                 * 46003,46000, for both SIM inserted, but SIM1 register to only CDMA
                 */
                if (operatorNumeric != null
                        && operatorNumeric.contains(CdmaApnSetting.CT_NUMERIC_LTE)) {
                    apnNumeric = CdmaApnSetting.CT_NUMERIC_LTE;
                } else if (operatorNumeric != null
                        && operatorNumeric.contains(CdmaApnSetting.CT_NUMERIC_CDMA)) {
                    /// M: for ALPS02109453 @{
                    // when network type is EHRPD, use 46011 to add new APN,
                    // because we need to use
                    // 46011 to query APN list
                    if (CdmaApnSetting.getNetworkType(subId)
                            == TelephonyManager.NETWORK_TYPE_EHRPD) {
                        apnNumeric = CdmaApnSetting.CT_NUMERIC_LTE;
                    } else {
                        /// @}
                        apnNumeric = CdmaApnSetting.CT_NUMERIC_CDMA;
                    }
                } else {
                    apnNumeric =
                            TelephonyManager.getDefault().getNetworkOperatorForSubscription(subId);
                    Log.d(TAG, "plmnNumeric not contains 46003 or 46011, as ROAMING mumeric: "
                            + apnNumeric);
                }
                Log.d(TAG, "updateMccMncForSvlte iccNumeric=" + iccNumeric + ", apnNumeric="
                        + apnNumeric);
            }
        }
        return apnNumeric;
    }

}

redpajama_set_name: RedPajamaGithub


text:
module.exports={
attributes:{
		route_id : {unique:true, display:2},
		short_name : {eType:'string',importKey:'route_short_name', display:1},
		long_name : {eType:'string',importKey:'route_long_name',order:true},
		desc : {eType:'string',importKey:'route_desc'},
		type : {type : 'INTEGER',importKey:'route_type'},
		url : {eType:'string',importKey:'route_url'},
		colour : {eType:'colour',importKey:'route_color'},
		text_colour : {eType:'colour',importKey:'route_text_colour'},
//		geo_poly :{type:require("sequelize").GEOMETRY('POLYGON'),allowNull:false,index:true}
	},
relations:[ {
		relatedModel:'Trip',
		type:'HasMany'
	},{
		relatedModel:'Agency',
		type:'belongsTo',
		options:{onDelete: "CASCADE"},
		importKey:'agency_id',
		importForeignKey:'agency_id', 	// this only needs specifiying if different from importKey
	}],

Options:{
		noHistory:true,
		fileName:'routes',
	}
}


text:
<?php

/**
 * Created by PhpStorm.
 * User: jonathan
 * Date: 16/05/17
 * Time: 08:43
 */
class TestCron extends \Core\AutoCron\AutoCron
{
    public function checkParameters()
    {
        return parent::checkParameters();
    }

    public function run()
    {
        \Core\AutoCron\Tools::writeMessage('Do things');
        return \Core\AutoCron\Tools::RETURN_CODE_SUCCESS;
    }
}


text:
#include "Iceberg.h"

class ExampleState : public iceberg::GameState
{
public:
    ExampleState(iceberg::Game* game) : GameState(game){}
    ~ExampleState(){}

    void initialize() override;
    void finalize() override;

    void pause() override;
    void resume() override;

    void draw() override;
    void update() override;

private:
	/* Add state items here */
};


text:
var cells = document.getElementsByClassName('cell') || [];
var resultBox = document.getElementById('result') || {};
var reset = document.getElementById('reset') || {};

// confingig the game in self calling function
(function(cells = [], resultBox = {}, reset = {}){

  // Staging the Tic Tac Toe Game
  var board;

  const huPlayer = 'O';
  const huWin = 'You Won!!';
  const huWinColor = '#18FFFF';

  const aiPlayer = 'X';
  const aiWin = 'I Win :P';
  const aiWinColor = '#FFFF00';

  const tie = "It's a \nTie :(";
  const tieColor = '#1DE9B6';

  const winCombos = [
    [0,1,2],
    [3,4,5],
    [6,7,8],
    [0,3,6],
    [1,4,7],
    [2,5,8],
    [0,4,8],
    [2,4,6]
  ];

  // starting the game and setting the initial setup
  (function startGame(){
    board = Array.from(Array(9).keys());
    reset.addEventListener( 'click' , startGame, false );
    resultBox.classList.add('d-none')
    for(let i = 0; i < cells.length; i++){
      cells[i].innerHTML = '';
      cells[i].style.removeProperty('background-color')
      cells[i].addEventListener('click', turnClick, false)
    }
    turn(bestSpotID(), aiPlayer)
  })();

  function turnClick(cell){
    if( typeof board[cell.target.id] == 'number'){
      if(turn(cell.target.id, huPlayer) && !checkTie()){
        turn(bestSpotID(), aiPlayer)
      }
    }
  }

  function turn(id, player){
    board[id] = player;
    cells[id].innerHTML = player
    let gameWon = checkWin(board, player)
    if(gameWon){
      gameOver(gameWon)
      return false
    }
    return true
  }

  function bestSpotID(){
    return minimax(board, aiPlayer).index;
  }

  function emptySpots(curBoard = []){
    return curBoard.filter(el => {
      return !(el === huPlayer) && !(el === aiPlayer)
    })
  }

  function checkWin(board, player){
    let play = board.reduce((a,el,index) => (el === player) ? a.concat(index) : a, []);
    let gameWon = null
    winCombos.forEach((win, index) => {
      if(win.every(el => play.indexOf(el) > -1)){
        gameWon = {index: index, player: player}
      }
    })
    return gameWon;
  }

  function gameOver(gameWon){
    winCombos[gameWon.index].forEach(el=>{
      document.getElementById(el).style.backgroundColor
        = (gameWon.player === huPlayer) ? huWinColor : aiWinColor
    })
    for(let i =0; i < this.cells.length; i++){
      cells[i].removeEventListener('click', turnClick)
    }
    result((gameWon.player === huPlayer) ? huWin: aiWin)
  }

  function result(text = ''){
    resultBox.querySelector('.text').innerHTML = text
    resultBox.classList.remove('d-none')
  }

  function checkTie(){
    if(emptySpots(board).length === 0){
      for(let i =0; i < this.cells.length; i++){
        cells[i].style.backgroundColor = tieColor
        cells[i].removeEventListener('click', turnClick)
      }
      result(tie)
      return true;
    }
    else return false ;
  }

  function minimax(curBoard, player){
    let availableSpots = emptySpots(curBoard)

    if(checkWin(curBoard, huPlayer)) return {score: -10};
    else if(checkWin(curBoard, aiPlayer)) return {score: 10};
    else if(availableSpots.length === 0) return {score: 0};

    let moves = []
    for(let i = 0; i < availableSpots.length; i++){
      let move = {};
      move.index = curBoard[availableSpots[i]];
      curBoard[availableSpots[i]] = player;

      move.score
        = minimax(
            curBoard,
            (player === aiPlayer) ? huPlayer : aiPlayer
          ).score;
      curBoard[availableSpots[i]] = move.index;

      moves.push(move);
    }

    var bestMove;
    if(player === aiPlayer) {
      var bestScore = -10000;
      for(var i = 0; i < moves.length; i++) {
        if (moves[i].score > bestScore) {
          bestScore = moves[i].score;
          bestMove = i;
        }
      }
    } else {
      var bestScore = 10000;
      for(var i = 0; i < moves.length; i++) {
        if (moves[i].score < bestScore) {
          bestScore = moves[i].score;
          bestMove = i;
        }
      }
    }

    return moves[bestMove];
  }

})(cells, resultBox, reset)


text:
import {Component} from 'angular2/core';

@Component({
  selector: 'download',
  moduleId: module.id,
  templateUrl: './download.html'
})
export class DownloadCmp {}


text:
class wxDataViewRendererNativeData;

// ----------------------------------------------------------------------------
// wxDataViewRenderer
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_ADV wxDataViewRenderer : public wxDataViewRendererBase
{
public:
    // constructors / destructor
    // -------------------------

    wxDataViewRenderer(const wxString& varianttype,
                       wxDataViewCellMode mode = wxDATAVIEW_CELL_INERT,
                       int align = wxDVR_DEFAULT_ALIGNMENT);

    virtual ~wxDataViewRenderer();

    // inherited methods from wxDataViewRendererBase
    // ---------------------------------------------

    virtual int GetAlignment() const wxOVERRIDE
    {
        return m_alignment;
    }
    virtual wxDataViewCellMode GetMode() const wxOVERRIDE
    {
        return m_mode;
    }
    virtual bool GetValue(wxVariant& value) const wxOVERRIDE
    {
        value = m_value;
        return true;
    }

    // NB: in Carbon this is always identical to the header alignment
    virtual void SetAlignment(int align) wxOVERRIDE;
    virtual void SetMode(wxDataViewCellMode mode) wxOVERRIDE;
    virtual bool SetValue(const wxVariant& newValue) wxOVERRIDE
    {
        m_value = newValue;
        return true;
    }

    virtual void EnableEllipsize(wxEllipsizeMode mode = wxELLIPSIZE_MIDDLE) wxOVERRIDE;
    virtual wxEllipsizeMode GetEllipsizeMode() const wxOVERRIDE;

    // implementation
    // --------------

    const wxVariant& GetValue() const
    {
        return m_value;
    }

    wxDataViewRendererNativeData* GetNativeData() const
    {
        return m_NativeDataPtr;
    }

    // a call to the native data browser function to render the data;
    // returns true if the data value could be rendered, false otherwise
    virtual bool MacRender() = 0;

    void SetNativeData(wxDataViewRendererNativeData* newNativeDataPtr);

    void OSXUpdateAlignment();

#if wxOSX_USE_COCOA
    // called when a value was edited by user
    virtual void OSXOnCellChanged(NSObject *value,
                                  const wxDataViewItem& item,
                                  unsigned col);

protected:
    virtual void SetAttr(const wxDataViewItemAttr& attr) wxOVERRIDE;
    virtual void SetEnabled(bool enabled) wxOVERRIDE;
#else
protected:
    void SetAttr(const wxDataViewItemAttr& WXUNUSED(attr)) wxOVERRIDE { };
    void SetEnabled(bool WXUNUSED(enabled)) wxOVERRIDE { };
#endif

    virtual bool IsHighlighted() const wxOVERRIDE;

private:
    // contains the alignment flags
    int m_alignment;

    // storing the mode that determines how the cell is going to be shown
    wxDataViewCellMode m_mode;

    // data used by implementation of the native renderer
    wxDataViewRendererNativeData* m_NativeDataPtr;

    // value that is going to be rendered
    wxVariant m_value;

    wxDECLARE_DYNAMIC_CLASS_NO_COPY(wxDataViewRenderer);
};

#endif // _WX_OSX_DVRENDERER_H_


text:
package org.apereo.cas.config;

import org.apereo.cas.acme.AcmeAuthorizationExecutor;
import org.apereo.cas.acme.AcmeCertificateManager;
import org.apereo.cas.acme.AcmeChallengeRepository;
import org.apereo.cas.acme.AcmeWellKnownChallengeController;
import org.apereo.cas.configuration.CasConfigurationProperties;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import java.security.Security;

/**
 * This is {@link CasAcmeConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 6.4.0
 */
@Slf4j
@Configuration(value = "CasAcmeConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
@ConditionalOnProperty(name = "cas.acme.server-url")
public class CasAcmeConfiguration {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    @Autowired
    private CasConfigurationProperties casProperties;

    @Bean
    public AcmeWellKnownChallengeController acmeWellKnownChallengeController() {
        return new AcmeWellKnownChallengeController(acmeChallengeRepository());
    }

    @Bean
    public AcmeChallengeRepository acmeChallengeRepository() {
        return new AcmeChallengeRepository();
    }

    @Bean
    @ConditionalOnMissingBean(name = "acmeAuthorizationExecutor")
    public AcmeAuthorizationExecutor acmeAuthorizationExecutor() {
        return AcmeAuthorizationExecutor.defaultChallenge();
    }

    @Bean
    @ConditionalOnProperty(prefix = "cas.acme", name = "terms-of-use-accepted", havingValue = "true")
    public AcmeCertificateManager acmeCertificateManager() {
        return new AcmeCertificateManager(acmeChallengeRepository(),
            casProperties, acmeAuthorizationExecutor());
    }

    /**
     * Handle application ready event.
     *
     * @param event the event
     * @throws Exception the exception
     */
    @EventListener
    public void handleApplicationReadyEvent(final ApplicationReadyEvent event) throws Exception {
        val domains = casProperties.getAcme().getDomains();
        LOGGER.info("Fetching certificates for domains [{}]", domains);
        if (event.getApplicationContext().containsBean("acmeCertificateManager")) {
            acmeCertificateManager().fetchCertificate(domains);
        }
    }
}


text:
<!DOCTYPE HTML>

<title>Trip_Purpose</title>
<meta name="date" content="2016-05-18">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Library

Object

Prev Object

Next Object

Frames

No Frames

http://www.opentravel.org/OTM/profile/v0

CoreObject Trip_Purpose

http://www.opentravel.org/OTM/profile/v0:Trip_Purpose

Description

A trip purpose code used by this company.

Additional Documentation

Type
Value

Implementers
Assigned XSD Type: {http://chameleon.anonymous/ns}StringLength1to8

Facet Summary

Facets

Name
Type

Trip_Purpose_Summary
SUMMARY

Overview

Library

Object

Prev Object

Next Object

Frames

No Frames


text:
#include<string>
#include<vector>
#include "vmf/metadatastream.hpp"
#include "throwJavaException.hpp"

extern "C" {

using namespace vmf;

/*
 * Class:     com_intel_vmf_ReferenceDesc
 * Method:    n_ReferenceDesc
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_ReferenceDesc_n_1ReferenceDesc__(JNIEnv *env, jclass);

JNIEXPORT jlong JNICALL Java_com_intel_vmf_ReferenceDesc_n_1ReferenceDesc__ (JNIEnv *env, jclass)
{
    static const char method_name[] = "ReferenceDesc::n_1ReferenceDesc__";

    try
    {
        std::shared_ptr<ReferenceDesc>* obj = new std::shared_ptr<ReferenceDesc>(new ReferenceDesc());
        return (jlong)obj;
    }
    catch (const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_ReferenceDesc
 * Method:    n_ReferenceDesc
 * Signature: (Ljava/lang/String;ZZ)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_ReferenceDesc_n_1ReferenceDesc__Ljava_lang_String_2ZZ (JNIEnv *env, jclass, jstring name, jboolean isUnique, jboolean isCustom)
{
    static const char method_name[] = "ReferenceDesc::n_1ReferenceDesc__Ljava_lang_String_2ZZ";

    try
    {
        const char* tmp = env->GetStringUTFChars(name, NULL);
        std::string sName(tmp);
        std::shared_ptr<ReferenceDesc>* obj = new std::shared_ptr<ReferenceDesc>(new ReferenceDesc(sName, (isUnique == JNI_TRUE) ? true : false, (isCustom == JNI_TRUE) ? true : false));
        env->ReleaseStringUTFChars(name, tmp);
        return (jlong)obj;
    }
    catch (const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_ReferenceDesc
 * Method:    n_getName
 * Signature: (J)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_intel_vmf_ReferenceDesc_n_1getName (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "ReferenceDesc::n_1getName";

    try
    {
        std::shared_ptr<ReferenceDesc>* obj = (std::shared_ptr<ReferenceDesc>*) self;

        if ((obj == NULL) || (obj->get() == NULL))
            return 0;

        std::string str = (**obj).name;
        return env->NewStringUTF(str.c_str());
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_ReferenceDesc
 * Method:    n_isUnique
 * Signature: (J)Z
 */
JNIEXPORT jboolean JNICALL Java_com_intel_vmf_ReferenceDesc_n_1isUnique (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "ReferenceDesc::n_1isUnique";

    try
    {
        std::shared_ptr<ReferenceDesc>* obj = (std::shared_ptr<ReferenceDesc>*) self;

        if ((obj == NULL) || (obj->get() == NULL))
            return 0;

        jboolean isUnique = (jboolean)(**obj).isUnique;
        return isUnique;
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_ReferenceDesc
 * Method:    n_isCustom
 * Signature: (J)Z
 */
JNIEXPORT jboolean JNICALL Java_com_intel_vmf_ReferenceDesc_n_1isCustom (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "ReferenceDesc::n_1isCustom";

    try
    {
        std::shared_ptr<ReferenceDesc>* obj = (std::shared_ptr<ReferenceDesc>*) self;

        if ((obj == NULL) || (obj->get() == NULL))
            return 0;

        jboolean isCustom = (jboolean)(**obj).isCustom;
        return isCustom;
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_ReferenceDesc
 * Method:    n_delete
 * Signature: (J)V
 */
JNIEXPORT void JNICALL Java_com_intel_vmf_ReferenceDesc_n_1delete (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "ReferenceDesc::n_1delete";

    try
    {
        std::shared_ptr<ReferenceDesc>* obj = (std::shared_ptr<ReferenceDesc>*) self;

        if ((obj == NULL) || (obj->get() == NULL))
            VMF_EXCEPTION(NullPointerException, "Reference description is null pointer.");

        delete obj;
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }
}

}


text:
<router-outlet></router-outlet>
<router-outlet name='exercise-nav'></router-outlet>


text:
typedef NS_ENUM(NSUInteger, MWKSavedPageEntrySchemaVersion) {
    MWKSavedPageEntrySchemaVersionUnknown = 0,
    MWKSavedPageEntrySchemaVersion1 = 1,
    MWKSavedPageEntrySchemaVersion2 = 2,
    MWKSavedPageEntrySchemaVersionCurrent = MWKSavedPageEntrySchemaVersion2
};

static NSString *const MWKSavedPageEntrySchemaVersionKey = @"schemaVerison";

static NSString *const MWKSavedPageEntryDidMigrateImageDataKey = @"didMigrateImageData";

@interface MWKSavedPageEntry ()

@property (readwrite, strong, nonatomic) NSDate *date;

@property (nonatomic, readwrite) BOOL didMigrateImageData;

@end

@implementation MWKSavedPageEntry

- (instancetype)initWithURL:(NSURL *)url {
    url = [NSURL wmf_desktopURLForURL:url];
    NSParameterAssert(url.wmf_title);
    self = [super initWithURL:url];
    if (self) {
        self.date = [NSDate date];
        // defaults to true for instances since new image data will go to the correct location
        self.didMigrateImageData = YES;
    }
    return self;
}

- (instancetype)initWithDict:(NSDictionary *)dict {
    NSString *urlString = dict[@"url"];
    NSString *domain = dict[@"domain"];
    NSString *language = dict[@"language"];
    NSString *title = dict[@"title"];

    NSURL *url;

    if ([urlString length]) {
        url = [NSURL URLWithString:urlString];
    } else if (domain && language && title) {
        url = [NSURL wmf_URLWithDomain:domain language:language title:title fragment:nil];
    } else {
        return nil;
    }

    self = [self initWithURL:url];
    if (self) {
        NSNumber *schemaVersion = dict[MWKSavedPageEntrySchemaVersionKey];

        if (schemaVersion.unsignedIntegerValue > MWKSavedPageEntrySchemaVersion1) {
            self.date = [self requiredDate:@"date" dict:dict];
        } else {
            self.date = [NSDate date];
        }

        if (schemaVersion.unsignedIntegerValue >= MWKSavedPageEntrySchemaVersion1) {
            self.didMigrateImageData =
                [[self requiredNumber:MWKSavedPageEntryDidMigrateImageDataKey dict:dict] boolValue];
        } else {
            // entries reading legacy data have not been migrated
            self.didMigrateImageData = NO;
        }
    }
    return self;
}

- (BOOL)isEqual:(id)object {
    if (self == object) {
        return YES;
    } else if ([object isKindOfClass:[MWKSavedPageEntry class]]) {
        return [self isEqualToEntry:object];
    } else {
        return NO;
    }
}

- (BOOL)isEqualToEntry:(MWKSavedPageEntry *)rhs {
    return WMF_RHS_PROP_EQUAL(url, isEqual:);
}

- (NSUInteger)hash {
    return self.url.hash;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"%@ %@, didMigrateImageData: %d",
                                      [super description], self.url, self.didMigrateImageData];
}

#pragma mark - MWKListObject

- (id<NSCopying>)listIndex {
    return self.url;
}

- (id)dataExport {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

    [dict wmf_maybeSetObject:@(MWKSavedPageEntrySchemaVersionCurrent) forKey:MWKSavedPageEntrySchemaVersionKey];
    [dict wmf_maybeSetObject:@(self.didMigrateImageData) forKey:MWKSavedPageEntryDidMigrateImageDataKey];
    [dict wmf_maybeSetObject:[self.url absoluteString] forKey:@"url"];
    [dict wmf_maybeSetObject:[self iso8601DateString:self.date] forKey:@"date"];
    return [NSDictionary dictionaryWithDictionary:dict];
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" android:background="@color/bg">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:gravity="center"
        android:paddingTop="5pt"
        android:paddingBottom="3pt"
        android:textColor="@color/火"
        android:text="@string/no_sex"
        android:id="@+id/textView" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/boder">

        <TextView
            android:layout_width="0pt"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="一"
            android:gravity="center" />

        <TextView
            android:layout_width="0pt"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="二"
            android:gravity="center" />

        <TextView
            android:layout_width="0pt"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="三"
            android:gravity="center" />

        <TextView
            android:layout_width="0pt"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="四"
            android:gravity="center" />

        <TextView
            android:layout_width="0pt"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="五"
            android:gravity="center" />

        <TextView
            android:layout_width="0pt"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="六"
            android:gravity="center" />

        <TextView
            android:layout_width="0pt"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="日"
            android:gravity="center" />
    </LinearLayout>

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/layout"></LinearLayout>
    </ScrollView>
</LinearLayout>


text:
package com.zeroq6.moehelper.app;

import com.zeroq6.moehelper.conn.ConnThread;
import com.zeroq6.moehelper.config.Configuration;
import com.zeroq6.moehelper.conn.ConnManager;
import com.zeroq6.moehelper.resources.ResourcesHolder;
import com.zeroq6.moehelper.utils.MyLogUtils;

/**
 * 主方法调用
 *
 * @author icgeass@hotmail.com
 * @date 2015年6月2日
 */
public class App {

    public static void main(String[] args) {
        try{
            Configuration.init(args);
            begin();
            Configuration.newWriter().writeToFile();
            MyLogUtils.stdOut("所有操作已完成");
        }catch (Exception e){
            MyLogUtils.fatal(e.getMessage(), e);
        }
    }

    private static void begin() throws InterruptedException {
        lab:
        while (true) {
            int pageId = ConnManager.getInstance().getPageId();
            if (pageId != ConnManager.ALL_COMPLETED && pageId != ConnManager.LOCKED) {
                new ConnThread(pageId).start();
            } else if (pageId == ConnManager.ALL_COMPLETED) {
                // 对应下载完成但是本地是否解析完成的判断
                int allPageNum = Configuration.getToPage() - Configuration.getFromPage() + 1;
                if (ResourcesHolder.getMapIdPage().size() + ResourcesHolder.getReadFailedPageCount() != allPageNum || ResourcesHolder.getMapIdLog().size() != allPageNum) {
                    MyLogUtils.stdOut("等待本地处理完成");
                    Thread.sleep(500);
                }
                // 若匹配完成则跳出外层循环,否则循环等待
                while (true) {
                    if (ResourcesHolder.getMapIdPage().size() + ResourcesHolder.getReadFailedPageCount() == allPageNum && ResourcesHolder.getMapIdLog().size() == allPageNum) {
                        MyLogUtils.stdOut("本地处理完成");
                        break lab;
                    } else {
                        Thread.sleep(500);
                    }
                }
            }
            // 每隔0.02秒获取pageId
            Thread.sleep(20);
        }
    }

}


text:
class DResourceLoader;

class DResource :
	public DawnEngineObject
{
	DClass(DResource)
public:
	DResource(DResourceLoader* loader);
	~DResource();
	virtual void Load();
	virtual void Destroy();
protected:
	DResourceLoader* Loader;
private:
	bool __isLoad;
public:
	bool isLoad() const;
};


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>K-Index (Parse4CN1 API Documentation)</title>
<meta name="date" content="2017-01-24">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G H I J K L M N O P Q R S T U V W

K

keySet() - Method in class com.parse4cn1.ParseObject

Returns a set view of the keys contained in this object.

KEYWORD_OP - Static variable in class com.parse4cn1.ParseConstants

KEYWORD_TYPE - Static variable in class com.parse4cn1.ParseConstants

A C D E F G H I J K L M N O P Q R S T U V W

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?php
/**
 * @namespace
 */
namespace Vein\Core\Crud\Grid;

use Vein\Core\Crud\Grid,
    Vein\Core\Crud\Container\Grid as GridContainer;

/**
 * Interface of grid column
 *
 * @category   Vein\Core
 * @package    Crud
 * @subpackage Grid
 */
interface ColumnInterface
{
	/**
	 * Render column
	 *
	 * @param mixed $row
     *
     * @return string
	 */
	public function render($row);

	/**
	 * Update grid container
	 *
	 * @param \Vein\Core\Crud\Container\Grid\Adapter $container
     *
     * @return \Vein\Core\Crud\Grid\ColumnInterface
	 */
	public function updateContainer(GridContainer\Adapter $container);

	/**
	 * Update container data source
	 *
	 * @param mixed $dataSource
     *
     * @return \Vein\Core\Crud\Grid\ColumnInterface
	 */
	public function updateDataSource($dataSource);
}


text:
/** Automatically generated file. DO NOT MODIFY */
package com.example.testwrapper;

public final class BuildConfig {
    public final static boolean DEBUG = false;
}


text:
class Tr8n::TranslationDomain < ActiveRecord::Base

  after_save      :clear_cache
  after_destroy   :clear_cache

  has_many    :translation_sources,       :class_name => "Tr8n::TranslationSource",     :dependent => :destroy
  has_many    :translation_key_sources,   :class_name => "Tr8n::TranslationKeySource",  :through => :translation_sources
  has_many    :translation_keys,          :class_name => "Tr8n::TranslationKey",        :through => :translation_key_sources

  alias :sources      :translation_sources
  alias :key_sources  :translation_key_sources
  alias :keys         :translation_keys

  def self.cache_key(domain_name)
    "translation_domain_#{domain_name}"
  end

  def cache_key
    self.class.cache_key(name)
  end

  def self.find_or_create(url = nil)
    domain_name = URI.parse(url || 'localhost').host || 'localhost'
    Tr8n::Cache.fetch(cache_key(domain_name)) do
      find_by_name(domain_name) || create(:name => domain_name)
    end
  end

  def clear_cache
    Tr8n::Cache.delete(cache_key)
  end

end


text:
/*!
	@file
	@author		Georgiy Evmenov
	@date		12/2009
*/

#include "Precompiled.h"
#include "PanelControllers.h"
#include "EditorWidgets.h"
#include "UndoManager.h"
#include "PropertyFieldManager.h"
#include "Localise.h"

namespace tools
{

	PanelControllers::PanelControllers() :
		BasePanelViewItem("PanelControllers.layout"),
		mControllerName(nullptr),
		mButtonAdd(nullptr),
		mButtonDelete(nullptr),
		mList(nullptr),
		mCurrentWidget(nullptr),
		mButtonLeft(0),
		mButtonRight(0),
		mButtonSpace(0),
		mIndexSelected(MyGUI::ITEM_NONE)
	{
	}

	void PanelControllers::initialise()
	{
		mPanelCell->setCaption(replaceTags("PanelControllersName"));

		assignWidget(mControllerName, "controllerName");
		assignWidget(mButtonAdd, "buttonAdd");
		assignWidget(mButtonDelete, "buttonDelete");
		assignWidget(mList, "list");

		mButtonAdd->eventMouseButtonClick += MyGUI::newDelegate(this, &PanelControllers::notifyAdd);
		mButtonDelete->eventMouseButtonClick += MyGUI::newDelegate(this, &PanelControllers::notifyDelete);
		mList->eventListChangePosition += MyGUI::newDelegate(this, &PanelControllers::notifySelectItem);

		mButtonLeft = mButtonAdd->getLeft();
		mButtonRight = mMainWidget->getWidth() - mButtonDelete->getRight();
		mButtonSpace = mButtonDelete->getLeft() - mButtonAdd->getRight();

		MyGUI::ResourceManager::getInstance().registerLoadXmlDelegate("ControllerTypes") = MyGUI::newDelegate(this, &PanelControllers::loadControllerTypes);
		MyGUI::ResourceManager::getInstance().load("Controllers.xml");
	}

	void PanelControllers::shutdown()
	{
		destroyPropertyFields();
	}

	void PanelControllers::update(MyGUI::Widget* _currentWidget)
	{
		destroyPropertyFields();

		mCurrentWidget = _currentWidget;
		if (mCurrentWidget == nullptr)
			return;

		WidgetContainer* widgetContainer = EditorWidgets::getInstance().find(_currentWidget);

		mList->removeAllItems();
		for (std::vector<ControllerInfo*>::iterator iter = widgetContainer->mController.begin(); iter != widgetContainer->mController.end(); ++iter)
		{
			mList->addItem((*iter)->mType, *iter);
		}

		mPanelCell->setClientHeight(mButtonDelete->getCoord().bottom());
	}

	void PanelControllers::notifyChangeWidth(int _width)
	{
		int width = mMainWidget->getClientCoord().width;

		int half_width = (width - (mButtonLeft + mButtonRight + mButtonSpace)) / 2;
		mButtonAdd->setSize(half_width, mButtonAdd->getHeight());
		mButtonDelete->setCoord(mButtonAdd->getRight() + mButtonSpace, mButtonDelete->getTop(), width - (mButtonAdd->getRight() + mButtonSpace + mButtonRight), mButtonDelete->getHeight());
	}

	void PanelControllers::notifyAdd(MyGUI::Widget* _sender)
	{
		std::string key = mControllerName->getOnlyText();
		WidgetContainer* widgetContainer = EditorWidgets::getInstance().find(mCurrentWidget);

		ControllerInfo* controllerInfo = new ControllerInfo();
		controllerInfo->mType = key;
		widgetContainer->mController.push_back(controllerInfo);

		mList->addItem(key, controllerInfo);
		UndoManager::getInstance().addValue();
	}

	void PanelControllers::notifyDelete(MyGUI::Widget* _sender)
	{
		size_t index = mList->getIndexSelected();
		if (MyGUI::ITEM_NONE == index)
			return;

		WidgetContainer* widgetContainer = EditorWidgets::getInstance().find(mCurrentWidget);
		std::vector<ControllerInfo*>::iterator iter = std::find(widgetContainer->mController.begin(), widgetContainer->mController.end(), *mList->getItemDataAt<ControllerInfo*>(index));
		if (iter != widgetContainer->mController.end())
		{
			delete *iter;
			widgetContainer->mController.erase(iter);
		}

		mList->removeItemAt(index);
		UndoManager::getInstance().addValue();

		// обновляем текущий индекс
		notifySelectItem(mList, mList->getIndexSelected());
	}

	void PanelControllers::notifySelectItem(MyGUI::ListBox* _sender, size_t _index)
	{
		destroyPropertyFields();

		mIndexSelected = mList->getIndexSelected();
		if (MyGUI::ITEM_NONE == mIndexSelected)
			return;

		std::string key = mList->getItemNameAt(mIndexSelected);
		mControllerName->setOnlyText(key);

		if (mControllersProperties.find(key) != mControllersProperties.end())
		{
			ControllerInfo* controllerInfo = *mList->getItemDataAt<ControllerInfo*>(mIndexSelected);

			for (MyGUI::MapString::iterator iter = mControllersProperties[key].begin(); iter != mControllersProperties[key].end(); ++iter)
			{
				std::string value = "";
				if (controllerInfo->mProperty.find(iter->first) != controllerInfo->mProperty.end())
					value = controllerInfo->mProperty[iter->first];

				IPropertyField* field = PropertyFieldManager::getInstance().createPropertyField(mWidgetClient, iter->second);
				field->setTarget(mCurrentWidget);
				field->setName(iter->first);
				field->setValue(value);
				field->eventAction = MyGUI::newDelegate(this, &PanelControllers::notifyAction);
				mFields.push_back(field);
			}
		}

		updateSize();
	}

	void PanelControllers::updateSize()
	{
		int height = mButtonDelete->getCoord().bottom() + 3;

		for (VectorPropertyField::iterator item = mFields.begin(); item != mFields.end(); ++ item)
		{
			MyGUI::IntSize size = (*item)->getContentSize();
			(*item)->setCoord(MyGUI::IntCoord(0, height, mMainWidget->getWidth(), size.height));
			height += size.height;
		}

		mPanelCell->setClientHeight(height);
	}

	void PanelControllers::loadControllerTypes(MyGUI::xml::ElementPtr _node, const std::string& _file, MyGUI::Version _version)
	{
		MyGUI::xml::ElementEnumerator controller = _node->getElementEnumerator();
		while (controller.next("Controller"))
		{
			MyGUI::MapString controllerProperties;
			std::string name = controller->findAttribute("name");
			mControllerName->addItem(name);
			MyGUI::xml::ElementEnumerator prop = controller->getElementEnumerator();
			while (prop.next("Property"))
				controllerProperties[prop->findAttribute("key")] = prop->findAttribute("type");
			mControllersProperties[name] = controllerProperties;
		}
	}

	void PanelControllers::destroyPropertyFields()
	{
		for (VectorPropertyField::iterator item = mFields.begin(); item != mFields.end(); ++ item)
			delete (*item);
		mFields.clear();
	}

	void PanelControllers::notifyAction(const std::string& _name, const std::string& _value, bool _final)
	{
		if (_final)
		{
			if (mIndexSelected != MyGUI::ITEM_NONE)
			{
				WidgetContainer* widgetContainer = EditorWidgets::getInstance().find(mCurrentWidget);
				widgetContainer->mController[mIndexSelected]->mProperty[_name] = _value;

				UndoManager::getInstance().addValue(PR_PROPERTIES);
			}
		}
	}

}


text:
import { UISref, UISrefActive } from '@uirouter/react';
import React from 'react';

import type { Application } from '@spinnaker/core';
import { AccountTag, CollapsibleSection, Spinner, timestamp } from '@spinnaker/core';

import type { IEcsLoadBalancer } from '../../domain/IEcsLoadBalancer';
import { EcsListener } from '../listener';

interface IEcsLoadBalancerFromStateParams {
  accountId: string;
  region: string;
  name: string;
  vpcId: string;
}

interface IEcsLoadBalancerDetailsState {
  loadBalancer: IEcsLoadBalancer;
  loadBalancerNotFound?: string;
  loading: boolean;
  refreshListenerUnsubscribe: () => void;
}

export interface IEcsLoadBalancerDetailsProps {
  app: Application;
  accountId: string;
  loadBalancer: IEcsLoadBalancerFromStateParams;
}

export class EcsLoadBalancerDetails extends React.Component<
  IEcsLoadBalancerDetailsProps,
  IEcsLoadBalancerDetailsState
> {
  constructor(props: IEcsLoadBalancerDetailsProps) {
    super(props);
    this.state = {
      loading: true,
      loadBalancer: undefined,
      refreshListenerUnsubscribe: () => {},
    };

    props.app
      .getDataSource('loadBalancers')
      .ready()
      .then(() => this.extractLoadBalancer());
  }

  public componentWillUnmount(): void {
    this.state.refreshListenerUnsubscribe();
  }

  private extractLoadBalancer(): void {
    const { name, region } = this.props.loadBalancer;
    const loadBalancer: IEcsLoadBalancer = this.props.app
      .getDataSource('loadBalancers')
      .data.find((test: IEcsLoadBalancer) => {
        return test.name === name && test.account === this.props.loadBalancer.accountId && test.region === region;
      });

    this.setState({
      loading: false,
      loadBalancer,
    });
    this.state.refreshListenerUnsubscribe();

    if (loadBalancer) {
      this.setState({
        refreshListenerUnsubscribe: this.props.app
          .getDataSource('loadBalancers')
          .onRefresh(null, () => this.extractLoadBalancer()),
      });
    } else {
      this.setState({
        refreshListenerUnsubscribe: () => {},
      });
    }
  }

  public render(): React.ReactElement<EcsLoadBalancerDetails> {
    const loadBalancerName = this.props.loadBalancer.name;
    const { loadBalancer, loading } = this.state;
    const { accountId } = this.props;

    const CloseButton = (

        <UISref to="^">

        </UISref>

    );

    const loadingHeader = () => (

        {CloseButton}

          <Spinner size="small" />

    );

    const notFoundContent = () => (

Load balancer not found.

    );

    const loadBalancerHeader = () => (

        {CloseButton}

{loadBalancerName}

    );

    const loadBalancerContent = () => (

        <CollapsibleSection heading="Load Balancer Details" defaultExpanded={true}>

Created

{timestamp(loadBalancer.createdTime)}

In

              <AccountTag account={accountId} />

              {loadBalancer.region}

VPC

{loadBalancer.vpcId}

Type

{loadBalancer.loadBalancerType}

IP Type

{loadBalancer.ipAddressType}

Availability Zones

                {loadBalancer.availabilityZones.map((az) => {
                  return
{az}
;
                })}

Target Groups

                {loadBalancer.targetGroups.map((tg) => {
                  return (

                      <UISrefActive class="active">
                        <UISref
                          to="^.ecsTargetGroupDetails"
                          params={{
                            loadBalancerName: loadBalancer.name,
                            region: loadBalancer.region,
                            accountId: loadBalancer.account,
                            name: tg.targetGroupName,
                            vpcId: tg.vpcId,
                            provider: loadBalancer.cloudProvider,
                          }}
                        >
                          {tg.targetGroupName}
                        </UISref>
                      </UISrefActive>

                  );
                })}

DNS Name

                {loadBalancer.dnsname}

        </CollapsibleSection>
        <CollapsibleSection heading="Status" defaultExpanded={false}>
          Select a target group to check the instance health status from the view of its server groups.
        </CollapsibleSection>
        <CollapsibleSection heading="Listeners" defaultExpanded={false}>
          {loadBalancer.listeners ? (
            loadBalancer.listeners.map((listener, index) => {
              return (

                    <EcsListener listener={listener}></EcsListener>

              );
            })
          ) : (

No listeners provided.

          )}
        </CollapsibleSection>
        <CollapsibleSection heading="Firewalls" defaultExpanded={false}>

            {loadBalancer.securityGroups ? (
              loadBalancer.securityGroups.map((sg) => {
                return
{sg}
;
              })
            ) : (

No security groups provided.

            )}

        </CollapsibleSection>
        <CollapsibleSection heading="Subnets" defaultExpanded={false}>

            {loadBalancer.subnets.map((subnet) => {
              return
{subnet}
;
            })}

        </CollapsibleSection>

    );

    return (

        {loading && loadingHeader()}
        {!loading && loadBalancerHeader()}
        {!loading && !loadBalancer && notFoundContent()}
        {!loading && loadBalancer && loadBalancerContent()}

    );
  }
}


text:
require "statusboard"
require "statusboard/server"

require "rack/handler"
require "rack-handlers"

app = Statusboard::StatusboardServer.new! # create a new, _unwrapped_ instance of the server class

# Make the top-level syntax work by delegating the right function calls to the right destination
Sinatra::Delegator.target = app.server_description		# Why this? We want all top level function calls to be DSL calls -> So we have to call them in the actual DSL instance, and not the app class itself (which gets its settings from its DSL class instance)
Sinatra::Delegator.delegate :widget, :server_settings	# Allowed calls

# include would include the module in Object
# extend only extends the main object
extend Sinatra::Delegator

class Rack::Builder
  include Sinatra::Delegator
end

# Run the app _after_ the applications main file (where this file was included in) was executed successfully to allow for configuration
at_exit { Rack::Handler.default.run(app, app.server_description.server_settings) if $!.nil? }


text:
import { fetchData } from '../../commons/resource';
import { QUEUE_LIST_PATH } from '../../consts/path';
import { GET_QUEUE_LIST } from '../../consts/action';

export function getQueueList(params) {
    return fetchData(Object.assign({
        category: GET_QUEUE_LIST,
        query: params
    }, QUEUE_LIST_PATH));
};


text:
namespace MassTransit.Configuration
{
    public interface IMessageTopologyConfigurator<TMessage> :
        IMessageTypeTopologyConfigurator,
        IMessageTopology<TMessage>
        where TMessage : class
    {
        /// <summary>
        /// Sets the entity name formatter used for this message type
        /// </summary>
        /// <param name="entityNameFormatter"></param>
        void SetEntityNameFormatter(IMessageEntityNameFormatter<TMessage> entityNameFormatter);

        /// <summary>
        /// Sets the entity name for this message type
        /// </summary>
        /// <param name="entityName">The entity name</param>
        void SetEntityName(string entityName);
    }

    public interface IMessageTopologyConfigurator :
        IMessageTopology
    {
        /// <summary>
        /// Replace the default entity name formatter
        /// </summary>
        void SetEntityNameFormatter(IEntityNameFormatter entityNameFormatter);

        new IMessageTopologyConfigurator<T> GetMessageTopology<T>()
            where T : class;
    }
}


text:
name: joohee.lee
title: 이주희
image: /files/authors/movie_image.jpg
---


text:
cmake_minimum_required(VERSION 2.6 FATAL_ERROR)
cmake_policy(VERSION 2.6)

project(tinyxml2)
include(GNUInstallDirs)

#CMAKE_BUILD_TOOL

################################
# set lib version here

set(GENERIC_LIB_VERSION "1.0.11")
set(GENERIC_LIB_SOVERSION "1")

################################
# Add common source

include_directories("${CMAKE_CURRENT_SOURCE_DIR}/.")

################################
# Add definitions

if(MSVC)
	add_definitions(-D_CRT_SECURE_NO_WARNINGS)
endif(MSVC)

################################
# Add targets
add_library(tinyxml2static STATIC tinyxml2.cpp tinyxml2.h)
set_target_properties(tinyxml2static PROPERTIES OUTPUT_NAME tinyxml2)

install(TARGETS tinyxml2static #tinyxml2
		RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
		LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
		ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(FILES tinyxml2.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})

foreach(p LIB INCLUDE)
	set(var CMAKE_INSTALL_${p}DIR)
	if(NOT IS_ABSOLUTE "${${var}}")
		set(${var} "${CMAKE_INSTALL_PREFIX}/${${var}}")
	endif()
endforeach()

configure_file(tinyxml2.pc.in tinyxml2.pc @ONLY)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/tinyxml2.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)


text:
#ifndef _WX_XH_FILECTRL_H_
#define _WX_XH_FILECTRL_H_

#include "wx/xrc/xmlres.h"

#if wxUSE_XRC && wxUSE_FILECTRL

class WXDLLIMPEXP_XRC wxFileCtrlXmlHandler : public wxXmlResourceHandler
{
public:
    wxFileCtrlXmlHandler();
    virtual wxObject *DoCreateResource();
    virtual bool CanHandle(wxXmlNode *node);

private:
    DECLARE_DYNAMIC_CLASS(wxFileCtrlXmlHandler)
};

#endif // wxUSE_XRC && wxUSE_FILECTRL

#endif // _WX_XH_FILEPICKERCTRL_H_


text:
declare namespace OIPF {
    export class LocalSystem {

    }
}


text:
Ruby Process Tree displays a process and its childern as a tree.

This application uses:

* [Methadone](https://github.com/davetron5000/methadone) library, by [David Bryant Copeland](http://www.naildrivin5.com/blog/2011/12/19/methadone-the-awesome-cli-library.html)
* [RubyTree](http://rubytree.rubyforge.org/)

## Usage

The following command dispays all top-level processes and their childeren:

	rpstree

If you know the process id you're lookiging for, you can use the following command to show that process:

	rpstree 1234

You can get help by running:

	rpstree --help

## Installation

	$ gem install rpstree

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request