text:
$(function() {
  var ACE_FILES_PATH = '/assets/ace/';
  var ADEQUATE_PERCENTAGE = 50;
  var ALT_1_KEY_CODE = 161;
  var ALT_2_KEY_CODE = 8220;
  var ALT_3_KEY_CODE = 182;
  var ALT_4_KEY_CODE = 162;
  var ALT_R_KEY_CODE = 174;
  var ALT_S_KEY_CODE = 8218;
  var ALT_T_KEY_CODE = 8224;
  var FILENAME_URL_PLACEHOLDER = '{filename}';
  var SUCCESSFULL_PERCENTAGE = 90;
  var THEME = 'ace/theme/textmate';

  var editors = [];
  var active_file = undefined;
  var active_frame = undefined;
  var running = false;
  var qa_api = undefined;
  var output_mode_is_streaming = true;

  var flowrResultHtml = '

'

  var ajax = function(options) {
    return $.ajax(_.extend({
      dataType: 'json',
      method: 'POST',
    }, options));
  };

  var ajaxError = function(response) {
    var message = ((response || {}).responseJSON || {}).message || '';

    $.flash.danger({
      text: message.length > 0 ? message : $('#flash').data('message-failure')
    });
  };

  var clearOutput = function() {
    $('#output pre').remove();
  };

  var closeEventSource = function(event) {
    event.target.close();
    hideSpinner();
    running = false;
    toggleButtonStates();

    if (event.type === 'error' || JSON.parse(event.data).code !== 200) {
      ajaxError();
      showTab(1);
    }
  };

  var collectFiles = function() {
    var editable_editors = _.filter(editors, function(editor) {
      return !editor.getReadOnly();
    });
    return _.map(editable_editors, function(editor) {
      return {
        content: editor.getValue(),
        file_id: $(editor.container).data('file-id')
      };
    });
  };

  var configureEditors = function() {
    _.each(['modePath', 'themePath', 'workerPath'], function(attribute) {
      ace.config.set(attribute, ACE_FILES_PATH);
    });
  };

  var confirmDestroy = function(event) {
    event.preventDefault();
    if (confirm($(this).data('message-confirm'))) {
      destroyFile();
    }
  };

  var confirmReset = function(event) {
    event.preventDefault();
    if (confirm($(this).data('message-confirm'))) {
      resetCode();
    }
  };

  var confirmSubmission = function(event) {
    event.preventDefault();
    if (confirm($(this).data('message-confirm'))) {
      submitCode();
    }
  };

  var createSubmission = function(initiator, filter, callback) {
    showSpinner(initiator);

      var annotations = {};
      var annotations_arr = [];
      var file_ids = [];

      $('.editor').each(function(index, element) {
          var file_id =  $(element).data('id');
          var editor = ace.edit(element);
          //annotations[file_id] = editor.getSession().getAnnotations();
          var cleaned_annotations = editor.getSession().getAnnotations();
          for(var i = cleaned_annotations.length-1; i>=0; --i){
              cleaned_annotations[i].text = cleaned_annotations[i].text.replace(cleaned_annotations[i].username + ": ", "");
          }
          annotations_arr = annotations_arr.concat(editor.getSession().getAnnotations());
      });

    var jqxhr = ajax({
      data: {
        submission: {
          cause: $(initiator).data('cause') || $(initiator).prop('id'),
          exercise_id: $('#editor').data('exercise-id'),
          files_attributes: (filter || _.identity)(collectFiles())
        },
        source_submission_id: $('.ace_editor',$('#editor'))[0].dataset.id,
        //annotations: annotations,
        annotations_arr: annotations_arr
      },
      dataType: 'json',
      method: 'POST',
      url: $(initiator).data('url') || $('#editor').data('submissions-url')
    });
    jqxhr.always(hideSpinner);
    jqxhr.done(createSubmissionCallback);
    jqxhr.done(callback);
    jqxhr.fail(ajaxError);
  };

    var createSubmissionCallback = function(data){
      var id =  $('.editor').data('id');
    };

  var destroyFile = function() {
    createSubmission($('#destroy-file'), function(files) {
      return _.reject(files, function(file) {
        return file.file_id === active_file.id;
      });
    }, window.CodeOcean.refresh);
  };

  var downloadCode = function(event) {
    event.preventDefault();
    createSubmission(this, null,function(response) {
      var url = response.download_url.replace(FILENAME_URL_PLACEHOLDER, active_file.filename);
      window.location = url;
    });
  };

  var evaluateCode = function(url, streamed, callback) {
    (streamed ? evaluateCodeWithStreamedResponse : evaluateCodeWithoutStreamedResponse)(url, callback);
  };

  var evaluateCodeWithStreamedResponse = function(url, callback) {
    var event_source = new EventSource(url);

    event_source.addEventListener('close', closeEventSource);
    event_source.addEventListener('error', closeEventSource);
    event_source.addEventListener('hint', renderHint);
    event_source.addEventListener('info', storeContainerInformation);
    event_source.addEventListener('output', callback);
    event_source.addEventListener('start', callback);

    if ($('#flowrHint').isPresent()) {
      event_source.addEventListener('output', handleStderrOutputForFlowr);
      event_source.addEventListener('close', handleStderrOutputForFlowr);
    }

    if (qa_api) {
      event_source.addEventListener('close', handleStreamedResponseForCodePilot);
    }

    event_source.addEventListener('status', function(event) {
      showStatus(JSON.parse(event.data));
    });
  };

  var handleStreamedResponseForCodePilot = function(event) {
      qa_api.executeCommand('syncOutput', [chunkBuffer]);
      chunkBuffer = [{streamedResponse: true}];
  }

  var evaluateCodeWithoutStreamedResponse = function(url, callback) {
    var jqxhr = ajax({
      method: 'GET',
      url: url
    });
    jqxhr.always(hideSpinner);
    jqxhr.done(callback);
    jqxhr.fail(ajaxError);
  };

  var fileActionsAvailable = function() {
    return isActiveFileRenderable() || isActiveFileRunnable() || isActiveFileStoppable() || isActiveFileTestable();
  };

  var findOrCreateOutputElement = function(index) {
    if ($('#output-' + index).isPresent()) {
      return $('#output-' + index);
    } else {
      var element = $('
').attr('id', 'output-' + index);
      $('#output').append(element);
      return element;
    }
  };

  var getPanelClass = function(result) {
    if (result.stderr && !result.score) {
      return 'panel-danger';
    } else if (result.score < 1) {
      return 'panel-warning';
    } else {
      return 'panel-success';
    }
  };

  var getProgressBarClass = function(percentage) {
    if (percentage < ADEQUATE_PERCENTAGE) {
      return 'progress-bar progress-bar-striped progress-bar-danger';
    } else if (percentage < SUCCESSFULL_PERCENTAGE) {
      return 'progress-bar progress-bar-striped progress-bar-warning';
    } else {
      return 'progress-bar progress-bar-striped progress-bar-success';
    }
  };

  var handleKeyPress = function(event) {
    if (event.which === ALT_1_KEY_CODE) {
      showTab(0);
    } else if (event.which === ALT_2_KEY_CODE) {
      showWorkspaceTab(event);
    } else if (event.which === ALT_3_KEY_CODE) {
      showTab(2);
    } else if (event.which === ALT_4_KEY_CODE) {
      showTab(3);
    } else if (event.which === ALT_R_KEY_CODE) {
      $('#run').trigger('click');
    } else if (event.which === ALT_S_KEY_CODE) {
      $('#assess').trigger('click');
    } else if (event.which === ALT_T_KEY_CODE) {
      $('#test').trigger('click');
    } else {
      return;
    }
    event.preventDefault();
  };

  var handleScoringResponse = function(response) {
    printScoringResults(response);
    var score = _.reduce(response, function(sum, result) {
      return sum + result.score * result.weight;
    }, 0).toFixed(2);
    $('#score').data('score', score);
    renderScore();
    showTab(3);
  };

  var stderrOutput = '';
  // activate flowr only for half of the audience
  var isFlowrEnabled = parseInt($('#editor').data('user-id'))%2 == 0;
  var handleStderrOutputForFlowr = function(event) {
  if (!isFlowrEnabled) return
    var json = JSON.parse(event.data);

    if (json.stderr) {
      stderrOutput += json.stderr;
    } else if (json.code) {
      if (stderrOutput == '') {
        return;
      }

      var flowrUrl = $('#flowrHint').data('url');
      var flowrHintBody = $('#flowrHint .panel-body');
      var queryParameters = {
        query: stderrOutput
      }

      flowrHintBody.empty();

      jQuery.getJSON(flowrUrl, queryParameters, function(data) {
        for (var question in data.queryResults) {
          var collapsibleTileHtml = flowrResultHtml.replace(/{{collapseId}}/g, 'collapse-' + question).replace(/{{headingId}}/g, 'heading-' + question);
          var resultTile = $(collapsibleTileHtml);

          resultTile.find('h4 > a').text(data.queryResults[question].title + ' | Found via ' + data.queryResults[question].source);
          resultTile.find('.panel-body').html(data.queryResults[question].body);
          resultTile.find('.panel-body').append('Open this question');

          flowrHintBody.append(resultTile);
        }

        if (data.queryResults.length !== 0) {
          $('#flowrHint').fadeIn();
        }
      })

      stderrOutput = '';
    }
  };

  var handleTestResponse = function(response) {
    clearOutput();
    printOutput(response[0], false, 0);
    if (qa_api) {
      qa_api.executeCommand('syncOutput', [response]);
    }
    showStatus(response[0]);
    showTab(2);
  };

  var hideSpinner = function() {
    $('button i.fa').show();
    $('button i.fa-spin').hide();
  };

  var initializeEditors = function() {
    $('.editor').each(function(index, element) {
      var editor = ace.edit(element);
      if (qa_api) {
        editor.getSession().on("change", function (deltaObject) {
          qa_api.executeCommand('syncEditor', [active_file, deltaObject]);
        });
      }

      var document = editor.getSession().getDocument();
      // insert pre-existing code into editor. we have to use insertLines, otherwise the deltas are not properly added
      var file_id = $(element).data('file-id');
      var content = $('.editor-content[data-file-id=' + file_id + ']');
      setActiveFile($(element).parent().data('filename'), file_id);

      document.insertLines(0, content.text().split(/\n/));
      editor.setReadOnly($(element).data('read-only') !== undefined);
      editor.setShowPrintMargin(false);
      editor.setTheme(THEME);
      editors.push(editor);
      var session = editor.getSession();
      session.setMode($(element).data('mode'));
      session.setTabSize($(element).data('indent-size'));
      session.setUseSoftTabs(true);
      session.setUseWrapMode(true);

      var file_id =  $(element).data('id');
      setAnnotations(editor, file_id);

      session.on('annotationRemoval', handleAnnotationRemoval);
      session.on('annotationChange', handleAnnotationChange);

      // TODO refactor here
      // Code for clicks on gutter / sidepanel
      editor.on("guttermousedown", function(e){
        var target  = e.domEvent.target;

        if (target.className.indexOf("ace_gutter-cell") == -1) return;
        if (!editor.isFocused()) return;
        if (e.clientX > 25 + target.getBoundingClientRect().left) return;

        var row = e.getDocumentPosition().row;
        e.stop();

        var commentModal = $('#comment-modal');

        if (hasCommentsInRow(editor, row)) {
          var rowComments = getCommentsForRow(editor, row);
          var comments = _.pluck(rowComments, 'text').join('\n');
          commentModal.find('#other-comments').text(comments);
        } else {
          commentModal.find('#other-comments').text('none');
        }

        commentModal.find('#addCommentButton').off('click');
        commentModal.find('#removeAllButton').off('click');

        commentModal.find('#addCommentButton').on('click', function(e){
          var user_id = $(element).data('user-id');
          var commenttext = commentModal.find('textarea').val();

          if (commenttext !== "") {
            createComment(user_id, file_id, row, editor, commenttext);
            commentModal.modal('hide');
          }
        })

        commentModal.find('#removeAllButton').on('click', function(e){
          var user_id = $(element).data('user-id');
          deleteComment(user_id,file_id,row,editor);
          commentModal.modal('hide');
        })

        commentModal.modal('show');
      });
    });
  };

  var hasCommentsInRow = function (editor, row){
    return editor.getSession().getAnnotations().some(function(element) {
      return element.row === row;
    })
  }

  var getCommentsForRow = function (editor, row){
    return editor.getSession().getAnnotations().filter(function(element) {
      return element.row === row;
    })
  }

  var setAnnotations = function (editor, file_id){
      var session = editor.getSession();
      var url = "/comments";

      var jqrequest = $.ajax({
          dataType: 'json',
          method: 'GET',
          url: url,
          data: {
            file_id: file_id
          }
      });

      jqrequest.done(function(response){
          setAnnotationsCallback(response, session);
      });
      jqrequest.fail(ajaxError);
  }

  var setAnnotationsCallback = function (response, session) {
      var annotations = response;

      $.each(annotations, function(index, comment){
          comment.className = "code-ocean_comment";
          comment.text = comment.username + ": " + comment.text;
        //  comment.text = comment.user_id + ": " + comment.text;
      });

      session.setAnnotations(annotations);
  }

  var deleteComment = function (user_id, file_id, row, editor) {
      var jqxhr = $.ajax({
          type: 'DELETE',
          url: "/comments",
          data: {
            row: row,
            file_id: file_id,
            user_id: user_id
          }
      });
      jqxhr.done(function (response) {
          setAnnotations(editor, file_id);
      });
      jqxhr.fail(ajaxError);
  }

  var createComment = function (user_id, file_id, row, editor, commenttext){
      var jqxhr = $.ajax({
        data: {
          comment: {
            user_id: user_id,
            file_id: file_id,
            row: row,
            column: 0,
            text: commenttext
          }
        },
        dataType: 'json',
        method: 'POST',
        url:  "/comments"
      });
      jqxhr.done(function(response){
          setAnnotations(editor, file_id);
      });
      jqxhr.fail(ajaxError);
  }

  var handleAnnotationRemoval = function(removedAnnotations) {
    removedAnnotations.forEach(function(annotation) {
      $.ajax({
        method: 'DELETE',
        url:  '/comment_by_id',
        data: {
          id: annotation.id,
        }
      })
    })
  }

  var handleAnnotationChange = function(changedAnnotations) {
    changedAnnotations.forEach(function(annotation) {
      $.ajax({
        method: 'PUT',
        url:  '/comments',
        data: {
          id: annotation.id,
          user_id: $('#editor').data('user-id'),
          comment: {
            row: annotation.row,
            text: annotation.text
          }
        }
      })
    })
  }

  var initializeEventHandlers = function() {
    $(document).on('click', '#results a', showOutput);
    $(document).on('keypress', handleKeyPress);
    $('a[data-toggle="tab"]').on('show.bs.tab', storeTab);
    initializeFileTreeButtons();
    initializeWorkflowButtons();
    initializeWorkspaceButtons();
  };

  var initializeFileTree = function() {
    $('#files').jstree($('#files').data('entries'));
    $('#files').on('click', 'li.jstree-leaf', function() {
      active_file = {
        filename: $(this).text(),
        id: parseInt($(this).attr('id'))
      };
      var frame = $('[data-file-id="' + active_file.id + '"]').parent();
      showFrame(frame);
      toggleButtonStates();
    });
  };

  var initializeFileTreeButtons = function() {
    $('#create-file').on('click', showFileDialog);
    $('#destroy-file').on('click', confirmDestroy);
    $('#download').on('click', downloadCode);
    $('#request-for-comments').on('click', requestComments);
  };

  var initializeTooltips = function() {
    $('[data-tooltip]').tooltip();
  };

  var initializeWorkflowButtons = function() {
    $('#start').on('click', showWorkspaceTab);
    $('#submit').on('click', confirmSubmission);
  };

  var initializeWorkspaceButtons = function() {
    $('#assess').on('click', scoreCode);
    $('#dropdown-render, #render').on('click', renderCode);
    $('#dropdown-run, #run').on('click', runCode);
    $('#dropdown-stop, #stop').on('click', stopCode);
    $('#dropdown-test, #test').on('click', testCode);
    $('#save').on('click', saveCode);
    $('#start-over').on('click', confirmReset);
  };

  var isActiveFileExecutable = function() {
    return 'executable' in active_frame.data();
  };

  var setActiveFile = function (filename, fileId) {
      active_file = {
          filename: filename,
          id: fileId
      };
  }

  var isActiveFileRenderable = function() {
    return 'renderable' in active_frame.data();
  };

  var isActiveFileRunnable = function() {
    return isActiveFileExecutable() && ['main_file', 'user_defined_file'].includes(active_frame.data('role'));
  };

  var isActiveFileStoppable = function() {
    return isActiveFileRunnable() && running;
  };

  var isActiveFileTestable = function() {
    return isActiveFileExecutable() && ['teacher_defined_test', 'user_defined_test'].includes(active_frame.data('role'));
  };

  var isBrowserSupported = function() {
    return window.EventSource !== undefined;
  };

  var populatePanel = function(panel, result, index) {
    panel.removeClass('panel-default').addClass(getPanelClass(result));
    panel.find('.panel-title .filename').text(result.filename);
    panel.find('.panel-title .number').text(index + 1);
    panel.find('.row .col-sm-9').eq(0).find('.number').eq(0).text(result.passed);
    panel.find('.row .col-sm-9').eq(0).find('.number').eq(1).text(result.count);
    panel.find('.row .col-sm-9').eq(1).find('.number').eq(0).text((result.score * result.weight).toFixed(2));
    panel.find('.row .col-sm-9').eq(1).find('.number').eq(1).text(result.weight);
    panel.find('.row .col-sm-9').eq(2).text(result.message);
    panel.find('.row .col-sm-9').eq(3).find('a').attr('href', '#output-' + index);
  };

  var chunkBuffer = [{streamedResponse: true}];

  var printChunk = function(event) {
    var output = JSON.parse(event.data);
    if (output) {
        printOutput(output, true, 0);
        // send test response to QA
        // we are expecting an array of outputs:
        if (qa_api) {
            chunkBuffer.push(output);
        }
    } else {
      clearOutput();
      $('#hint').fadeOut();
      $('#flowrHint').fadeOut();
      showTab(2);
    }
  };

  var printOutput = function(output, colorize, index) {
    var element = findOrCreateOutputElement(index);
    // disable streaming if desired
    //if (output.stdout && output.stdout.length >= 20 && output.stdout.substr(0,20) == "##DISABLESTREAMING##"){
    //    output_mode_is_streaming = false;
    //}
    if (!colorize) {
      var stream = _.sortBy([output.stderr || '', output.stdout || ''], function(stream) {
        return stream.length;
      })[1];
      element.append(stream);
    } else if (output.stderr) {
      element.addClass('text-warning').append(output.stderr);
    } else if (output.stdout) {
      //if (output_mode_is_streaming){
      element.addClass('text-success').append(output.stdout);
      //}else{
      //  element.addClass('text-success');
      //  element.data('content_buffer' , element.data('content_buffer') + output.stdout);
      //}
    //} else if (output.code && output.code == '200'){
    //  element.append( element.data('content_buffer'));
    } else {
      element.addClass('text-muted').text($('#output').data('message-no-output'));
    }
  };

  var printScoringResult = function(result, index) {
    $('#results').show();
    var panel = $('#dummies').children().first().clone();
    populatePanel(panel, result, index);
    $('#results ul').first().append(panel);
  };

  var printScoringResults = function(response) {
    $('#results ul').first().html('');
    $('.test-count .number').html(response.length);
    clearOutput();

    _.each(response, function(result, index) {
      printOutput(result, false, index);
      printScoringResult(result, index);
    });

    if (_.some(response, function(result) {
      return result.status === 'timeout';
    })) {
      showTimeoutMessage();
    }
    if (_.some(response, function(result) {
          return result.status === 'container_depleted';
      })) {
      showContainerDepletedMessage();
    }
    if (qa_api) {
      // send test response to QA
      qa_api.executeCommand('syncOutput', [response]);
    }
  };

  var renderCode = function(event) {
    event.preventDefault();
    if ($('#render').is(':visible')) {
      createSubmission(this, null, function(response) {
        var url = response.render_url.replace(FILENAME_URL_PLACEHOLDER, active_file.filename);
        var pop_up_window = window.open(url);
        if (pop_up_window) {
          pop_up_window.onerror = function(message) {
            clearOutput();
            printOutput({
              stderr: message
            }, true, 0);
            sendError(message, response.id);
            showTab(2);
          };
        }
      });
    }
  };

  var renderHint = function(object) {
    var hint = object.data || object.hint;
    if (hint) {
      $('#hint .panel-body').text(hint);
      $('#hint').fadeIn();
    }
  };

  var renderProgressBar = function(score, maximum_score) {
    var percentage = score / maximum_score * 100;
    var progress_bar = $('#score .progress-bar');
    progress_bar.removeClass().addClass(getProgressBarClass(percentage));
    progress_bar.attr({
      'aria-valuemax': maximum_score,
      'aria-valuemin': 0,
      'aria-valuenow': score
    });
    progress_bar.css('width', percentage + '%');
  };

  var renderScore = function() {
    var score = $('#score').data('score');
    var maxium_score = $('#score').data('maximum-score');
    $('.score').html((score || '?') + ' / ' + maxium_score);
    renderProgressBar(score, maxium_score);
  };

  var resetCode = function() {
    showSpinner(this);
    ajax({
      method: 'GET',
      url: $('#start-over').data('url')
    }).success(function(response) {
      hideSpinner();
      _.each(editors, function(editor) {
        var file_id = $(editor.container).data('file-id');
        var file = _.find(response.files, function(file) {
          return file.id === file_id;
        });
        editor.setValue(file.content);
      });
    });
  };

  var runCode = function(event) {
    event.preventDefault();
    if ($('#run').is(':visible')) {
      createSubmission(this, null, function(response) {
        $('#stop').data('url', response.stop_url);
        running = true;
        showSpinner($('#run'));
        toggleButtonStates();
        var url = response.run_url.replace(FILENAME_URL_PLACEHOLDER, active_file.filename);
        evaluateCode(url, true, printChunk);
      });
    }
  };

  var saveCode = function(event) {
    event.preventDefault();
    createSubmission(this, null, function() {
      $.flash.success({
        text: $('#save').data('message-success')
      });
    });
  };

  var sendError = function(message, submission_id) {
    showSpinner($('#render'));
    var jqxhr = ajax({
      data: {
        error: {
          message: message,
          submission_id: submission_id
        }
      },
      url: $('#editor').data('errors-url')
    });
    jqxhr.always(hideSpinner);
    jqxhr.success(renderHint);
  };

  var scoreCode = function(event) {
    event.preventDefault();
    createSubmission(this, null, function(response) {
      showSpinner($('#assess'));
      var url = response.score_url;
      evaluateCode(url, false, handleScoringResponse);
    });
  };

  var showFileDialog = function(event) {
    event.preventDefault();
    createSubmission(this, null, function(response) {
      $('#code_ocean_file_context_id').val(response.id);
      $('#modal-file').modal('show');
    });
  };

  var showFirstFile = function() {
    var frame = $('.frame[data-role="main_file"]').isPresent() ? $('.frame[data-role="main_file"]') : $('.frame').first();
    var file_id = frame.find('.editor').data('file-id');
    setActiveFile(frame.data('filename'), file_id);
    $('#files').jstree().select_node(file_id);
    showFrame(frame);
    toggleButtonStates();
  };

  var showFrame = function(frame) {
    active_frame = frame;
    $('.frame').hide();
    frame.show();
  };

  var showOutput = function(event) {
    event.preventDefault();
    showTab(2);
    $('#output').scrollTo($(this).attr('href'));
  };

  var showRequestedTab = function() {
    var regexp = /tab=(\d+)/;
    if (regexp.test(window.location.search)) {
      var index = regexp.exec(window.location.search)[1] - 1;
    } else {
      var index = localStorage.tab;
    }
    showTab(index);
  };

  var showSpinner = function(initiator) {
    $(initiator).find('i.fa').hide();
    $(initiator).find('i.fa-spin').show();
  };

  var showStatus = function(output) {
    if (output.status === 'timeout') {
      showTimeoutMessage();
    } else if (output.status === 'container_depleted') {
        showContainerDepletedMessage();
    } else if (output.stderr) {
      $.flash.danger({
        icon: ['fa', 'fa-bug'],
        text: $('#run').data('message-failure')
      });
    } else {
      $.flash.success({
        icon: ['fa', 'fa-check'],
        text: $('#run').data('message-success')
      });
    }
  };

  var showContainerDepletedMessage = function() {
    $.flash.danger({
      icon: ['fa', 'fa-clock-o'],
      text: $('#editor').data('message-depleted')
    });
  };

  var showTab = function(index) {
    $('a[data-toggle="tab"]').eq(index || 0).tab('show');
  };

  var showTimeoutMessage = function() {
    $.flash.danger({
      icon: ['fa', 'fa-clock-o'],
      text: $('#editor').data('message-timeout')
    });
  };

  var showWorkspaceTab = function(event) {
    event.preventDefault();
    showTab(1);
  };

  var stopCode = function(event) {
    event.preventDefault();
    if ($('#stop').is(':visible')) {
      var jqxhr = ajax({
        data: {
          container_id: $('#stop').data('container').id
        },
        url: $('#stop').data('url')
      });
      jqxhr.always(function() {
        hideSpinner();
        running = false;
        toggleButtonStates();
      });
      jqxhr.fail(ajaxError);
    }
  };

  var storeContainerInformation = function(event) {
    var container_information = JSON.parse(event.data);
    $('#stop').data('container', container_information);

    if (_.size(container_information.port_bindings) > 0) {
      $.flash.info({
        icon: ['fa', 'fa-exchange'],
        text: _.map(container_information.port_bindings, function(key, value) {
          var url = window.location.protocol + '//' + window.location.hostname + ':' + key;
          return $('#run').data('message-network').replace('%{port}', value).replace(/%{address}/g, url);
        }).join('\n')
      });
    }
  };

  var storeTab = function(event) {
    localStorage.tab = $(event.target).parent().index();
  };

  var submitCode = function() {
    createSubmission($('#submit'), null, function(response) {
      if (response.redirect) {
        localStorage.removeItem('tab');
        window.location = response.redirect;
      }
    });
  };

  var testCode = function(event) {
    event.preventDefault();
    if ($('#test').is(':visible')) {
      createSubmission(this, null, function(response) {
        showSpinner($('#test'));
        var url = response.test_url.replace(FILENAME_URL_PLACEHOLDER, active_file.filename);
        evaluateCode(url, false, handleTestResponse);
      });
    }
  };

  var toggleButtonStates = function() {
    $('#destroy-file').prop('disabled', active_frame.data('role') !== 'user_defined_file');
    $('#dropdown-render').toggleClass('disabled', !isActiveFileRenderable());
    $('#dropdown-run').toggleClass('disabled', !isActiveFileRunnable() || running);
    $('#dropdown-stop').toggleClass('disabled', !isActiveFileStoppable());
    $('#dropdown-test').toggleClass('disabled', !isActiveFileTestable());
    $('#dummy').toggle(!fileActionsAvailable());
    $('#editor-buttons .dropdown-toggle').toggle(fileActionsAvailable());
    $('#render').toggle(isActiveFileRenderable());
    $('#run').toggle(isActiveFileRunnable() && !running);
    $('#stop').toggle(isActiveFileStoppable());
    $('#test').toggle(isActiveFileTestable());
  };

  var requestComments = function(e) {
    var user_id = $('#editor').data('user-id')
    var exercise_id = $('#editor').data('exercise-id')
    var file_id = $('.editor').data('id')

    $.ajax({
      method: 'POST',
      url: '/request_for_comments',
      data: {
        request_for_comment: {
          requestorid: user_id,
          exerciseid: exercise_id,
          fileid: file_id,
          "requested_at(1i)": 2015, // these are the timestamp values that the request handler demands
          "requested_at(2i)":3, // they could be random here, because the timestamp is updated on serverside anyway
          "requested_at(3i)":27,
          "requested_at(4i)":17,
          "requested_at(5i)":06
        }
      }
    }).done(function() {
      hideSpinner()
      $.flash.success({ text: 'Request for comments sent!' })
    })

    showSpinner($('#request-for-comments'))
  }

    var initializeCodePilot = function() {
        if ($('#questions-column').isPresent() && (typeof QaApi != 'undefined') && QaApi.isBrowserSupported()) {
            $('#editor-column').addClass('col-md-8').removeClass('col-md-10');
            $('#questions-column').addClass('col-md-3');

            var node = document.getElementById('questions-holder');
            var url = $('#questions-holder').data('url');

            qa_api = new QaApi(node, url);
        }
    }

  if ($('#editor').isPresent()) {
      if (isBrowserSupported()) {
          initializeCodePilot();
          $('.score, #development-environment').show();
          configureEditors();
          initializeEditors();
          initializeEventHandlers();
          initializeFileTree();
          initializeTooltips();
          renderScore();
          showFirstFile();
          showRequestedTab();
      } else {
          $('#alert').show();
      }
  }
});


text:
FOUNDATION_EXPORT double RSRoundBorderedButtonVersionNumber;

//! Project version string for RSRoundBorderedButton.
FOUNDATION_EXPORT const unsigned char RSRoundBorderedButtonVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <RSRoundBorderedButton/PublicHeader.h>

redpajama_set_name: RedPajamaGithub


text:
//
//  AMAlbumDetailsViewController.m
//  Lezione3_a
//
//  Created by Andrea Maschio on 16/03/14.
//  Copyright (c) 2014 2AM Code. All rights reserved.
//

#import "AMAlbumDetailsViewController.h"
#import "Album.h"

@interface AMAlbumDetailsViewController ()

@end

@implementation AMAlbumDetailsViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    txtAlbumTitle.text = _album.title;
    txtBandName.text = _album.band;

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    //self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//#warning Potentially incomplete method implementation.
//    // Return the number of sections.
//    return 0;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//#warning Incomplete method implementation.
//    // Return the number of rows in the section.
//    return 0;
//}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];

    // Configure the cell...

    return cell;
}
*/

// Override to support conditional editing of the table view.
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    // Return NO if you do not want the specified item to be editable.
//    return NO;
//}

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)cancel:(id)sender {

    [self.delegate albumDetailsViewControllerDidCancel:self];
    //oppure
    //[self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)done:(id)sender {
    if(!self.album){
    self.album = [Album new];
    }
    self.album.title = txtAlbumTitle.text;
    self.album.band = txtBandName.text;
    self.album.rating  =1;
    [self.delegate albumDetailsViewController:self didAddAlbum:self.album];
    //oppure
    //[self dismissViewControllerAnimated:YES completion:nil];
}
@end


text:
/**
 * Created by jzb on 17-6-6.
 */
import {Action} from '@ngrx/store';
import {TaskGroup} from '../../../shared/models/task-group';

export const INIT = '[TaskGroupManagePage] INIT';

export class Init implements Action {
  readonly type = INIT;
}

export const INIT_SUCCESS = '[TaskGroupManagePage] INIT_SUCCESS';

export class InitSuccess implements Action {
  readonly type = INIT_SUCCESS;

  constructor(public taskGroups: TaskGroup[]) {
  }
}

export type Actions
  = Init
  | InitSuccess;


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview The ChromeVox panel and menus.
 */

goog.provide('Panel');

goog.require('ISearchUI');
goog.require('Msgs');
goog.require('PanelCommand');
goog.require('PanelMenu');
goog.require('PanelMenuItem');
goog.require('cvox.ChromeVoxKbHandler');
goog.require('cvox.CommandStore');

/**
 * Class to manage the panel.
 * @constructor
 */
Panel = function() {
};

/**
 * Initialize the panel.
 */
Panel.init = function() {
  /** @type {Element} @private */
  this.speechContainer_ = $('speech-container');

  /** @type {Element} @private */
  this.speechElement_ = $('speech');

  /** @type {Element} @private */
  this.brailleContainer_ = $('braille-container');

  /** @type {Element} @private */
  this.searchContainer_ = $('search-container');

  /** @type {Element} @private */
  this.searchInput_ = $('search');

  /** @type {Element} @private */
  this.brailleTextElement_ = $('braille-text');

  /** @type {Element} @private */
  this.brailleCellsElement_ = $('braille-cells');

  /**
   * The array of top-level menus.
   * @type {!Array<PanelMenu>}
   * @private
   */
  this.menus_ = [];

  /**
   * The currently active menu, if any.
   * @type {PanelMenu}
   * @private
   */
  this.activeMenu_ = null;

  /**
   * True if the menu button in the panel is enabled at all. It's disabled if
   * ChromeVox Next is not active.
   * @type {boolean}
   * @private
   */
  this.menusEnabled_ = false;

  /**
   * A callback function to be executed to perform the action from selecting
   * a menu item after the menu has been closed and focus has been restored
   * to the page or wherever it was previously.
   * @type {?Function}
   * @private
   */
  this.pendingCallback_ = null;

  /**
   * True if we're currently in incremental search mode.
   * @type {boolean}
   * @private
   */
  this.searching_ = false;

  Panel.updateFromPrefs();

  Msgs.addTranslatedMessagesToDom(document);

  window.addEventListener('storage', function(event) {
    if (event.key == 'brailleCaptions') {
      Panel.updateFromPrefs();
    }
  }, false);

  window.addEventListener('message', function(message) {
    var command = JSON.parse(message.data);
    Panel.exec(/** @type {PanelCommand} */(command));
  }, false);

  $('menus_button').addEventListener('mousedown', Panel.onOpenMenus, false);
  $('options').addEventListener('click', Panel.onOptions, false);
  $('close').addEventListener('click', Panel.onClose, false);

  document.addEventListener('keydown', Panel.onKeyDown, false);
  document.addEventListener('mouseup', Panel.onMouseUp, false);

  Panel.searchInput_.addEventListener('blur', Panel.onSearchInputBlur, false);
};

/**
 * Update the display based on prefs.
 */
Panel.updateFromPrefs = function() {
  if (Panel.searching_) {
    this.speechContainer_.style.display = 'none';
    this.brailleContainer_.style.display = 'none';
    this.searchContainer_.style.display = 'block';
    return;
  }

  this.speechContainer_.style.display = 'block';
  this.brailleContainer_.style.display = 'block';
  this.searchContainer_.style.display = 'none';

  if (localStorage['brailleCaptions'] === String(true)) {
    this.speechContainer_.style.visibility = 'hidden';
    this.brailleContainer_.style.visibility = 'visible';
  } else {
    this.speechContainer_.style.visibility = 'visible';
    this.brailleContainer_.style.visibility = 'hidden';
  }
};

/**
 * Execute a command to update the panel.
 *
 * @param {PanelCommand} command The command to execute.
 */
Panel.exec = function(command) {
  /**
   * Escape text so it can be safely added to HTML.
   * @param {*} str Text to be added to HTML, will be cast to string.
   * @return {string} The escaped string.
   */
  function escapeForHtml(str) {
    return String(str)
        .replace(/&/g, '&')
        .replace(/</g, '<')
        .replace(/\>/g, '>')
        .replace(/"/g, '"')
        .replace(/'/g, ''')
        .replace(/\//g, '/');
  }

  switch (command.type) {
    case PanelCommandType.CLEAR_SPEECH:
      this.speechElement_.innerHTML = '';
      break;
    case PanelCommandType.ADD_NORMAL_SPEECH:
      if (this.speechElement_.innerHTML != '') {
        this.speechElement_.innerHTML += '  ';
      }
      this.speechElement_.innerHTML += '' +
                                       escapeForHtml(command.data) +
                                       '';
      break;
    case PanelCommandType.ADD_ANNOTATION_SPEECH:
      if (this.speechElement_.innerHTML != '') {
        this.speechElement_.innerHTML += '  ';
      }
      this.speechElement_.innerHTML += escapeForHtml(command.data);
      break;
    case PanelCommandType.UPDATE_BRAILLE:
      this.brailleTextElement_.textContent = command.data.text;
      this.brailleCellsElement_.textContent = command.data.braille;
      break;
    case PanelCommandType.ENABLE_MENUS:
      Panel.onEnableMenus();
      break;
    case PanelCommandType.DISABLE_MENUS:
      Panel.onDisableMenus();
      break;
    case PanelCommandType.OPEN_MENUS:
      Panel.onOpenMenus();
      break;
    case PanelCommandType.SEARCH:
      Panel.onSearch();
      break;
  }
};

/**
 * Enable the ChromeVox Menus.
 */
Panel.onEnableMenus = function() {
  Panel.menusEnabled_ = true;
  $('menus_button').disabled = false;
  $('triangle').style.display = '';
};

/**
 * Disable the ChromeVox Menus.
 */
Panel.onDisableMenus = function() {
  Panel.menusEnabled_ = false;
  $('menus_button').disabled = true;
  $('triangle').style.display = 'none';
};

/**
 * Open / show the ChromeVox Menus.
 * @param {Event=} opt_event An optional event that triggered this.
 */
Panel.onOpenMenus = function(opt_event) {
  // Don't open the menu if it's not enabled, such as when ChromeVox Next
  // is not active.
  if (!Panel.menusEnabled_)
    return;

  // Eat the event so that a mousedown isn't turned into a drag, allowing
  // users to click-drag-release to select a menu item.
  if (opt_event) {
    opt_event.stopPropagation();
    opt_event.preventDefault();
  }

  // Change the url fragment to 'fullscreen', which signals the native
  // host code to make the window fullscreen, revealing the menus.
  window.location = '#fullscreen';

  // Clear any existing menus and clear the callback.
  Panel.clearMenus();
  Panel.pendingCallback_ = null;

  // Build the top-level menus.
  var jumpMenu = Panel.addMenu('Jump');
  var speechMenu = Panel.addMenu('Speech');
  var tabsMenu = Panel.addMenu('Tabs');
  var chromevoxMenu = Panel.addMenu('ChromeVox');

  // Create a mapping between categories from CommandStore, and our
  // top-level menus. Some categories aren't mapped to any menu.
  var categoryToMenu = {
    'navigation': jumpMenu,
    'jump_commands': jumpMenu,
    'controlling_speech': speechMenu,
    'modifier_keys': chromevoxMenu,
    'help_commands': chromevoxMenu,

    'information': null,  // Get link URL, get page title, etc.
    'overview': null,     // Headings list, etc.
    'tables': null,       // Table navigation.
    'braille': null,
    'developer': null};

  // Get the key map from the background page.
  var bkgnd = chrome.extension.getBackgroundPage();
  var keymap = bkgnd['cvox']['KeyMap']['fromCurrentKeyMap']();

  // Make a copy of the key bindings, get the localized title of each
  // command, and then sort them.
  var sortedBindings = keymap.bindings().slice();
  sortedBindings.forEach(goog.bind(function(binding) {
    var command = binding.command;
    var keySeq = binding.sequence;
    binding.keySeq = cvox.KeyUtil.keySequenceToString(keySeq, true);
    var titleMsgId = cvox.CommandStore.messageForCommand(command);
    if (!titleMsgId) {
      console.error('No localization for: ' + command);
      binding.title = '';
      return;
    }
    var title = Msgs.getMsg(titleMsgId);
    // Convert to title case.
    title = title.replace(/\w\S*/g, function(word) {
      return word.charAt(0).toUpperCase() + word.substr(1);
    });
    binding.title = title;
  }, this));
  sortedBindings.sort(function(binding1, binding2) {
    return binding1.title.localeCompare(binding2.title);
  });

  // Insert items from the bindings into the menus.
  sortedBindings.forEach(goog.bind(function(binding) {
    var category = cvox.CommandStore.categoryForCommand(binding.command);
    var menu = category ? categoryToMenu[category] : null;
    if (binding.title && menu) {
      menu.addMenuItem(
          binding.title,
          binding.keySeq,
          function() {
            var bkgnd =
                chrome.extension.getBackgroundPage()['global']['backgroundObj'];
            bkgnd['onGotCommand'](binding.command);
          });
    }
  }, this));

  // Add all open tabs to the Tabs menu.
  bkgnd.chrome.windows.getLastFocused(function(lastFocusedWindow) {
    bkgnd.chrome.windows.getAll({'populate': true}, function(windows) {
      for (var i = 0; i < windows.length; i++) {
        var tabs = windows[i].tabs;
        for (var j = 0; j < tabs.length; j++) {
          var title = tabs[j].title;
          if (tabs[j].active && windows[i].id == lastFocusedWindow.id)
            title += ' ' + Msgs.getMsg('active_tab');
          tabsMenu.addMenuItem(title, '', (function(win, tab) {
            bkgnd.chrome.windows.update(win.id, {focused: true}, function() {
              bkgnd.chrome.tabs.update(tab.id, {active: true});
            });
          }).bind(this, windows[i], tabs[j]));
        }
      }
    });
  });

  // Add a menu item that disables / closes ChromeVox.
  chromevoxMenu.addMenuItem(
      Msgs.getMsg('disable_chromevox'), 'Ctrl+Alt+Z', function() {
        Panel.onClose();
      });

  // Activate the first menu.
  Panel.activateMenu(Panel.menus_[0]);
};

/** Open incremental search. */
Panel.onSearch = function() {
  Panel.clearMenus();
  Panel.pendingCallback_ = null;
  Panel.searching_ = true;
  Panel.updateFromPrefs();

  window.location = '#focus';

  ISearchUI.get(Panel.searchInput_);
};

/**
 * Clear any previous menus. The menus are all regenerated each time the
 * menus are opened.
 */
Panel.clearMenus = function() {
  while (this.menus_.length) {
    var menu = this.menus_.pop();
    $('menu-bar').removeChild(menu.menuBarItemElement);
    $('menus_background').removeChild(menu.menuContainerElement);
  }
  this.activeMenu_ = null;
};

/**
 * Create a new menu with the given name and add it to the menu bar.
 * @param {string} menuTitle The title of the new menu to add.
 * @return {PanelMenu} The menu just created.
 */
Panel.addMenu = function(menuTitle) {
  var menu = new PanelMenu(menuTitle);
  $('menu-bar').appendChild(menu.menuBarItemElement);
  menu.menuBarItemElement.addEventListener('mouseover', function() {
    Panel.activateMenu(menu);
  }, false);

  $('menus_background').appendChild(menu.menuContainerElement);
  this.menus_.push(menu);
  return menu;
};

/**
 * Activate a menu, which implies hiding the previous active menu.
 * @param {PanelMenu} menu The new menu to activate.
 */
Panel.activateMenu = function(menu) {
  if (menu == this.activeMenu_)
    return;

  if (this.activeMenu_) {
    this.activeMenu_.deactivate();
    this.activeMenu_ = null;
  }

  this.activeMenu_ = menu;
  this.pendingCallback_ = null;

  if (this.activeMenu_) {
    this.activeMenu_.activate();
  }
};

/**
 * Advance the index of the current active menu by |delta|.
 * @param {number} delta The number to add to the active menu index.
 */
Panel.advanceActiveMenuBy = function(delta) {
  var activeIndex = -1;
  for (var i = 0; i < this.menus_.length; i++) {
    if (this.activeMenu_ == this.menus_[i]) {
      activeIndex = i;
      break;
    }
  }

  if (activeIndex >= 0) {
    activeIndex += delta;
    activeIndex = (activeIndex + this.menus_.length) % this.menus_.length;
  } else {
    if (delta >= 0)
      activeIndex = 0;
    else
      activeIndex = this.menus_.length - 1;
  }
  Panel.activateMenu(this.menus_[activeIndex]);
};

/**
 * Advance the index of the current active menu item by |delta|.
 * @param {number} delta The number to add to the active menu item index.
 */
Panel.advanceItemBy = function(delta) {
  if (this.activeMenu_)
    this.activeMenu_.advanceItemBy(delta);
};

/**
 * Called when the user releases the mouse button. If it's anywhere other
 * than on the menus button, close the menus and return focus to the page,
 * and if the mouse was released over a menu item, execute that item's
 * callback.
 * @param {Event} event The mouse event.
 */
Panel.onMouseUp = function(event) {
  var target = event.target;
  while (target && !target.classList.contains('menu-item')) {
    // Allow the user to click and release on the menu button and leave
    // the menu button. Otherwise releasing the mouse anywhere else will
    // close the menu.
    if (target.id == 'menus_button')
      return;

    target = target.parentElement;
  }

  if (target && Panel.activeMenu_)
    Panel.pendingCallback_ = Panel.activeMenu_.getCallbackForElement(target);
  Panel.closeMenusAndRestoreFocus();
};

/**
 * Called when a key is pressed. Handle arrow keys to navigate the menus,
 * Esc to close, and Enter/Space to activate an item.
 * @param {Event} event The key event.
 */
Panel.onKeyDown = function(event) {
  if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)
    return;

  switch (event.keyIdentifier) {
    case 'Left':
      Panel.advanceActiveMenuBy(-1);
      break;
    case 'Right':
      Panel.advanceActiveMenuBy(1);
      break;
    case 'Up':
      Panel.advanceItemBy(-1);
      break;
    case 'Down':
      Panel.advanceItemBy(1);
      break;
    case 'U+001B':  // Escape
      Panel.closeMenusAndRestoreFocus();
      break;
    case 'Enter':  // Enter
    case 'U+0020':  // Space
      Panel.pendingCallback_ = Panel.getCallbackForCurrentItem();
      Panel.closeMenusAndRestoreFocus();
      break;
    default:
      // Don't mark this event as handled.
      return;
  }

  event.preventDefault();
  event.stopPropagation();
};

/**
 * Called when focus leaves the search input.
 */
Panel.onSearchInputBlur = function() {
  if (Panel.searching_) {
    if (document.activeElement != Panel.searchInput_ || !document.hasFocus()) {
      Panel.searching_ = false;
      if (window.location == '#focus')
        window.location = '#';
      Panel.updateFromPrefs();
      Panel.searchInput_.value = '';
    }
  }
};

/**
 * Open the ChromeVox Options.
 */
Panel.onOptions = function() {
  var bkgnd =
      chrome.extension.getBackgroundPage()['global']['backgroundObj'];
  bkgnd['showOptionsPage']();
  window.location = '#';
};

/**
 * Exit ChromeVox.
 */
Panel.onClose = function() {
  window.location = '#close';
};

/**
 * Get the callback for whatever item is currently selected.
 * @return {Function} The callback for the current item.
 */
Panel.getCallbackForCurrentItem = function() {
  if (this.activeMenu_)
    return this.activeMenu_.getCallbackForCurrentItem();
  return null;
};

/**
 * Close the menus and restore focus to the page. If a menu item's callback
 * was queued, execute it once focus is restored.
 */
Panel.closeMenusAndRestoreFocus = function() {
  // Make sure we're not in full-screen mode.
  window.location = '#';

  var bkgnd =
      chrome.extension.getBackgroundPage()['global']['backgroundObj'];
  bkgnd['endExcursion']();
  if (Panel.pendingCallback_)
    Panel.pendingCallback_();
};

window.addEventListener('load', function() {
  Panel.init();
}, false);

window.addEventListener('hashchange', function() {
  if (location.hash == '#fullscreen' || location.hash == '#focus') {
    this.originalStickyState_ = cvox.ChromeVox.isStickyPrefOn;
    cvox.ChromeVox.isStickyPrefOn = false;
  } else {
    cvox.ChromeVox.isStickyPrefOn = this.originalStickyState_;
  }
}, false);


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-1353',
  templateUrl: './comp-1353.component.html',
  styleUrls: ['./comp-1353.component.css']
})
export class Comp1353Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
export default class OSFactory {
    constructor() {
        if (new.target !== undefined) {
            throw new Error("You cannot instantiate an abstract class!");
        }
    }

    getLinuxDistro(id) {
        throw new Error("You cannot call an abstract method!");
    }

    getMacRelease(id) {
        throw new Error("You cannot call an abstract method!");
    }

    getWindowsVersion(id) {
        throw new Error("You cannot call an abstract method!");
    }
}


text:
package com.ilad.testtopqteamwork;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Configuration {

	private static Properties properties;

	private static Configuration configuration = null;

	//Constructor
	private Configuration() {
		properties = new Properties();
		InputStream input = null;
		try {
			input = new FileInputStream
					("/home/developer/git/Infinity-Labs-Repository/"
				   + "topqteamworkandroid/src/test/java/com/ilad/"
				   + "testtopqteamwork/config.properties");
			properties.load(input);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(null != input) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	//Getters
	private static Configuration getInstance() {
		if(null == configuration) {
			configuration = new Configuration();
		}
		return configuration;
	}

	public static String getApkFileName() {
		getInstance();
		return properties.getProperty("apkFileName");
	}

	public static String getUrl() {
		getInstance();
		return properties.getProperty("url");
	}

	public static String getUserName() {
		getInstance();
		return properties.getProperty("userName");
	}

	public static String getUserPassword() {
		getInstance();
		return properties.getProperty("userPassword");
	}

	public static String getTaskListName() {
		getInstance();
		return properties.getProperty("taskListName");
	}
}


text:
package info.histei.contextual_info;

import info.histei.lists.ListItemAdapter;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.XdmNode;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static info.histei.utils.SaxonUtils.getChildText;

/**
 * Created by mike on 2/10/14.
 */
public class ContextualItem extends ListItemAdapter {

    private static final Logger logger = Logger.getLogger(ContextualItem.class.getName());

    //  Regexp info for retrieving IDs
    private static final String TYPE_REGEX = "(" + StringUtils.join(ContextualType.getKeys(), "|") + ")";
    private static final String ID_REGEX = "(\\S+)";
    private static final Pattern REF_PATTERN = Pattern.compile(TYPE_REGEX + ":" + ID_REGEX);

    protected static final String TYPE_ATTRIB_NAME = "type";

    @Nullable
    public static ContextualItem get(ContextualType contextualType, XdmNode item) {
        ContextualItem contextualItem = null;

        String value = StringUtils.trimToNull(item.getAttributeValue(new QName(VALUE_ATTRIB_NAME)));

        if (value != null && contextualType != null) {
            value = contextualType.getKey() + ":" + value;

            String label = StringUtils.trimToEmpty(getChildText(item, LABEL_ELEMENT_NAME));
            if (label.isEmpty()) label = value;

            String tooltip = StringUtils.trimToEmpty(getChildText(item, TOOLTIP_ELEMENT_NAME));

            String type = StringUtils.trimToEmpty(item.getAttributeValue(new QName(TYPE_ATTRIB_NAME)));

            contextualItem = new ContextualItem(value, label, tooltip, contextualType, type);
        }
        return contextualItem;
    }

    /* Instance Members*/

    protected ContextualType contextualType;
    protected String type;

    protected ContextualItem(String value, String label, String tooltip,
                             ContextualType contextualType, String type) {
        super(value, label, tooltip);
        this.contextualType = contextualType;
        this.type = type;
    }

    @NotNull
    public ContextualType getContextualType() {
        return contextualType;
    }

    @NotNull
    public String getType() {
        return type;
    }

    @NotNull
    public String getRefID() {
        String id = "";
        String value = getValue();

        if (!value.isEmpty()) {
            Matcher matcher = REF_PATTERN.matcher(value);
            if (matcher.matches()) {
                id = matcher.group(2);
            }
        }
        return id;
    }

    @Nullable
    public URL getURL() {
        ContextualInfo info = ContextualInfo.get(getContextualType());
        URL url = info.getURL();

        if (url != null) {
            try {
                String id = getRefID();
                if (!id.isEmpty()) url = new URL(url, "#" + id);
            } catch (MalformedURLException e) {
                logger.error(e, e);
            }
        }
        return url;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proceedings of the IV International Palynology Conference, Lucknow 1976-1977 1: 299 (1979)

#### Original name
Alleppeysporonites Ramanujam & Rao

### Remarks
null


text:
'use strict';

function getModuleName(filePath) {
  // index.js -> index
  // index.js.flow -> index.js
  var filename = require('path').basename(filePath, require('path').extname(filePath));

  // index.js -> index (when extension has multiple segments)
  filename = filename.replace(/(?:\.\w+)+/, '');

  // /path/to/button/index.js -> button
  var moduleName = filename === 'index' ? require('path').basename(require('path').dirname(filePath)) : filename;

  // Example.ios -> Example
  // Example.product.android -> Example
  moduleName = moduleName.replace(/(?:\.\w+)+/, '');

  // foo-bar -> fooBar
  // Relay compatibility mode splits on _, so we can't use that here.
  moduleName = moduleName.replace(/[^a-zA-Z0-9]+(\w?)/g, function (match, next) {
    return next.toUpperCase();
  });

  return moduleName;
}

module.exports = getModuleName;


text:
package com.vmware.dcp.services.samples;

import org.junit.Before;
import org.junit.Test;

import com.vmware.xenon.common.BasicTestCase;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.samples.SampleBootstrapService;

public class TestSampleBootstrapService extends BasicTestCase {

    public int nodeCount = 3;

    @Before
    public void setUp() throws Throwable {

        // setup peer
        this.host.setUpPeerHosts(this.nodeCount);
        VerificationHost peer = this.host.getPeerHost();

        // create a nodegroup with peers. HOST will NOT join the node group.
        this.host.joinNodesAndVerifyConvergence(this.nodeCount);
        this.host.waitForNodeGroupConvergence(this.nodeCount);

        for (VerificationHost h : this.host.getInProcessHostMap().values()) {
            h.startServiceAndWait(SampleBootstrapService.createFactory(),
                    SampleBootstrapService.FACTORY_LINK, null);
        }

        peer.waitForReplicatedFactoryServiceAvailable(
                UriUtils.buildUri(peer, SampleBootstrapService.FACTORY_LINK));

        // register callback. triggered when service become available in cluster.
        // only one will be created on owner node, and rest will be ignored after converted to PUT
        for (VerificationHost h : this.host.getInProcessHostMap().values()) {
            h.registerForServiceAvailability(SampleBootstrapService.startTask(h), true,
                    SampleBootstrapService.FACTORY_LINK);
        }

        host.waitFor("Failed to verify completion of bootstrap/preparation-task", () -> {
            boolean[] isReady = new boolean[1];

            Operation get = Operation.createGet(peer, "/core/bootstrap/preparation-task")
                    .setCompletion((o, e) -> {
                        // wait until successful GET response
                        isReady[0] = e == null;
                        host.completeIteration();
                    });
            host.sendAndWait(get);
            return isReady[0];
        });

    }

    @Override
    public void beforeHostTearDown(VerificationHost host) {
        this.host.tearDownInProcessPeers();
    }

    @Test
    public void taskCreation() throws Throwable {
        VerificationHost peer = this.host.getPeerHost();

        peer.sendAndWaitExpectSuccess(
                Operation.createGet(peer, "/core/bootstrap/preparation-task"));

        // admin@vmware.com must be created
        peer.sendAndWaitExpectSuccess(
                Operation.createGet(peer, "/core/authz/users/admin@vmware.com"));
    }

    @Test
    public void put() throws Throwable {
        VerificationHost peer = this.host.getPeerHost();

        // direct put should fail
        Operation op = Operation.createPut(peer, "/core/bootstrap/preparation-task")
                .setBody(new ServiceDocument());
        peer.sendAndWaitExpectFailure(op, Operation.STATUS_CODE_BAD_METHOD);
    }

}


text:
using System;
using gcl2;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace gclUnitTest
{
    [TestClass]
    public class SintacticPerserTesting
    {

    }
}


text:
namespace Azure.Maps.Search.Models
{
    /// <summary> Information about the geometric shape of the result. Only present if type == Geography. </summary>
    public partial class GeometryIdentifier
    {
        /// <summary> Initializes a new instance of GeometryIdentifier. </summary>
        internal GeometryIdentifier()
        {
        }

        /// <summary> Initializes a new instance of GeometryIdentifier. </summary>
        /// <param name="id"> Pass this as geometryId to the [Get Search Polygon](https://docs.microsoft.com/rest/api/maps/search/getsearchpolygon) API to fetch geometry information for this result. </param>
        internal GeometryIdentifier(string id)
        {
            Id = id;
        }

        /// <summary> Pass this as geometryId to the [Get Search Polygon](https://docs.microsoft.com/rest/api/maps/search/getsearchpolygon) API to fetch geometry information for this result. </summary>
        public string Id { get; }
    }
}


text:
.class Lcom/nineoldandroids/animation/u;
.super Lcom/nineoldandroids/util/FloatProperty;

# annotations
.annotation system Ldalvik/annotation/Signature;
    value = {
        "Lcom/nineoldandroids/util/FloatProperty",
        "<",
        "Landroid/view/View;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>(Ljava/lang/String;)V
    .locals 0

    invoke-direct {p0, p1}, Lcom/nineoldandroids/util/FloatProperty;-><init>(Ljava/lang/String;)V

    return-void
.end method

# virtual methods
.method public a(Landroid/view/View;)Ljava/lang/Float;
    .locals 1

    invoke-static {p1}, Lcom/nineoldandroids/view/animation/AnimatorProxy;->wrap(Landroid/view/View;)Lcom/nineoldandroids/view/animation/AnimatorProxy;

    move-result-object v0

    invoke-virtual {v0}, Lcom/nineoldandroids/view/animation/AnimatorProxy;->getTranslationX()F

    move-result v0

    invoke-static {v0}, Ljava/lang/Float;->valueOf(F)Ljava/lang/Float;

    move-result-object v0

    return-object v0
.end method

.method public a(Landroid/view/View;F)V
    .locals 1

    invoke-static {p1}, Lcom/nineoldandroids/view/animation/AnimatorProxy;->wrap(Landroid/view/View;)Lcom/nineoldandroids/view/animation/AnimatorProxy;

    move-result-object v0

    invoke-virtual {v0, p2}, Lcom/nineoldandroids/view/animation/AnimatorProxy;->setTranslationX(F)V

    return-void
.end method

.method public synthetic get(Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1

    check-cast p1, Landroid/view/View;

    invoke-virtual {p0, p1}, Lcom/nineoldandroids/animation/u;->a(Landroid/view/View;)Ljava/lang/Float;

    move-result-object v0

    return-object v0
.end method

.method public synthetic setValue(Ljava/lang/Object;F)V
    .locals 0

    check-cast p1, Landroid/view/View;

    invoke-virtual {p0, p1, p2}, Lcom/nineoldandroids/animation/u;->a(Landroid/view/View;F)V

    return-void
.end method


text:
=pod

=head1 NAME

dsa - DSA key processing

=head1 SYNOPSIS

B<openssl> B<dsa>
[B<-inform PEM|DER>]
[B<-outform PEM|DER>]
[B<-in filename>]
[B<-passin arg>]
[B<-out filename>]
[B<-passout arg>]
[B<-aes128>]
[B<-aes192>]
[B<-aes256>]
[B<-camellia128>]
[B<-camellia192>]
[B<-camellia256>]
[B<-des>]
[B<-des3>]
[B<-idea>]
[B<-text>]
[B<-noout>]
[B<-modulus>]
[B<-pubin>]
[B<-pubout>]
[B<-engine id>]

=head1 DESCRIPTION

The B<dsa> command processes DSA keys. They can be converted between various
forms and their components printed out. B<Note> This command uses the
traditional SSLeay compatible format for private key encryption: newer
applications should use the more secure PKCS#8 format using the B<pkcs8>

=head1 COMMAND OPTIONS

=over 4

=item B<-inform DER|PEM>

This specifies the input format. The B<DER> option with a private key uses
an ASN1 DER encoded form of an ASN.1 SEQUENCE consisting of the values of
version (currently zero), p, q, g, the public and private key components
respectively as ASN.1 INTEGERs. When used with a public key it uses a
SubjectPublicKeyInfo structure: it is an error if the key is not DSA.

The B<PEM> form is the default format: it consists of the B<DER> format base64
encoded with additional header and footer lines. In the case of a private key
PKCS#8 format is also accepted.

=item B<-outform DER|PEM>

This specifies the output format, the options have the same meaning as the
B<-inform> option.

=item B<-in filename>

This specifies the input filename to read a key from or standard input if this
option is not specified. If the key is encrypted a pass phrase will be
prompted for.

=item B<-passin arg>

the input file password source. For more information about the format of B<arg>
see the B<PASS PHRASE ARGUMENTS> section in L<openssl(1)|openssl(1)>.

=item B<-out filename>

This specifies the output filename to write a key to or standard output by
is not specified. If any encryption options are set then a pass phrase will be
prompted for. The output filename should B<not> be the same as the input
filename.

=item B<-passout arg>

the output file password source. For more information about the format of B<arg>
see the B<PASS PHRASE ARGUMENTS> section in L<openssl(1)|openssl(1)>.

=item B<-aes128|-aes192|-aes256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea>

These options encrypt the private key with the specified
cipher before outputting it. A pass phrase is prompted for.
If none of these options is specified the key is written in plain text. This
means that using the B<dsa> utility to read in an encrypted key with no
encryption option can be used to remove the pass phrase from a key, or by
setting the encryption options it can be use to add or change the pass phrase.
These options can only be used with PEM format output files.

=item B<-text>

prints out the public, private key components and parameters.

=item B<-noout>

this option prevents output of the encoded version of the key.

=item B<-modulus>

this option prints out the value of the public key component of the key.

=item B<-pubin>

by default a private key is read from the input file: with this option a
public key is read instead.

=item B<-pubout>

by default a private key is output. With this option a public
key will be output instead. This option is automatically set if the input is
a public key.

=item B<-engine id>

specifying an engine (by it's unique B<id> string) will cause B<req>
to attempt to obtain a functional reference to the specified engine,
thus initialising it if needed. The engine will then be set as the default
for all available algorithms.

=back

=head1 NOTES

The PEM private key format uses the header and footer lines:

 -----BEGIN DSA PRIVATE KEY-----
 -----END DSA PRIVATE KEY-----

The PEM public key format uses the header and footer lines:

 -----BEGIN PUBLIC KEY-----
 -----END PUBLIC KEY-----

=head1 EXAMPLES

To remove the pass phrase on a DSA private key:

 openssl dsa -in key.pem -out keyout.pem

To encrypt a private key using triple DES:

 openssl dsa -in key.pem -des3 -out keyout.pem

To convert a private key from PEM to DER format:

 openssl dsa -in key.pem -outform DER -out keyout.der

To print out the components of a private key to standard output:

 openssl dsa -in key.pem -text -noout

To just output the public part of a private key:

 openssl dsa -in key.pem -pubout -out pubkey.pem

=head1 SEE ALSO

L<dsaparam(1)|dsaparam(1)>, L<gendsa(1)|gendsa(1)>, L<rsa(1)|rsa(1)>,
L<genrsa(1)|genrsa(1)>

=cut


text:
package generic

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"github.com/gavincabbage/embd"
)

type led struct {
	id string

	brightness *os.File

	initialized bool
}

func NewLED(id string) embd.LED {
	return &led{id: id}
}

func (l *led) init() error {
	if l.initialized {
		return nil
	}

	var err error
	if l.brightness, err = l.brightnessFile(); err != nil {
		return err
	}

	l.initialized = true

	return nil
}

func (l *led) brightnessFilePath() string {
	return fmt.Sprintf("/sys/class/leds/%v/brightness", l.id)
}

func (l *led) openFile(path string) (*os.File, error) {
	return os.OpenFile(path, os.O_RDWR, os.ModeExclusive)
}

func (l *led) brightnessFile() (*os.File, error) {
	return l.openFile(l.brightnessFilePath())
}

func (l *led) On() error {
	if err := l.init(); err != nil {
		return err
	}

	_, err := l.brightness.WriteString("1")
	return err
}

func (l *led) Off() error {
	if err := l.init(); err != nil {
		return err
	}

	_, err := l.brightness.WriteString("0")
	return err
}

func (l *led) isOn() (bool, error) {
	l.brightness.Seek(0, 0)
	bytes, err := ioutil.ReadAll(l.brightness)
	if err != nil {
		return false, err
	}
	str := string(bytes)
	str = strings.TrimSpace(str)
	if str == "1" {
		return true, nil
	}
	return false, nil
}

func (l *led) Toggle() error {
	if err := l.init(); err != nil {
		return err
	}

	state, err := l.isOn()
	if err != nil {
		return err
	}

	if state {
		return l.Off()
	}
	return l.On()
}

func (l *led) Close() error {
	if !l.initialized {
		return nil
	}

	if err := l.brightness.Close(); err != nil {
		return err
	}

	l.initialized = false

	return nil
}


text:
package is.hail.expr.ir

import is.hail.asm4s._
import is.hail.types._
import is.hail.types.physical.stypes.{SCode, SType, SValue}
import is.hail.types.physical.stypes.interfaces._
import is.hail.types.physical.{PType, typeToTypeInfo}
import is.hail.types.virtual._
import is.hail.utils._

object BinaryOp {
  private val returnType: ((BinaryOp, Type, Type)) => Option[Type] = lift {
    case (FloatingPointDivide(), TInt32, TInt32) => TFloat64
    case (FloatingPointDivide(), TInt64, TInt64) => TFloat64
    case (FloatingPointDivide(), TFloat32, TFloat32) => TFloat32
    case (FloatingPointDivide(), TFloat64, TFloat64) => TFloat64
    case (Add() | Subtract() | Multiply() | RoundToNegInfDivide() | BitAnd() | BitOr() | BitXOr(), TInt32, TInt32) => TInt32
    case (Add() | Subtract() | Multiply() | RoundToNegInfDivide() | BitAnd() | BitOr() | BitXOr(), TInt64, TInt64) => TInt64
    case (Add() | Subtract() | Multiply() | RoundToNegInfDivide(), TFloat32, TFloat32) => TFloat32
    case (Add() | Subtract() | Multiply() | RoundToNegInfDivide(), TFloat64, TFloat64) => TFloat64
    case (LeftShift() | RightShift() | LogicalRightShift(), t@(TInt32 | TInt64), TInt32) => t
  }

  def defaultDivideOp(t: Type): BinaryOp = t match {
    case TInt32 | TInt64 => RoundToNegInfDivide()
    case TFloat32 | TFloat64 => FloatingPointDivide()
  }

  def returnTypeOption(op: BinaryOp, l: Type, r: Type): Option[Type] =
    returnType((op, l, r))

  def getReturnType(op: BinaryOp, l: Type, r: Type): Type =
    returnType((op, l, r)).getOrElse(incompatible(l, r, op))

  private def incompatible[T](lt: Type, rt: Type, op: BinaryOp): T =
    throw new RuntimeException(s"Cannot apply $op to $lt and $rt")

  def emit(cb: EmitCodeBuilder, op: BinaryOp, l: SValue, r: SValue): SValue = {
    val lt = l.st.virtualType
    val rt = r.st.virtualType

    val retCode = emit(op, lt, rt, SType.extractPrimValue(cb, l), SType.extractPrimValue(cb, r))
    val retT = getReturnType(op, lt, rt)
    primitive(retT, cb.memoizeAny(retCode, typeToTypeInfo(PType.canonical(retT))))
  }

  private[this] def emit(op: BinaryOp, lt: Type, rt: Type, l: Code[_], r: Code[_]): Code[_] =
    (lt, rt) match {
      case (TInt32, TInt32) =>
        val ll = coerce[Int](l)
        val rr = coerce[Int](r)
        op match {
          case Add() => ll + rr
          case Subtract() => ll - rr
          case Multiply() => ll * rr
          case FloatingPointDivide() => ll.toD / rr.toD
          case RoundToNegInfDivide() => Code.invokeStatic2[Math, Int, Int, Int]("floorDiv", ll, rr)
          case BitAnd() => ll & rr
          case BitOr() => ll | rr
          case BitXOr() => ll ^ rr
          case LeftShift() => ll << rr
          case RightShift() => ll >> rr
          case LogicalRightShift() => ll >>> rr
          case _ => incompatible(lt, rt, op)
        }
      case (TInt64, TInt32) =>
        val ll = coerce[Long](l)
        val rr = coerce[Int](r)
        op match {
          case LeftShift() => ll << rr
          case RightShift() => ll >> rr
          case LogicalRightShift() => ll >>> rr
          case _ => incompatible(lt, rt, op)
        }
      case (TInt64, TInt64) =>
        val ll = coerce[Long](l)
        val rr = coerce[Long](r)
        op match {
          case Add() => ll + rr
          case Subtract() => ll - rr
          case Multiply() => ll * rr
          case FloatingPointDivide() => ll.toD / rr.toD
          case RoundToNegInfDivide() => Code.invokeStatic2[Math, Long, Long, Long]("floorDiv", ll, rr)
          case BitAnd() => ll & rr
          case BitOr() => ll | rr
          case BitXOr() => ll ^ rr
          case _ => incompatible(lt, rt, op)
        }
      case (TFloat32, TFloat32) =>
        val ll = coerce[Float](l)
        val rr = coerce[Float](r)
        op match {
          case Add() => ll + rr
          case Subtract() => ll - rr
          case Multiply() => ll * rr
          case FloatingPointDivide() => ll / rr
          case RoundToNegInfDivide() => Code.invokeStatic1[Math, Double, Double]("floor", ll.toD / rr.toD).toF
          case _ => incompatible(lt, rt, op)
        }
      case (TFloat64, TFloat64) =>
        val ll = coerce[Double](l)
        val rr = coerce[Double](r)
        op match {
          case Add() => ll + rr
          case Subtract() => ll - rr
          case Multiply() => ll * rr
          case FloatingPointDivide() => ll / rr
          case RoundToNegInfDivide() => Code.invokeStatic1[Math, Double, Double]("floor", ll / rr)
          case _ => incompatible(lt, rt, op)
        }
      case (TBoolean, TBoolean) =>
        val ll = coerce[Boolean](l)
        val rr = coerce[Boolean](r)
        op match {
          case _ => incompatible(lt, rt, op)
        }

      case _ => incompatible(lt, rt, op)
    }

  val fromString: PartialFunction[String, BinaryOp] = {
    case "+" | "Add" => Add()
    case "-" | "Subtract" => Subtract()
    case "*" | "Multiply" => Multiply()
    case "/" | "FloatingPointDivide"  => FloatingPointDivide()
    case "//" | "RoundToNegInfDivide" => RoundToNegInfDivide()
    case "|" | "BitOr" => BitOr()
    case "&" | "BitAnd" => BitAnd()
    case "^" | "BitXOr" => BitXOr()
    case "<<" | "LeftShift" => LeftShift()
    case ">>" | "RightShift" => RightShift()
    case ">>>" | "LogicalRightShift" => LogicalRightShift()
  }
}

sealed trait BinaryOp {}

case class Add() extends BinaryOp {}

case class Subtract() extends BinaryOp {}

case class Multiply() extends BinaryOp {}

case class FloatingPointDivide() extends BinaryOp {}

case class RoundToNegInfDivide() extends BinaryOp {}

case class BitAnd() extends BinaryOp

case class BitOr() extends BinaryOp

case class BitXOr() extends BinaryOp

case class LeftShift() extends BinaryOp

case class RightShift() extends BinaryOp

case class LogicalRightShift() extends BinaryOp


text:
package org.scalactic.equalities

import org.scalactic.Equality

import scala.language.{higherKinds, implicitConversions}

/**
 * An [[Equality]] that allows the comparison of values nested in [[java.util.List]]s using whatever Equality is
 * in scope for the contained type.
 */
trait RecursiveJavaListEquality {
  implicit def recursiveJavaListEquality[E, JLIST[e] <: java.util.List[e]](implicit eqE: Equality[E]): Equality[JLIST[E]] =
    new Equality[JLIST[E]] {
      import collection.JavaConverters._

      val scalaEq = RecursiveSeqEquality.recursiveSeqEquality[E, Seq](eqE)
      def areEqual(seqA: JLIST[E], other: Any): Boolean = (seqA, other) match {
        case (jlistA: java.util.List[E], jlistB: java.util.List[_]) => scalaEq.areEqual(jlistA.asScala.toSeq, jlistB.asScala.toSeq)
        case _ => false
      }
    }

}

object RecursiveJavaListEquality extends RecursiveJavaListEquality


text:
"""
Author: Justin Cappos
Module: Module for persisting data (one writer, one reader).   I will persist
        data in a safe way where I can be interrupted at any point and will be
        able to get the information back.

Start date: Sept 1st, 2008
The design goals of this version are to be secure, simple, and reliable
(in that order).

Were it not for the eval / repr ugliness, I would write this in repy...
"""

# NOTE: This is intended to be safe for one reader, one writer regardless of
# when and where failures occur.   I assume this will break if there are
# multiple of either.

# BUG: How do I ensure the file is flushed to disk?   Does flush / close do it?

# the commit protocol is:
# 1) if filename does not exist and filename+'.new' exists, move
#    filename+'.new' to filename
# 2) open filename+'.new'
# 3) write the object
# 4) close the file
# 5) delete filename
# 6) move filename+'.new' to filename
#
# the reason for step 1 is in case a previous incarnation died after step 5
# but before step 6.
# the reason for having step 5 is (from the Python docs on os.rename): On
# Windows, if dst already exists, OSError will be raised even if it is a file;
# there may be no way to implement an atomic rename when dst names an existing
# file.
#
# the recovery protocol is:
# 1) try to get the ctime for filename+'.new"
# 2) try to copy filename to filename+".tmp"
# 3) if step 2 succeeded, goto step 8
# 4) if step 1 failed, goto step 1
# 5) try to copy filename+'.new' to filename+'.tmp'
# 6) if step 5 failed, goto step 1
# 7) if the ctime of filename+'.new' != the ctime we saw in step 1 goto step 1
# 8) read the contents of filename+'.tmp'
# 9) delete filename+'.tmp'
# 10) return the result read in step 8
#
# The gist of what this does is: read filename if it exists.   If not, then
# readefilename+'.new' only if it doesn't change since the last time we checked
# for the existance of filename.
#
# This is complex because I need to prevent against race conditions.   The
# problem is that it's hard to differentiate between another process that is
# doing a commit while I'm doing the recovery protocol and another process that
# died while doing the recovery protocol.   The specific case where this is a
# problem is when filename does not exist but filename+'.new' does.   A simple
# way to do recovery would be:
# 1) if filename exists, open it and return the contents
# 2) elif filename.'.new' exists, open it and return the contents
# 3) else throw an exception...
# the problem is that it may be that the other process had just completed step
# 4 of the commit protocol when we did step 1 and then may be on step 1 of the
# commit protocol when we do step 2.   We would get an empty file!
# To protect against this, I will copy the file I'm using to a temporary file
# and check the ctime of the file I use to ensure that it hasn't changed since
# I checked.

# various file information / removal / renaming routines
import os

# copy
import shutil

# AR: Determine whether we're running on Android
try:
  import android
  is_android = True
except ImportError:
  is_android = False

def _copy(orig_filename, copy_filename):
  # AR: Wrap Android-specific shutil.copy() quirks. They seem to have a problem
  # setting the file access mode bits there, and shutil.copyfile() suffices
  # for the task at hand.

  if not is_android:
    shutil.copy(orig_filename, copy_filename)
  else:
    shutil.copyfile(orig_filename, copy_filename)

# commits the given object to a file with the provided name
def commit_object(object, filename):
  # the commit protocol is:

  # 1) if filename does not exist and filename+'.new' exists, move
  #    filename+'.new' to filename
  if not os.path.exists(filename) and os.path.exists(filename+'.new'):
    os.rename(filename+'.new',filename)

  # 2) open filename+'.new'
  outobj = open(filename+'.new', "w")

  # 3) write the object
  outobj.write(repr(object))

  # 4) close the file
  outobj.flush()
  outobj.close()

  # 5) delete filename
  # it should exist unless this is our first time...
  if os.path.exists(filename):
    os.remove(filename)

  # 6) move filename+'.new' to filename
  os.rename(filename+'.new',filename)

# reads the disk version of an object from a file with the provided name
def restore_object(filename):

  # BUG FIX:   Previously I just did os.listdir('.') below.   This makes
  # this function fail if the file isn't in this directory.

  # I need to find the directory of the object.
  filedirectory = os.path.dirname(filename)

  # I need to find the filename of the object.
  filenameonly = os.path.basename(filename)

  # however, for some silly reason, this sometimes returns '' instead of '.'
  if filedirectory == '':
    filedirectory = '.'

  # I'm assuming that listdir is an atomic way that I'll be able to check for
  # the existence of filename and filename.new

  # either filename or filename+'.new' must exist (or else something is wrong)
  filelist = os.listdir(filedirectory)

  if filenameonly not in filelist and filenameonly+'.new' not in filelist:
    raise ValueError, "Filename '"+filename+"' missing."

  # the recovery protocol is:
  while True:
    # 1) try to get the ctime for filename+'.new"
    try:
      currentctime = os.path.getctime(filename+'.new')
    except OSError, e:
      if e[0] == 2: # file not found
        currentctime = None
      else:
        raise

    # 2) try to copy filename to filename+".tmp"
    try:
      _copy(filename, filename+'.tmp')
    except IOError, e:
      if e[0] == 2: # file not found
        pass
      else:
        raise
    else:
      # 3) if step 2 succeeded, goto step 8
      break

    # 4) if step 1 failed, goto step 1
    if currentctime == None:
      continue

    # 5) try to copy filename+'.new' to filename+'.tmp'
    try:
      _copy(filename+'.new', filename+'.tmp')
    except IOError, e:
      if e[0] == 2: # file not found
        # 6) if step 5 failed, goto step 1
        continue
      else:
        raise

    # 7) if the ctime of filename+'.new' != the ctime we saw in step 1 then
    #    goto step 1
    try:
      latestctime = os.path.getctime(filename+'.new')
    except OSError, e:
      if e[0] == 2: # file not found
        continue
      else:
        raise

    if latestctime != currentctime:
      continue

  # 8) read the contents of filename+'.tmp'
  readfileobj = open(filename+'.tmp')
  readdata = readfileobj.read()
  readfileobj.close()

  # 9) delete filename+'.tmp'
  os.remove(filename+'.tmp')

  # 10) return the result read in step 8
  return eval(readdata)


text:
package org.apache.syncope.core.provisioning.java;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.apache.syncope.core.persistence.api.dao.ExternalResourceDAO;
import org.apache.syncope.core.provisioning.api.ConnIdBundleManager;
import org.apache.syncope.core.provisioning.api.Connector;
import org.apache.syncope.core.spring.ApplicationContextProvider;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Transactional("Master")
public class ConnectorManagerTest extends AbstractTest {

    @Autowired
    private ConnIdBundleManager connIdBundleManager;

    @Autowired
    private ExternalResourceDAO resourceDAO;

    private DefaultConnectorManager connManager;

    @BeforeEach
    public void before() {
        connManager = new DefaultConnectorManager(connIdBundleManager, null, resourceDAO, null, null, null);

        // Remove any other connector instance bean set up by standard ConnectorManager.load()
        connManager.unload();
    }

    @Test
    public void load() {
        connManager.load();

        // only consider local connector bundles
        long expected = resourceDAO.findAll().stream().
                filter(resource -> resource.getConnector().getLocation().startsWith("file")).count();

        assertEquals(expected,
                ApplicationContextProvider.getBeanFactory().getBeanNamesForType(Connector.class, false, true).length);
    }
}


text:
package io.rsocket.exceptions;

public class InvalidSetupException extends SetupException {
  public InvalidSetupException(String message) {
    super(message);
  }
}


text:
"""Change the keys in the packet through a dictionary"""

import logging

import pypes.component

log = logging.getLogger(__name__)

class NameChanger(pypes.component.Component):
    """
    The run method will get the keys from the input packet and set them back
    in the packet with the new key specified by the value in the init
    dictionary.

    """

    # defines the type of component we're creating.
    __metatype__ = 'TRANSFORMER'

    def __init__(self, dictionary):
        # initialize parent class
        pypes.component.Component.__init__(self)

        # Optionally add/remove component ports
        # self.remove_output('out')
        self._dictionary = dictionary

        # log successful initialization message
        log.debug('Component Initialized: %s', self.__class__.__name__)

    def run(self):
        # Define our components entry point
        while True:
            packet = self.receive("in")
            if packet is None:
                self.yield_ctrl()
                continue
            try:
                for key, value in self._dictionary.items():
                    data = packet.get(key)
                    packet.delete(key)
                    packet.set(value, data)
            except:
                log.error('Component Failed: %s',
                          name, exc_info=True)
            self.send("out", packet)
            # yield the CPU, allowing another component to run
            self.yield_ctrl()


text:
define({
  "_widgetLabel": "Navigasi Jangkauan",
  "previousExtent": "Jangkauan sebelumnya",
  "nextExtent": "Jangkauan selanjutnya"
});