text:
package com.android.server.voiceinteraction;

import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.app.AppOpsManager;
import android.app.IActivityManager;
import android.app.assist.AssistContent;
import android.app.assist.AssistStructure;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.UserHandle;
import android.provider.Settings;
import android.service.voice.IVoiceInteractionSession;
import android.service.voice.IVoiceInteractionSessionService;
import android.service.voice.VoiceInteractionService;
import android.service.voice.VoiceInteractionSession;
import android.util.Slog;
import android.view.IWindowManager;
import android.view.WindowManager;

import com.android.internal.app.IAssistScreenshotReceiver;
import com.android.internal.app.IVoiceInteractionSessionShowCallback;
import com.android.internal.app.IVoiceInteractor;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.os.IResultReceiver;
import com.android.server.LocalServices;
import com.android.server.statusbar.StatusBarManagerInternal;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

final class VoiceInteractionSessionConnection implements ServiceConnection {

    final static String TAG = "VoiceInteractionServiceManager";

    private static final String KEY_RECEIVER_EXTRA_COUNT = "count";
    private static final String KEY_RECEIVER_EXTRA_INDEX = "index";

    final IBinder mToken = new Binder();
    final Object mLock;
    final ComponentName mSessionComponentName;
    final Intent mBindIntent;
    final int mUser;
    final Context mContext;
    final Callback mCallback;
    final int mCallingUid;
    final Handler mHandler;
    final IActivityManager mAm;
    final IWindowManager mIWindowManager;
    final AppOpsManager mAppOps;
    final IBinder mPermissionOwner;
    boolean mShown;
    Bundle mShowArgs;
    int mShowFlags;
    boolean mBound;
    boolean mFullyBound;
    boolean mCanceled;
    IVoiceInteractionSessionService mService;
    IVoiceInteractionSession mSession;
    IVoiceInteractor mInteractor;
    boolean mHaveAssistData;
    int mPendingAssistDataCount;
    ArrayList<AssistDataForActivity> mAssistData = new ArrayList<>();
    boolean mHaveScreenshot;
    Bitmap mScreenshot;
    ArrayList<IVoiceInteractionSessionShowCallback> mPendingShowCallbacks = new ArrayList<>();

    static class AssistDataForActivity {
        int activityIndex;
        int activityCount;
        Bundle data;

        public AssistDataForActivity(Bundle data) {
            this.data = data;
            Bundle receiverExtras = data.getBundle(VoiceInteractionSession.KEY_RECEIVER_EXTRAS);
            if (receiverExtras != null) {
                activityIndex = receiverExtras.getInt(KEY_RECEIVER_EXTRA_INDEX);
                activityCount = receiverExtras.getInt(KEY_RECEIVER_EXTRA_COUNT);
            }
        }
    }

    IVoiceInteractionSessionShowCallback mShowCallback =
            new IVoiceInteractionSessionShowCallback.Stub() {
        @Override
        public void onFailed() throws RemoteException {
            synchronized (mLock) {
                notifyPendingShowCallbacksFailedLocked();
            }
        }

        @Override
        public void onShown() throws RemoteException {
            synchronized (mLock) {
                // TODO: Figure out whether this is good enough or whether we need to hook into
                // Window manager to actually wait for the window to be drawn.
                notifyPendingShowCallbacksShownLocked();
            }
        }
    };

    public interface Callback {
        public void sessionConnectionGone(VoiceInteractionSessionConnection connection);
    }

    final ServiceConnection mFullConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    final IResultReceiver mAssistReceiver = new IResultReceiver.Stub() {
        @Override
        public void send(int resultCode, Bundle resultData) throws RemoteException {
            synchronized (mLock) {
                if (mShown) {
                    mHaveAssistData = true;
                    mAssistData.add(new AssistDataForActivity(resultData));
                    deliverSessionDataLocked();
                }
            }
        }
    };

    final IAssistScreenshotReceiver mScreenshotReceiver = new IAssistScreenshotReceiver.Stub() {
        @Override
        public void send(Bitmap screenshot) throws RemoteException {
            synchronized (mLock) {
                if (mShown) {
                    mHaveScreenshot = true;
                    mScreenshot = screenshot;
                    deliverSessionDataLocked();
                }
            }
        }
    };

    public VoiceInteractionSessionConnection(Object lock, ComponentName component, int user,
            Context context, Callback callback, int callingUid, Handler handler) {
        mLock = lock;
        mSessionComponentName = component;
        mUser = user;
        mContext = context;
        mCallback = callback;
        mCallingUid = callingUid;
        mHandler = handler;
        mAm = ActivityManagerNative.getDefault();
        mIWindowManager = IWindowManager.Stub.asInterface(
                ServiceManager.getService(Context.WINDOW_SERVICE));
        mAppOps = context.getSystemService(AppOpsManager.class);
        IBinder permOwner = null;
        try {
            permOwner = mAm.newUriPermissionOwner("voicesession:"
                    + component.flattenToShortString());
        } catch (RemoteException e) {
            Slog.w("voicesession", "AM dead", e);
        }
        mPermissionOwner = permOwner;
        mBindIntent = new Intent(VoiceInteractionService.SERVICE_INTERFACE);
        mBindIntent.setComponent(mSessionComponentName);
        mBound = mContext.bindServiceAsUser(mBindIntent, this,
                Context.BIND_AUTO_CREATE | Context.BIND_WAIVE_PRIORITY
                        | Context.BIND_ALLOW_OOM_MANAGEMENT, new UserHandle(mUser));
        if (mBound) {
            try {
                mIWindowManager.addWindowToken(mToken,
                        WindowManager.LayoutParams.TYPE_VOICE_INTERACTION);
            } catch (RemoteException e) {
                Slog.w(TAG, "Failed adding window token", e);
            }
        } else {
            Slog.w(TAG, "Failed binding to voice interaction session service "
                    + mSessionComponentName);
        }
    }

    public int getUserDisabledShowContextLocked() {
        int flags = 0;
        if (Settings.Secure.getIntForUser(mContext.getContentResolver(),
                Settings.Secure.ASSIST_STRUCTURE_ENABLED, 1, mUser) == 0) {
            flags |= VoiceInteractionSession.SHOW_WITH_ASSIST;
        }
        if (Settings.Secure.getIntForUser(mContext.getContentResolver(),
                Settings.Secure.ASSIST_SCREENSHOT_ENABLED, 1, mUser) == 0) {
            flags |= VoiceInteractionSession.SHOW_WITH_SCREENSHOT;
        }
        return flags;
    }

    public boolean showLocked(Bundle args, int flags, int disabledContext,
            IVoiceInteractionSessionShowCallback showCallback, IBinder activityToken,
            List<IBinder> topActivities) {
        if (mBound) {
            if (!mFullyBound) {
                mFullyBound = mContext.bindServiceAsUser(mBindIntent, mFullConnection,
                        Context.BIND_AUTO_CREATE | Context.BIND_TREAT_LIKE_ACTIVITY
                                | Context.BIND_FOREGROUND_SERVICE,
                        new UserHandle(mUser));
            }
            mShown = true;
            boolean isAssistDataAllowed = true;
            try {
                isAssistDataAllowed = mAm.isAssistDataAllowedOnCurrentActivity();
            } catch (RemoteException e) {
            }
            disabledContext |= getUserDisabledShowContextLocked();
            boolean structureEnabled = isAssistDataAllowed
                    && (disabledContext&VoiceInteractionSession.SHOW_WITH_ASSIST) == 0;
            boolean screenshotEnabled = isAssistDataAllowed && structureEnabled
                    && (disabledContext&VoiceInteractionSession.SHOW_WITH_SCREENSHOT) == 0;
            mShowArgs = args;
            mShowFlags = flags;
            mHaveAssistData = false;
            mPendingAssistDataCount = 0;
            boolean needDisclosure = false;
            if ((flags&VoiceInteractionSession.SHOW_WITH_ASSIST) != 0) {
                if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ASSIST_STRUCTURE, mCallingUid,
                        mSessionComponentName.getPackageName()) == AppOpsManager.MODE_ALLOWED
                        && structureEnabled) {
                    mAssistData.clear();
                    final int count = activityToken != null ? 1 : topActivities.size();
                    // Temp workaround for bug: 28348867  Revert after DP3
                    for (int i = 0; i < count && i < 1; i++) {
                        IBinder topActivity = count == 1 ? activityToken : topActivities.get(i);
                        try {
                            MetricsLogger.count(mContext, "assist_with_context", 1);
                            Bundle receiverExtras = new Bundle();
                            receiverExtras.putInt(KEY_RECEIVER_EXTRA_INDEX, i);
                            receiverExtras.putInt(KEY_RECEIVER_EXTRA_COUNT, count);
                            if (mAm.requestAssistContextExtras(ActivityManager.ASSIST_CONTEXT_FULL,
                                    mAssistReceiver, receiverExtras, topActivity,
                                    /* focused= */ i == 0, /* newSessionId= */ i == 0)) {
                                needDisclosure = true;
                                mPendingAssistDataCount++;
                            } else if (i == 0) {
                                // Wasn't allowed... given that, let's not do the screenshot either.
                                mHaveAssistData = true;
                                mAssistData.clear();
                                screenshotEnabled = false;
                                break;
                            }
                        } catch (RemoteException e) {
                        }
                    }
                } else {
                    mHaveAssistData = true;
                    mAssistData.clear();
                }
            } else {
                mAssistData.clear();
            }
            mHaveScreenshot = false;
            if ((flags&VoiceInteractionSession.SHOW_WITH_SCREENSHOT) != 0) {
                if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ASSIST_SCREENSHOT, mCallingUid,
                        mSessionComponentName.getPackageName()) == AppOpsManager.MODE_ALLOWED
                        && screenshotEnabled) {
                    try {
                        MetricsLogger.count(mContext, "assist_with_screen", 1);
                        needDisclosure = true;
                        mIWindowManager.requestAssistScreenshot(mScreenshotReceiver);
                    } catch (RemoteException e) {
                    }
                } else {
                    mHaveScreenshot = true;
                    mScreenshot = null;
                }
            } else {
                mScreenshot = null;
            }
            if (needDisclosure) {
                mHandler.post(mShowAssistDisclosureRunnable);
            }
            if (mSession != null) {
                try {
                    mSession.show(mShowArgs, mShowFlags, showCallback);
                    mShowArgs = null;
                    mShowFlags = 0;
                } catch (RemoteException e) {
                }
                deliverSessionDataLocked();
            } else if (showCallback != null) {
                mPendingShowCallbacks.add(showCallback);
            }
            return true;
        }
        if (showCallback != null) {
            try {
                showCallback.onFailed();
            } catch (RemoteException e) {
            }
        }
        return false;
    }

    void grantUriPermission(Uri uri, int mode, int srcUid, int destUid, String destPkg) {
        if (!"content".equals(uri.getScheme())) {
            return;
        }
        long ident = Binder.clearCallingIdentity();
        try {
            // This will throw SecurityException for us.
            mAm.checkGrantUriPermission(srcUid, null, ContentProvider.getUriWithoutUserId(uri),
                    mode, ContentProvider.getUserIdFromUri(uri, UserHandle.getUserId(srcUid)));
            // No security exception, do the grant.
            int sourceUserId = ContentProvider.getUserIdFromUri(uri, mUser);
            uri = ContentProvider.getUriWithoutUserId(uri);
            mAm.grantUriPermissionFromOwner(mPermissionOwner, srcUid, destPkg,
                    uri, Intent.FLAG_GRANT_READ_URI_PERMISSION, sourceUserId, mUser);
        } catch (RemoteException e) {
        } catch (SecurityException e) {
            Slog.w(TAG, "Can't propagate permission", e);
        } finally {
            Binder.restoreCallingIdentity(ident);
        }

    }

    void grantClipDataItemPermission(ClipData.Item item, int mode, int srcUid, int destUid,
            String destPkg) {
        if (item.getUri() != null) {
            grantUriPermission(item.getUri(), mode, srcUid, destUid, destPkg);
        }
        Intent intent = item.getIntent();
        if (intent != null && intent.getData() != null) {
            grantUriPermission(intent.getData(), mode, srcUid, destUid, destPkg);
        }
    }

    void grantClipDataPermissions(ClipData data, int mode, int srcUid, int destUid,
            String destPkg) {
        final int N = data.getItemCount();
        for (int i=0; i<N; i++) {
            grantClipDataItemPermission(data.getItemAt(i), mode, srcUid, destUid, destPkg);
        }
    }

    void deliverSessionDataLocked() {
        if (mSession == null) {
            return;
        }
        if (mHaveAssistData) {
            AssistDataForActivity assistData;
            if (mAssistData.isEmpty()) {
                // We're not actually going to get any data, deliver some nothing
                try {
                    mSession.handleAssist(null, null, null, 0, 0);
                } catch (RemoteException e) {
                }
            } else {
                while (!mAssistData.isEmpty()) {
                    if (mPendingAssistDataCount <= 0) {
                        Slog.e(TAG, "mPendingAssistDataCount is " + mPendingAssistDataCount);
                    }
                    mPendingAssistDataCount--;
                    assistData = mAssistData.remove(0);
                    if (assistData.data == null) {
                        try {
                            mSession.handleAssist(null, null, null, assistData.activityIndex,
                                    assistData.activityCount);
                        } catch (RemoteException e) {
                        }
                    } else {
                        deliverSessionDataLocked(assistData);
                    }
                }
            }
            if (mPendingAssistDataCount <= 0) {
                mHaveAssistData = false;
            } // else, more to come
        }
        if (mHaveScreenshot) {
            try {
                mSession.handleScreenshot(mScreenshot);
            } catch (RemoteException e) {
            }
            mScreenshot = null;
            mHaveScreenshot = false;
        }
    }

    private void deliverSessionDataLocked(AssistDataForActivity assistDataForActivity) {
        Bundle assistData = assistDataForActivity.data.getBundle(
                VoiceInteractionSession.KEY_DATA);
        AssistStructure structure = assistDataForActivity.data.getParcelable(
                VoiceInteractionSession.KEY_STRUCTURE);
        AssistContent content = assistDataForActivity.data.getParcelable(
                VoiceInteractionSession.KEY_CONTENT);
        int uid = assistDataForActivity.data.getInt(Intent.EXTRA_ASSIST_UID, -1);
        if (uid >= 0 && content != null) {
            Intent intent = content.getIntent();
            if (intent != null) {
                ClipData data = intent.getClipData();
                if (data != null && Intent.isAccessUriMode(intent.getFlags())) {
                    grantClipDataPermissions(data, intent.getFlags(), uid,
                            mCallingUid, mSessionComponentName.getPackageName());
                }
            }
            ClipData data = content.getClipData();
            if (data != null) {
                grantClipDataPermissions(data,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION,
                        uid, mCallingUid, mSessionComponentName.getPackageName());
            }
        }
        try {
            mSession.handleAssist(assistData, structure, content,
                    assistDataForActivity.activityIndex, assistDataForActivity.activityCount);
        } catch (RemoteException e) {
        }
    }

    public boolean hideLocked() {
        if (mBound) {
            if (mShown) {
                mShown = false;
                mShowArgs = null;
                mShowFlags = 0;
                mHaveAssistData = false;
                mAssistData.clear();
                if (mSession != null) {
                    try {
                        mSession.hide();
                    } catch (RemoteException e) {
                    }
                }
                try {
                    mAm.revokeUriPermissionFromOwner(mPermissionOwner, null,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION
                                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
                            mUser);
                } catch (RemoteException e) {
                }
                if (mSession != null) {
                    try {
                        mAm.finishVoiceTask(mSession);
                    } catch (RemoteException e) {
                    }
                }
            }
            if (mFullyBound) {
                mContext.unbindService(mFullConnection);
                mFullyBound = false;
            }
            return true;
        }
        return false;
    }

    public void cancelLocked(boolean finishTask) {
        hideLocked();
        mCanceled = true;
        if (mBound) {
            if (mSession != null) {
                try {
                    mSession.destroy();
                } catch (RemoteException e) {
                    Slog.w(TAG, "Voice interation session already dead");
                }
            }
            if (finishTask && mSession != null) {
                try {
                    mAm.finishVoiceTask(mSession);
                } catch (RemoteException e) {
                }
            }
            mContext.unbindService(this);
            try {
                mIWindowManager.removeWindowToken(mToken);
            } catch (RemoteException e) {
                Slog.w(TAG, "Failed removing window token", e);
            }
            mBound = false;
            mService = null;
            mSession = null;
            mInteractor = null;
        }
        if (mFullyBound) {
            mContext.unbindService(mFullConnection);
            mFullyBound = false;
        }
    }

    public boolean deliverNewSessionLocked(IVoiceInteractionSession session,
            IVoiceInteractor interactor) {
        mSession = session;
        mInteractor = interactor;
        if (mShown) {
            try {
                session.show(mShowArgs, mShowFlags, mShowCallback);
                mShowArgs = null;
                mShowFlags = 0;
            } catch (RemoteException e) {
            }
            deliverSessionDataLocked();
        }
        return true;
    }

    private void notifyPendingShowCallbacksShownLocked() {
        for (int i = 0; i < mPendingShowCallbacks.size(); i++) {
            try {
                mPendingShowCallbacks.get(i).onShown();
            } catch (RemoteException e) {
            }
        }
        mPendingShowCallbacks.clear();
    }

    private void notifyPendingShowCallbacksFailedLocked() {
        for (int i = 0; i < mPendingShowCallbacks.size(); i++) {
            try {
                mPendingShowCallbacks.get(i).onFailed();
            } catch (RemoteException e) {
            }
        }
        mPendingShowCallbacks.clear();
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        synchronized (mLock) {
            mService = IVoiceInteractionSessionService.Stub.asInterface(service);
            if (!mCanceled) {
                try {
                    mService.newSession(mToken, mShowArgs, mShowFlags);
                } catch (RemoteException e) {
                    Slog.w(TAG, "Failed adding window token", e);
                }
            }
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mCallback.sessionConnectionGone(this);
        mService = null;
    }

    public void dump(String prefix, PrintWriter pw) {
        pw.print(prefix); pw.print("mToken="); pw.println(mToken);
        pw.print(prefix); pw.print("mShown="); pw.println(mShown);
        pw.print(prefix); pw.print("mShowArgs="); pw.println(mShowArgs);
        pw.print(prefix); pw.print("mShowFlags=0x"); pw.println(Integer.toHexString(mShowFlags));
        pw.print(prefix); pw.print("mBound="); pw.println(mBound);
        if (mBound) {
            pw.print(prefix); pw.print("mService="); pw.println(mService);
            pw.print(prefix); pw.print("mSession="); pw.println(mSession);
            pw.print(prefix); pw.print("mInteractor="); pw.println(mInteractor);
        }
        pw.print(prefix); pw.print("mHaveAssistData="); pw.println(mHaveAssistData);
        if (mHaveAssistData) {
            pw.print(prefix); pw.print("mAssistData="); pw.println(mAssistData);
        }
    }

    private Runnable mShowAssistDisclosureRunnable = new Runnable() {
        @Override
        public void run() {
            StatusBarManagerInternal statusBarInternal = LocalServices.getService(
                    StatusBarManagerInternal.class);
            if (statusBarInternal != null) {
                statusBarInternal.showAssistDisclosure();
            }
        }
    };
};


text:
import bigcommerce
import os
import decimal
decimal.getcontext().prec = 2
from decimal import Decimal
import csv

api = bigcommerce.api.BigcommerceApi(
    host=os.environ['BIGCOMMERCE_HOST'],
    basic_auth=(os.environ['BIGCOMMERCE_USER'],
                os.environ['BIGCOMMERCE_APIKEY']))

print('Testing BigCommerce Api - if your credentials check out,')
print('the next line should be the time')
print(repr(api.Time.all()))
print()

# Helper function for finding an element in a list or other iteratable object.
# @param iterable
# @param {Function} predicate - a function that is given an element from the
#                   list and returns true if it is in the list.
def find(iterable, predicate):
    for el in iterable:
        if predicate(el):
            return el
    raise LookupError

productsCount = api.Products.count()
productsLeft = productsCount
print("Downloading {} products".format(productsCount))
products = []
page=1
while productsLeft > 0:
    products += api.Products.all(limit=200, page=page)
    productsLeft -= 200
    page += 1

print("Successfully downloaded {} products".format(len(products)))

outfile = open('./output.csv', 'w')
fieldnames = ['Product/Service Name',
              'Sales Description',
              'Sales Price/Rate',
              'Income Account',
              'Purchase Description',
              'Purchase Cost',
              'Expense Account',
              'Inventory Asset Account',
              'Quantity On Hand',
              'Quantity as-of Date']

csvwriter = csv.DictWriter(outfile, fieldnames, delimiter=',')
csvwriter.writerow(dict((fn,fn) for fn in fieldnames))
def recordVariant(variant):
    csvwriter.writerow(variant)

for product in products:
    if (not product.is_visible) or product.availability == 'disabled':
        continue
    variant = dict()
    variant['Sales Description'] = product.name
    variant['Purchase Description'] = variant['Sales Description']
    variant['Sales Price/Rate'] = Decimal(product.price)
    sale_price = Decimal(product.sale_price)
    if sale_price > 0:
        variant["Sales Price/Rate"] = sale_price

    skus = product.skus()
    if isinstance(skus, list):
        print('Product "{}" has option skus. Will create multiple variants for this product.'.format(product.name))
        options = product.options()
        for option in options:
            option.vals = api.OptionValues.all(option.option_id)
        variantToClone = variant
        for sku in skus:
            variant = dict(variantToClone)
            variant['Product/Service Name'] = sku.sku

            for optDict in sku.options:
                option_id = optDict['product_option_id']
                value_id = optDict['option_value_id']
                option = find(options, lambda option: option.id == option_id)
                value = find(option.vals, lambda value: value['id'] == value_id)
                variant['Sales Description'] += '\n' + option.display_name + ': ' + value['value']
            variant['Purchase Description'] = variant['Sales Description']
            recordVariant(variant)
    else:
        print('Product "{}" does not have option skus. Will create a single variant for this product.'.format(product.name))
        variant['Product/Service Name'] = product.sku
        recordVariant(variant)

outfile.close()

redpajama_set_name: RedPajamaGithub


text:
module.exports = {
  name: 'plain route',

  beforeEach: function(){
    var router = basis.createSandbox().require('basis.router');
  },
  afterEach: function(){
    router.stop();
    location.hash = '';
  },

  test: [
    {
      name: 'checkUrl',
      test: function(){
        var checker = 0;

        router.add('test', function(){
          checker++;
        });
        location.hash = 'test';
        router.checkUrl();

        assert(checker === 1);

        router.add('test', function(){
          checker++;
        });
        assert(checker === 1);

        router.checkUrl();
        assert(checker === 2);
      }
    },
    {
      name: 'navigate',
      test: function(){
        var checker = 0;

        router.add('test', function(){
          checker++;
        });
        router.navigate('test');

        assert(location.hash.substr(1) === 'test');
        assert(checker === 1);
      }
    },
    {
      name: 'callbacks',
      test: function(){
        router.stop();  // router starts by default
        var log = [];

        router.add('foo', function(){
          log.push('foo');
        });
        router.add('bar', function(){
          log.push('bar');
        });
        assert([], log);

        router.navigate('foo');
        assert([], log);

        router.start();
        assert(['foo'], log);

        router.add('foo', function(){
          log.push('foo2');
        });
        assert(['foo'], log);

        router.checkUrl();
        assert(['foo', 'foo2'], log);

        router.navigate('bar');
        assert(['foo', 'foo2', 'bar'], log);
      }
    },
    {
      name: 'callbacks - enter/leave order',
      test: function(){
        var log = [];

        router.add('foo', {
          enter: function(){
            log.push('enter foo');
          },
          leave: function(){
            log.push('leave foo');
          }
        });
        router.add('bar', {
          enter: function(){
            log.push('enter bar');
          },
          leave: function(){
            log.push('leave bar');
          }
        });

        router.navigate('bar');
        router.navigate('foo');
        assert(['enter bar', 'leave bar', 'enter foo'], log);
      }
    },
    {
      name: 'params',
      test: function(){
        var checker;

        router.add('param/:id', function(id){
          checker = Number(id);
        });
        router.navigate('param/5');
        assert(checker === 5);

        router.add('path/*path', function(path){
          checker = path;
        });
        router.navigate('path/some/stuff');
        assert(checker === 'some/stuff');
      }
    },
    {
      name: 'route',
      test: [
        {
          name: 'should be the same token for one path',
          test: function(){
            assert(router.route('foo') === router.route('foo'));
            assert(router.route(/foo/) === router.route(/foo/));
          }
        },
        {
          name: 'router.route(route) should route itself',
          test: function(){
            var route = router.route('foo');
            assert(router.route(route) === route);
          }
        },
        {
          name: 'should match the same values when router.add() invoke for route and route.path',
          test: function(){
            var matches = 0;
            var paramName = basis.genUID();
            var paramValue = basis.genUID();
            var route = router.route(':' + paramName);
            router.navigate(paramValue);

            router.add(route, function(param){
              matches++;
              assert(param === paramValue);
            });

            router.add(route.path, function(param){
              matches++;
              assert(param === paramValue);
            });

            assert(matches === 0);

            router.checkUrl();
            assert(matches === 2);
          }
        },
        {
          name: 'callback added via router.add() should invoke async or asap',
          test: function(done){
            function checkDone(){
              if (matches === 2)
                done();

              assert(matches === 1 || matches === 2);
            }

            var matches = 0;
            var paramName = basis.genUID();
            var paramValue = basis.genUID();

            router.navigate(paramValue);

            var route = router.route(':' + paramName).add(function(){
              assert(route.matched.value);
              matches++;
              checkDone();
            });

            router.add(route, function(){
              assert(route.matched.value);
              matches++;
              checkDone();
            });

            assert(matches === 0);
            assert(route.matched.value === true);
          }
        },
        {
          name: 'when handler removes leave callback should be invoked if route matched',
          test: function(){
            var matches = 0;

            router.navigate('123');

            var matchHandler = {
              leave: function(){
                matches++;
              }
            };

            var nonmatchHandler = {
              leave: function(){
                matches++;
              }
            };

            router.add('1:foo', matchHandler);
            router.add('2:foo', nonmatchHandler);

            assert(matches === 0);

            router.checkUrl();
            assert(matches === 0);

            router.navigate('222');
            assert(matches === 1);

            router.remove('1:foo', matchHandler);
            router.remove('2:foo', nonmatchHandler);

            assert(matches === 2);
          }
        }
      ]
    },
    {
      name: 'recursion aware',
      test: [
        {
          name: 'should delay url check if cycle in same frame',
          test: function(done){
            function finish(){
              assert(counter < 10);
              stopped = true;
              done();
            }

            var counter = 0;
            var stopped = false;

            router.add('foo', function(){
              if (stopped)
                return;

              if (++counter < 10)
                router.navigate('bar');
              else
                finish();
            });

            router.add('bar', function(){
              if (stopped)
                return;

              if (++counter < 10)
                router.navigate('foo');
              else
                finish();
            });

            router.navigate('foo');
            setTimeout(finish, 20);
          }
        },
        {
          name: 'should delay url check if cycle in short period',
          test: function(done){
            function finish(){
              assert(counter < 10);
              stopped = true;
              done();
            }

            var counter = 0;
            var stopped = false;

            router.add('foo', function(){
              if (stopped)
                return;

              if (++counter < 10)
                setTimeout(function(){
                  router.start(); // due to bug in yatra, afterEach invokes before done
                  router.navigate('bar');
                }, 10);
              else
                finish();
            });

            router.add('bar', function(){
              if (stopped)
                return;

              if (++counter < 10)
                setTimeout(function(){
                  router.start(); // due to bug in yatra, afterEach invokes before done
                  router.navigate('foo');
                }, 10);
              else
                finish();
            });

            router.navigate('foo');
            setTimeout(function(){
              finish();
            }, 200);
          }
        }
      ]
    },
    {
      name: 'regular expression route',
      test: function(){
        var checker = 0;

        router.add(/^tost(\w+)$/, function(){
          checker++;
        });
        location.hash = 'tostobar';
        router.checkUrl();

        assert(checker === 1);
      }
    }
  ]
};


text:
/*-------------------------------------------------------
 * This file was generated by XpeCodeGen
 * Version 1.0.0
 *
 * Do not make changes to this file
 *-------------------------------------------------------*/
package com.badlogic.gdx.physics.bullet.linearmath;

import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.BulletBase;

/** @author xpenatan */
public class btVector3Array extends BulletBase {

    public btVector3Array(long cPtr, boolean cMemoryOwn) {
        resetObj(cPtr, cMemoryOwn);
    }

	protected void cacheObj() {
		com.dragome.commons.javascript.ScriptHelper.put("addr",this.cPointer,this);
		this.jsObj = com.dragome.commons.javascript.ScriptHelper.eval("Bullet.wrapPointer(addr,Bullet.MyVector3Array)",this);
	}

    public int size() {
		checkPointer();
		com.dragome.commons.javascript.ScriptHelper.put("jsObj",this.jsObj,this);
		return com.dragome.commons.javascript.ScriptHelper.evalInt("jsObj.size();",this);
    }

    public void at(int n, Vector3 out) {
		com.dragome.commons.javascript.ScriptHelper.put("n",n,this);
		checkPointer();
		float x=0,y=0,z=0;
		com.dragome.commons.javascript.ScriptHelper.put("jsObj",this.jsObj,this);
		com.dragome.commons.javascript.ScriptHelper.evalNoResult("var vec=jsObj.at(n);x=vec.x();y=vec.y();z=vec.z();out.set(x,y,z);",this);
    }

    public int capacity() {
		checkPointer();
		com.dragome.commons.javascript.ScriptHelper.put("jsObj",this.jsObj,this);
		return com.dragome.commons.javascript.ScriptHelper.evalInt("jsObj.capacity();",this);
    }

    public void resize(int newsize) {
		com.dragome.commons.javascript.ScriptHelper.put("newsize",newsize,this);
		checkPointer();
		com.dragome.commons.javascript.ScriptHelper.put("jsObj",this.jsObj,this);
		com.dragome.commons.javascript.ScriptHelper.evalNoResult("jsObj.resize(newsize);",this);
    }
}


text:
/**
 * This demonstrates how to create a Qlik Sense application and a data connection.
 *
 * This sample assumes a Desktop installation but the logic is the same
 * for a Qlik Sense Server installation.
 */

const qsocks = require('qsocks');
const applicationName = 'My Application';

qsocks.Connect( {appname: applicationName} )
.then( global => {

    // Access to the global class
    // http://help.qlik.com/en-US/sense-developer/2.2/Subsystems/EngineAPI/Content/Classes/GlobalClass/Global-class.htm

    return global.createApp( applicationName )
        .then( () => global.openDoc( applicationName ) )
        .then( app => {

        // Access to the app class
        // http://help.qlik.com/en-US/sense-developer/2.2/Subsystems/EngineAPI/Content/Classes/AppClass/App-class.htm

        // Create a data connection and save the app.
        // http://help.qlik.com/en-US/sense-developer/2.2/Subsystems/EngineAPI/Content/Classes/AppClass/App-class-CreateConnection-method.htm
        return app.createConnection({
            qType: 'internet',
            qName: 'MyWebConnection',
            qConnectionString: 'https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)'
        }).then(() => {
            return app.doSave();
        })

    })
    .then(() => {
        // Close our connection.
        return global.connection.close();
    })
    .catch( err => {
        // Failed to create app. In Desktop application names are unique.
        console.log( err )
    })

})
.then(() => {
    console.log('Done!')
})


text:
$packageName = '{{PackageName}}'
$fileType = "exe"
$silentArgs = "/S"
$validExitCodes = @(0)

$unfile = "${Env:ProgramFiles}\TV-Browser\Uninstall.exe"
$unfilex86 = "${Env:ProgramFiles(x86)}\TV-Browser\Uninstall.exe"

if (Test-Path "$unfile") {$file = "$unfile"}
if (Test-Path "$unfilex86") {$file = "$unfilex86"}

if ((Test-Path "$unfile") -or (Test-Path "$unfilex86")) {
  Uninstall-ChocolateyPackage $packageName $fileType $silentArgs $file -validExitCodes $validExitCodes
}


text:
const should = require('chai').should()

const Heap = require('./../heap')
const StableHeap = require('./../stable-heap')

describe('StableHeap', () => {
    it('Should ensure a First In First Out mechanism between each item that is equal.', () => {
        const aCollection = [
            {aNr: 2, aValue: 'A'},
            {aNr: 4, aValue: 'B'},
            {aNr: 2, aValue: 'C'},
            {aNr: 2, aValue: 'D'}
        ]

        const useComparator = (itemA, itemB) => itemA.aNr === itemB.aNr ? 0 : itemA.aNr > itemB.aNr ? +1 : -1

        const aHeap = Heap.from(aCollection, useComparator)

        let toArray = aHeap.toArray()

        toArray[0].aValue.should.equal('A')
        toArray[1].aValue.should.equal('D')
        toArray[2].aValue.should.equal('C')
        toArray[3].aValue.should.equal('B')

        const stableHeap = StableHeap.from(aCollection, useComparator)

        toArray = stableHeap.toArray()

        toArray[0].aValue.should.equal('A')
        toArray[1].aValue.should.equal('C')
        toArray[2].aValue.should.equal('D')
        toArray[3].aValue.should.equal('B')

        stableHeap.pop().aValue.should.equal('A')
        stableHeap.pop().aValue.should.equal('C')
        stableHeap.pop().aValue.should.equal('D')
        stableHeap.pop().aValue.should.equal('B')

        should.not.exist(stableHeap.pop() /* `undefined` */)
    })

    it('Should ensure a First In First Out mechanism, even after extensive use for a long(er) period of time.', (whenDone) => {
        const stableHeap = new StableHeap((itemA, itemB) => {
            return 0
        })

        let insertNr = 0

        const testInterval = setInterval(() => {
            for (let maxNr = insertNr + 32; insertNr < maxNr; insertNr++) stableHeap.push(insertNr)

            if (insertNr >= 128) {
                clearInterval(testInterval)

                stableHeap.size.should.equal(insertNr)

                for (let equalNr = 0; equalNr < insertNr; equalNr++) stableHeap.pop().should.equal(equalNr)

                whenDone()
            }
        }, 1024)
    }).timeout(6000)

    it.skip('Should use both `createdAt` & `insertNr` to decide the position of an item within (the Stable Heap).', () => {
        const stableHeap = new StableHeap()

        stableHeap.insertNr_ = 4

        stableHeap.push('A')
        stableHeap.push('B')
        stableHeap.push('C')
        stableHeap.push('D')

        stableHeap.insertNr_.should.equal(0)

        stableHeap.push('E')
        stableHeap.push('F')

        stableHeap.insertNr_.should.equal(/* Number.MIN_SAFE_INTEGER, but can't test that. That number is too large to wait on. */)
    })

    context('#.peekFront', () => {
        it('Should be an alias of #.peek.', () => {
            const stableHeap = new StableHeap()

            stableHeap.peekFront.should.equal(stableHeap.peek)
        })
    })
})


text: You just received an **encrypted message**. Decode it.


text:
package org.apache.cassandra.net.io;

import org.apache.cassandra.utils.*;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.io.IOException;
import org.apache.cassandra.net.MessagingService;

public class ProtocolState extends StartState
{
    private ByteBuffer buffer_;

    public ProtocolState(TcpReader stream)
    {
        super(stream);
        buffer_ = ByteBuffer.allocate(16);
    }

    public byte[] read() throws IOException, ReadNotCompleteException
    {
        return doRead(buffer_);
    }

    public void morphState() throws IOException
    {
        byte[] protocol = buffer_.array();
        if ( MessagingService.isProtocolValid(protocol) )
        {
            StartState nextState = stream_.getSocketState(TcpReader.TcpReaderState.PROTOCOL);
            if ( nextState == null )
            {
                nextState = new ProtocolHeaderState(stream_);
                stream_.putSocketState( TcpReader.TcpReaderState.PROTOCOL, nextState );
            }
            stream_.morphState( nextState );
            buffer_.clear();
        }
        else
        {
            throw new IOException("Invalid protocol header. The preamble seems to be messed up.");
        }
    }

    public void setContextData(Object data)
    {
        throw new UnsupportedOperationException("This method is not supported in the ProtocolState");
    }
}


text:
package com.dangdang.ddframe.job.lite.lifecycle.domain;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class ServerStatusTest {

    @Test
    public void assertGetServerStatusWhenIsShutdown() {
        assertThat(ServerInfo.ServerStatus.getServerStatus("", false, false, true), is(ServerInfo.ServerStatus.SHUTDOWN));
    }

    @Test
    public void assertGetServerStatusWhenIsCrashed() {
        assertThat(ServerInfo.ServerStatus.getServerStatus("", false, false, false), is(ServerInfo.ServerStatus.CRASHED));
    }

    @Test
    public void assertGetServerStatusWhenIsDisabled() {
        assertThat(ServerInfo.ServerStatus.getServerStatus("READY", true, false, false), is(ServerInfo.ServerStatus.DISABLED));
    }

    @Test
    public void assertGetServerStatusWhenIsPaused() {
        assertThat(ServerInfo.ServerStatus.getServerStatus("READY", false, true, false), is(ServerInfo.ServerStatus.PAUSED));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="preferences" type="id"/>
    <item name="btn_add_server" type="id"/>
</resources>


text:
import pyat.sync
import time
import random

from .util import a_task, a_failing_task, make_args, make_kwargs, \
        FailedTaskException

MIN_TIME = 1.0
MAX_TIME = 2.0
DELTA_TIME = MAX_TIME - MIN_TIME
STEP_TIME = 0.1
TIMEOUT_DELAY = 0.5

def test_future():
    '''
    Test a task scheduled N seconds in the future is executed close to the
    requested time.
    '''
    # Create scheduler
    scheduler = pyat.sync.SynchronousTaskScheduler()

    # Pick some random arguments
    args = make_args()
    kwargs = make_kwargs()

    # Pick a time between 1-5 seconds in the future
    delay = MIN_TIME + (random.random() * DELTA_TIME)
    at_time = time.time() + delay

    # Schedule task
    task = scheduler.schedule(at_time, a_task, *args, **kwargs)

    # Pick a timeout
    timeout = at_time + TIMEOUT_DELAY

    # Wait for timeout
    while time.time() < timeout:
        time.sleep(STEP_TIME)
        scheduler.poll()

    # Did our function get run?
    try:
        (run_at, run_args, run_kwargs) = task.result
        assert run_args == args, 'args does not match'
        assert run_kwargs == kwargs, 'kwargs does not match'
        assert run_at > at_time, 'Ran too early'
        assert run_at < (at_time + STEP_TIME), 'Ran too late'
    except pyat.sync.NotExecutedYet:
        assert False, 'Did not get executed'

def test_future_exception():
    '''
    Test a task scheduled N seconds in the future that fails.
    '''
    # Create scheduler
    scheduler = pyat.sync.SynchronousTaskScheduler()

    # Pick some random arguments
    args = make_args()
    kwargs = make_kwargs()

    # Pick a time between 1-5 seconds in the future
    delay = MIN_TIME + (random.random() * DELTA_TIME)
    at_time = time.time() + delay

    # Schedule task
    task = scheduler.schedule(at_time, a_failing_task, *args, **kwargs)

    # Pick a timeout
    timeout = at_time + TIMEOUT_DELAY

    # Wait for timeout
    while time.time() < timeout:
        time.sleep(STEP_TIME)
        scheduler.poll()

    # Did our function get run?
    try:
        (run_at, run_args, run_kwargs) = task.result
        assert False, 'Did not fail'
    except FailedTaskException as e:
        (msg, run_at, run_args, run_kwargs) = e.args
        assert run_args == args, 'args does not match'
        assert run_kwargs == kwargs, 'kwargs does not match'
        assert run_at > at_time, 'Ran too early'
        assert run_at < (at_time + STEP_TIME), 'Ran too late'
    except pyat.sync.NotExecutedYet:
        assert False, 'Did not get executed'

def test_future_cancelled():
    '''
    Test a task scheduled N seconds in the future then cancelled doesn't
    execute.
    '''
    # Create scheduler
    scheduler = pyat.sync.SynchronousTaskScheduler()

    # Pick some random arguments
    args = make_args()
    kwargs = make_kwargs()

    # Pick a time between 1-5 seconds in the future
    delay = MIN_TIME + (random.random() * DELTA_TIME)
    at_time = time.time() + delay

    # Schedule task
    task = scheduler.schedule(at_time, a_task, *args, **kwargs)

    # Poll once
    scheduler.poll()

    # Cancel the task
    task.cancel()
    assert task.cancelled, 'Not cancelled'

    # Pick a timeout
    timeout = at_time + TIMEOUT_DELAY

    # Wait for timeout
    while time.time() < timeout:
        time.sleep(STEP_TIME)
        scheduler.poll()

    # Did our function get run?
    try:
        (run_at, run_args, run_kwargs) = task.result
        assert False, 'Task executed'
    except pyat.sync.NotExecutedYet:
        pass

def test_cancel_all():
    '''
    Test we can cancel all tasks.
    '''
    # Create scheduler
    scheduler = pyat.sync.SynchronousTaskScheduler()

    # Pick some random arguments
    args = make_args()
    kwargs = make_kwargs()

    # Pick a time between 1-5 seconds in the future
    delay = MIN_TIME + (random.random() * DELTA_TIME)
    at_time = time.time() + delay

    # Schedule tasks
    task1 = scheduler.schedule(at_time, a_task, *args, **kwargs)
    task2 = scheduler.schedule(at_time + 1, a_task, *args, **kwargs)
    task3 = scheduler.schedule(at_time + 2, a_task, *args, **kwargs)

    # Poll once
    scheduler.poll()

    # Cancel all tasks
    scheduler.cancel_all()

    # Pick a timeout
    timeout = at_time + TIMEOUT_DELAY

    # Wait for timeout
    while time.time() < timeout:
        time.sleep(STEP_TIME)
        scheduler.poll()

    # Did our functions get run?
    for task in (task1, task2, task3):
        try:
            (run_at, run_args, run_kwargs) = task.result
            assert False, 'Task executed'
        except pyat.sync.NotExecutedYet:
            pass

def test_not_yet_executed():
    '''
    Test NotYetExecuted gets raised if we ask the task early.
    '''
    # Create scheduler
    scheduler = pyat.sync.SynchronousTaskScheduler()

    # Pick some random arguments
    args = make_args()
    kwargs = make_kwargs()

    # Pick a time between 1-5 seconds in the future
    delay = MIN_TIME + (random.random() * DELTA_TIME)
    at_time = time.time() + delay

    # Schedule task
    task = scheduler.schedule(at_time, a_task, *args, **kwargs)

    # Poll once
    scheduler.poll()

    # Did our function get run?
    try:
        (run_at, run_args, run_kwargs) = task.result
        assert False, 'Task executed early'
    except pyat.sync.NotExecutedYet:
        pass


text:
export default function buildShapesResponse (data) {
  return data.map(shape => ({
    shapeId: shape.shape_id,
    lat: shape.shape_pt_lat,
    lng: shape.shape_pt_lon,
    sequence: shape.shape_pt_sequence,
    traveled: shape.shape_dist_traveled
  }))
}


text:
package tanukki.akka.cluster.autodown

import akka.cluster.MultiNodeClusterSpec
import akka.remote.testkit.{STMultiNodeSpec, MultiNodeSpec}
import akka.testkit.LongRunningTest
import scala.concurrent.duration._

class RoleLeaderDowningNodeThatIsUnreachableWithFailureDetectorPuppetMultiJvmNode1 extends MultiNodeRoleLeaderAutoDownRolesSpec(MultiNodeRoleLeaderDownRolesSpecConfig(failureDetectorPuppet = true))
class RoleLeaderDowningNodeThatIsUnreachableWithFailureDetectorPuppetMultiJvmNode2 extends MultiNodeRoleLeaderAutoDownRolesSpec(MultiNodeRoleLeaderDownRolesSpecConfig(failureDetectorPuppet = true))
class RoleLeaderDowningNodeThatIsUnreachableWithFailureDetectorPuppetMultiJvmNode3 extends MultiNodeRoleLeaderAutoDownRolesSpec(MultiNodeRoleLeaderDownRolesSpecConfig(failureDetectorPuppet = true))
class RoleLeaderDowningNodeThatIsUnreachableWithFailureDetectorPuppetMultiJvmNode4 extends MultiNodeRoleLeaderAutoDownRolesSpec(MultiNodeRoleLeaderDownRolesSpecConfig(failureDetectorPuppet = true))
class RoleLeaderDowningNodeThatIsUnreachableWithFailureDetectorPuppetMultiJvmNode5 extends MultiNodeRoleLeaderAutoDownRolesSpec(MultiNodeRoleLeaderDownRolesSpecConfig(failureDetectorPuppet = true))

class RoleLeaderDowningNodeThatIsUnreachableWithAccrualFailureDetectorMultiJvmNode1 extends MultiNodeRoleLeaderAutoDownRolesSpec(MultiNodeRoleLeaderDownRolesSpecConfig(failureDetectorPuppet = false))
class RoleLeaderDowningNodeThatIsUnreachableWithAccrualFailureDetectorMultiJvmNode2 extends MultiNodeRoleLeaderAutoDownRolesSpec(MultiNodeRoleLeaderDownRolesSpecConfig(failureDetectorPuppet = false))
class RoleLeaderDowningNodeThatIsUnreachableWithAccrualFailureDetectorMultiJvmNode3 extends MultiNodeRoleLeaderAutoDownRolesSpec(MultiNodeRoleLeaderDownRolesSpecConfig(failureDetectorPuppet = false))
class RoleLeaderDowningNodeThatIsUnreachableWithAccrualFailureDetectorMultiJvmNode4 extends MultiNodeRoleLeaderAutoDownRolesSpec(MultiNodeRoleLeaderDownRolesSpecConfig(failureDetectorPuppet = false))
class RoleLeaderDowningNodeThatIsUnreachableWithAccrualFailureDetectorMultiJvmNode5 extends MultiNodeRoleLeaderAutoDownRolesSpec(MultiNodeRoleLeaderDownRolesSpecConfig(failureDetectorPuppet = false))

abstract class MultiNodeRoleLeaderAutoDownRolesSpec(multiNodeConfig: MultiNodeRoleLeaderDownRolesSpecConfig) extends MultiNodeSpec(multiNodeConfig)
with STMultiNodeSpec with MultiNodeClusterSpec {
  import multiNodeConfig._

  muteMarkingAsUnreachable()

  "The RoleLeader in a 4 node cluster" must {

    "be able to DOWN a 'last' node that is UNREACHABLE" taggedAs LongRunningTest in {
      awaitClusterUp(node_A_1, node_A_2, node_A_3, node_B_1, node_B_2)

      val fourthAddress = address(node_B_2)

      enterBarrier("before-exit-fourth-node")
      runOn(node_A_1) {
        // kill 'fourth' node
        testConductor.exit(node_B_2, 0).await
        enterBarrier("down-fourth-node")

        // mark the node as unreachable in the failure detector
        markNodeAsUnavailable(fourthAddress)

        // --- HERE THE LEADER SHOULD DETECT FAILURE AND AUTO-DOWN THE UNREACHABLE NODE ---

        awaitMembersUp(numberOfMembers = 4, canNotBePartOfMemberRing = Set(fourthAddress), 30.seconds)
      }

      runOn(node_B_2) {
        enterBarrier("down-fourth-node")
      }

      runOn(node_A_2, node_A_3, node_B_1) {
        enterBarrier("down-fourth-node")

        awaitMembersUp(numberOfMembers = 4, canNotBePartOfMemberRing = Set(fourthAddress), 30.seconds)
      }

      enterBarrier("await-completion-1")
    }

    "be able to DOWN a 'middle' node that is UNREACHABLE" taggedAs LongRunningTest in {
      val secondAddress = address(node_B_1)

      enterBarrier("before-down-second-node")
      runOn(node_A_1) {
        // kill 'second' node
        testConductor.exit(node_B_1, 0).await
        enterBarrier("down-second-node")

        // mark the node as unreachable in the failure detector
        markNodeAsUnavailable(secondAddress)

        // --- HERE THE LEADER SHOULD DETECT FAILURE AND AUTO-DOWN THE UNREACHABLE NODE ---

        awaitMembersUp(numberOfMembers = 3, canNotBePartOfMemberRing = Set(secondAddress), 30.seconds)
      }

      runOn(node_B_1) {
        enterBarrier("down-second-node")
      }

      runOn(node_A_2) {
        enterBarrier("down-second-node")

        awaitMembersUp(numberOfMembers = 3, canNotBePartOfMemberRing = Set(secondAddress), 30 seconds)
      }

      runOn(node_A_3) {
        enterBarrier("down-second-node")

        awaitMembersUp(numberOfMembers = 3, canNotBePartOfMemberRing = Set(secondAddress), 30 seconds)
      }

      enterBarrier("await-completion-2")
    }

    "NOT be able to DOWN a 'middle' node that is UNREACHABLE" taggedAs LongRunningTest in {
      val thirdAddress = address(node_A_3)

      enterBarrier("before-down-third-node")
      runOn(node_A_1) {
        // kill 'third' node
        testConductor.exit(node_A_3, 0).await
        enterBarrier("down-third-node")

        // mark the node as unreachable in the failure detector
        markNodeAsUnavailable(thirdAddress)

        // ROLE LEADER SHOULD NOT DOWN UNREACHABLE MEMBER WITH DIFFERENT TARGET ROLE

        remainMembersUnreachable(numberOfMembers = 3, unreachableMember = Set(thirdAddress), 10 seconds)
      }

      runOn(node_A_2) {
        enterBarrier("down-third-node")
        remainMembersUnreachable(numberOfMembers = 3, unreachableMember = Set(thirdAddress), 10 seconds)
      }

      runOn(node_A_3) {
        enterBarrier("down-third-node")
      }

      enterBarrier("await-completion-3")
    }
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Br. mycol. Soc. 48: 525 (1965)

#### Original name
Leccinum carpini f. carpini (R. Schulz) M.M. Moser ex D.A. Reid

### Remarks
null


text:
```bash
yarn global add nodemon --prefix /usr/local

yarn global add nodemon --prefix /home/app/.local
```


text:
/**
 * Module dependencies.
 */

const deferApp = require('./support/defer')
const commonApp = require('./support/server')
const request = require('supertest')
const mm = require('mm')

describe('test/store.test.js', () => {
  afterEach(mm.restore)
  describe('common session middleware', () => {
    afterEach(() => {
      commonApp.store.emit('connect')
      mm.restore()
    })
    let cookie

    it('should get session error when disconnect', () => {
      commonApp.store.emit('disconnect')
      return request(commonApp)
        .get('/session/get')
        .expect(500)
        .expect('session store is unavailable')
    })

    it('should get session ok when reconnect', () => {
      commonApp.store.emit('disconnect')
      setTimeout(() => {
        commonApp.store.emit('connect')
      }, 10)
      return request(commonApp)
        .get('/session/get')
        .expect(200)
        .expect('1')
    })

    it('should ignore disconnect event', () => {
      commonApp.store.emit('disconnect')
      commonApp.store.emit('disconnect')
      return request(commonApp)
        .get('/session/get')
        .expect(500)
        .expect('session store is unavailable')
    })

    it('should error when status is unavailable', (done) => {
      commonApp.store.emit('disconnect')
      setTimeout(() => {
        request(commonApp)
          .get('/session/get')
          .expect(500)
          .expect('session store is unavailable', done)
      }, 200)
    })

    it('should get session ok when store.get error but session not exist', async () => {
      mm.error(commonApp.store, 'get', 'mock error')
      const res = await request(commonApp)
        .get('/session/get')
        .expect(/1/)
        .expect(200)
      cookie = res.headers['set-cookie'].join(';')
      cookie.indexOf('httponly').should.above(0)
      cookie.indexOf('expires=').should.above(0)
    })

    it('should get session error when store.get error', () => {
      mm(commonApp.store, 'get', () => {
        throw new Error('mock get error')
      })
      return request(commonApp)
        .get('/session/get')
        .set('cookie', cookie)
        .expect(500)
    })

    it('should get /session/notuse error when store.get error', () => {
      mm(commonApp.store, 'get', () => {
        throw new Error('mock get error')
      })
      return request(commonApp)
        .get('/session/notuse')
        .set('cookie', cookie)
        .expect(500)
    })

    it('should handler session error when store.set error', async () => {
      await request(commonApp)
        .get('/session/get')
        .set('cookie', cookie)
        .expect(200)
        .expect(/2/)
      mm(commonApp.store, 'set', () => {
        throw new Error('mock set error')
      })
      await request(commonApp)
        .get('/session/get')
        .set('cookie', cookie)
        .expect(500)
        .expect('mock set error')

    })

    it('should handler session error when store.set error and logic error', () => {
      mm(commonApp.store, 'set', () => {
        throw new Error('mock set error')
      })
      return request(commonApp)
        .get('/session/get_error')
        .expect(500)
        .expect('oops')
    })
  })

  describe('defer session middleware', () => {
    afterEach(() => {
      deferApp.store.emit('connect')
      mm.restore()
    })
    let cookie
    const mockCookie = 'koa.sid=s:dsfdss.PjOnUyhFG5bkeHsZ1UbEY7bDerxBINnZsD5MUguEph8; path=/; httponly'

    it('should get session error when disconnect', () => {
      deferApp.store.emit('disconnect')
      return request(deferApp)
        .get('/session/get')
        .expect(500)
        .expect('session store is unavailable')
    })

    it('should get session ok when store.get error but session not exist', async () => {
      mm.error(deferApp.store, 'get', 'mock error')
      const res = await request(deferApp)
        .get('/session/get')
        .expect(/1/)
        .expect(200)

      cookie = res.headers['set-cookie'].join(';')
      cookie.indexOf('httponly').should.above(0)
      cookie.indexOf('expires=').should.above(0)

    })

    it('should get session error when store.get error', () => {
      mm(deferApp.store, 'get', () => {
        throw new Error('mock get error')
      })
      return request(deferApp)
        .get('/session/get')
        .set('cookie', cookie)
        .expect(500)
    })

    it('should get /session/notuse ok when store.get error', () => {
      mm(deferApp.store, 'get', () => {
        throw new Error('mock get error')
      })
      return request(deferApp)
        .get('/session/notuse')
        .set('cookie', cookie)
        .expect(200)
    })

    it('should handler session error when store.set error', (done) => {
      cookie = 'koss:test_sid=bGX1r5jcQHX4CqO1Heiy_DLvkTpQvx3M; path=/session; expires=Thu, 13 Apr 2017 17:19:04 GMT; httponly;koss:test_sid.sig=ZvZ8W0x9akbySx-9kEUkVPqAd2g; path=/session; expires=Thu, 13 Apr 2017 17:19:04 GMT; httponly'
      request(commonApp)
        .get('/session/get')
        .set('cookie', cookie)
        .expect(200)
        .expect(/2/, () => {
          mm(commonApp.store, 'set', () => {
            throw new Error('mock set error')
          })
          request(commonApp)
            .get('/session/get')
            .set('cookie', cookie)
            .expect(500)
            .expect('mock set error', done)
        })
    })

  })

})