<commit_before>var midas = midas || {};
midas.upload = midas.upload || {};
midas.upload.simpleupload = {};

midas.upload.simpleupload.updateUploadedCount = function()
  {
  var count = parseInt($('.uploadedSimple').val()) +
              parseInt($('.uploadedLinks').val()) +
              parseInt($('.uploadedJava').val());
  $('.globalUploadedCount').html(count);
  if(count > 0)
    {
    $('.reviewUploaded').show();
    }
  else
    {
    $('.reviewUploaded').hide();
    }
  }

midas.upload.simpleupload.initJqueryFileupload = function()
  {
  midas.upload.simpleupload.updateUploadedCount();
  //see http://aquantum-demo.appspot.com/file-upload
  $('.file_upload:visible').fileUploadUIX({
    beforeSend: function (event, files, index, xhr, handler, callBack) {
      if(index == 0) //only do this once since we have all the files every time
        {
        var retVal = midas.doCallback('CALLBACK_CORE_VALIDATE_UPLOAD', {files: files});
        $.each(retVal, function(module, resp) {
          if(resp.status === false)
            {
            $('div.uploadValidationError b').html(resp.message);
            $('div.uploadValidationError').show();
            }
          });
        }

      handler.uploadRow.find('.file_upload_start').click(function () {
        var path = '';
        $.each(files, function (index, file) {
          path += file.webkitRelativePath+';;';
          });
        handler.formData = {
          parent: $('#destinationId').val(),
          path: path,
          license: $('select[name=licenseSelect]').val()
          };
        callBack();
        });
      $('.file_name').each(function(){
        if($(this).html() == '.' || $(this).html() == '..')
          {
          $(this).parent('tr').find('.file_upload_cancel button').click();
          }
        });

      $('#startUploadLink').css('box-shadow', '0 0 5px blue');
      $('#startUploadLink').css('-webkit-box-shadow', '0 0 5px blue');
      $('#startUploadLink').css('-moz-box-shadow', '0 0 5px blue');
      },
    onComplete:  function (event, files, index, xhr, handler) {
      midas.doCallback('CALLBACK_CORE_RESET_UPLOAD_TOTAL');
      $('.uploadedSimple').val(parseInt($('.uploadedSimple').val())+1);
        midas.upload.simpleupload.updateUploadedCount();
      },
    sequentialUploads: true
    });

    $('#startUploadLink').click(function () {
      if($('#destinationId').val() == undefined || $('#destinationId').val().length == 0)
        {
        createNotice("Please select where you want to upload your files.", 4000);
        return false;
        }
      $('.file_upload_start button').click();
      $('#startUploadLink').css('box-shadow', '0 0 0px blue');
      $('#startUploadLink').css('-webkit-box-shadow', '0 0 0px blue');
      $('#startUploadLink').css('-moz-box-shadow', '0 0 0px blue');
      return false;
    });
  }

// Callback hook for the flash uploader
midas.upload.simpleupload.uploadPreStart = function(file)
  {
  midas.upload.simpleupload.swfu.setPostParams({
    'sid': $('.sessionId').val(),
    'parent': $('#destinationId').val(),
    'license': $('select[name=licenseSelect]').val()
    });
  }

// We use shockwave flash uploader for IE (no multi-file upload support)
midas.upload.simpleupload.initSwfupload = function()
  {
  var settings = {
    flash_url: json.global.coreWebroot+"/public/js/swfupload/swfupload_fp10/swfupload.swf",
    flash9_url: json.global.coreWebroot+"/public/js/swfupload/swfupload_fp9/swfupload_fp9.swf",
    upload_url: json.global.webroot+"/upload/saveuploaded",
    post_params: {
      'sid': $('.sessionId').val(),
      'parent': $('#destinationId').val(),
      'license': $('select[name=licenseSelect]').val()
      },
    file_size_limit: $('.maxSizeFile').val()+" MB",
    file_types: "*.*",
    file_types_description: "All Files",
    file_upload_limit: 100,
    file_queue_limit: 0,
    custom_settings: {
      progressTarget: "fsUploadProgress",
      cancelButtonId: "btnCancel",
      pageObj: midas.upload.simpleupload
      },
    debug: false,

    // Button settings
    button_image_url: json.global.coreWebroot+"/public/js/swfupload/images/Button_65x29.png",
    button_width: "65",
    button_height: "20",
    button_placeholder_id: "spanButtonPlaceHolder",
    button_text: ''+$('.buttonBrowse').val()+'',
    button_text_style: ".theFont { font-size: 12; }",
    button_text_left_padding: 5,
    button_text_top_padding: 0,

    // The event handler functions are defined in handlers.js
    swfupload_preload_handler: preLoad,
    swfupload_load_failed_handler: loadFailed,
    file_queued_handler: fileQueued,
    file_queue_error_handler: fileQueueError,
    file_dialog_complete_handler: fileDialogComplete,
    upload_start_handler: midas.upload.simpleupload.uploadPreStart,
    upload_progress_handler: uploadProgress,
    upload_error_handler: uploadError,
    upload_success_handler: uploadSuccess,
    upload_complete_handler: uploadComplete,
    queue_complete_handler: queueComplete  // Queue plugin event
    };

  $('#swfuploadContent').show();
  midas.upload.simpleupload.swfu = new SWFUpload(settings);

  $('#startUploadLink').click(function() {
    if($('#destinationId').val() == undefined || $('#destinationId').val().length == 0)
      {
      createNotice("Please select where you want to upload your files.", 4000);
      return false;
      }
    midas.upload.simpleupload.swfu.startUpload();
    });
  }

$('img#uploadAFile').show();
$('img#uploadAFileLoading').hide();

// detect chrom or firefox 7+
try
  {
  var is_chrome = /chrome/.test(navigator.userAgent.toLowerCase());
  var version = jQuery.browser.version.split('.');
  version = parseInt(version[0]);
  var is_firefox = jQuery.browser.mozilla != undefined && version > 6;

  if(is_chrome) //|| is_firefox
    {
    $('#changeUploadMode').show();
    }
  } catch (e) { }

midas.upload.simpleupload.mode = "file";
midas.upload.simpleupload.htmlFileMode = $('.file_upload_label').html();
midas.upload.simpleupload.htmlFolderMode = $('.file_upload_label_folder').html();

$('#uploadModeFileLink').hide();

$('.uploadModeLink').click(function() {
  if(midas.upload.simpleupload.mode == 'file')
    {
    midas.upload.simpleupload.mode = 'folder';
    $('.fileUploaderInput').attr('webkitdirectory', '');
    $('.fileUploaderInput').attr('directory', '');
    $('.fileUploaderInput').attr('mozdirectory', '');
    $('.file_upload_label').html(midas.upload.simpleupload.htmlFolderMode);
    $('#uploadModeFileLink').show();
    $('#uploadModeFolderLink').hide();
    }
  else
    {
    midas.upload.simpleupload.mode = 'file';
    $('.fileUploaderInput').removeAttr('webkitdirectory');
    $('.fileUploaderInput').removeAttr('directory');
    $('.fileUploaderInput').removeAttr('mozdirectory');
    $('.file_upload_label').html(midas.upload.simpleupload.htmlFileMode);
    $('#uploadModeFileLink').hide();
    $('#uploadModeFolderLink').show();
    }
});

$(".uploadTabs").tabs({
  ajaxOptions: {
    beforeSend: function() {
      $('div.MainDialogLoading').show();
      },
    success: function() {
      $('div.MainDialogLoading').hide();
      $(".uploadTabs").show();
      },
    error: function(xhr, status, index, anchor) {
      $(anchor.hash).html("Couldn't load this tab. ");
      }
    }
  });

$(".uploadTabs").show();
$('#linkForm').ajaxForm(function() {
  $('.uploadedLinks').val(parseInt($('.uploadedLinks').val()) + 1);
  midas.upload.simpleupload.updateUploadedCount();
  });

if($.browser.msie)
  {
  $('#swfuploadContent').show();
  $('#jqueryFileUploadContent').hide();
  midas.upload.simpleupload.initSwfupload();
  }
else
  {
  $('#swfuploadContent').hide();
  $('#jqueryFileUploadContent').show();
  midas.upload.simpleupload.initJqueryFileupload();
  }

$('#startUploadLink').qtip({
  content: {
    attr: 'qtip'
    }
  });

$('.browseMIDASLink').click(function() {
  loadDialog("select", "/browse/selectfolder/?policy=write");
  showDialog('Browse');
  });
midas.doCallback('CALLBACK_CORE_SIMPLEUPLOAD_LOADED');
<commit_msg>BUG: refs #489 Disabling drag and drop when uploading directories<commit_after>var midas = midas || {};
midas.upload = midas.upload || {};
midas.upload.simpleupload = {};

midas.upload.simpleupload.updateUploadedCount = function()
  {
  var count = parseInt($('.uploadedSimple').val()) +
              parseInt($('.uploadedLinks').val()) +
              parseInt($('.uploadedJava').val());
  $('.globalUploadedCount').html(count);
  if(count > 0)
    {
    $('.reviewUploaded').show();
    }
  else
    {
    $('.reviewUploaded').hide();
    }
  }

midas.upload.simpleupload.initJqueryFileupload = function()
  {
  midas.upload.simpleupload.updateUploadedCount();
  //see http://aquantum-demo.appspot.com/file-upload
  $('.file_upload:visible').fileUploadUIX({
    beforeSend: function (event, files, index, xhr, handler, callBack) {
      if(index == 0) //only do this once since we have all the files every time
        {
        var retVal = midas.doCallback('CALLBACK_CORE_VALIDATE_UPLOAD', {files: files});
        $.each(retVal, function(module, resp) {
          if(resp.status === false)
            {
            $('div.uploadValidationError b').html(resp.message);
            $('div.uploadValidationError').show();
            }
          });
        }

      handler.uploadRow.find('.file_upload_start').click(function () {
        var path = '';
        $.each(files, function (index, file) {
          path += file.webkitRelativePath+';;';
          });
        handler.formData = {
          parent: $('#destinationId').val(),
          path: path,
          license: $('select[name=licenseSelect]').val()
          };
        callBack();
        });
      $('.file_name').each(function(){
        if($(this).html() == '.' || $(this).html() == '..')
          {
          $(this).parent('tr').find('.file_upload_cancel button').click();
          }
        });

      $('#startUploadLink').css('box-shadow', '0 0 5px blue');
      $('#startUploadLink').css('-webkit-box-shadow', '0 0 5px blue');
      $('#startUploadLink').css('-moz-box-shadow', '0 0 5px blue');
      },
    onComplete:  function (event, files, index, xhr, handler) {
      midas.doCallback('CALLBACK_CORE_RESET_UPLOAD_TOTAL');
      $('.uploadedSimple').val(parseInt($('.uploadedSimple').val())+1);
        midas.upload.simpleupload.updateUploadedCount();
      },
    sequentialUploads: true
    });

    $('#startUploadLink').click(function () {
      if($('#destinationId').val() == undefined || $('#destinationId').val().length == 0)
        {
        createNotice("Please select where you want to upload your files.", 4000);
        return false;
        }
      $('.file_upload_start button').click();
      $('#startUploadLink').css('box-shadow', '0 0 0px blue');
      $('#startUploadLink').css('-webkit-box-shadow', '0 0 0px blue');
      $('#startUploadLink').css('-moz-box-shadow', '0 0 0px blue');
      return false;
    });
  }

// Callback hook for the flash uploader
midas.upload.simpleupload.uploadPreStart = function(file)
  {
  midas.upload.simpleupload.swfu.setPostParams({
    'sid': $('.sessionId').val(),
    'parent': $('#destinationId').val(),
    'license': $('select[name=licenseSelect]').val()
    });
  }

// We use shockwave flash uploader for IE (no multi-file upload support)
midas.upload.simpleupload.initSwfupload = function()
  {
  var settings = {
    flash_url: json.global.coreWebroot+"/public/js/swfupload/swfupload_fp10/swfupload.swf",
    flash9_url: json.global.coreWebroot+"/public/js/swfupload/swfupload_fp9/swfupload_fp9.swf",
    upload_url: json.global.webroot+"/upload/saveuploaded",
    post_params: {
      'sid': $('.sessionId').val(),
      'parent': $('#destinationId').val(),
      'license': $('select[name=licenseSelect]').val()
      },
    file_size_limit: $('.maxSizeFile').val()+" MB",
    file_types: "*.*",
    file_types_description: "All Files",
    file_upload_limit: 100,
    file_queue_limit: 0,
    custom_settings: {
      progressTarget: "fsUploadProgress",
      cancelButtonId: "btnCancel",
      pageObj: midas.upload.simpleupload
      },
    debug: false,

    // Button settings
    button_image_url: json.global.coreWebroot+"/public/js/swfupload/images/Button_65x29.png",
    button_width: "65",
    button_height: "20",
    button_placeholder_id: "spanButtonPlaceHolder",
    button_text: ''+$('.buttonBrowse').val()+'',
    button_text_style: ".theFont { font-size: 12; }",
    button_text_left_padding: 5,
    button_text_top_padding: 0,

    // The event handler functions are defined in handlers.js
    swfupload_preload_handler: preLoad,
    swfupload_load_failed_handler: loadFailed,
    file_queued_handler: fileQueued,
    file_queue_error_handler: fileQueueError,
    file_dialog_complete_handler: fileDialogComplete,
    upload_start_handler: midas.upload.simpleupload.uploadPreStart,
    upload_progress_handler: uploadProgress,
    upload_error_handler: uploadError,
    upload_success_handler: uploadSuccess,
    upload_complete_handler: uploadComplete,
    queue_complete_handler: queueComplete  // Queue plugin event
    };

  $('#swfuploadContent').show();
  midas.upload.simpleupload.swfu = new SWFUpload(settings);

  $('#startUploadLink').click(function() {
    if($('#destinationId').val() == undefined || $('#destinationId').val().length == 0)
      {
      createNotice("Please select where you want to upload your files.", 4000);
      return false;
      }
    midas.upload.simpleupload.swfu.startUpload();
    });
  }

$('img#uploadAFile').show();
$('img#uploadAFileLoading').hide();

// detect chrome or firefox 7+
try
  {
  var is_chrome = /chrome/.test(navigator.userAgent.toLowerCase());
  var version = jQuery.browser.version.split('.');
  version = parseInt(version[0]);
  var is_firefox = jQuery.browser.mozilla != undefined && version > 6;

  if(is_chrome) //|| is_firefox
    {
    $('#changeUploadMode').show();
    }
  } catch (e) { }

midas.upload.simpleupload.mode = "file";
midas.upload.simpleupload.htmlFileMode = $('.file_upload_label').html();
midas.upload.simpleupload.htmlFolderMode = $('.file_upload_label_folder').html();

$('#uploadModeFileLink').hide();

$('.uploadModeLink').click(function() {
  if(midas.upload.simpleupload.mode == 'file')
    {
    midas.upload.simpleupload.mode = 'folder';
    $('.fileUploaderInput').attr('webkitdirectory', '');
    $('.fileUploaderInput').attr('directory', '');
    $('.fileUploaderInput').attr('mozdirectory', '');
    $('.file_upload_label').html(midas.upload.simpleupload.htmlFolderMode);
    $('#uploadModeFileLink').show();
    $('#uploadModeFolderLink').hide();
    $('div.file_upload').fileUploadUIX('option','dragDropSupport',false); // disable drag and drop support
    }
  else
    {
    midas.upload.simpleupload.mode = 'file';
    $('.fileUploaderInput').removeAttr('webkitdirectory');
    $('.fileUploaderInput').removeAttr('directory');
    $('.fileUploaderInput').removeAttr('mozdirectory');
    $('.file_upload_label').html(midas.upload.simpleupload.htmlFileMode);
    $('#uploadModeFileLink').hide();
    $('#uploadModeFolderLink').show();
    $('div.file_upload').fileUploadUIX('option','dragDropSupport',true); // enable drag and drop support
    }
});

$(".uploadTabs").tabs({
  ajaxOptions: {
    beforeSend: function() {
      $('div.MainDialogLoading').show();
      },
    success: function() {
      $('div.MainDialogLoading').hide();
      $(".uploadTabs").show();
      },
    error: function(xhr, status, index, anchor) {
      $(anchor.hash).html("Couldn't load this tab. ");
      }
    }
  });

$(".uploadTabs").show();
$('#linkForm').ajaxForm(function() {
  $('.uploadedLinks').val(parseInt($('.uploadedLinks').val()) + 1);
  midas.upload.simpleupload.updateUploadedCount();
  });

if($.browser.msie)
  {
  $('#swfuploadContent').show();
  $('#jqueryFileUploadContent').hide();
  midas.upload.simpleupload.initSwfupload();
  }
else
  {
  $('#swfuploadContent').hide();
  $('#jqueryFileUploadContent').show();
  midas.upload.simpleupload.initJqueryFileupload();
  }

$('#startUploadLink').qtip({
  content: {
    attr: 'qtip'
    }
  });

$('.browseMIDASLink').click(function() {
  loadDialog("select", "/browse/selectfolder/?policy=write");
  showDialog('Browse');
  });
midas.doCallback('CALLBACK_CORE_SIMPLEUPLOAD_LOADED');
<|endoftext|>


<commit_before>/**
 * Branch.IO SDK
 * -------------
 * Method usage:
 *     All methods are promisified, therefore you can call .then(successCallback, errorCallback) for any of the method
 *     called for executing success or error callbacks.
 */

var exec = require('cordova/exec');
var deviceVendor = window.clientInformation.vendor;
var _API_CLASS = 'BranchSDK'; // SDK Class

/**
 * Execute SDK method using cordova.exec()
 *
 * @param  (String) method - The class method to execute.
 * @param  (Array) params  - Method parameter(s) to pass.
 *
 * @return (Promise)
 */
function execute(method, params) {

    params = (!params) ? [] : params;

    return new Promise(function(resolve, reject) {
        exec(function(res) {
            resolve(res);
        }, function(err) {
            reject(err);
        }, _API_CLASS, method, params);
    });

}

/**
 * Set listener callback for SDK method.
 *
 * @param  (String) method      - The class method to execute.
 * @param  (Function) callback  - The method listener callback.
 * @param  (Array) params       - The method listener parameters.
 *
 * @return (Promise)
 */
function executeCallback(method, callback, params) {

    params = (!params) ? [] : params;

    exec(callback, function(err) {
        console.error(err);
    }, _API_CLASS, method, params);

}

/**
 * @class Branch
 */
var Branch = function() {

    this.debugMode = false;

};

var disableGlobalListenersWarnings = false;

/**
 * Don't emit warnings regarding use of global listeners.
 */
Branch.prototype.disableGlobalListenersWarnings = function() {
    disableGlobalListenersWarnings = true;
};

var branchLinkListener = null;
function onBranchLinkStub(data) {
    branchLinkListener(data);
}

/**
 * Initialize the Branch instance.
 * @param (Function) onBranchLinkHook. listener to trigger on deep links.
 * @return (Promise)
 */
Branch.prototype.initSession = function(onBranchLinkHook) {
    if (!onBranchLinkHook && !disableGlobalListenersWarnings) {
        console.log('WARNING: branch link hook is not being passed to initSession. ' +
            'Falling back to global DeepLinkHandler method. See https://goo.gl/GijGKP for details.');
    }
    else {
        var currentHook = window.DeepLinkHandler;
        if (currentHook !== undefined && currentHook !== onBranchLinkStub) {
            if (!disableGlobalListenersWarnings) {
                console.log('WARNING: you are calling initSession with a branch link hook when an ' +
                    'existing global DeepLinkHandler is defined. The global ' +
                    'DeepLinkHandler will be overwritten. See https://goo.gl/GijGKP ' +
                    'for details.');
            }
        }
        if (onBranchLinkHook) {
            branchLinkListener = onBranchLinkHook;
            window.DeepLinkHandler = onBranchLinkStub;
        }
    }

    return execute('initSession');
};

var nonBranchLinkListener = null;
function onNonBranchLinkStub(data) {
    nonBranchLinkListener(data);
}

/**
 * Register listener for non branch links.
 */
Branch.prototype.onNonBranchLink = function(newHook) {
    if (!newHook) {
        throw new Error('non branch link hook is falsy, expected a function, not: "' + newHook + '"');
    }

    var currentHook = window.NonBranchLinkHandler;
    if (currentHook !== undefined && currentHook !== onNonBranchLinkStub) {
        if (!disableGlobalListenersWarnings) {
            console.log('WARNING: you are calling onNonBranchLink when an ' +
                'existing global NonBranchLinkHandler is defined. The global ' +
                'NonBranchLinkHandler will be overwritten. See https://goo.gl/GijGKP ' +
                'for details.');
        }
    }
    nonBranchLinkListener = newHook;
    window.NonBranchLinkHandler = onNonBranchLinkStub;
}

/**
 * Get Mixpanel tolen/assisstance.
 * NOTE: This must be called before initSession
 *
 * @param (String) token. Default = false
 *
 * @return (Promise)
 */
Branch.prototype.setMixpanelToken = function(token) {

    return execute('setMixpanelToken', [ token ]);

};

/**
 * Set debug mode to simulate fresh installs.
 * NOTE: This must be called before initSession
 *
 * @param (Boolean) isEnabled. Default = false
 *
 * @return (Promise)
 */
Branch.prototype.setDebug = function(isEnabled) {

    isEnabled = (typeof isEnabled !== 'boolean') ? false : isEnabled;

    this.debugMode = isEnabled;

    return execute('setDebug', [ isEnabled ]);

};

/**
 * Retrieves the install session parameters.
 *
 * @return (Promise)
 */
Branch.prototype.getFirstReferringParams = function() {

    return execute('getFirstReferringParams');

};

/**
 * Retrieves the latest referring parameters.
 *
 * @return (Promise)
 */
Branch.prototype.getLatestReferringParams = function() {

    return execute('getLatestReferringParams');

};

/**
 * Sets the identity of a user and returns the data.
 *
 * @param (String) identity - A unique identifier for the user [REQUIRED]
 *
 * @return (Promise)
 *
 */
Branch.prototype.setIdentity = function(identity) {

    if (identity) {
        return execute('setIdentity', [ identity ]);
    }
 else {
        return new Promise(function(resolve, reject) {
            reject('Please set an identity');
        });
    }

};

/**
 * Logout from the current session. Replace session and identity IDs.
 *
 * @return (Promise)
 */
Branch.prototype.logout = function() {

    return execute('logout');

};

/**
 * Register custom events.
 *
 * @param (String) action - Name of the custom action
 * @param (Object) metaData - Data to pass with the action [OPTIONAL]
 *
 * @return (Promise)
 */
Branch.prototype.userCompletedAction = function(action, metaData) {

    var args = [ action ];

    if (metaData) {
        args.push(metaData);
    }

    return execute('userCompletedAction', args);

};

/**
 * Create an universal Branch object
 *
 * @params (Object) options
 *
 * @return (Promise)
 *
 * options:
 *    --------------------------------------------------------------
 *    |          KEY          |    TYPE    |      DESCRIPTION      |
 *    --------------------------------------------------------------
 *    |  canonicalIdentifier  |   String   | The object identifier |
 *    |         title         |   String   |   The object title    |
 *    |  contentDescription   |   String   |  Object description   |
 *    |    contentImageUrl    |   String   |     The image URL     |
 *    |  contentIndexingMode  |   String   |    Indexing Mode      |
 *    |                       |            |('private' or 'public')|
 *    |    contentMetadata    |   Object   |   Custom key/value    |
 *    --------------------------------------------------------------
 */
Branch.prototype.createBranchUniversalObject = function(options) {

    return new Promise(function(resolve, reject) {
        execute('createBranchUniversalObject', [ options ]).then(function(res) {

            var obj = {
                message: res.message,
                instanceId: res.branchUniversalObjectId
            };

            // Attach object functions
            /**
             * Register view count.
             *
             * @return (Promise)
             */
            obj.registerView = function() {

                return execute('registerView', [ obj.instanceId ]);

            };

            /**
             * Generates a short url.
             *
             * @param (Object) options
             * @param (Object) controlParameters
             *
             * @return (Promise)
             *
             * options:
             *    --------------------------------------------------
             *    |    KEY    |    TYPE    |      DESCRIPTION      |
             *    --------------------------------------------------
             *    |  feature  |   String   |   The link feature    |
             *    |   alias   |   String   |    The link alias     |
             *    |  channel  |   String   |   The link channel    |
             *    |   stage   |   String   |    The link stage     |
             *    |  duration |    Int     |   The link duration   |
             *    --------------------------------------------------
             *
             * controlParameters:
             *    -------------------------------------------------------
             *    |         KEY        |    TYPE    |    DESCRIPTION    |
             *    -------------------------------------------------------
             *    |    $fallback_url   |   String   |   Fallback URL    |
             *    |    $desktop_url    |   String   |   Desktop URL     |
             *    |    $android_url    |   String   |   Android URL     |
             *    |      $ios_url      |   String   |     iOS URL       |
             *    |      $ipad_url     |   String   |    iPad URL       |
             *    |      $fire_url     |   String   |  Kindle Fire URL  |
             *    |  $blackberry_url   |   String   |   Blackberry URL  |
             *    | $windows_phone_url |   String   |  Kindle Fire URL  |
             *    -------------------------------------------------------
             */
            obj.generateShortUrl = function(options, controlParameters) {

                return execute('generateShortUrl', [ obj.instanceId, options, controlParameters ]);

            };

            /**
             * Show the share dialog.
             *
             * @param (Object) options
             * @param (Object) controlParameters
             * @param (String) shareText [OPTIONAL]
             *
             * @return (Promise)
             *
             * options:
             *    --------------------------------------------------
             *    |    KEY    |    TYPE    |      DESCRIPTION      |
             *    --------------------------------------------------
             *    |  feature  |   String   |   The link feature    |
             *    |   alias   |   String   |    The link alias     |
             *    |  channel  |   String   |   The link channel    |
             *    |   stage   |   String   |    The link stage     |
             *    |  duration |    Int     |   The link duration   |
             *    --------------------------------------------------
             *
             * controlParameters:
             *    -------------------------------------------------------
             *    |         KEY        |    TYPE    |    DESCRIPTION    |
             *    -------------------------------------------------------
             *    |    $fallback_url   |   String   |   Fallback URL    |
             *    |    $desktop_url    |   String   |   Desktop URL     |
             *    |    $android_url    |   String   |   Android URL     |
             *    |      $ios_url      |   String   |     iOS URL       |
             *    |      $ipad_url     |   String   |    iPad URL       |
             *    |      $fire_url     |   String   |  Kindle Fire URL  |
             *    |  $blackberry_url   |   String   |   Blackberry URL  |
             *    | $windows_phone_url |   String   |  Kindle Fire URL  |
             *    -------------------------------------------------------
             */
            obj.showShareSheet = function(options, controlParameters, shareText) {

                if (!shareText) {
                    shareText = 'This stuff is awesome: ';
                }

                return execute('showShareSheet', [ obj.instanceId, options, controlParameters, shareText ]);

            };

            /**
             * Set on share sheet launched listener callback.
             *
             * @param (Function) callback
             */
            obj.onShareSheetLaunched = function(callback) {

                if (deviceVendor.indexOf('Apple') < 0) {
                    executeCallback('onShareLinkDialogLaunched', callback, [ obj.instanceId ]);
                }

            };

            obj.onShareSheetDismissed = function(callback) {

                executeCallback('onShareLinkDialogDismissed', callback, [ obj.instanceId ]);

            }

            /**
             * Set on link share listener callback.
             *
             * @param (Function) callback
             */
            obj.onLinkShareResponse = function(callback) {

                executeCallback('onLinkShareResponse', callback, [ obj.instanceId ]);

            };

            /**
             * Set on channel select listener callback.
             *
             * @param (Function) callback
             */
            obj.onChannelSelected = function(callback) {

                if (deviceVendor.indexOf('Apple') < 0) {
                    executeCallback('onChannelSelected', callback, [ obj.instanceId ]);
                }

            };

            /**
             * List item on Spotlight (iOS Only).
             */
            obj.listOnSpotlight = function() {

                return execute('listOnSpotlight', [ obj.instanceId ]);

            };

            resolve(obj);

        }, function(err) {
            reject(err);
        });
    });

};

/**
 * Retrieve the current reward balance.
 *
 * @return (Promise)
 */
Branch.prototype.loadRewards = function(bucket) {

    if (!bucket) {
        bucket = '';
    }

    return execute('loadRewards', [ bucket ]);

};

/**
 * Redeem rewards to your account.
 *
 * @param (Int) value - The amount to redeem.
 * @param (String) bucket - The value containing the name of the referral bucket to attempt to redeem credits from. [OPTIONAL]
 *
 * @return (Promise)
 */
Branch.prototype.redeemRewards = function(value, bucket) {

    var params = [ value ];

    if (bucket) {
        params.push(bucket);
    }

    return execute('redeemRewards', params);

};

/**
 * Retrieve the entire history of credits and redemptions from the individual user.
 *
 * @return (Promise)
 */
Branch.prototype.creditHistory = function() {

    return execute('getCreditHistory');

};

/**
 * NonBranchLinkHandler callback placeholder.
 *
 * @param {String} response
 */
window.NonBranchLinkHandler = (typeof NonBranchLinkHandler === 'undefined') ? function(response) {} : NonBranchLinkHandler;

module.exports = new Branch;
<commit_msg>fix: detect defaultNonBranchLinkHandler<commit_after>/**
 * Branch.IO SDK
 * -------------
 * Method usage:
 *     All methods are promisified, therefore you can call .then(successCallback, errorCallback) for any of the method
 *     called for executing success or error callbacks.
 */

var exec = require('cordova/exec');
var deviceVendor = window.clientInformation.vendor;
var _API_CLASS = 'BranchSDK'; // SDK Class

/**
 * Execute SDK method using cordova.exec()
 *
 * @param  (String) method - The class method to execute.
 * @param  (Array) params  - Method parameter(s) to pass.
 *
 * @return (Promise)
 */
function execute(method, params) {

    params = (!params) ? [] : params;

    return new Promise(function(resolve, reject) {
        exec(function(res) {
            resolve(res);
        }, function(err) {
            reject(err);
        }, _API_CLASS, method, params);
    });

}

/**
 * Set listener callback for SDK method.
 *
 * @param  (String) method      - The class method to execute.
 * @param  (Function) callback  - The method listener callback.
 * @param  (Array) params       - The method listener parameters.
 *
 * @return (Promise)
 */
function executeCallback(method, callback, params) {

    params = (!params) ? [] : params;

    exec(callback, function(err) {
        console.error(err);
    }, _API_CLASS, method, params);

}

/**
 * @class Branch
 */
var Branch = function() {

    this.debugMode = false;

};

var disableGlobalListenersWarnings = false;

/**
 * Don't emit warnings regarding use of global listeners.
 */
Branch.prototype.disableGlobalListenersWarnings = function() {
    disableGlobalListenersWarnings = true;
};

var branchLinkListener = null;
function onBranchLinkStub(data) {
    branchLinkListener(data);
}

/**
 * Initialize the Branch instance.
 * @param (Function) onBranchLinkHook. listener to trigger on deep links.
 * @return (Promise)
 */
Branch.prototype.initSession = function(onBranchLinkHook) {
    if (!onBranchLinkHook && !disableGlobalListenersWarnings) {
        console.log('WARNING: branch link hook is not being passed to initSession. ' +
            'Falling back to global DeepLinkHandler method. See https://goo.gl/GijGKP for details.');
    }
    else {
        var currentHook = window.DeepLinkHandler;
        if (currentHook !== undefined && currentHook !== onBranchLinkStub) {
            if (!disableGlobalListenersWarnings) {
                console.log('WARNING: you are calling initSession with a branch link hook when an ' +
                    'existing global DeepLinkHandler is defined. The global ' +
                    'DeepLinkHandler will be overwritten. See https://goo.gl/GijGKP ' +
                    'for details.');
            }
        }
        if (onBranchLinkHook) {
            branchLinkListener = onBranchLinkHook;
            window.DeepLinkHandler = onBranchLinkStub;
        }
    }

    return execute('initSession');
};

var nonBranchLinkListener = null;
function onNonBranchLinkStub(data) {
    nonBranchLinkListener(data);
}

/**
 * Register listener for non branch links.
 */
Branch.prototype.onNonBranchLink = function(newHook) {
    if (!newHook) {
        throw new Error('non branch link hook is falsy, expected a function, not: "' + newHook + '"');
    }

    var currentHook = window.NonBranchLinkHandler;
    if (currentHook !== undefined && currentHook !== onNonBranchLinkStub && currentHook !== defaultNonBranchLinkHandler) {
        if (!disableGlobalListenersWarnings) {
            console.log('WARNING: you are calling onNonBranchLink when an ' +
                'existing global NonBranchLinkHandler is defined. The global ' +
                'NonBranchLinkHandler will be overwritten. See https://goo.gl/GijGKP ' +
                'for details.');
        }
    }
    nonBranchLinkListener = newHook;
    window.NonBranchLinkHandler = onNonBranchLinkStub;
}

/**
 * Get Mixpanel tolen/assisstance.
 * NOTE: This must be called before initSession
 *
 * @param (String) token. Default = false
 *
 * @return (Promise)
 */
Branch.prototype.setMixpanelToken = function(token) {

    return execute('setMixpanelToken', [ token ]);

};

/**
 * Set debug mode to simulate fresh installs.
 * NOTE: This must be called before initSession
 *
 * @param (Boolean) isEnabled. Default = false
 *
 * @return (Promise)
 */
Branch.prototype.setDebug = function(isEnabled) {

    isEnabled = (typeof isEnabled !== 'boolean') ? false : isEnabled;

    this.debugMode = isEnabled;

    return execute('setDebug', [ isEnabled ]);

};

/**
 * Retrieves the install session parameters.
 *
 * @return (Promise)
 */
Branch.prototype.getFirstReferringParams = function() {

    return execute('getFirstReferringParams');

};

/**
 * Retrieves the latest referring parameters.
 *
 * @return (Promise)
 */
Branch.prototype.getLatestReferringParams = function() {

    return execute('getLatestReferringParams');

};

/**
 * Sets the identity of a user and returns the data.
 *
 * @param (String) identity - A unique identifier for the user [REQUIRED]
 *
 * @return (Promise)
 *
 */
Branch.prototype.setIdentity = function(identity) {

    if (identity) {
        return execute('setIdentity', [ identity ]);
    }
 else {
        return new Promise(function(resolve, reject) {
            reject('Please set an identity');
        });
    }

};

/**
 * Logout from the current session. Replace session and identity IDs.
 *
 * @return (Promise)
 */
Branch.prototype.logout = function() {

    return execute('logout');

};

/**
 * Register custom events.
 *
 * @param (String) action - Name of the custom action
 * @param (Object) metaData - Data to pass with the action [OPTIONAL]
 *
 * @return (Promise)
 */
Branch.prototype.userCompletedAction = function(action, metaData) {

    var args = [ action ];

    if (metaData) {
        args.push(metaData);
    }

    return execute('userCompletedAction', args);

};

/**
 * Create an universal Branch object
 *
 * @params (Object) options
 *
 * @return (Promise)
 *
 * options:
 *    --------------------------------------------------------------
 *    |          KEY          |    TYPE    |      DESCRIPTION      |
 *    --------------------------------------------------------------
 *    |  canonicalIdentifier  |   String   | The object identifier |
 *    |         title         |   String   |   The object title    |
 *    |  contentDescription   |   String   |  Object description   |
 *    |    contentImageUrl    |   String   |     The image URL     |
 *    |  contentIndexingMode  |   String   |    Indexing Mode      |
 *    |                       |            |('private' or 'public')|
 *    |    contentMetadata    |   Object   |   Custom key/value    |
 *    --------------------------------------------------------------
 */
Branch.prototype.createBranchUniversalObject = function(options) {

    return new Promise(function(resolve, reject) {
        execute('createBranchUniversalObject', [ options ]).then(function(res) {

            var obj = {
                message: res.message,
                instanceId: res.branchUniversalObjectId
            };

            // Attach object functions
            /**
             * Register view count.
             *
             * @return (Promise)
             */
            obj.registerView = function() {

                return execute('registerView', [ obj.instanceId ]);

            };

            /**
             * Generates a short url.
             *
             * @param (Object) options
             * @param (Object) controlParameters
             *
             * @return (Promise)
             *
             * options:
             *    --------------------------------------------------
             *    |    KEY    |    TYPE    |      DESCRIPTION      |
             *    --------------------------------------------------
             *    |  feature  |   String   |   The link feature    |
             *    |   alias   |   String   |    The link alias     |
             *    |  channel  |   String   |   The link channel    |
             *    |   stage   |   String   |    The link stage     |
             *    |  duration |    Int     |   The link duration   |
             *    --------------------------------------------------
             *
             * controlParameters:
             *    -------------------------------------------------------
             *    |         KEY        |    TYPE    |    DESCRIPTION    |
             *    -------------------------------------------------------
             *    |    $fallback_url   |   String   |   Fallback URL    |
             *    |    $desktop_url    |   String   |   Desktop URL     |
             *    |    $android_url    |   String   |   Android URL     |
             *    |      $ios_url      |   String   |     iOS URL       |
             *    |      $ipad_url     |   String   |    iPad URL       |
             *    |      $fire_url     |   String   |  Kindle Fire URL  |
             *    |  $blackberry_url   |   String   |   Blackberry URL  |
             *    | $windows_phone_url |   String   |  Kindle Fire URL  |
             *    -------------------------------------------------------
             */
            obj.generateShortUrl = function(options, controlParameters) {

                return execute('generateShortUrl', [ obj.instanceId, options, controlParameters ]);

            };

            /**
             * Show the share dialog.
             *
             * @param (Object) options
             * @param (Object) controlParameters
             * @param (String) shareText [OPTIONAL]
             *
             * @return (Promise)
             *
             * options:
             *    --------------------------------------------------
             *    |    KEY    |    TYPE    |      DESCRIPTION      |
             *    --------------------------------------------------
             *    |  feature  |   String   |   The link feature    |
             *    |   alias   |   String   |    The link alias     |
             *    |  channel  |   String   |   The link channel    |
             *    |   stage   |   String   |    The link stage     |
             *    |  duration |    Int     |   The link duration   |
             *    --------------------------------------------------
             *
             * controlParameters:
             *    -------------------------------------------------------
             *    |         KEY        |    TYPE    |    DESCRIPTION    |
             *    -------------------------------------------------------
             *    |    $fallback_url   |   String   |   Fallback URL    |
             *    |    $desktop_url    |   String   |   Desktop URL     |
             *    |    $android_url    |   String   |   Android URL     |
             *    |      $ios_url      |   String   |     iOS URL       |
             *    |      $ipad_url     |   String   |    iPad URL       |
             *    |      $fire_url     |   String   |  Kindle Fire URL  |
             *    |  $blackberry_url   |   String   |   Blackberry URL  |
             *    | $windows_phone_url |   String   |  Kindle Fire URL  |
             *    -------------------------------------------------------
             */
            obj.showShareSheet = function(options, controlParameters, shareText) {

                if (!shareText) {
                    shareText = 'This stuff is awesome: ';
                }

                return execute('showShareSheet', [ obj.instanceId, options, controlParameters, shareText ]);

            };

            /**
             * Set on share sheet launched listener callback.
             *
             * @param (Function) callback
             */
            obj.onShareSheetLaunched = function(callback) {

                if (deviceVendor.indexOf('Apple') < 0) {
                    executeCallback('onShareLinkDialogLaunched', callback, [ obj.instanceId ]);
                }

            };

            obj.onShareSheetDismissed = function(callback) {

                executeCallback('onShareLinkDialogDismissed', callback, [ obj.instanceId ]);

            }

            /**
             * Set on link share listener callback.
             *
             * @param (Function) callback
             */
            obj.onLinkShareResponse = function(callback) {

                executeCallback('onLinkShareResponse', callback, [ obj.instanceId ]);

            };

            /**
             * Set on channel select listener callback.
             *
             * @param (Function) callback
             */
            obj.onChannelSelected = function(callback) {

                if (deviceVendor.indexOf('Apple') < 0) {
                    executeCallback('onChannelSelected', callback, [ obj.instanceId ]);
                }

            };

            /**
             * List item on Spotlight (iOS Only).
             */
            obj.listOnSpotlight = function() {

                return execute('listOnSpotlight', [ obj.instanceId ]);

            };

            resolve(obj);

        }, function(err) {
            reject(err);
        });
    });

};

/**
 * Retrieve the current reward balance.
 *
 * @return (Promise)
 */
Branch.prototype.loadRewards = function(bucket) {

    if (!bucket) {
        bucket = '';
    }

    return execute('loadRewards', [ bucket ]);

};

/**
 * Redeem rewards to your account.
 *
 * @param (Int) value - The amount to redeem.
 * @param (String) bucket - The value containing the name of the referral bucket to attempt to redeem credits from. [OPTIONAL]
 *
 * @return (Promise)
 */
Branch.prototype.redeemRewards = function(value, bucket) {

    var params = [ value ];

    if (bucket) {
        params.push(bucket);
    }

    return execute('redeemRewards', params);

};

/**
 * Retrieve the entire history of credits and redemptions from the individual user.
 *
 * @return (Promise)
 */
Branch.prototype.creditHistory = function() {

    return execute('getCreditHistory');

};

/**
 * NonBranchLinkHandler callback placeholder.
 *
 * @param {String} response
 */
var defaultNonBranchLinkHandler = function(response) {};
window.NonBranchLinkHandler = (typeof NonBranchLinkHandler === 'undefined') ? defaultNonBranchLinkHandler : NonBranchLinkHandler;

module.exports = new Branch;
<|endoftext|>


<commit_before>console.clear()

window.util = (function(){

  var data = window.__datacache = window.__datacache || {}

  var queue = []
  var queueCount = 0
  async function queueCheck(id){
    function finishFn(){
      var prevQueue = queue.slice()
      queue = queue.filter(d => id != d.id)
      // console.log({status: 'done', id, queue})
      if (prevQueue.length != queue.length){
        queue[0]?.startFn()
      }
    }

    // auto flush after a second
    setTimeout(finishFn, 1000)

    if (queue.length == 0){
      queue.push({id, startFn: d => d})
      return finishFn
    }
    else {
      return new Promise((resolve) => {
        var startFn = () => {
          resolve(finishFn)
        }
        queue.push({id, startFn})
      })
    }
  }

  async function getFile(path, uploadData={}){
    var [slug, type] = path.split('.')

    var id = queueCount++
    // console.log({status: 'start', id, queue})
    var finishFn = await queueCheck(id)

    var uploadDataStr = JSON.stringify(uploadData)
    slug = path + ' __ ' + uploadDataStr
    if (data[slug]){
      finishFn()
      return data[slug]
    }

    var datadir = 'https://localhost:' + python_settings.port + '/'

    var res = await fetch(datadir + path + '', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(uploadData),
    })
    // console.log({'status': 'fetching', id, queue})

    if (type == 'csv'){
      var parsed = d3.csvParse(await res.text())
    } else if (type == 'npy'){
      var parsed = npyjs.parse(await(res).arrayBuffer())
    } else if (type == 'json'){
      var parsed = await res.json()
    } else{
      throw 'unknown type'
    }

    data[slug] = parsed

    finishFn()
    return parsed
  }

  return {
    getFile,
  }
})()

async function main(){
  var data = await util.getFile('hello.npy')

  console.log(data)

}
main()

// TODO: auto add clientside code from 1wheel/hot-server
function initReloadInit(){
  if (window.__isInitReload) return
  window.__isInitReload = true

  new WebSocket('wss://hot-server-test-domain:3989').onmessage = msg => {
    var {path, type, str} = JSON.parse(msg.data)

    if (type == 'reload'){
      location.reload()
    } else if (type == 'jsInject'){
      console.clear() // enable with --consoleclear
      // Function is faster than eval but adds two extra lines at start of file
      Function(str)()
      if (window.__onHotServer) window.__onHotServer({path, type, str})
    } else if (type == 'cssInject') {
      Array.from(document.querySelectorAll('link'))
        .filter(d => d.href.includes(path.split('/').slice(-1)[0]))
        .forEach(d => d.href = d.href.split('?')[0] + '?' + Math.random())
    }
  }
}
if (!window.__isInitReload) initReloadInit()

<commit_msg>works<commit_after>console.clear()

window.util = (function(){

  var data = window.__datacache = window.__datacache || {}

  var queue = []
  var queueCount = 0
  async function queueCheck(id){
    function finishFn(){
      var prevQueue = queue.slice()
      queue = queue.filter(d => id != d.id)
      // console.log({status: 'done', id, queue})
      if (prevQueue.length != queue.length){
        queue[0]?.startFn()
      }
    }

    // auto flush after a second
    setTimeout(finishFn, 1000)

    if (queue.length == 0){
      queue.push({id, startFn: d => d})
      return finishFn
    }
    else {
      return new Promise((resolve) => {
        var startFn = () => {
          resolve(finishFn)
        }
        queue.push({id, startFn})
      })
    }
  }

  async function getFile(path, uploadData={}){
    var [slug, type] = path.split('.')

    var id = queueCount++
    // console.log({status: 'start', id, queue})
    var finishFn = await queueCheck(id)

    var uploadDataStr = JSON.stringify(uploadData)
    slug = path + ' __ ' + uploadDataStr
    if (data[slug]){
      finishFn()
      return data[slug]
    }

    var datadir = 'https://localhost:' + python_settings.port + '/'

    var res = await fetch(datadir + path + '', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(uploadData),
    })
    // console.log({'status': 'fetching', id, queue})

    if (type == 'csv'){
      var parsed = d3.csvParse(await res.text())
    } else if (type == 'npy'){
      var parsed = npyjs.parse(await(res).arrayBuffer())
    } else if (type == 'json'){
      var parsed = await res.json()
    } else{
      throw 'unknown type'
    }

    data[slug] = parsed

    finishFn()
    return parsed
  }

  return {
    getFile,
  }
})()

var str = `
@   @        @  @          @   @   @          @     @
@   @        @  @          @  @ @  @          @     @
@   @   @@   @  @   @@      @ @ @ @   @@   @@ @   @@@
@@@@@  @  @  @  @  @  @     @ @ @ @  @  @  @  @  @  @
@   @  @@@@  @  @  @  @     @ @ @ @  @  @  @  @  @  @
@   @  @     @  @  @  @     @ @ @ @  @  @  @  @  @  @
@   @   @@@  @  @   @@       @   @    @@   @  @   @@@
`.trim()

async function main(){
  var helloData = await util.getFile('hello.npy')
  var particles = await util.getFile('particles.npy', {str})
  // console.log(particles)

  var size = 800

  var scene = new THREE.Scene()
  var camera = new THREE.PerspectiveCamera(45, size / size, 1, 23500)

  camera.position.x = -300
  camera.position.y = -100
  camera.position.z = 1050
  camera.zoom = 1
  camera.updateProjectionMatrix()

  var renderer = new THREE.WebGLRenderer()

  var chartNode = d3.select('.chart').html('')
    .st({width: size, height: size})
    .node()
  renderer.setSize(size, size)
  chartNode.appendChild(renderer.domElement)

  new THREE.OrbitControls(camera, renderer.domElement)
  d3.timer(() => renderer.render(scene, camera))

  var positions = []
  var colors = []

  for (var i = 0; i < particles.shape[0]; i++){
    positions.push(particles.data[i*3 + 0], particles.data[i*3 + 1], particles.data[i*3 + 2])
    colors.push(255, 255, 255)
  }

  console.log(positions, particles.shape)

  var geometry = new THREE.BufferGeometry()
  geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3))
  geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3))

  var material = new THREE.PointsMaterial({
    size: 1,
    vertexColors: THREE.VertexColors
  })

  scene.add(new THREE.Points(geometry, material))

}
main()

// TODO: auto add clientside code from 1wheel/hot-server
function initReloadInit(){
  if (window.__isInitReload) return
  window.__isInitReload = true

  new WebSocket('wss://hot-server-test-domain:3989').onmessage = msg => {
    var {path, type, str} = JSON.parse(msg.data)

    if (type == 'reload'){
      location.reload()
    } else if (type == 'jsInject'){
      console.clear() // enable with --consoleclear
      // Function is faster than eval but adds two extra lines at start of file
      Function(str)()
      if (window.__onHotServer) window.__onHotServer({path, type, str})
    } else if (type == 'cssInject') {
      Array.from(document.querySelectorAll('link'))
        .filter(d => d.href.includes(path.split('/').slice(-1)[0]))
        .forEach(d => d.href = d.href.split('?')[0] + '?' + Math.random())
    }
  }
}
if (!window.__isInitReload) initReloadInit()

<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var jobSchema = new Schema({
    movie: {type:  Schema.Types.ObjectId, ref: 'Movie'},
    theater: {type:  Schema.Types.ObjectId, ref: 'Theater'},
    time_start: Date,
    time_end: Date,
    active: Boolean,
    created_at: Date,
    updated_at: Date
});

// on every save, add the date
jobSchema.pre('save', function(next) {
  // get the current date
  var currentDate = new Date();

  // change the updated_at field to current date
  this.updated_at = currentDate;

  // if created_at doesn't exist, add to that field
  if (!this.created_at)
    this.created_at = currentDate;

  next();
});
// the schema is useless so far
// we need to create a model using it
var Job = mongoose.model('Job', jobSchema);

// make this available to our Jobs in our Node applications
module.exports = Job;<commit_msg>New attribute so users can choose their preferred movie format<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var jobSchema = new Schema({
    movie: {type:  Schema.Types.ObjectId, ref: 'Movie'},
    theater: {type:  Schema.Types.ObjectId, ref: 'Theater'},
    format: String,
    time_start: Date,
    time_end: Date,
    active: Boolean,
    created_at: Date,
    updated_at: Date
});

// on every save, add the date
jobSchema.pre('save', function(next) {
  // get the current date
  var currentDate = new Date();

  // change the updated_at field to current date
  this.updated_at = currentDate;

  // if created_at doesn't exist, add to that field
  if (!this.created_at)
    this.created_at = currentDate;

  next();
});
// the schema is useless so far
// we need to create a model using it
var Job = mongoose.model('Job', jobSchema);

// make this available to our Jobs in our Node applications
module.exports = Job;<|endoftext|>


<commit_before>var found = [];
var words = [];

function find_words() {
    var letters = "dog";
    var reg = new RegExp("^(?!.*?(.).*?\1)["+letters+"]*["+letters+"]*$");

    found = [];
    for ( var i in words ) {
      w = words[i];

      contains = w.match(reg);

      if ( contains ) {
        found.push(w);
      }
    }

  found.sort(function(a, b){
    return b.length - a.length; // ASC -> a - b; DESC -> b - a
  });

  for ( var i in found ) {
	for ( var j in letters ) {
		var num_letters = letters.split(letters[j]).length -1;
		var num_of_occurences = found[i].split(letters[j]).length-1;
		if ( num_of_occurences > num_letters ) {
			found[i] = '';
		}
	}
  }

  console.log(found);
}

var client = new XMLHttpRequest();

client.open('GET', 'word-list-en.txt');

client.onreadystatechange = function() {

  	if ( client.readyState==4 && client.status==200 ) {
	  	file = client.responseText;
		words = file.split(/\n\r|\n/);

		find_words();
	}
}

client.send();

<commit_msg>try some stuff<commit_after>var found = [];
var words = [];

function find_words() {
    var letters = "dog";
    var reg = new RegExp("^(?!.*?(.).*?\1)["+letters+"]*["+letters+"]*$");

    found = [];
    for ( var i in words ) {
      w = words[i];

      contains = w.match(reg);

      if ( contains ) {
        found.push(w);
      }
    }

  for ( var i in found ) {
	for ( var j in letters ) {
		var num_letters = letters.split(letters[j]).length -1;
		var num_of_occurences = found[i].split(letters[j]).length-1;
		if ( num_of_occurences > num_letters ) {
			found[i] = '';
		}
	}
  }

  found.sort(function(a, b){
    return b.length - a.length; // ASC -> a - b; DESC -> b - a
  });
}

var client = new XMLHttpRequest();

client.open('GET', 'word-list-en.txt');

client.onreadystatechange = function() {

  	if ( client.readyState==4 && client.status==200 ) {
	  	file = client.responseText;
		words = file.split(/\n\r|\n/);

		find_words();
	}
}

client.send();

<|endoftext|>


<commit_before>// Preload images and randomly rotate
const newSlide = () => {

	const literalNumbers = ['one', 'two', 'three', 'four', 'five', 'six']

	// Hero Image
	const hero = getElementByClassName('hero-slide')
	hero.classList.add('fade')

	// Slide in Hero Text
	setTimeout(() => {
		for (let i = 0; i < 3; i++) {
			const title = getElementByClassName('hero-title ' + literalNumbers[i])
			title.classList.add('fade-slide')
		}
	}, 500)

	// Slide in Hero Button
	setTimeout(() => {
		const heroButton = getElementByClassName('hero-button')
		heroButton.classList.add('fade-slide')
	}, 800)

	// Slide in Hero Arrows
	setTimeout(() => {
		const heroArrows = getElementByClassName('hero-arrows')
		heroArrows.classList.add('fade-slide')
	}, 1100)

}

// Begin
if (window.location.pathname === '/') {

	newSlide()

	// Add event listener to cycle through all hero messages on arrow click
	const rightArrow = getElementByClassName('hero-arrow right')
	rightArrow.addEventListener('click', () => {
		console.log('clicked')
		const tabs = getElementByClassName('hero-slider')
		for (let i = 0; i < tabs.length; i++) {
			console.log(tabs[i])
			if (tabs[i].classList.contains('w-tab-pane w--tab-active')) {
				console.log(i)
				// Remove active tab
				tabs[i].classList.remove('w--tab-active')
				// Add active status to next tab
				if (i === tabs.length - 1) {
					tabs[0].addClass('w--tab-active')
				}
				else {
					tabs[i + 1].addClass('w--tab-active')
				}
				break
			}
		}
	})

}<commit_msg>Hero.<commit_after>// Preload images and randomly rotate
const newSlide = () => {

	const literalNumbers = ['one', 'two', 'three', 'four', 'five', 'six']

	// Hero Image
	const hero = getElementByClassName('hero-slide')
	hero.classList.add('fade')

	// Slide in Hero Text
	setTimeout(() => {
		for (let i = 0; i < 3; i++) {
			const title = getElementByClassName('hero-title ' + literalNumbers[i])
			title.classList.add('fade-slide')
		}
	}, 500)

	// Slide in Hero Button
	setTimeout(() => {
		const heroButton = getElementByClassName('hero-button')
		heroButton.classList.add('fade-slide')
	}, 800)

	// Slide in Hero Arrows
	setTimeout(() => {
		const heroArrows = getElementByClassName('hero-arrows')
		heroArrows.classList.add('fade-slide')
	}, 1100)

}

// Begin
if (window.location.pathname === '/') {

	newSlide()

	// Add event listener to cycle through all hero messages on arrow click
	const rightArrow = getElementByClassName('hero-arrow right')
	console.log(rightArrow)
	rightArrow.addEventListener('click', () => {
		console.log('clicked')
		const tabs = getElementByClassName('hero-slider')
		for (let i = 0; i < tabs.length; i++) {
			console.log(tabs[i])
			if (tabs[i].classList.contains('w-tab-pane w--tab-active')) {
				console.log(i)
				// Remove active tab
				tabs[i].classList.remove('w--tab-active')
				// Add active status to next tab
				if (i === tabs.length - 1) {
					tabs[0].addClass('w--tab-active')
				}
				else {
					tabs[i + 1].addClass('w--tab-active')
				}
				break
			}
		}
	})

}<|endoftext|>


<commit_before>async function helpCommand (Bot, msg, args) {
  const filteredCommands = [];
  for (const command in Bot.commands) {
    if (!Bot.commands[command].ownerOnly) {
      filteredCommands.push(command);
    }
  }

  const prefix = await Bot.db.getPrefix(msg.channel.guild.id);

  if (!args[0]) {
    const content = `To set a reminder, simply send \`${prefix}remindme\` and follow the instructions.\n` +
      `Alternatively, you can also send \`${prefix}remindme time_argument "message"\`, ` +
      `e.g. \`${prefix}remindme 31 December 2017 "New Years"\`.\n` +
      `My current prefix is \`${prefix}\`, but you can also mention me.\nHere's a list of my commands:`;

    return {
      content,
      embed: {
        description: filteredCommands.join(', ')
      }
    };
  } else {
    const command = Bot.commands[args[0]] || Bot.commands[Object.keys(Bot.commands).find(c => Bot.commands[c].aliases.includes(args[0]))];

    if (!command || command.ownerOnly) {
      return; // TODO: decide whether this should be a silent exit or not
    }

    return {
      embed: {
        title: `Help for command: ${command.name}`,
        fields: [
          { 'name': 'Description: ', 'value': command.description },
          { 'name': 'Usage: ', 'value': `${'```'}\n${command.usage.replace('{command}', prefix + command.name)}${'```'}` },
          { 'name': 'Aliases: ', 'value': command.aliases[0] ? command.aliases.join(', ') : 'None' }
        ]
      }
    };
  }
}

module.exports = {
  call: helpCommand,
  name: 'help',
  usage: '{command} [command]',
  description: 'Returns extra documentation for a specific command (or a list of all commands).'
};<commit_msg>update to use new format<commit_after>async function helpCommand (msg, args) {
  const filteredCommands = [];
  for (const command in this.commands) {
    if (!this.commands[command].ownerOnly) {
      filteredCommands.push(command);
    }
  }

  const prefix = await this.db.getPrefix(msg.channel.guild.id);

  if (!args[0]) {
    const content = `To set a reminder, simply send \`${prefix}remindme\` and follow the instructions.\n` +
      `Alternatively, you can also send \`${prefix}remindme time_argument "message"\`, ` +
      `e.g. \`${prefix}remindme 31 December 2017 "New Years"\`.\n` +
      `My current prefix is \`${prefix}\`, but you can also mention me.\nHere's a list of my commands:`;

    return {
      content,
      embed: {
        description: filteredCommands.join(', ')
      }
    };
  } else {
    const command = this.commands[args[0]] || this.commands[Object.keys(this.commands).find(c => this.commands[c].aliases.includes(args[0]))];

    if (!command || command.ownerOnly) {
      return; // TODO: decide whether this should be a silent exit or not
    }

    return {
      embed: {
        title: `Help for command: ${command.name}`,
        fields: [
          { 'name': 'Description: ', 'value': command.description },
          { 'name': 'Usage: ', 'value': `${'```'}\n${command.usage.replace('{command}', prefix + command.name)}${'```'}` },
          { 'name': 'Aliases: ', 'value': command.aliases[0] ? command.aliases.join(', ') : 'None' }
        ]
      }
    };
  }
}

module.exports = {
  call: helpCommand,
  name: 'help',
  usage: '{command} [command]',
  description: 'Returns extra documentation for a specific command (or a list of all commands).'
};<|endoftext|>


<commit_before>/** @jsx React.DOM */
/** @jsx React.DOM */
'use strict';
var React = require('react');
var _ = require('underscore');
var globals = require('./globals');
var dbxref = require('./dbxref');
var dataset = require('./dataset');
var statuslabel = require('./statuslabel');

var DbxrefList = dbxref.DbxrefList;
var FileTable = dataset.FileTable;
var StatusLabel = statuslabel.StatusLabel;

var Panel = function (props) {
    // XXX not all panels have the same markup
    var context;
    if (props['@id']) {
        context = props;
        props = {context: context};
    }
    return globals.panel_views.lookup(props.context)(props);
};

var Experiment = module.exports.Experiment = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'view-item');
        var replicates = _.sortBy(context.replicates, function(item) {
            return item.biological_replicate_number;
        });
        var aliasList = context.aliases.join(", ");

        var documents = {};
        replicates.forEach(function (replicate) {
            if (!replicate.library) return;
            replicate.library.documents.forEach(function (doc) {
                documents[doc['@id']] = Panel({context: doc});
            });
        });

        // Process biosamples for summary display
        var biosamples = [], lifeAge = [], organismName = [];
        replicates.forEach(function (replicate) {
            var biosample = replicate.library && replicate.library.biosample;
            if (biosample) {
                biosamples.push(biosample);

                // Add to array of scientific names for rare experiments with cross-species biosamples
                organismName.push(biosample.organism.scientific_name);

                // Build a string with non-'unknown' life_stage, age, and age_units concatenated
                var lifeAgeString = (biosample.life_stage && biosample.life_stage != 'unknown') ? biosample.life_stage : '';
                if (biosample.age && biosample.age != 'unknown') {
                    lifeAgeString += (lifeAgeString ? ' ' : '') + biosample.age;
                    lifeAgeString += (biosample.age_units && biosample.age_units != 'unknown') ? ' ' + biosample.age_units : '';
                }
                if (lifeAgeString) {
                    lifeAge.push(lifeAgeString);
                }
            }
        });

        // Eliminate duplicates in lifeAge and organismName arrays so each displayed only once
        if (lifeAge.length) {
            lifeAge = _.uniq(lifeAge);
        }
        if (organismName.length) {
            organismName = _.uniq(organismName);
        }

        // Build the text of the Treatment string
        var treatmentText = [];
        biosamples.map(function(biosample) {
            treatmentText = treatmentText.concat(biosample.treatments.map(function(treatment) {
                var singleTreatment = '';
                if (treatment.concentration) {
                    singleTreatment += treatment.concentration + (treatment.concentration_units ? ' ' + treatment.concentration_units : '') + ' ';
                }
                singleTreatment += treatment.treatment_term_name + (treatment.treatment_term_id ? ' (' + treatment.treatment_term_id + ')' : '') + ' ';
                if (treatment.duration) {
                    singleTreatment += 'for ' + treatment.duration + ' ' + (treatment.duration_units ? treatment.duration_units : '');
                }
                return singleTreatment;
            }));
        });
        if (treatmentText) {
            treatmentText = _.uniq(treatmentText);
        }

        // Adding experiment specific documents
        context.documents.forEach(function (document) {
            documents[document['@id']] = Panel({context: document});
        });
        var antibodies = {};
        replicates.forEach(function (replicate) {
            if (replicate.antibody) {
                antibodies[replicate.antibody['@id']] = replicate.antibody;
            }
        });
        var antibody_accessions = [];
        for (var key in antibodies) {
            antibody_accessions.push(antibodies[key].accession);
        }

        // Determine this experiment's ENCODE version
        var encodevers = "";
        if (context.award.rfa) {
            encodevers = globals.encodeVersionMap[context.award.rfa.substring(0,7)];
            if (typeof encodevers === "undefined") {
                encodevers = "";
            }
        }

        // Make list of statuses
        var statuses = [{status: context.status, title: "Status"}];
        if (encodevers === "3" && context.status === "released") {
            statuses.push({status: "pending", title: "Validation"});
        }

        // Make string of alternate accessions
        var altacc = context.alternate_accessions ? context.alternate_accessions.join(', ') : undefined;

        // XXX This makes no sense.
        //var control = context.possible_controls[0];
        return (

Experiment

{context.assay_term_name}

                            Experiment summary for {context.accession}

                        {altacc ?
Replaces {altacc}
 : null}

                            <StatusLabel status={statuses} />

Assay

{context.assay_term_name}

Accession

{context.accession}

                        {biosamples.length || context.biosample_term_name ?
Biosample summary
 : null}
                        {biosamples.length || context.biosample_term_name ?

                                {context.biosample_term_name ? {context.biosample_term_name + ' '} : null}
                                {organismName.length || lifeAge.length ? '(' : null}
                                {organismName.length ?

                                        {organismName.map(function(name, i) {
                                            if (i === 0) {
                                                return ({name});
                                            } else {
                                                return ({' and '}{name});
                                            }
                                        })}

                                : null}
                                {lifeAge.length ? ', ' + lifeAge.join(' and ') : ''}
                                {organismName.length || lifeAge.length ? ')' : null}

                        : null}

                        {context.biosample_type ?
Type
 : null}
                        {context.biosample_type ?
{context.biosample_type}
 : null}

                        {treatmentText.length ?
Treatment
 : null}
                        {treatmentText.length ?

                                    {treatmentText.map(function (treatment) {
                                        return (
{treatment}
);
                                    })}

                        : null}

                        {context.target ?
Target
 : null}
                        {context.target ?
{context.target.label}
 : null}

                        {antibody_accessions.length ?
Antibody
 : null}
                        {antibody_accessions.length ?
{antibody_accessions.join(', ')}
 : null}

                        {context.possible_controls.length ?
Controls
 : null}
                        {context.possible_controls.length ?

                                    {context.possible_controls.map(function (control) {
                                        return (

                                                    {control.accession}

                                        );
                                    })}

                        : null}

                        {context.description ?
Description
 : null}
                        {context.description ?
{context.description}
 : null}

Lab

{context.lab.title}

Project

{context.award.project}

                        {context.dbxrefs.length ?
External resources
 : null}
                        {context.dbxrefs.length ?
<DbxrefList values={context.dbxrefs} />
 : null}

                        {context.aliases.length ?
Aliases
 : null}
                        {context.aliases.length ?
{aliasList}
 : null}

                        {context.references.length ?
References
 : null}
                        {context.references.length ?
<DbxrefList values={context.references} className="horizontal-list"/>
 : null}

                        {context.date_released ?
Date released
 : null}
                        {context.date_released ?
{context.date_released}
 : null}

                <AssayDetails replicates={replicates} />

                {Object.keys(documents).length ?

Protocols

                        {documents}

                : null}

                {replicates.map(function (replicate, index) {
                    return (
                        <Replicate replicate={replicate} key={index} />
                    );
                })}

                {context.visualize_ucsc  && context.status == "released" ?

                        Visualize Data

                : null }

                {context.files.length ?

Files linked to {context.accession}

                        <FileTable items={context.files} encodevers={encodevers} />

                : null }

        );
    }
});

globals.content_views.register(Experiment, 'experiment');

var AssayDetails = module.exports.AssayDetails = function (props) {
    var replicates = props.replicates.sort(function(a, b) {
        if (b.biological_replicate_number === a.biological_replicate_number) {
            return a.technical_replicate_number - b.technical_replicate_number;
        }
        return a.biological_replicate_number - b.biological_replicate_number;
    });

    if (!replicates.length) return (

);

    var replicate = replicates[0];
    var library = replicate.library;
    var platform = replicate.platform;
    var depletedIn;
    var treatments;

    if (library && library.depleted_in_term_name && library.depleted_in_term_name.length) {
        depletedIn = library.depleted_in_term_name.join(", ");
    }

    if (library && library.treatments && library.treatments.length) {
        var i = library.treatments.length;
        var t;
        var treatmentList = [];
        while (i--) {
            t = library.treatments[i];
            treatmentList.push(t.treatment_term_name);
        }
        treatments = treatmentList.join(", ");
    }

    if (!library && !depletedIn && !treatments && !platform) {
        return (

);
    }

    return (

Assay details

                {library && library.nucleic_acid_term_name ?
Nucleic acid type
 : null}
				{library && library.nucleic_acid_term_name ?
{library.nucleic_acid_term_name}
 : null}

                {depletedIn ?
Depleted in
 : null}
				{depletedIn ?
{depletedIn}
 : null}

                {library && library.lysis_method ?
Lysis method
 : null}
				{library && library.lysis_method ?
{library.lysis_method}
 : null}

                {library && library.extraction_method ?
Extraction method
 : null}
				{library && library.extraction_method ?
{library.extraction_method}
 : null}

                {library && library.fragmentation_method ?
Fragmentation method
 : null}
				{library && library.fragmentation_method ?
{library.fragmentation_method}
 : null}

                {library && library.size_range ?
Size range
 : null}
				{library && library.size_range ?
{library.size_range}
 : null}

                {library && library.library_size_selection_method ?
Size selection method
 : null}
				{library && library.library_size_selection_method ?
{library.library_size_selection_method}
 : null}

                {treatments ?
Treatments
 : null}
				{treatments ?
{treatments}
 : null}

                {platform ?
Platform
 : null}
				{platform ?
{platform.title}
 : null}

    );
};

var Replicate = module.exports.Replicate = function (props) {
    var replicate = props.replicate;
    var concentration = replicate.rbns_protein_concentration;
    var library = replicate.library;
    var biosample = library && library.biosample;
    var paired_end = replicate.paired_ended;
    return (

Biological replicate - {replicate.biological_replicate_number}

Technical replicate

{replicate.technical_replicate_number}

                {concentration ?
Protein concentration
 : null}
                {concentration ?
{concentration}{replicate.rbns_protein_concentration_units}
 : null}

                {library ?
Library
 : null}
                {library ?
{library.accession}
 : null}

                {library && library.nucleic_acid_starting_quantity ?
Library starting quantity
 : null}
                {library && library.nucleic_acid_starting_quantity ?

{library.nucleic_acid_starting_quantity}{library.nucleic_acid_starting_quantity_units}

                : null}

                {biosample ?
Biosample
 : null}
                {biosample ?

                        {biosample.accession}
                    {' '}-{' '}{biosample.biosample_term_name}

 : null}

                {replicate.read_length ?
Run type
 : null}
                {replicate.read_length ?
{paired_end ? 'paired-end' : 'single-end'}
 : null}

                {replicate.read_length ?
Read length
 : null}
                {replicate.read_length ?
{replicate.read_length}{replicate.read_length_units}
 : null}

    );
};

// Can't be a proper panel as the control must be passed in.
//globals.panel_views.register(Replicate, 'replicate');
<commit_msg>Don’t build accession array; just show antibodies<commit_after>/** @jsx React.DOM */
/** @jsx React.DOM */
'use strict';
var React = require('react');
var _ = require('underscore');
var globals = require('./globals');
var dbxref = require('./dbxref');
var dataset = require('./dataset');
var statuslabel = require('./statuslabel');

var DbxrefList = dbxref.DbxrefList;
var FileTable = dataset.FileTable;
var StatusLabel = statuslabel.StatusLabel;

var Panel = function (props) {
    // XXX not all panels have the same markup
    var context;
    if (props['@id']) {
        context = props;
        props = {context: context};
    }
    return globals.panel_views.lookup(props.context)(props);
};

var Experiment = module.exports.Experiment = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'view-item');
        var replicates = _.sortBy(context.replicates, function(item) {
            return item.biological_replicate_number;
        });
        var aliasList = context.aliases.join(", ");

        var documents = {};
        replicates.forEach(function (replicate) {
            if (!replicate.library) return;
            replicate.library.documents.forEach(function (doc) {
                documents[doc['@id']] = Panel({context: doc});
            });
        });

        // Process biosamples for summary display
        var biosamples = [], lifeAge = [], organismName = [];
        replicates.forEach(function (replicate) {
            var biosample = replicate.library && replicate.library.biosample;
            if (biosample) {
                biosamples.push(biosample);

                // Add to array of scientific names for rare experiments with cross-species biosamples
                organismName.push(biosample.organism.scientific_name);

                // Build a string with non-'unknown' life_stage, age, and age_units concatenated
                var lifeAgeString = (biosample.life_stage && biosample.life_stage != 'unknown') ? biosample.life_stage : '';
                if (biosample.age && biosample.age != 'unknown') {
                    lifeAgeString += (lifeAgeString ? ' ' : '') + biosample.age;
                    lifeAgeString += (biosample.age_units && biosample.age_units != 'unknown') ? ' ' + biosample.age_units : '';
                }
                if (lifeAgeString) {
                    lifeAge.push(lifeAgeString);
                }
            }
        });

        // Eliminate duplicates in lifeAge and organismName arrays so each displayed only once
        if (lifeAge.length) {
            lifeAge = _.uniq(lifeAge);
        }
        if (organismName.length) {
            organismName = _.uniq(organismName);
        }

        // Build the text of the Treatment string
        var treatmentText = [];
        biosamples.map(function(biosample) {
            treatmentText = treatmentText.concat(biosample.treatments.map(function(treatment) {
                var singleTreatment = '';
                if (treatment.concentration) {
                    singleTreatment += treatment.concentration + (treatment.concentration_units ? ' ' + treatment.concentration_units : '') + ' ';
                }
                singleTreatment += treatment.treatment_term_name + (treatment.treatment_term_id ? ' (' + treatment.treatment_term_id + ')' : '') + ' ';
                if (treatment.duration) {
                    singleTreatment += 'for ' + treatment.duration + ' ' + (treatment.duration_units ? treatment.duration_units : '');
                }
                return singleTreatment;
            }));
        });
        if (treatmentText) {
            treatmentText = _.uniq(treatmentText);
        }

        // Adding experiment specific documents
        context.documents.forEach(function (document) {
            documents[document['@id']] = Panel({context: document});
        });
        var antibodies = {};
        replicates.forEach(function (replicate) {
            if (replicate.antibody) {
                antibodies[replicate.antibody['@id']] = replicate.antibody;
            }
        });

        // Determine this experiment's ENCODE version
        var encodevers = "";
        if (context.award.rfa) {
            encodevers = globals.encodeVersionMap[context.award.rfa.substring(0,7)];
            if (typeof encodevers === "undefined") {
                encodevers = "";
            }
        }

        // Make list of statuses
        var statuses = [{status: context.status, title: "Status"}];
        if (encodevers === "3" && context.status === "released") {
            statuses.push({status: "pending", title: "Validation"});
        }

        // Make string of alternate accessions
        var altacc = context.alternate_accessions ? context.alternate_accessions.join(', ') : undefined;

        // XXX This makes no sense.
        //var control = context.possible_controls[0];
        return (

Experiment

{context.assay_term_name}

                            Experiment summary for {context.accession}

                        {altacc ?
Replaces {altacc}
 : null}

                            <StatusLabel status={statuses} />

Assay

{context.assay_term_name}

Accession

{context.accession}

                        {biosamples.length || context.biosample_term_name ?
Biosample summary
 : null}
                        {biosamples.length || context.biosample_term_name ?

                                {context.biosample_term_name ? {context.biosample_term_name + ' '} : null}
                                {organismName.length || lifeAge.length ? '(' : null}
                                {organismName.length ?

                                        {organismName.map(function(name, i) {
                                            if (i === 0) {
                                                return ({name});
                                            } else {
                                                return ({' and '}{name});
                                            }
                                        })}

                                : null}
                                {lifeAge.length ? ', ' + lifeAge.join(' and ') : ''}
                                {organismName.length || lifeAge.length ? ')' : null}

                        : null}

                        {context.biosample_type ?
Type
 : null}
                        {context.biosample_type ?
{context.biosample_type}
 : null}

                        {treatmentText.length ?
Treatment
 : null}
                        {treatmentText.length ?

                                    {treatmentText.map(function (treatment) {
                                        return (
{treatment}
);
                                    })}

                        : null}

                        {context.target ?
Target
 : null}
                        {context.target ?
{context.target.label}
 : null}

                        {Object.keys(antibodies).length ?

Antibody

{Object.keys(antibodies).map(function(antibody, i) {
                                    return ({i !== 0 ? ', ' : ''}{antibodies[antibody].accession});
                                })}

                        : null}

                        {context.possible_controls.length ?
Controls
 : null}
                        {context.possible_controls.length ?

                                    {context.possible_controls.map(function (control) {
                                        return (

                                                    {control.accession}

                                        );
                                    })}

                        : null}

                        {context.description ?
Description
 : null}
                        {context.description ?
{context.description}
 : null}

Lab

{context.lab.title}

Project

{context.award.project}

                        {context.dbxrefs.length ?
External resources
 : null}
                        {context.dbxrefs.length ?
<DbxrefList values={context.dbxrefs} />
 : null}

                        {context.aliases.length ?
Aliases
 : null}
                        {context.aliases.length ?
{aliasList}
 : null}

                        {context.references.length ?
References
 : null}
                        {context.references.length ?
<DbxrefList values={context.references} className="horizontal-list"/>
 : null}

                        {context.date_released ?
Date released
 : null}
                        {context.date_released ?
{context.date_released}
 : null}

                <AssayDetails replicates={replicates} />

                {Object.keys(documents).length ?

Protocols

                        {documents}

                : null}

                {replicates.map(function (replicate, index) {
                    return (
                        <Replicate replicate={replicate} key={index} />
                    );
                })}

                {context.visualize_ucsc  && context.status == "released" ?

                        Visualize Data

                : null }

                {context.files.length ?

Files linked to {context.accession}

                        <FileTable items={context.files} encodevers={encodevers} />

                : null }

        );
    }
});

globals.content_views.register(Experiment, 'experiment');

var AssayDetails = module.exports.AssayDetails = function (props) {
    var replicates = props.replicates.sort(function(a, b) {
        if (b.biological_replicate_number === a.biological_replicate_number) {
            return a.technical_replicate_number - b.technical_replicate_number;
        }
        return a.biological_replicate_number - b.biological_replicate_number;
    });

    if (!replicates.length) return (

);

    var replicate = replicates[0];
    var library = replicate.library;
    var platform = replicate.platform;
    var depletedIn;
    var treatments;

    if (library && library.depleted_in_term_name && library.depleted_in_term_name.length) {
        depletedIn = library.depleted_in_term_name.join(", ");
    }

    if (library && library.treatments && library.treatments.length) {
        var i = library.treatments.length;
        var t;
        var treatmentList = [];
        while (i--) {
            t = library.treatments[i];
            treatmentList.push(t.treatment_term_name);
        }
        treatments = treatmentList.join(", ");
    }

    if (!library && !depletedIn && !treatments && !platform) {
        return (

);
    }

    return (

Assay details

                {library && library.nucleic_acid_term_name ?
Nucleic acid type
 : null}
				{library && library.nucleic_acid_term_name ?
{library.nucleic_acid_term_name}
 : null}

                {depletedIn ?
Depleted in
 : null}
				{depletedIn ?
{depletedIn}
 : null}

                {library && library.lysis_method ?
Lysis method
 : null}
				{library && library.lysis_method ?
{library.lysis_method}
 : null}

                {library && library.extraction_method ?
Extraction method
 : null}
				{library && library.extraction_method ?
{library.extraction_method}
 : null}

                {library && library.fragmentation_method ?
Fragmentation method
 : null}
				{library && library.fragmentation_method ?
{library.fragmentation_method}
 : null}

                {library && library.size_range ?
Size range
 : null}
				{library && library.size_range ?
{library.size_range}
 : null}

                {library && library.library_size_selection_method ?
Size selection method
 : null}
				{library && library.library_size_selection_method ?
{library.library_size_selection_method}
 : null}

                {treatments ?
Treatments
 : null}
				{treatments ?
{treatments}
 : null}

                {platform ?
Platform
 : null}
				{platform ?
{platform.title}
 : null}

    );
};

var Replicate = module.exports.Replicate = function (props) {
    var replicate = props.replicate;
    var concentration = replicate.rbns_protein_concentration;
    var library = replicate.library;
    var biosample = library && library.biosample;
    var paired_end = replicate.paired_ended;
    return (

Biological replicate - {replicate.biological_replicate_number}

Technical replicate

{replicate.technical_replicate_number}

                {concentration ?
Protein concentration
 : null}
                {concentration ?
{concentration}{replicate.rbns_protein_concentration_units}
 : null}

                {library ?
Library
 : null}
                {library ?
{library.accession}
 : null}

                {library && library.nucleic_acid_starting_quantity ?
Library starting quantity
 : null}
                {library && library.nucleic_acid_starting_quantity ?

{library.nucleic_acid_starting_quantity}{library.nucleic_acid_starting_quantity_units}

                : null}

                {biosample ?
Biosample
 : null}
                {biosample ?

                        {biosample.accession}
                    {' '}-{' '}{biosample.biosample_term_name}

 : null}

                {replicate.read_length ?
Run type
 : null}
                {replicate.read_length ?
{paired_end ? 'paired-end' : 'single-end'}
 : null}

                {replicate.read_length ?
Read length
 : null}
                {replicate.read_length ?
{replicate.read_length}{replicate.read_length_units}
 : null}

    );
};

// Can't be a proper panel as the control must be passed in.
//globals.panel_views.register(Replicate, 'replicate');
<|endoftext|>