text:
'use strict';

(function(pagecode) { //eslint-disable-line wrap-iife
  pagecode(window.jQuery, window, document, R6MMainData, R6MMainRender, R6MMainControls, R6MMainDrawing, R6MMainSelectMaps, R6MMainSessions, R6MHelpers, R6MLangTerms);
}(function($, window, document, R6MMainData, R6MMainRender, R6MMainControls, R6MMainDrawing, R6MMainSelectMaps, R6MMainSessions, R6MHelpers, R6MLangTerms, undefined) {
  var $mapWrappers,
    $mapPanelWrappers,
    $mapMains,
    $mapElements,
    $svgMapWrappers,
    $mapPanelLabels,
    $drawingMarkerWrappers,
    $navLogo,
    $body,
    $mainNav,
    $sessionsDialog,
    SHOW_MAP = 'show-map',
    SHOW_SELECT_MAP = 'show-select-map',
    HASH_SPLIT_CHAR = '/',
    DEFAULT_LOS_OPACITY = 0.15,
    UPDATE_HIGHLIGHT = {
      LOCALSTORAGE_READ_STRING: 'feb2017updateread', // set in update html page
      CUTOFF_TIME_MS: 1489536000000 //March 15 2017
    };

  $(function() { // equivanelt to $(document).ready() - but a bit faster
    setPageElements();
    R6MMainRender.setupMapPanels($mapPanelWrappers, 4);
    setMapElements();
    R6MHelpers.tryLoadStartingLanguage(R6MLangTerms.tryLoadLanguage);
    R6MHelpers.tryChangeDirection(R6MLangTerms.getLoadedDirection());
    setupMenu();
    setupSelectMap();
    R6MMainControls.maps.populate(R6MMainData.getMapData());

    $sessionsDialog = $('#sessions-dialog');
    R6MMainSessions.createJoinDialog.setup($sessionsDialog);

    setupEvents();
    $navLogo.on('click', toggleShowSelectMap);
    tryLoadMenuOptions();

    R6MMainControls.setupPanZoom($mapMains, $mapElements);

    if (trySelectBookmarkedMap()) {
      loadMap();
      trySelectBookmarkedObjective();
      trySelectBookmarkedFloor();
      showMap();
    } else {
      showSelectMap();
      document.title = R6MLangTerms.terms.general.pageTitleStart;
    }

    setTimeout(function() {
      $body.removeClass('loading');
    }, 10);
  });

  var checkIfMapLoaded = function checkIfMapLoaded() {
    return $body.attr('loaded-map');
  };

  var closeMenu = function closeMenu() {
    getMenuApi().close();
  };

  var isCamera = function isCamera(element) {
    return element.hasClass('camera');
  };

  var isShowingMap = function isShowingMap() {
    return $body.hasClass(SHOW_MAP);
  };

  var getCameraIdFromEvent = function getCameraIdFromEvent(event) {
    return $(event.target).data('camera-id');
  };

  var getCameraLosOpacity = function getCameraLosOpacity() {
    var opacity = localStorage.getItem('cameralosopacity');

    if (opacity) {
      return opacity;
    } else {
      return DEFAULT_LOS_OPACITY;
    }
  };

  var getHashArgs = function getHashArgs() {
    return window.location.hash.substr(1).split(HASH_SPLIT_CHAR);
  };

  var getLoadedMapKey = function getLoadedMapKey() {
    return $('body').attr('loaded-map');
  };

  var getMenuApi = function getMenuApi() {
    return $('#mmenu-menu').data( 'mmenu' );
  };

  var getResetDimensions = function getResetDimensions() {
    var currentMapKey = R6MMainControls.maps.get(),
      zoomPoints = {
        topLeft: { top: -180, left: -312 }, // default
        bottomRight: { top: 180, left: 312 }
      };

    if (currentMapKey) {
      zoomPoints = $.extend(
        zoomPoints,
        R6MMainData.getMapData()[currentMapKey].zoomPoints
      );
    }
    var zoomWidth = zoomPoints.bottomRight.left - zoomPoints.topLeft.left,
      zoomHeight = zoomPoints.bottomRight.top - zoomPoints.topLeft.top,
      centerTop = Math.round(zoomPoints.bottomRight.top - (zoomHeight / 2)),
      centerLeft = Math.round(zoomPoints.topLeft.left + (zoomWidth / 2)),
      panelWidth = $mapWrappers.width(),
      panelHeight = $mapWrappers.height(),
      navHeight = $mainNav.height(),
      paddingWidth = Math.min(panelHeight * 0.1, navHeight),
      paddingHeight = Math.min(panelHeight * 0.1, navHeight * 2);

    panelWidth = panelWidth - paddingWidth;
    panelHeight = panelHeight - paddingHeight;
    var result = {
      debugZoomWidth: zoomWidth,
      debugZoomHeight: zoomHeight,
      centerTop: centerTop,
      centerLeft: centerLeft,
      debugPanelWidth: panelWidth,
      debugPanelHeight: panelHeight,
      debugPaddingWidth: paddingWidth,
      debugPaddingHeight: paddingHeight,
      zoomValue: Math.max(
        Math.min(
          1,
          panelWidth / zoomWidth,
          panelHeight / zoomHeight
        ),
        0.5
      )
    };

    return result;
  };

  var handleCameraIn = function handleCameraHoverIn(event) {
    var cameraId = getCameraIdFromEvent(event);

    $('.camera-los.camera-' + cameraId).addClass('show-more');
  };

  var handleCameraOut = function handleCameraHoverOut(event) {
    var cameraId = getCameraIdFromEvent(event);

    $('.camera-los.camera-' + cameraId).removeClass('show-more');
  };

  var handleFloorChange = function handleFloorChange() {
    sendFloorSelectAnalyticsEvent();
    showSelectedFloor();
    updateUrl();
    R6MMainDrawing.refreshPings(); // hacky drawing module for now
  };

  var handleLangChange = function handleLangChange(event) {
    var newLang = $(event.target).data('lang');

    event.preventDefault();

    R6MLangTerms.tryLoadLanguage(newLang);
    localStorageSetItem('language', newLang);

    if (R6MHelpers.tryChangeDirection(R6MLangTerms.getLoadedDirection())) {
      location.reload();
    }

    setupSelectMap();
    R6MMainControls.maps.populate(R6MMainData.getMapData());
    setupEvents();
    tryLoadMenuOptions();
    updateTitle();
    setupMenu();

    if (checkIfMapLoaded()) {
      loadMap();
    }
  };

  var handleEnableScreenshotsChange = function handleEnableScreenshotsChange(value) {
    localStorageSetItem('enablescreenshots', value);
    R6MMainRender.setEnableScreenshots($mapWrappers, value);
  };

  var handleMapChange = function handleMapChange() {
    sendMapSelectAnalyticsEvent();
    loadMap();
    updateUrl();
  };

  var handleMapPanelCountChange = function handleMapPanelCountChange(numPanels) {
    sendMapPanelCountEvent(numPanels);
    setMapPanelCount(numPanels);
  };

  var handleMenuClick = function handleMenuClick(e) {
    var menuApi = getMenuApi();

    e.preventDefault();
    menuApi.open();
    R6MMainControls.removeLatestUpdateHighlight(200);
  };

  var handleObjectiveChange = function handleObjectiveChange() {
    sendObjectiveSelectAnalyticsEvent();
    showSelectedObjective();
    updateUrl();
  };

  var hideSelectMap = function hideSelectMap() {
    $body.removeClass(SHOW_SELECT_MAP);
  };

  var localStorageSetItem = function localStorageSetItem(index, value) {
    try {
      localStorage.setItem(index, value);
    } catch (e) {
      //guarding against safari in private browsing mode
    }
  };

  var loadMap = function loadMap() {
    var currentlySelectedMap = R6MMainControls.maps.get(),
      mapData = R6MMainData.getMapData();

    R6MMainControls.objectives.populate(mapData[currentlySelectedMap].objectives);
    R6MMainControls.floors.populate(mapData[currentlySelectedMap].floors);
    R6MMainRender.renderMap(mapData[currentlySelectedMap], $mapWrappers, $mapElements, $svgMapWrappers, $mapPanelLabels);
    if (!DEV_MODE) {
      R6MMainControls.pan.reset($mapMains, getResetDimensions);
      R6MMainControls.zoom.reset($mapMains, getResetDimensions);
    }

    setupCameraScreenshots();
    setupCameraLos();
    showSelectedFloor();
    showSelectedObjective();

    setLoadedMapKey(currentlySelectedMap);
    $navLogo.addClass('enabled');
    updateTitle();

    R6MMainDrawing.setup(
      $mapMains,
      $drawingMarkerWrappers,
      isCamera,
      R6MMainRender.SVG_DIM
    );
  };

  var outputCoordinates = function outputCoordinates(e) {
    if (!DEV_MODE) {
      return;
    }

    var warning = R6MMainControls.zoom.isZoomed() ? ' Warning, currently zoomed, coordinates are not accurate for CSS.' : '';

    console.log('SINGLE LINE TEXT:');
    console.log(
      'top: ' + Math.round(e.pageY - $mapElements.offset().top + 14) + ', ' +
      'left: ' + Math.round(e.pageX - $mapElements.offset().left)
    );

    console.log('REGULAR/DOUBLE LINE TEXT:');
    console.log(
      'top: ' + Math.round(e.pageY - $mapElements.offset().top) + ', ' +
      'left: ' + Math.round(e.pageX - $mapElements.offset().left) +
      warning
    );
  };

  var removeHashFromUrl = function removeHashFromUrl() {
    var scrollV, scrollH, loc = window.location;

    if ('pushState' in history) {
      history.pushState('', document.title, loc.pathname + loc.search);
    } else {
      // Prevent scrolling by storing the page's current scroll offset
      scrollV = document.body.scrollTop;
      scrollH = document.body.scrollLeft;

      loc.hash = '';
      // Restore the scroll offset, should be flicker free
      document.body.scrollTop = scrollV;
      document.body.scrollLeft = scrollH;
    }
  };

  var saveLockPanningOption = function saveLockPanningOption(value) {
    localStorageSetItem('lockpanning', value);
    if (value) {
      R6MMainControls.pan.reset($mapMains, getResetDimensions);
    }
  };

  var sendControlAnalyticsEvent = function sendControlAnalyticsEvent(control, value) {
    ga('send', {
      hitType: 'event',
      eventCategory: 'Controls',
      eventAction: control,
      eventLabel: value
    });
  };

  var sendFloorSelectAnalyticsEvent = function sendFloorSelectAnalyticsEvent() {
    sendControlAnalyticsEvent('Floor', R6MMainControls.floors.get());
  };

  var sendMapPanelCountEvent = function sendMapPanelCountEvent(panelCount) {
    sendControlAnalyticsEvent('PanelsCount', panelCount);
  };

  var sendMapSelectAnalyticsEvent = function sendMapSelectAnalyticsEvent() {
    sendControlAnalyticsEvent('Map', R6MMainControls.maps.get());
  };

  var sendObjectiveSelectAnalyticsEvent = function sendObjectiveSelectAnalyticsEvent() {
    sendControlAnalyticsEvent('Objective', R6MMainControls.objectives.get());
  };

  var sendRoomLabelEvent = function sendRoomLabelEvent(style) {
    sendControlAnalyticsEvent('RoomLabel', style);
  };

  var setLoadedMapKey = function setLoadedMapKey(mapKey) {
    $body.attr('loaded-map', mapKey);
  };

  var setMapElements = function setMapElements() {
    $mapWrappers = $('.map-wrapper');
    $mapMains = $mapWrappers.find('.map-main');
    $mapElements = $mapMains.find('.map-elements');
    $svgMapWrappers = $mapMains.find('.svg-wrapper.map');
    $mapPanelLabels = $('.map-panel-label');
    $drawingMarkerWrappers = $mapMains.find('.svg-wrapper.drawing-markers');
  };

  var setMapPanelCount = function setMapPanelCount(numPanels) {
    localStorageSetItem('mappanelcount', numPanels);
    $mapPanelWrappers.attr('map-panel-count', numPanels);

    $.each($mapMains, function (index, map) {
      if (index < numPanels) {
        $(map).css('display', 'block');
        R6MMainControls.zoom.enable($(map));
      } else {
        $(map).css('display', 'none');
        R6MMainControls.zoom.disable($(map));
      }
    });

    R6MMainControls.pan.reset($mapMains, getResetDimensions);
    R6MMainControls.zoom.reset($mapMains, getResetDimensions);

    showSelectedFloor();
  };

  var setPageElements = function setPageElements() {
    $mapPanelWrappers = $('#map-panel-wrapper');
    $navLogo = $('#nav-logo');
    $body = $('body');
    $mainNav = $('#main-nav');
  };

  var setRoomLabelStyle = function setRoomLabelStyle(style) {
    R6MMainRender.setRoomLabelStyle($mapElements, style);
    localStorageSetItem('roomlabelstyle', style);
    sendRoomLabelEvent(style);
  };

  var setupCameraLos = function setupCameraLos() {
    $('.camera').on('mouseenter', handleCameraIn);
    $('.camera').on('mouseleave', handleCameraOut);
    updateLosOpacity(getCameraLosOpacity());
  };

  var setupCameraScreenshots = function setupCameraScreenShots(){
    $('a.camera').fancybox({
      padding: 0,
      helpers: {
        overlay: {
          css: {
            background: 'rgba(48,113,169, 0.3)'
          }
        }
      }
    });
  };

  var setupEvents = function setupEvents() {
    $mapMains.on('click', outputCoordinates);
    R6MMainControls.objectives.setup(handleObjectiveChange);
    R6MMainControls.maps.setup(handleMapChange);
    R6MMainControls.floors.setup(handleFloorChange, showSelectedFloor);
    R6MMainControls.roomLabelStyles.setup(setRoomLabelStyle);
    R6MMainControls.mapPanels.setup(handleMapPanelCountChange);
    R6MMainControls.pan.setupLockOption(saveLockPanningOption);
    R6MMainControls.enableScreenshots.setup(handleEnableScreenshotsChange);
    R6MMainControls.menu.setupSelectMaps(showSelectMap, closeMenu);
    R6MMainControls.menu.setupFullScreen();
    R6MMainControls.sessions.setup(R6MMainSessions.createJoinDialog.getOpenFn($sessionsDialog), closeMenu);

    $(window).on('orientationchange', function() {
      R6MMainControls.pan.reset($mapMains, getResetDimensions);
      R6MMainControls.zoom.reset($mapMains, getResetDimensions);
    });
  };

  var showMap = function showMap() {
    hideSelectMap();
    $body.addClass(SHOW_MAP);
    updateUrl();
    updateTitle();
  };

  var showSelectMap = function showSelectMap() {
    $body.removeClass(SHOW_MAP);
    $body.addClass(SHOW_SELECT_MAP);
    updateUrl();
    updateTitle();
  };

  var setupMenu = function setupMenu() {
    var $menuLink = $('#mmenu-link'),
      useRtl = (R6MLangTerms.getLoadedDirection() === 'RTL');

    R6MMainControls.menu.setup(R6MMainRender.roomLabelStyles, showUpdateLinkHighlighted);

    var foo = $('#mmenu-menu').mmenu({
      offCanvas: {
        position: useRtl ? 'left' : 'right',
        pageSelector: '#mmenu-page'
      },
      extensions: ['pagedim'],
      rtl: {
        use: useRtl
      }
    });

    $menuLink.click(handleMenuClick);
    if (showUpdateLinkHighlighted()) {
      R6MMainControls.highlightControl($menuLink);
      R6MMainControls.unhighlightControl($menuLink, 1000);
    }

    $('#lang-choices').on('click','button', handleLangChange);

    R6MMainControls.setupLosOpacity(updateLosOpacity, getCameraLosOpacity(), DEFAULT_LOS_OPACITY);
  };

  var setupSelectMap = function seteupSelectMap() {
    R6MMainSelectMaps.setup(
      $('#select-map-grid'),
      $('#select-map-heading'),
      $mainNav,
      R6MMainData.getMapData(),
      switchToMap,
      tryHideMapSelect
    );
  };

  var showUpdateLinkHighlighted = function showUpdateLinkHighlighted() {
    var date = new Date();

    return (
      (!localStorage.getItem(UPDATE_HIGHLIGHT.LOCALSTORAGE_READ_STRING)) &&
      (date.getTime() < UPDATE_HIGHLIGHT.CUTOFF_TIME_MS)
    );
  };

  var showSelectedFloor =  function showSelectedFloor() {
    var minMadFlorIndexes = R6MMainControls.floors.getMinMaxIndex();

    R6MMainRender.showFloor(
      R6MMainControls.floors.get(),
      $mapPanelWrappers,
      $mapWrappers,
      minMadFlorIndexes.min,
      minMadFlorIndexes.max
    );
  };

  var showSelectedObjective =  function showSelectedObjective() {
    R6MMainRender.showObjective(R6MMainControls.objectives.get(), $mapElements);
  };

  var switchToMap = function switchToMap(mapArg) {
    if (R6MMainControls.maps.trySelect(mapArg)) {
      hideSelectMap();
      setTimeout(function() {
        loadMap();
        showMap();
      },1);
    }
  };

  var toggleShowSelectMap = function toggleShowSelectMap(event) {
    var menuApi = getMenuApi();

    event.preventDefault();
    if (isShowingMap()) {
      showSelectMap();
      menuApi.close();
    } else if (checkIfMapLoaded()) {
      showMap();
      menuApi.close();
    }
  };

  var tryHideMapSelect = function tryHideMapSelect() {
    if (checkIfMapLoaded()) {
      showMap();
    }
  };

  var tryLoadEnableScreenshotsOption = function tryLoadEnableScreenshotsOption() {
    var enableScreenshotsOption = localStorage.getItem('enablescreenshots');

    if (enableScreenshotsOption !== null) {
      R6MMainControls.enableScreenshots.set(enableScreenshotsOption);
      handleEnableScreenshotsChange((enableScreenshotsOption === 'true'));
    }
  };

  var tryLoadLockPanningOption = function tryLoadLockPanningOption() {
    var lockPanningOption = localStorage.getItem('lockpanning');

    if (lockPanningOption !== null) {
      R6MMainControls.pan.setLockOption(lockPanningOption);
    }
  };

  var tryLoadMapPanelCount = function tryLoadMapPanelCount() {
    var mapPanelCount = localStorage.getItem('mappanelcount');

    if (!mapPanelCount) {
      var $window = $(window);

      mapPanelCount = (
        ($window.width() > 1000) || ($window.height() > 1000)
      ) ? 2 : 1;
    }
    R6MMainControls.mapPanels.trySelect(mapPanelCount);
    setMapPanelCount(mapPanelCount);
  };

  var tryLoadMenuOptions = function tryLoadMenuOptions() {
    tryEnableSessionFeature();
    tryLoadMapPanelCount();
    tryLoadLockPanningOption();
    tryLoadRoomLabelStyle();
    tryLoadEnableScreenshotsOption();
  };

  var tryLoadRoomLabelStyle = function tryLoadRoomLabelStyle() {
    var style = localStorage.getItem('roomlabelstyle');

    if (style) {
      R6MMainControls.roomLabelStyles.trySelect(style);
      R6MMainRender.setRoomLabelStyle($mapElements, style);
    }
  };

  var trySelectBookmarkedMap = function trySelectBookmarkedMap() {
    var hashArgs = getHashArgs(),
      mapArg = hashArgs[0];

    return R6MMainControls.maps.trySelect(mapArg);
  };

  var trySelectBookmarkedObjective = function trySelectBookmarkedObjective() {
    var hashArgs = getHashArgs(),
      objectiveArg = hashArgs[2];

    if (R6MMainControls.objectives.trySelect(objectiveArg)) {
      showSelectedObjective();
    }
  };

  var trySelectBookmarkedFloor = function trySelectBookmarkedFloor() {
    var hashArgs = getHashArgs(),
      floorArg = hashArgs[1];

    if (R6MMainControls.floors.trySelect(floorArg)) {
      showSelectedFloor();
    }
  };

  var tryEnableSessionFeature = function tryEnableSessionFeature() {
    if (R6MHelpers.queryString('sessions')) {
      R6MMainControls.sessions.enable();
    }
  };

  var updateUrl = function updateUrl() {
    if (isShowingMap()) {
      var hashText = '';

      hashText += '' + R6MMainControls.maps.get();
      hashText += HASH_SPLIT_CHAR + R6MMainControls.floors.get();
      hashText += HASH_SPLIT_CHAR + R6MMainControls.objectives.get();
      window.location.hash = hashText;
    } else {
      removeHashFromUrl();
    }
  };

  var updateLosOpacity = function updateLosOpacity(opacity) {
    var $cameraLines = $('.camera-los');

    localStorageSetItem('cameralosopacity', opacity);
    $cameraLines.css('opacity', opacity);
    $cameraLines.removeClass('opacity-105');
    $cameraLines.removeClass('opacity-110');
    if (opacity == 1.05) {
      $cameraLines.addClass('opacity-105');
    } else if (opacity == 1.10) {
      $cameraLines.addClass('opacity-110');
    }
  };

  var updateTitle = function updateTitle() {
    document.title = isShowingMap() ?
      R6MLangTerms.terms.general.pageTitle.replace(
        '{mapName}',
        R6MMainData.getMapData()[getLoadedMapKey()].name
      ) :
      R6MLangTerms.terms.general.pageTitleSelectMap;
  };
}));


text:
using PGFPlots
import JSON

case = ARGS[1]
case_kind = ARGS[2]
string_split = split(case, "_")
case_number = parse(Int, string_split[1])
case_type = string_split[2]

k_max = 0
if case_number == 24
    if case_kind == "det"
        k_max = 38
    else
        k_max = 20
    end
else
    if case_kind == "det"
        k_max = 20
    else
        k_max = 10
    end
end

k_values = collect(2:k_max)

dc_load_shed = zeros(length(k_values))
dc_expected_load_shed = zeros(length(k_values))
dc_times = zeros(length(k_values))
dc_iterations = zeros(length(k_values))
dc_ac_load_shed = zeros(length(k_values))
dc_expected_ac_load_shed = zeros(length(k_values))

soc1_load_shed = zeros(length(k_values))
soc1_expected_load_shed = zeros(length(k_values))
soc1_times = zeros(length(k_values))
soc1_iterations = zeros(length(k_values))
soc1_ac_load_shed = zeros(length(k_values))
soc1_expected_ac_load_shed = zeros(length(k_values))

soc2_load_shed = zeros(length(k_values))
soc2_times = zeros(length(k_values))
soc2_iterations = zeros(length(k_values))
soc2_ac_load_shed = zeros(length(k_values))

for k in 2:k_max
    if case_type == "normal"
        file = string(case_kind, "_", k, "_", case_number, ".json")
    else
        file = string(case_kind, "_", k, "_", case_number, "_", case_type, ".json")
    end
    solution = JSON.parsefile(file)["solution"]
    dc_load_shed[k-1] = solution[1]["load_shed"]
    dc_expected_load_shed[k-1] = solution[1]["expected_load_shed"]
    dc_ac_load_shed[k-1] = (typeof(solution[1]["ac_load_shed"]) == Void) ? dc_load_shed[k-1] : solution[1]["ac_load_shed"]
    dc_expected_ac_load_shed[k-1] = (typeof(solution[1]["expected_ac_load_shed"]) == Void) ? dc_load_shed[k-1] : solution[1]["expected_ac_load_shed"]
    dc_times[k-1] = solution[1]["time"]
    dc_iterations[k-1] = solution[1]["iterations"]

    soc1_load_shed[k-1] = solution[2]["load_shed"]
    soc1_expected_load_shed[k-1] = solution[2]["expected_load_shed"]
    soc1_ac_load_shed[k-1] = (typeof(solution[2]["ac_load_shed"]) == Void) ? soc1_load_shed[k-1] : solution[2]["ac_load_shed"]
    soc1_expected_ac_load_shed[k-1] = (typeof(solution[2]["expected_ac_load_shed"]) == Void) ? soc1_load_shed[k-1] : solution[2]["expected_ac_load_shed"]
    soc1_times[k-1] = solution[2]["time"]
    soc1_iterations[k-1] = solution[2]["iterations"]

    #=
    soc2_load_shed[k-1] = solution[3]["load_shed"]
    soc2_ac_load_shed[k-1] = (typeof(solution[3]["ac_load_shed"]) == Void) ? soc2_load_shed[k-1] : solution[3]["ac_load_shed"]
    soc2_times[k-1] = solution[3]["time"]
    soc2_iterations[k-1] = solution[3]["iterations"]
    =#
end

plt = Axis([
            Plots.Linear(k_values, dc_load_shed*100, markSize=0.5, legendentry=L"DC"),
            Plots.Linear(k_values, soc1_load_shed*100, markSize=0.5, legendentry=L"SOC"),
            Plots.Linear(k_values, dc_ac_load_shed*100, markSize=0.5, legendentry=L"DC(AC)"),
            Plots.Linear(k_values, soc1_ac_load_shed*100, markSize=0.5, legendentry=L"SOC(AC)"),
            #Plots.Linear(k_values, soc2_load_shed, markSize=0.5, legendentry=L"soc-ac")
           ],
           xlabel="k value", title="objective values", xmin=0, xmax=k_values[length(k_values)]+1, legendPos="south east")

save("objective_$(case_number)_$(case_type)_$(case_kind).pdf", plt)

plt = Axis([
            Plots.Linear(k_values, dc_expected_load_shed*100, markSize=0.5, legendentry=L"DC"),
            Plots.Linear(k_values, soc1_expected_load_shed*100, markSize=0.5, legendentry=L"SOC"),
            Plots.Linear(k_values, dc_expected_ac_load_shed*100, markSize=0.5, legendentry=L"DC(AC)"),
            Plots.Linear(k_values, soc1_expected_ac_load_shed*100, markSize=0.5, legendentry=L"SOC(AC)"),
            #Plots.Linear(k_values, soc2_load_shed, markSize=0.5, legendentry=L"soc-ac")
           ],
           xlabel="k value", title="expected values", xmin=0, xmax=k_values[length(k_values)]+1, legendPos="north east")

save("expected_objective_$(case_number)_$(case_type)_$(case_kind).pdf", plt)

plt = Axis([
            Plots.Linear(k_values, dc_iterations, markSize=0.5, legendentry=L"DC"),
            Plots.Linear(k_values, soc1_iterations, markSize=0.5, legendentry=L"SOC"),
            #Plots.Linear(k_values, soc2_iterations, markSize=0.5, legendentry=L"soc-ac")
           ],
           xlabel="k value", title="iteration count", xmin=0, xmax=k_values[length(k_values)]+1, legendPos="north east")

save("iteration_$(case_number)_$(case_type)_$(case_kind).pdf", plt)

plt = Axis([
            Plots.Linear(k_values, dc_times, markSize=0.5, legendentry=L"DC"),
            Plots.Linear(k_values, soc1_times, markSize=0.5, legendentry=L"SOC"),
            #Plots.Linear(k_values, soc2_times, markSize=0.5, legendentry=L"soc-ac")
           ],
           xlabel="k value", title="time taken (seconds)", xmin=0, xmax=k_values[length(k_values)]+1, legendPos="north east")

save("time_$(case_number)_$(case_type)_$(case_kind).pdf", plt)

redpajama_set_name: RedPajamaGithub


text:
#ifndef KEYFROGCONFIGURATION_H
#define KEYFROGCONFIGURATION_H

#include "FilterConfig.h"
#include "Options.h"
#include <string>

namespace keyfrog {
    /**
     * @author Sebastian Gniazdowski
     */
    class Configuration {
        std::string m_sqliteDbFilePath;
        std::string m_homeDir;
        std::string m_configPath;

        // Configuration packs
        FilterConfig m_filterConfig;
        Options m_options;

        public:
        Configuration();
        ~Configuration();

        // Options pack
        Options & options() {
            return m_options;
        }
        // Filter config pack
        FilterConfig & filterConfig() {
            return m_filterConfig;
        }
        // Sqlite db path
        std::string & sqliteDbFilePath() {
            return m_sqliteDbFilePath;
        }
        // Home dir
        std::string & homeDir() {
            return m_homeDir;
        }
        // Configuration path
        std::string & configPath() {
            return m_configPath;
        }

        //protected:
        // Home dir
        void setHomeDir(std::string & theVal) {
            m_homeDir = theVal;
        }
        // Configuration path
        void setConfigPath(std::string & theVal) {
            m_configPath = theVal;
        }
        // Sqlite db path
        void setSqliteDbFilePath(const std::string & sqliteDbFilePath) {
            m_sqliteDbFilePath = sqliteDbFilePath;
        }
        // Filter config pack
        void setFilterConfig(const FilterConfig & theValue) {
            m_filterConfig = theValue;
        }
        // Options pack
        void setOptions(const Options & theValue) {
            m_options = theValue;
        }
    };
}
#endif


text:
package org.fabric3.samples.bigbank.client.ws.loan;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for apply complex type.
 *

 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <complexType name="apply">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="arg0" type="{http://loan.api.bigbank.samples.fabric3.org/}loanRequest" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "apply", propOrder = {
        "arg0"
})
public class Apply {

    protected LoanRequest arg0;

    /**
     * Gets the value of the arg0 property.
     *
     * @return possible object is {@link LoanRequest }
     */
    public LoanRequest getArg0() {
        return arg0;
    }

    /**
     * Sets the value of the arg0 property.
     *
     * @param value allowed object is {@link LoanRequest }
     */
    public void setArg0(LoanRequest value) {
        this.arg0 = value;
    }

}


text:
@interface BaseNetManager : NSObject

+(id)GET:(NSString *)path paramaters:(NSDictionary *)paramaters completionHandler:(void(^)(id responseObj,NSError *error))completionHandler;

@end


text:
<?php

namespace Test\DoctrineBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */

class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $name;
}


text:
package com.spotify.heroic;

import com.google.common.collect.ImmutableSet;
import com.spotify.heroic.ingestion.Ingestion;
import com.spotify.heroic.ingestion.IngestionManager;
import com.spotify.heroic.metric.MetricCollection;
import com.spotify.heroic.metric.QueryResult;
import com.spotify.heroic.metric.ShardedResultGroup;
import eu.toolchain.async.AsyncFuture;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.spotify.heroic.test.Data.points;
import static org.junit.Assert.assertEquals;

public class ClusterQueryIT extends AbstractLocalClusterIT {
    @Test
    public void basicQueryTest() throws Exception {
        final QueryResult result = query("sum(10ms)");

        final Set<MetricCollection> m = result
            .getGroups()
            .stream()
            .map(ShardedResultGroup::getMetrics)
            .collect(Collectors.toSet());

        assertEquals(ImmutableSet.of(points().p(10, 2D).p(20, 4D).p(30, 2D).build()), m);
    }

    @Test
    public void distributedQueryTest() throws Exception {
        final QueryResult result = query("sum(10ms) by shared");

        final Set<MetricCollection> m = result
            .getGroups()
            .stream()
            .map(ShardedResultGroup::getMetrics)
            .collect(Collectors.toSet());

        assertEquals(ImmutableSet.of(points().p(10, 2D).p(20, 4D).p(30, 2D).build()), m);
    }

    @Test
    public void distributedDifferentQueryTest() throws Exception {
        final QueryResult result = query("sum(10ms) by diff");

        final Set<MetricCollection> m = result
            .getGroups()
            .stream()
            .map(ShardedResultGroup::getMetrics)
            .collect(Collectors.toSet());

        assertEquals(ImmutableSet.of(points().p(10, 1D).p(30, 2D).build(),
            points().p(10, 1D).p(20, 4D).build()), m);
    }

    @Test
    public void filterQueryTest() throws Exception {
        final QueryResult result = query("average(10ms) by * | topk(2) | bottomk(1) | sum(10ms)");

        final Set<MetricCollection> m = result
            .getGroups()
            .stream()
            .map(ShardedResultGroup::getMetrics)
            .collect(Collectors.toSet());

        assertEquals(ImmutableSet.of(points().p(10, 1D).p(20, 4D).build()), m);
    }

    @Test
    public void cardinalityTest() throws Exception {
        final QueryResult result = query("cardinality(10ms)");

        final Set<MetricCollection> m = result
            .getGroups()
            .stream()
            .map(ShardedResultGroup::getMetrics)
            .collect(Collectors.toSet());

        assertEquals(ImmutableSet.of(points().p(10, 1D).p(20, 1D).p(30, 1D).p(40, 0D).build()), m);
    }

    @Test
    public void cardinalityWithKeyTest() throws Exception {
        // TODO: support native booleans in expressions
        final QueryResult result = query("cardinality(10ms, method=hllp(includeKey=\"true\"))");

        final Set<MetricCollection> m = result
            .getGroups()
            .stream()
            .map(ShardedResultGroup::getMetrics)
            .collect(Collectors.toSet());

        assertEquals(ImmutableSet.of(points().p(10, 2D).p(20, 1D).p(30, 1D).p(40, 0D).build()), m);
    }

    @Override
    protected List<AsyncFuture<Ingestion>> setupWrites(
        final List<IngestionManager> ingestion
    ) {
        final List<AsyncFuture<Ingestion>> writes = new ArrayList<>();

        final IngestionManager m1 = ingestion.get(0);
        final IngestionManager m2 = ingestion.get(1);

        writes.add(m1
            .useDefaultGroup()
            .write(new Ingestion.Request(s1, points().p(10, 1D).p(30, 2D).build())));
        writes.add(m2
            .useDefaultGroup()
            .write(new Ingestion.Request(s2, points().p(10, 1D).p(20, 4D).build())));

        return writes;
    }
}


text:
<?php

defined('_JEXEC') or die;
?>

		<?php echo JText::_('COM_MAILTO_EMAIL_SENT'); ?>

		<a href="javascript: void window.close()" title="<?php echo JText::_('COM_MAILTO_CLOSE_WINDOW'); ?>">


text:
define([
	'knockout',
	'./http',
    'appConfig',
], function (
	ko,
	httpService,
	config,
) {
	const servicePath = config.webAPIRoot + 'reusable';

	const PARAMETER_TYPE = {
		CONCEPT_SET: 'Concept Set',
	};

	function list() {
		return httpService
			.doGet(servicePath + '?size=10000')
			.then(res => res.data);
	}

	function load(id) {
		return httpService
			.doGet(`${servicePath}/${id}`)
			.then(res => res.data);
	}

	function create(design) {
		design.data = ko.toJSON({
			type: design.type(),
			parameters: design.parameters(),
			conceptSets: design.conceptSets(),
			criteriaGroupExpression: design.criteriaGroupExpression,
			initialEventExpression: design.initialEventExpression,
			censoringEventExpression: design.censoringEventExpression,
		});
		return request = httpService.doPost(servicePath, design).then(res => res.data);
	}

	function exists(name, id) {
		return httpService.doGet(`${servicePath}/${id}/exists?name=${name}`).then(res => res.data);
	}

	function save(id, design) {
		design.data = ko.toJSON({
			type: design.type(),
			parameters: design.parameters(),
			conceptSets: design.conceptSets(),
			criteriaGroupExpression: design.criteriaGroupExpression,
			initialEventExpression: design.initialEventExpression,
			censoringEventExpression: design.censoringEventExpression,
		});
		return httpService.doPut(`${servicePath}/${id}`, design).then(res => res.data);
	}

	function copy(id) {
		return httpService.doPost(`${servicePath}/${id}`).then(res => res.data);
	}

	function del(id) {
		return httpService
			.doDelete(`${servicePath}/${id}`)
			.then(res => res.data);
	}

	function getVersions(id) {
		return httpService.doGet(`${servicePath}/${id}/version/`)
			.then(res => res.data);
	}

	function getVersion(id, versionNumber) {
		return httpService.doGet(`${servicePath}/${id}/version/${versionNumber}`)
			.then(res => res.data);
	}

	function copyVersion(id, versionNumber) {
		return httpService.doPut(`${servicePath}/${id}/version/${versionNumber}/createAsset`)
			.then(res => res.data);
	}

	function updateVersion(version) {
		return httpService.doPut(`${servicePath}/${version.assetId}/version/${version.version}`, {
			comment: version.comment,
			archived: version.archived
		}).then(res => res.data);
	}

	return {
		PARAMETER_TYPE,
		list,
		create,
		exists,
		copy,
		load,
		save,
		del,
		getVersions,
		getVersion,
		updateVersion,
		copyVersion
	};
});


text:
require 'hbc/staged'

class Hbc::DSL::UninstallPreflight < Hbc::DSL::Base
  include Hbc::Staged

  def method_missing(method, *args)
    Hbc::Utils.method_missing_message(method, @cask.to_s, 'uninstall_preflight')
    return nil
  end
end


text:
package com.alibaba.otter.shared.arbitrate.exception;

import org.apache.commons.lang.exception.NestableRuntimeException;

/**
 * @author jianghang 2011-9-16 下午01:59:25
 * @version 4.0.0
 */
public class ArbitrateException extends NestableRuntimeException {

    private static final long serialVersionUID = -7288830284122672209L;

    public ArbitrateException(String errorCode){
        super(errorCode);
    }

    public ArbitrateException(String errorCode, Throwable cause){
        super(errorCode, cause);
    }

    public ArbitrateException(String errorCode, String errorDesc){
        super(errorCode + ":" + errorDesc);
    }

    public ArbitrateException(String errorCode, String errorDesc, Throwable cause){
        super(errorCode + ":" + errorDesc, cause);
    }

    public ArbitrateException(Throwable cause){
        super(cause);
    }

    public Throwable fillInStackTrace() {
        return this;
    }

}


text:
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace MangaReader.Avalonia.View
{
  public class Library : UserControl
  {
    public Library()
    {
      this.InitializeComponent();
    }

    private void InitializeComponent()
    {
      AvaloniaXamlLoader.Load(this);
    }
  }
}


text:
/*
 * Created on Sep 9, 2004
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package yaes.world.physical.map;

/**
 * @author Lotzi Boloni
 *
 *         To change the template for this generated type comment go to Window -
 *         Preferences - Java - Code Generation - Code and Comments
 */
public interface MapConstants {
    public static final String ACCESSIBLE = "Accessible";
    public static final String SAFE       = "Safe";
}


text:
<?php
namespace app\models;

use Yii;
use yii\base\Model;

/**
 * User form
 */
class UserForm extends Model
{

	public $username;
	public $password;
	public $status; // 1正常,2锁定
    public $project;
    public $department;
    public $qq;
    public $rememberMe = true;

    private $_userForm = false;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        	// 添加
            // username and email are both required, create scenario
            [['username','password','project','department'], 'required', 'on' => 'create'],
            // 登录
            // username and password are both required
            [['username', 'password'], 'required', 'on' => 'login'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean', 'on' => 'login'],
            // password is validated by validatePassword()
            ['password', 'validatePassword', 'on' => 'login'],
        ];
    }

    /**
     * (non-PHPdoc)
     * @see \yii\base\Model::scenarios()
     */
    public function scenarios() {
    	return [
    		// 场景,块赋值和验证规则
			'create' => ['username','password','project','department','qq'],
			'login' => ['username', 'password', 'rememberMe'],
    	];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
    	if (!$this->hasErrors()) {
    		$user = $this->getUser();
    		if (!$user || !$user->validatePassword($this->password)){
    			$this->addError($attribute, 'Incorrect username or password.');
    		}
    	}
    }

    /**
     * 用户名是否存在,存在返回true,否则返回false
     * @return boolean
     */
    public function existUsername()
    {
    	$model = User::findOne(['username' => $this->username]);
    	if($model === null) {
    		return false;
    	}
    	return true;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
    	if ($this->_userForm === false) {
    		$this->_userForm = User::findByUsername($this->username);
    	}

    	return $this->_userForm;
    }

}


text:
import InCallManager from 'react-native-incall-manager';

import {forceLogoutIfNecessary} from '@actions/remote/session';
import {fetchUsersByIds} from '@actions/remote/user';
import {
    getCallsConfig,
    getCallsState,
    setCalls,
    setChannelEnabled,
    setConfig,
    setPluginEnabled,
    setScreenShareURL,
    setSpeakerPhone,
    setCallForChannel,
    newCurrentCall,
    myselfLeftCall,
} from '@calls/state';
import {General, Preferences} from '@constants';
import Calls from '@constants/calls';
import DatabaseManager from '@database/manager';
import {getTeammateNameDisplaySetting} from '@helpers/api/preference';
import NetworkManager from '@managers/network_manager';
import {getChannelById} from '@queries/servers/channel';
import {queryPreferencesByCategoryAndName} from '@queries/servers/preference';
import {getConfig, getLicense} from '@queries/servers/system';
import {getCurrentUser, getUserById} from '@queries/servers/user';
import {displayUsername, getUserIdFromChannelName, isSystemAdmin} from '@utils/user';

import {newConnection} from '../connection/connection';

import type {
    ApiResp,
    Call,
    CallParticipant,
    CallsConnection,
    ServerCallState,
    ServerChannelState,
} from '@calls/types/calls';
import type {Client} from '@client/rest';
import type ClientError from '@client/rest/error';
import type {IntlShape} from 'react-intl';

let connection: CallsConnection | null = null;
export const getConnectionForTesting = () => connection;

export const loadConfig = async (serverUrl: string, force = false) => {
    const now = Date.now();
    const config = getCallsConfig(serverUrl);

    if (!force) {
        const lastRetrievedAt = config.last_retrieved_at || 0;
        if ((now - lastRetrievedAt) < Calls.RefreshConfigMillis) {
            return {data: config};
        }
    }

    let client: Client;
    try {
        client = NetworkManager.getClient(serverUrl);
    } catch (error) {
        return {error};
    }

    let data;
    try {
        data = await client.getCallsConfig();
    } catch (error) {
        await forceLogoutIfNecessary(serverUrl, error as ClientError);
        return {error};
    }

    const nextConfig = {...data, last_retrieved_at: now};
    setConfig(serverUrl, nextConfig);
    return {data: nextConfig};
};

export const loadCalls = async (serverUrl: string, userId: string) => {
    let client: Client;
    try {
        client = NetworkManager.getClient(serverUrl);
    } catch (error) {
        return {error};
    }
    let resp: ServerChannelState[] = [];
    try {
        resp = await client.getCalls() || [];
    } catch (error) {
        await forceLogoutIfNecessary(serverUrl, error as ClientError);
        return {error};
    }

    const callsResults: Dictionary<Call> = {};
    const enabledChannels: Dictionary<boolean> = {};
    const ids = new Set<string>();

    for (const channel of resp) {
        if (channel.call) {
            callsResults[channel.channel_id] = createCallAndAddToIds(channel.channel_id, channel.call, ids);
        }
        enabledChannels[channel.channel_id] = channel.enabled;
    }

    // Batch load user models async because we'll need them later
    if (ids.size > 0) {
        fetchUsersByIds(serverUrl, Array.from(ids));
    }

    setCalls(serverUrl, userId, callsResults, enabledChannels);

    return {data: {calls: callsResults, enabled: enabledChannels}};
};

export const loadCallForChannel = async (serverUrl: string, channelId: string) => {
    let client: Client;
    try {
        client = NetworkManager.getClient(serverUrl);
    } catch (error) {
        return {error};
    }

    let resp: ServerChannelState;
    try {
        resp = await client.getCallForChannel(channelId);
    } catch (error) {
        await forceLogoutIfNecessary(serverUrl, error as ClientError);
        return {error};
    }

    let call: Call | undefined;
    const ids = new Set<string>();
    if (resp.call) {
        call = createCallAndAddToIds(channelId, resp.call, ids);
    }

    // Batch load user models async because we'll need them later
    if (ids.size > 0) {
        fetchUsersByIds(serverUrl, Array.from(ids));
    }

    setCallForChannel(serverUrl, channelId, resp.enabled, call);

    return {data: {call, enabled: resp.enabled}};
};

const createCallAndAddToIds = (channelId: string, call: ServerCallState, ids: Set<string>) => {
    return {
        participants: call.users.reduce((accum, cur, curIdx) => {
            // Add the id to the set of UserModels we want to ensure are loaded.
            ids.add(cur);

            // Create the CallParticipant
            const muted = call.states && call.states[curIdx] ? !call.states[curIdx].unmuted : true;
            const raisedHand = call.states && call.states[curIdx] ? call.states[curIdx].raised_hand : 0;
            accum[cur] = {id: cur, muted, raisedHand};
            return accum;
        }, {} as Dictionary<CallParticipant>),
        channelId,
        startTime: call.start_at,
        screenOn: call.screen_sharing_id,
        threadId: call.thread_id,
        ownerId: call.owner_id,
    } as Call;
};

export const loadConfigAndCalls = async (serverUrl: string, userId: string) => {
    const res = await checkIsCallsPluginEnabled(serverUrl);
    if (res.data) {
        loadConfig(serverUrl, true);
        loadCalls(serverUrl, userId);
    }
};

export const checkIsCallsPluginEnabled = async (serverUrl: string) => {
    let client: Client;
    try {
        client = NetworkManager.getClient(serverUrl);
    } catch (error) {
        return {error};
    }

    let data: ClientPluginManifest[] = [];
    try {
        data = await client.getPluginsManifests();
    } catch (error) {
        await forceLogoutIfNecessary(serverUrl, error as ClientError);
        return {error};
    }

    const enabled = data.findIndex((m) => m.id === Calls.PluginId) !== -1;
    const curEnabled = getCallsConfig(serverUrl).pluginEnabled;
    if (enabled !== curEnabled) {
        setPluginEnabled(serverUrl, enabled);
    }

    return {data: enabled};
};

export const enableChannelCalls = async (serverUrl: string, channelId: string, enable: boolean) => {
    let client: Client;
    try {
        client = NetworkManager.getClient(serverUrl);
    } catch (error) {
        return {error};
    }

    try {
        const res = await client.enableChannelCalls(channelId, enable);
        if (res.enabled === enable) {
            setChannelEnabled(serverUrl, channelId, enable);
        }
    } catch (error) {
        await forceLogoutIfNecessary(serverUrl, error as ClientError);
        return {error};
    }

    return {};
};

export const joinCall = async (serverUrl: string, channelId: string, userId: string, hasMicPermission: boolean): Promise<{ error?: string | Error; data?: string }> => {
    // Edge case: calls was disabled when app loaded, and then enabled, but app hasn't
    // reconnected its websocket since then (i.e., hasn't called batchLoadCalls yet)
    const {data: enabled} = await checkIsCallsPluginEnabled(serverUrl);
    if (!enabled) {
        return {error: 'calls plugin not enabled'};
    }

    if (connection) {
        connection.disconnect();
        connection = null;
    }
    setSpeakerphoneOn(false);
    newCurrentCall(serverUrl, channelId, userId);

    try {
        connection = await newConnection(serverUrl, channelId, () => {
            myselfLeftCall();
        }, setScreenShareURL, hasMicPermission);
    } catch (error: unknown) {
        await forceLogoutIfNecessary(serverUrl, error as ClientError);
        return {error: error as Error};
    }

    try {
        await connection.waitForPeerConnection();
        return {data: channelId};
    } catch (e) {
        connection.disconnect();
        connection = null;
        return {error: `unable to connect to the voice call: ${e}`};
    }
};

export const leaveCall = () => {
    if (connection) {
        connection.disconnect();
        connection = null;
    }
    setSpeakerphoneOn(false);
};

export const muteMyself = () => {
    if (connection) {
        connection.mute();
    }
};

export const unmuteMyself = () => {
    if (connection) {
        connection.unmute();
    }
};

export const initializeVoiceTrack = () => {
    if (connection) {
        connection.initializeVoiceTrack();
    }
};

export const raiseHand = () => {
    if (connection) {
        connection.raiseHand();
    }
};

export const unraiseHand = () => {
    if (connection) {
        connection.unraiseHand();
    }
};

export const setSpeakerphoneOn = (speakerphoneOn: boolean) => {
    InCallManager.setSpeakerphoneOn(speakerphoneOn);
    setSpeakerPhone(speakerphoneOn);
};

export const canEndCall = async (serverUrl: string, channelId: string) => {
    const database = DatabaseManager.serverDatabases[serverUrl]?.database;
    if (!database) {
        return false;
    }

    const currentUser = await getCurrentUser(database);
    if (!currentUser) {
        return false;
    }

    const call = getCallsState(serverUrl).calls[channelId];
    if (!call) {
        return false;
    }

    return isSystemAdmin(currentUser.roles) || currentUser.id === call.ownerId;
};

export const getEndCallMessage = async (serverUrl: string, channelId: string, currentUserId: string, intl: IntlShape) => {
    let msg = intl.formatMessage({
        id: 'mobile.calls_end_msg_channel_default',
        defaultMessage: 'Are you sure you want to end the call?',
    });

    const database = DatabaseManager.serverDatabases[serverUrl]?.database;
    if (!database) {
        return msg;
    }

    const channel = await getChannelById(database, channelId);
    if (!channel) {
        return msg;
    }

    const call = getCallsState(serverUrl).calls[channelId];
    if (!call) {
        return msg;
    }

    const numParticipants = Object.keys(call.participants).length;

    msg = intl.formatMessage({
        id: 'mobile.calls_end_msg_channel',
        defaultMessage: 'Are you sure you want to end a call with {numParticipants} participants in {displayName}?',
    }, {numParticipants, displayName: channel.displayName});

    if (channel.type === General.DM_CHANNEL) {
        const otherID = getUserIdFromChannelName(currentUserId, channel.name);
        const otherUser = await getUserById(database, otherID);
        const license = await getLicense(database);
        const config = await getConfig(database);
        const preferences = await queryPreferencesByCategoryAndName(database, Preferences.CATEGORY_DISPLAY_SETTINGS, Preferences.NAME_NAME_FORMAT).fetch();
        const displaySetting = getTeammateNameDisplaySetting(preferences, config.LockTeammateNameDisplay, config.TeammateNameDisplay, license);
        msg = intl.formatMessage({
            id: 'mobile.calls_end_msg_dm',
            defaultMessage: 'Are you sure you want to end the call with {displayName}?',
        }, {displayName: displayUsername(otherUser, intl.locale, displaySetting)});
    }

    return msg;
};

export const endCall = async (serverUrl: string, channelId: string) => {
    const client = NetworkManager.getClient(serverUrl);

    let data: ApiResp;
    try {
        data = await client.endCall(channelId);
    } catch (error) {
        await forceLogoutIfNecessary(serverUrl, error as ClientError);
        throw error;
    }

    return data;
};


text:
package com.intellij.vcs.log.ui.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.VcsLogDataKeys;
import com.intellij.vcs.log.VcsLogProperties;
import com.intellij.vcs.log.VcsLogProvider;
import com.intellij.vcs.log.VcsLogUi;
import com.intellij.vcs.log.data.VcsLogData;
import com.intellij.vcs.log.impl.CommonUiProperties;
import com.intellij.vcs.log.impl.VcsLogUiProperties;
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys;
import com.intellij.vcs.log.ui.table.VcsLogColumn;
import com.intellij.vcs.log.util.VcsLogUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class PreferCommitDateAction extends BooleanPropertyToggleAction implements DumbAware {
  public PreferCommitDateAction() {
    super(VcsBundle.lazyMessage("prefer.commit.timestamp.action.text"),
          VcsBundle.lazyMessage("prefer.commit.timestamp.action.description"), null);
  }

  @Override
  protected VcsLogUiProperties.VcsLogUiProperty<Boolean> getProperty() {
    return CommonUiProperties.PREFER_COMMIT_DATE;
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    super.update(e);
    VcsLogData data = e.getData(VcsLogInternalDataKeys.LOG_DATA);
    VcsLogUi logUi = e.getData(VcsLogDataKeys.VCS_LOG_UI);
    if (data == null || logUi == null) {
      e.getPresentation().setEnabledAndVisible(false);
      return;
    }
    Map<VirtualFile, VcsLogProvider> providers = data.getLogProviders();
    if (!isCommitDateSupported(providers.values())) {
      e.getPresentation().setEnabledAndVisible(false);
      return;
    }
    Set<VcsLogProvider> visibleProviders = ContainerUtil.map2SetNotNull(VcsLogUtil.getVisibleRoots(logUi), root -> providers.get(root));
    if (!isDateDisplayed(e.getData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES)) ||
        !isCommitDateSupported(visibleProviders)) {
      e.getPresentation().setEnabled(false);
    }
  }

  private static boolean isCommitDateSupported(@NotNull Collection<VcsLogProvider> providers) {
    return providers.stream().anyMatch(VcsLogProperties.HAS_COMMITTER::getOrDefault);
  }

  private static boolean isDateDisplayed(@Nullable VcsLogUiProperties properties) {
    if (properties != null && properties.exists(CommonUiProperties.COLUMN_ORDER)) {
      List<Integer> columnOrder = properties.get(CommonUiProperties.COLUMN_ORDER);
      return columnOrder.contains(VcsLogColumn.DATE.ordinal());
    }
    return false;
  }
}


text:
from django.db import connection
from laboratory.settings import TIME_ZONE
from utils.db import namedtuplefetchall

def get_history_dir(d_s, d_e, card_id, who_create_dir, services, is_serv, iss_pk, is_parent, for_slave_hosp):
    with connection.cursor() as cursor:
        cursor.execute(
            """WITH
        t_iss AS (SELECT
            directions_issledovaniya.id as iss_id,
            directions_napravleniya.client_id,
            directory_researches.title as res_title,
            directory_researches.id as res_id,
            directory_researches.code,
            directory_researches.is_hospital,
            directory_researches.is_slave_hospital,
            directory_researches.is_treatment,
            directory_researches.is_stom,
            directory_researches.is_doc_refferal,
            directory_researches.is_paraclinic,
            directory_researches.is_form,
            directory_researches.is_microbiology,
            directory_researches.podrazdeleniye_id,
            directions_napravleniya.parent_id as dir_parent_id,
            directions_napravleniya.data_sozdaniya as dir_data_sozdaniya,
            directions_napravleniya.doc_who_create_id,
            directions_issledovaniya.napravleniye_id,
            directions_napravleniya.cancel as dir_cancel,
            directions_issledovaniya.time_confirmation,
            directions_issledovaniya.maybe_onco,
            to_char(directions_issledovaniya.time_save AT TIME ZONE %(tz)s, 'DD.MM.YYYY-HH24:MI:SS') as ch_time_save,
            directions_issledovaniya.study_instance_uid,
            directions_napravleniya.parent_slave_hosp_id as dir_parent_slave_hosp_id,
            directory_researches.is_application,
            directory_researches.is_expertise,
            person_contract.id as person_contract_id,
            person_contract.dir_list as contract_dirs,
            directions_napravleniya.hospital_id as dir_hosp
        FROM directions_issledovaniya
        LEFT JOIN directory_researches
        ON directions_issledovaniya.research_id = directory_researches.Id
        LEFT JOIN directions_napravleniya
        ON directions_issledovaniya.napravleniye_id = directions_napravleniya.id
        LEFT JOIN directions_personcontract person_contract on directions_napravleniya.num_contract = person_contract.num_contract
        WHERE directions_napravleniya.data_sozdaniya AT TIME ZONE %(tz)s BETWEEN %(d_start)s AND %(d_end)s
        AND NOT directory_researches.is_expertise
        AND
        CASE
        WHEN %(is_parent)s = TRUE AND %(for_slave_hosp)s = FALSE THEN
            directions_napravleniya.parent_id = %(iss_pk)s
        WHEN %(is_parent)s = TRUE AND %(for_slave_hosp)s = TRUE THEN
            directions_napravleniya.parent_slave_hosp_id = %(iss_pk)s
        when %(card_id)s > -1 THEN
        directions_napravleniya.client_id = %(card_id)s
        when %(who_create)s > -1 THEN
        directions_napravleniya.doc_who_create_id = %(who_create)s
        END),

        t_tubes AS (SELECT tubesregistration_id, issledovaniya_id as tubes_iss_id
        FROM directions_issledovaniya_tubes
        WHERE issledovaniya_id IN (SELECT iss_id FROM t_iss)),

        t_iss_tubes AS (SELECT * from t_iss
        LEFT JOIN t_tubes
        ON t_iss.iss_id = t_tubes.tubes_iss_id),

        t_recive AS (SELECT time_recive, id as id_t_recive FROM directions_tubesregistration
        WHERE directions_tubesregistration.id in (SELECT tubesregistration_id  FROM t_tubes)),

        t_podrazdeleniye AS (SELECT id AS podr_id, can_has_pacs, title AS podr_title FROM podrazdeleniya_podrazdeleniya)

        SELECT
            napravleniye_id,
            dir_cancel,
            iss_id,
            tubesregistration_id,
            res_id,
            res_title,
            to_char(dir_data_sozdaniya AT TIME ZONE %(tz)s, 'DD.MM.YY') as date_create,
            time_confirmation,
            to_char(time_recive AT TIME ZONE %(tz)s, 'DD.MM.YY HH24:MI:SS.US'),
            ch_time_save,
            podr_title,
            is_hospital,
            maybe_onco,
            can_has_pacs,
            is_slave_hospital,
            is_treatment,
            is_stom,
            is_doc_refferal,
            is_paraclinic,
            is_microbiology,
            dir_parent_id,
            study_instance_uid,
            dir_parent_slave_hosp_id,
            is_form,
            is_application,
            is_expertise,
            person_contract_id,
            contract_dirs,
            dir_hosp,
            directions_napravleniya.additional_number as register_number,
            ud.family,
            ud.name,
            ud.patronymic
        FROM t_iss_tubes
        LEFT JOIN t_recive
        ON t_iss_tubes.tubesregistration_id = t_recive.id_t_recive
        LEFT JOIN t_podrazdeleniye
        ON t_iss_tubes.podrazdeleniye_id = t_podrazdeleniye.podr_id
        LEFT JOIN directions_napravleniya
        ON directions_napravleniya.id = napravleniye_id
        LEFT JOIN users_doctorprofile ud
        ON directions_napravleniya.planed_doctor_executor_id = ud.id
        WHERE
        CASE
        WHEN %(is_serv)s = TRUE THEN
            res_id = ANY(ARRAY[%(services_p)s])
        WHEN %(is_serv)s = FALSE THEN
            EXISTS (SELECT res_id FROM t_iss)
        END

        ORDER BY napravleniye_id DESC""",
            params={
                'd_start': d_s,
                'd_end': d_e,
                'card_id': card_id,
                'who_create': who_create_dir,
                'services_p': services,
                'is_serv': is_serv,
                'tz': TIME_ZONE,
                'iss_pk': iss_pk,
                'is_parent': is_parent,
                'for_slave_hosp': for_slave_hosp,
            },
        )

        row = cursor.fetchall()
    return row

def get_directions_by_user(d_s, d_e, who_create_dir):
    with connection.cursor() as cursor:
        cursor.execute(
            """SELECT
            directions_napravleniya.id as direction_id
        FROM directions_napravleniya
        WHERE directions_napravleniya.data_sozdaniya AT TIME ZONE %(tz)s BETWEEN %(d_start)s AND %(d_end)s
        and directions_napravleniya.doc_who_create_id in %(who_create)s
        ORDER BY directions_napravleniya.id DESC""",
            params={
                'd_start': d_s,
                'd_end': d_e,
                'who_create': who_create_dir,
                'tz': TIME_ZONE,
            },
        )
        rows = namedtuplefetchall(cursor)
    return rows

def get_patient_contract(
    d_s,
    d_e,
    card_pk,
):
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT
        directions_napravleniya.num_contract,
        directions_personcontract.id,
        directions_personcontract.cancel,
        directions_personcontract.create_at,
        directions_personcontract.sum_contract,
        to_char(directions_personcontract.create_at AT TIME ZONE %(tz)s, 'DD.MM.YY') as date_create,
        directions_issledovaniya.napravleniye_id,
        directions_issledovaniya.coast,
        directions_issledovaniya.discount,
        directory_researches.title,
        directions_personcontract.dir_list
        FROM directions_issledovaniya
        LEFT JOIN directory_researches ON
        directory_researches.id=directions_issledovaniya.research_id
        LEFT JOIN directions_napravleniya ON
        directions_napravleniya.id=directions_issledovaniya.napravleniye_id
        LEFT JOIN directions_personcontract ON
        directions_personcontract.num_contract=directions_napravleniya.num_contract

        WHERE directions_issledovaniya.napravleniye_id::varchar in (
         select regexp_split_to_table(directions_personcontract.dir_list, ',') from directions_personcontract
            where directions_personcontract.patient_card_id=%(card_pk)s and directions_personcontract.create_at AT TIME ZONE %(tz)s BETWEEN %(d_start)s AND %(d_end)s
        )
        order by directions_personcontract.create_at DESC
        """,
            params={
                'd_start': d_s,
                'd_end': d_e,
                'tz': TIME_ZONE,
                'card_pk': card_pk,
            },
        )
        rows = namedtuplefetchall(cursor)
    return rows

def get_lab_podr():
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT id FROM public.podrazdeleniya_podrazdeleniya
        WHERE p_type=2
        """
        )
        row = cursor.fetchall()
    return row

def get_confirm_direction(d_s, d_e, lab_podr, is_lab=False, is_paraclinic=False, is_doc_refferal=False):
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT DISTINCT ON (napravleniye_id) napravleniye_id FROM public.directions_issledovaniya
        WHERE time_confirmation AT TIME ZONE %(tz)s BETWEEN %(d_start)s AND %(d_end)s
        AND research_id IN (SELECT id FROM directory_researches WHERE CASE

        WHEN  %(is_lab)s = FALSE AND %(is_paraclinic)s = TRUE AND %(is_doc_refferal)s = FALSE THEN
          is_paraclinic = TRUE
        WHEN %(is_lab)s = FALSE AND %(is_paraclinic)s = FALSE AND %(is_doc_refferal)s = TRUE THEN
          is_doc_refferal = TRUE

        WHEN  %(is_lab)s = FALSE AND %(is_paraclinic)s = TRUE AND %(is_doc_refferal)s = TRUE  THEN
          is_paraclinic = TRUE or is_doc_refferal = TRUE

        WHEN %(is_lab)s = TRUE AND %(is_paraclinic)s = FALSE AND %(is_doc_refferal)s = FALSE THEN
            podrazdeleniye_id = ANY(ARRAY[%(lab_podr)s])

        WHEN %(is_lab)s = TRUE AND %(is_paraclinic)s = TRUE AND %(is_doc_refferal)s = FALSE THEN
          is_paraclinic = TRUE and is_doc_refferal = FALSE or podrazdeleniye_id = ANY(ARRAY[%(lab_podr)s])

        WHEN %(is_lab)s = TRUE AND %(is_paraclinic)s = FALSE AND %(is_doc_refferal)s = TRUE THEN
          is_paraclinic = FALSE and is_doc_refferal = TRUE or podrazdeleniye_id = ANY(ARRAY[%(lab_podr)s])

        WHEN %(is_lab)s = TRUE AND %(is_paraclinic)s = TRUE AND %(is_doc_refferal)s = TRUE THEN
          is_paraclinic = TRUE or is_doc_refferal = TRUE or podrazdeleniye_id = ANY(ARRAY[%(lab_podr)s])
        END
        )

        """,
            params={'d_start': d_s, 'd_end': d_e, 'tz': TIME_ZONE, 'is_lab': is_lab, 'is_paraclinic': is_paraclinic, 'is_doc_refferal': is_doc_refferal, 'lab_podr': lab_podr},
        )
        row = cursor.fetchall()
    return row

def filter_direction_department(list_dirs, podrazdeleniye_id):
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT DISTINCT ON (id) id FROM public.directions_napravleniya
        WHERE id = ANY(ARRAY[%(num_dirs)s])
        AND doc_id IN (SELECT id from users_doctorprofile WHERE podrazdeleniye_id = %(podrazdeleniye_id)s)
        """,
            params={'num_dirs': list_dirs, 'podrazdeleniye_id': podrazdeleniye_id},
        )
        row = cursor.fetchall()
    return row

def filter_direction_doctor(list_dirs, doc_id):
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT DISTINCT ON (id) id FROM public.directions_napravleniya
        WHERE id = ANY(ARRAY[%(num_dirs)s]) AND doc_id = %(doc_id)s
        """,
            params={'num_dirs': list_dirs, 'doc_id': doc_id},
        )
        row = cursor.fetchall()
    return row

def get_confirm_direction_pathology(d_s, d_e):
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT DISTINCT ON (napravleniye_id) napravleniye_id FROM public.directions_issledovaniya
        WHERE time_confirmation AT TIME ZONE %(tz)s BETWEEN %(d_start)s AND %(d_end)s
        AND research_id IN (SELECT id FROM public.directory_researches where title ILIKE '%%профпатолог%%')
        """,
            params={'d_start': d_s, 'd_end': d_e, 'tz': TIME_ZONE},
        )
        row = cursor.fetchall()
    return row

def get_confirm_direction_patient_year(d_s, d_e, lab_podr, card_pk1, is_lab=False, is_paraclinic=False, is_doc_refferal=False, is_user_forms=False):
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT
            directions_napravleniya.id as direction,
            directions_issledovaniya.time_confirmation,
            to_char(directions_issledovaniya.time_confirmation AT TIME ZONE %(tz)s, 'DD.MM.YYYY') as ch_time_confirmation,
            directions_issledovaniya.research_id,
            directory_researches.title as research_title,
            directions_issledovaniya.study_instance_uid_tag
            FROM directions_napravleniya
            INNER JOIN directions_issledovaniya ON (directions_napravleniya.id = directions_issledovaniya.napravleniye_id)
            AND directions_issledovaniya.research_id IN
            (SELECT directory_researches.id FROM directory_researches WHERE CASE
             WHEN %(is_lab)s = TRUE THEN directory_researches.podrazdeleniye_id = ANY(ARRAY[%(lab_podr)s])
             WHEN %(is_doc_refferal)s = TRUE THEN is_doc_refferal = TRUE or is_treatment = TRUE
             WHEN %(is_paraclinic)s = TRUE THEN is_paraclinic = TRUE
             WHEN %(is_user_forms)s = TRUE THEN can_created_patient = TRUE
             END
            )
            LEFT JOIN directory_researches ON
            directions_issledovaniya.research_id=directory_researches.id
            WHERE directions_issledovaniya.time_confirmation IS NOT NULL
            AND directions_issledovaniya.time_confirmation AT TIME ZONE 'ASIA/Irkutsk' BETWEEN %(d_start)s AND %(d_end)s
            AND NOT EXISTS (SELECT directions_issledovaniya.napravleniye_id FROM directions_issledovaniya
                            WHERE time_confirmation IS NULL AND directions_issledovaniya.napravleniye_id = directions_napravleniya.id)
            AND client_id=%(card_pk)s
            ORDER BY directions_issledovaniya.time_confirmation DESC, directions_napravleniya.id
        """,
            params={
                'd_start': d_s,
                'd_end': d_e,
                'tz': TIME_ZONE,
                'is_lab': is_lab,
                'is_paraclinic': is_paraclinic,
                'is_doc_refferal': is_doc_refferal,
                'is_user_forms': is_user_forms,
                'lab_podr': lab_podr,
                'card_pk': card_pk1,
            },
        )
        rows = namedtuplefetchall(cursor)
    return rows

def get_confirm_direction_patient_year_is_extract(d_s, d_e, card_pk1, extract_research_pks):
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT
            directions_napravleniya.id as direction,
            directions_issledovaniya.time_confirmation,
            to_char(directions_issledovaniya.time_confirmation AT TIME ZONE %(tz)s, 'DD.MM.YYYY') as ch_time_confirmation,
            directions_issledovaniya.research_id,
            directory_researches.title as research_title,
            directions_issledovaniya.study_instance_uid_tag
            FROM directions_napravleniya
            INNER JOIN directions_issledovaniya ON (directions_napravleniya.id = directions_issledovaniya.napravleniye_id)
            AND directions_issledovaniya.research_id IN %(extract_research_pks)s
            LEFT JOIN directory_researches ON
            directions_issledovaniya.research_id=directory_researches.id
            WHERE directions_issledovaniya.time_confirmation IS NOT NULL
            AND directions_issledovaniya.research_id in %(extract_research_pks)s
            AND directions_issledovaniya.time_confirmation AT TIME ZONE 'ASIA/Irkutsk' BETWEEN %(d_start)s AND %(d_end)s
            AND client_id=%(card_pk)s
            ORDER BY directions_issledovaniya.time_confirmation DESC, directions_napravleniya.id
        """,
            params={
                'd_start': d_s,
                'd_end': d_e,
                'tz': TIME_ZONE,
                'card_pk': card_pk1,
                'extract_research_pks': extract_research_pks,
            },
        )
        rows = namedtuplefetchall(cursor)
    return rows

def direction_by_card(d_s, d_e, card_id):
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT
            directions_issledovaniya.id as iss_id,
            directions_issledovaniya.napravleniye_id,
            directions_issledovaniya.time_confirmation,
            to_char(directions_issledovaniya.time_confirmation AT TIME ZONE %(tz)s, 'DD.MM.YYYY') date_confirm,
            to_char(directions_issledovaniya.time_save AT TIME ZONE %(tz)s, 'DD.MM.YYYY-HH24:MI:SS') as ch_time_save,
            directions_issledovaniya.study_instance_uid,
            directory_researches.title as research_title,
            directory_researches.id as research_id,
            directory_researches.is_hospital,
            directory_researches.is_slave_hospital,
            directory_researches.is_treatment,
            directory_researches.is_stom,
            directory_researches.is_doc_refferal,
            directory_researches.is_paraclinic,
            directory_researches.is_form,
            directory_researches.is_microbiology,
            directory_researches.is_application,
            directory_researches.is_expertise,
            directory_researches.podrazdeleniye_id,
            directions_napravleniya.parent_slave_hosp_id,
            directions_napravleniya.client_id,
            directions_napravleniya.parent_id,
            directions_napravleniya.data_sozdaniya,
            to_char(data_sozdaniya AT TIME ZONE %(tz)s, 'DD.MM.YY') as date_create,
            directions_napravleniya.cancel
        FROM directions_issledovaniya
        LEFT JOIN directory_researches
        ON directions_issledovaniya.research_id = directory_researches.id
        LEFT JOIN directions_napravleniya
        ON directions_issledovaniya.napravleniye_id = directions_napravleniya.id
        WHERE directions_napravleniya.data_sozdaniya AT TIME ZONE %(tz)s BETWEEN %(d_start)s AND %(d_end)s
        AND directions_napravleniya.client_id = %(card_id)s
        AND NOT directory_researches.is_expertise AND NOT directory_researches.is_hospital AND NOT
            directory_researches.is_slave_hospital AND NOT directory_researches.is_application

        ORDER BY directions_issledovaniya.napravleniye_id DESC""",
            params={
                'd_start': d_s,
                'd_end': d_e,
                'card_id': card_id,
                'tz': TIME_ZONE,
            },
        )
        rows = namedtuplefetchall(cursor)
    return rows

def get_type_confirm_direction(directions_tuple):
    if not directions_tuple:
        return []
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT
            DISTINCT (directions_issledovaniya.napravleniye_id) as napravleniye_id,
            directory_researches.podrazdeleniye_id,
            directory_researches.is_stom,
            directory_researches.is_doc_refferal,
            directory_researches.is_paraclinic,
            directory_researches.is_form,
            directory_researches.is_microbiology,
            directory_researches.is_application
        FROM directions_issledovaniya
        LEFT JOIN directory_researches
        ON directions_issledovaniya.research_id = directory_researches.id
        WHERE directions_issledovaniya.napravleniye_id in %(directions_tuple)s
        ORDER BY directions_issledovaniya.napravleniye_id DESC""",
            params={
                'directions_tuple': directions_tuple,
            },
        )
        rows = namedtuplefetchall(cursor)
    return rows

def get_confirm_direction_by_hospital(hospitals, d_start, d_end):
    with connection.cursor() as cursor:
        cursor.execute(
            """
        SELECT
            DISTINCT (directions_napravleniya.id) as direction,
            directions_napravleniya.hospital_id as hospital,
            directions_napravleniya.email_with_results_sent
        FROM directions_napravleniya
        WHERE directions_napravleniya.hospital_id in %(hospitals)s and
        directions_napravleniya.last_confirmed_at AT TIME ZONE %(tz)s BETWEEN %(d_start)s AND %(d_end)s
        ORDER BY directions_napravleniya.hospital_id
        """,
            params={'hospitals': hospitals, 'd_start': d_start, 'd_end': d_end, 'tz': TIME_ZONE},
        )
        rows = namedtuplefetchall(cursor)
    return rows


text:
<TITLE>Review for Cotton Mary (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Cotton Mary (1999)

reviewed by
Harvey S. Karten

COTTON MARY

 Reviewed by Harvey Karten
 Merchant Ivory Productions/Universal Pictures
 Director: Ismail Merchant
 Writer:   Alexandra Viets
 Cast: Madhur Jaffrey, Greta Scacchi, Sakina Jaffrey, Prayag
Raaj, James Wilby

   There's something pathetic about the yearning of a peoples
who have been freed from their colonialist overlords to
continue identifying with their former rulers.  If you go today
to some developing nations particularly in Africa and parts of
Asia, you'll find that the educated people pride themselves on
speaking the European languages of their previous bosses,
looking down on the majorities who speak merely the
vernacular. Ousmene Sembene captured the servility of the
diplomatic classes in Senegal to the French culture,
particularly to its language and dress, in his masterful film of
government corruption in "Xala."

   What's perhaps even more wretched is the grandiosity of
those who are low on the totem pole: those who seek to put
themselves a few notches above their countrymen by their
identification with the departed Europeans.  Ismael
Merchant has done a bang-up job in adapting Alexandra
Viets' screenplay, "Cotton Mary," mixing humor, pathos, and
satire in a narrative of a fairly insignificant, middle-aged
Anglo-Indian woman in 1954--seven years after India's
independence from Britain--who refuses to recognize herself
as anything but a representative of British stock.  Her failure
to relate to her birthright as an Indian subject leads to her
rejection not only by the British who stayed on in India after
their government's withdrawal but by her own people and,
even most important, by herself.

   Ismail Merchant, the celebrated director who has long
collaborated with James Ivory to bring us colorful films like
"Shakespeare Wallah" and "A Room With a View," takes us
to a major southern town in the Indian province of Kerala, a
microcosm of the psychological battlefield pitting Indians
against Anglo-Indians, and both against the British who
remain. This is no mere sociological study but a deep-seated
account of one dysfunctional family on the Malabar coast and
their relationships with their servants.  The title character is
portrayed by Madhur Jaffrey, a highly talented woman as
acclaimed for writing a dozen cookbooks that have increased
the popularity of Indian food in the West as she is for acting
in four other Merchant-Ivory productions.  Her character's
deterioration from a person who is already deluding herself
about her status as the daughter of a British regiment officer
to one who has crossed the border into madness is carefully
developed in this 125-minute picture, which conveys the
lovely, exotic ambiance of a town cooled by the breezes of
the Indian Ocean.  Her passive-aggressive relationship with
the British woman who employs her, the confused and
detached Lily Macintosh (Greta Scacchi), styles the entire
film.

   The story opens on Lily, who has gone into labor while her
BBC-employed husband is in the field and not present at the
birth of her daughter.  The life of the prematurely born baby
is imperiled because her mother's breast is dry.  (Formula did
not exist at the time.)  As the little six-pound girl needs milk,
Lily's nurse, Cotton Mary, agrees to take responsibility for
finding a wet nurse--though Lily seems oddly apathetic and
unconcerned about the process.  Lily, whose remote behavior
might remind moviegoers of a similar demeanor from
Julianne Moore in Todd Haynes's film "Safe," employs Cotton
Mary as nanny and housekeeper, her dependence on this
conniving and repugnant woman so great that she allows her
servant too much responsibility.  After firing her long-time
cook, Abraham (Prayag Raaj) at the behest of this woman,
she feels increasingly lost and, given the regular absence of
her handsome and athletic husband, John (James Wilby), she
becomes increasingly withdrawn.

   Credible and moving that Greta Scacchi's performance is,
Madhur Jaffrey is the real jewel of this Merchant-Ivory work.
As the central bad-guy in a movie that furnishes us with only
one decent principal (Abraham, the loyal attendant), Jaffrey's
Mary appears to relish the ways she destroys the lives of
those about her.  Though she gives hell to a bunch of racist
British women who are friends of her mistress ("You think
because I'm black you can talk to me like that!"), her real
targets are those of her countrymen who are of unmixed
Indian blood.  "You can't trust those Indians," she regularly
exclaims, "They're dirty and they steal."  Successfully bearing
false witness against her co-servant, Abraham, she
nonetheless considers herself a religious person--though she
is obviously using the accoutrements of worship such as The
Lord's Prayer to further her identity with the Anglican British.
Not surprisingly, her young friend Rosie, who is pale-skinned
and almost able to pass for British, is taken in by Mary's
exhortations.  She dreams of attaining a job in a posh British
home.   When Blossom, who is Mary's sister and the actual
wet-nurse of Lily's baby, remains baffled that the infant's
mother never visits or acknowledges her efforts, she is
unaware that the malevolent Mary has never told her
mistress the identity of this source of nourishment.  The final
scene--a superb payoff that reminds one of Jean Genet's
uncharitable play "The Maids" (about two servants who take
turns playing the role of their employer)--ties the story
together strikingly in a single dramatic confrontation.

Not Rated.  Running Time: 125 minutes.  (C) 1999
Harvey Karten

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.sxdsf.sample.chapter6.lesson4.Lesson6_4Activity">

    <Button
        android:id="@+id/async"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Async"/>

</LinearLayout>


text:
#include "arm_gemm_local.hpp"

#include "pooling_implementation.hpp"
#include "pooling_depthfirst.hpp"
#include "pooling_depthfirst_generic.hpp"

#include "kernels/cpp_nhwc_1x1_stride_any_depthfirst.hpp"
#if defined(__aarch64__)
#if defined(ARM_COMPUTE_ENABLE_SVE)
#include "kernels/sve_u8_nhwc_avg_generic_depthfirst.hpp"
#include "kernels/sve_u8_nhwc_max_2x2_s1_output2x2_depthfirst.hpp"
#include "kernels/sve_u8_nhwc_max_generic_depthfirst.hpp"
#endif  // defined(ARM_COMPUTE_ENABLE_SVE)
#include "kernels/a64_u8_nhwc_max_2x2_s1_output2x2_depthfirst.hpp"
#include "kernels/a64_u8_nhwc_avg_generic_depthfirst.hpp"
#include "kernels/a64_u8_nhwc_max_generic_depthfirst.hpp"
#endif  // defined(__aarch64__)

#include <cstdint>

namespace arm_conv {
namespace pooling {

static const PoolingImplementation<uint8_t, uint8_t> pooling_u8_methods[] = {
  {
    PoolingMethod::DEPTHFIRST,
    "cpp_u8_nhwc_1x1_stride_any_depthfirst",
    [] (const PoolingArgs &args, const Nothing &) -> bool {
      return args.pool_window.rows == 1 && args.pool_window.cols == 1;
    },
    nullptr,
    [] (const PoolingArgs &args, const Nothing &) -> PoolingCommon<uint8_t, uint8_t> * {
      auto strat = new cpp_nhwc_1x1_stride_any_depthfirst<uint8_t>(args.cpu_info);
      return new PoolingDepthfirstGeneric<uint8_t>(strat, args);
    },
  },
#if defined(__aarch64__)
#if defined(ARM_COMPUTE_ENABLE_SVE)
  {
    PoolingMethod::DEPTHFIRST,
    "sve_u8_nhwc_max_2x2_s1_output2x2_depthfirst",
    [] (const PoolingArgs &args, const Nothing &os) -> bool {
      return args.cpu_info->has_sve() &&
             is_supported<sve_u8_nhwc_max_2x2_s1_output2x2_depthfirst>(args, os);
    },
    nullptr,
    [] (const PoolingArgs &args, const Nothing &) -> PoolingCommon<uint8_t, uint8_t> * {
      auto strat = new sve_u8_nhwc_max_2x2_s1_output2x2_depthfirst(args.cpu_info);
      return new PoolingDepthfirst<uint8_t>(strat, args);
    },
  },
  {
    PoolingMethod::DEPTHFIRST,
    "sve_u8_nhwc_avg_generic_depthfirst",
    [] (const PoolingArgs &args, const Nothing &) -> bool {
      // This kernel can only be used when there is either no padding, or we don't care
      // about the value of the padding. Otherwise, we would need to pass in the zero-point
      // for the quantization regime.
      return (args.exclude_padding ||
              (args.padding.top == 0 && args.padding.bottom == 0 &&
               args.padding.left == 0 && args.padding.right == 0)
              ) && args.pool_type == PoolingType::AVERAGE &&
             args.cpu_info->has_sve2();
    },
    nullptr,
    [] (const PoolingArgs &args, const Nothing &) -> PoolingCommon<uint8_t, uint8_t> * {
      auto strat = new sve_u8_nhwc_avg_generic_depthfirst(args.cpu_info);
      return new PoolingDepthfirstGeneric<uint8_t>(strat, args);
    },
  },
  {
    PoolingMethod::DEPTHFIRST,
    "sve_u8_nhwc_max_generic_depthfirst",
    [] (const PoolingArgs &args, const Nothing &) -> bool {
      return args.cpu_info->has_sve() && args.pool_type == PoolingType::MAX;
    },
    nullptr,
    [] (const PoolingArgs &args, const Nothing &) -> PoolingCommon<uint8_t, uint8_t> * {
      auto strat = new sve_u8_nhwc_max_generic_depthfirst(args.cpu_info);
      return new PoolingDepthfirstGeneric<uint8_t>(strat, args);
    },
  },
#endif  // defined(ARM_COMPUTE_ENABLE_SVE)
  {
    PoolingMethod::DEPTHFIRST,
    "a64_u8_nhwc_max_2x2_s1_output2x2_depthfirst",
    is_supported<a64_u8_nhwc_max_2x2_s1_output2x2_depthfirst>,
    nullptr,
    [] (const PoolingArgs &args, const Nothing &) -> PoolingCommon<uint8_t, uint8_t> * {
      auto strat = new a64_u8_nhwc_max_2x2_s1_output2x2_depthfirst(args.cpu_info);
      return new PoolingDepthfirst<uint8_t>(strat, args);
    },
  },
  {
    PoolingMethod::DEPTHFIRST,
    "a64_u8_nhwc_avg_generic_depthfirst",
    [] (const PoolingArgs &args, const Nothing &) -> bool {
      // This kernel can only be used when there is either no padding, or we don't care
      // about the value of the padding. Otherwise, we would need to pass in the zero-point
      // for the quantization regime.
      return (args.exclude_padding ||
              (args.padding.top == 0 && args.padding.bottom == 0 &&
               args.padding.left == 0 && args.padding.right == 0)
              ) && args.pool_type == PoolingType::AVERAGE;
    },
    nullptr,
    [] (const PoolingArgs &args, const Nothing &) -> PoolingCommon<uint8_t, uint8_t> * {
      auto strat = new a64_u8_nhwc_avg_generic_depthfirst(args.cpu_info);
      return new PoolingDepthfirstGeneric<uint8_t>(strat, args);
    },
  },
  {
    PoolingMethod::DEPTHFIRST,
    "a64_u8_nhwc_max_generic_depthfirst",
    [] (const PoolingArgs &args, const Nothing &) -> bool { return args.pool_type == PoolingType::MAX; },
    nullptr,
    [] (const PoolingArgs &args, const Nothing &) -> PoolingCommon<uint8_t, uint8_t> * {
      auto strat = new a64_u8_nhwc_max_generic_depthfirst(args.cpu_info);
      return new PoolingDepthfirstGeneric<uint8_t>(strat, args);
    },
  },
#endif  // defined(__aarch64__)
  { PoolingMethod::DEFAULT, "", nullptr, nullptr, nullptr },  // End of list
};

template <>
const PoolingImplementation<uint8_t, uint8_t> *pooling_implementation_list()
{
  return pooling_u8_methods;
}

template UniquePoolingCommon<uint8_t, uint8_t> pooling(const PoolingArgs &, const Nothing &);

}  //  namespace pooling
}  //  namespace arm_conv


text:
title:  Inside Story
date:   22/09/2017
---

### Estamos a trabalhar sobre esta lição.
Volte mais tarde, por favor.


text:
'''
Management of PostgreSQL tablespace
===================================

A module used to create and manage PostgreSQL tablespaces.

.. code-block:: yaml

    ssd-tablespace:
      postgres_tablespace.present:
        - name: indexes
        - directory: /mnt/ssd-data

.. versionadded:: 2015.8.0

'''
from __future__ import absolute_import

def __virtual__():
    '''
    Only load if the postgres module is present and is new enough (has ts funcs)
    '''
    return 'postgres.tablespace_exists' in __salt__

def present(name,
            directory,
            options=None,
            owner=None,
            user=None,
            maintenance_db=None,
            db_password=None,
            db_host=None,
            db_port=None,
            db_user=None):
    '''
    Ensure that the named tablespace is present with the specified properties.
    For more information about all of these options see man create_tablespace(1).

    name
        The name of the tablespace to create/manage.
    directory
        The directory where the tablespace will be located, must already exist.
    options
        A dictionary of options to specify for the table.
        Currently, the only tablespace options supported are
        seq_page_cost - float; default=1.0
        random_page_cost - float; default=4.0
    owner
        The database user that will be the owner of the tablespace
        Defaults to the user executing the command (i.e. the `user` option)
    db_user
        database username if different from config or default
    db_password
        user password if any password for a specified user
    db_host
        Database host if different from config or default
    db_port
        Database port if different from config or default
    user
        System user all operations should be performed on behalf of

    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': 'Tablespace {0} is already present'.format(name)}
    dbargs = {
        'maintenance_db': maintenance_db,
        'runas': user,
        'host': db_host,
        'user': db_user,
        'port': db_port,
        'password': db_password,
    }
    tblspaces = __salt__['postgres.tablespace_list'](**dbargs)
    if name not in tblspaces:
        # not there, create it
        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'Tablespace {0} is set to be created'.format(name)
            return ret
        if __salt__['postgres.tablespace_create'](name, directory, options,
                                                  owner, **dbargs):
            ret['comment'] = 'The tablespace {0} has been created'.format(name)
            ret['changes'][name] = 'Present'
            return ret

    # already exists, make sure it's got the right config
    if tblspaces[name]['Location'] != directory and not __opts__['test']:
        ret['comment'] = """Tablespace {0} is not at the right location. This is
            unfixable without dropping and recreating the tablespace.""".format(
                name)
        ret['result'] = False
        return ret

    if owner and not tblspaces[name]['Owner'] == owner:
        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'Tablespace {0} owner to be altered'.format(name)
        if (__salt__['postgres.tablespace_alter'](name, new_owner=owner)
            and not __opts__['test']):
            ret['comment'] = 'Tablespace {0} owner changed'.format(name)
            ret['result'] = True

    if options:
        # options comes from postgres as a sort of json(ish) string, but it
        # can't really be parsed out, but it's in a fairly consistent format
        # that we should be able to string check:
        # {seq_page_cost=1.1,random_page_cost=3.9}
        # TODO remove options that exist if possible
        for k, v in options:
            if '{0}={1}'.format(k, v) not in tblspaces[name]['Opts']:
                # if 'seq_page_cost=1.1' not in '{seq_page_cost=1.1,...}'
                if __opts__['test']:
                    ret['result'] = None
                    ret['comment'] = """Tablespace {0} options to be
                        altered""".format(name)
                    break  # we know it's going to be altered, no reason to cont
                if __salt__['postgres.tablespace_alter'](name,
                                                         set_options={k: v}):
                    ret['comment'] = 'Tablespace {0} opts changed'.format(name)
                    ret['result'] = True

    return ret

def absent(name,
           user=None,
           maintenance_db=None,
           db_password=None,
           db_host=None,
           db_port=None,
           db_user=None):
    '''
    Ensure that the named database is absent.

    name
        The name of the database to remove
    db_user
        database username if different from config or defaul
    db_password
        user password if any password for a specified user
    db_host
        Database host if different from config or default
    db_port
        Database port if different from config or default
    user
        System user all operations should be performed on behalf of
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': ''}

    db_args = {
        'maintenance_db': maintenance_db,
        'runas': user,
        'host': db_host,
        'user': db_user,
        'port': db_port,
        'password': db_password,
    }
    #check if tablespace exists and remove it
    if __salt__['postgres.tablespace_exists'](name, **db_args):
        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'Tablespace {0} is set to be removed'.format(name)
            return ret
        if __salt__['postgres.tablespace_remove'](name, **db_args):
            ret['comment'] = 'Tablespace {0} has been removed'.format(name)
            ret['changes'][name] = 'Absent'
            return ret

    # fallback
    ret['comment'] = 'Tablespace {0} is not present, so it cannot ' \
                     'be removed'.format(name)
    return ret


text:
/**
 * @file
 **/

#pragma once

#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "modules/common/util/factory.h"
#include "modules/map/hdmap/hdmap.h"
#include "modules/planning/proto/planning.pb.h"
#include "modules/planning/scenarios/scenario.h"

namespace apollo {
namespace planning {
namespace scenario {
namespace stop_sign {

// stage context
struct StopSignUnprotectedContext {
  ScenarioStopSignUnprotectedConfig scenario_config;
  std::string current_stop_sign_overlap_id;
  double stop_start_time = 0.0;
  double creep_start_time = 0.0;
  // watch_vehicle: <lane_id, perception_obstacle_ids>
  std::unordered_map<std::string, std::vector<std::string>> watch_vehicles;
  std::vector<std::pair<hdmap::LaneInfoConstPtr, hdmap::OverlapInfoConstPtr>>
      associated_lanes;
};

class StopSignUnprotectedScenario : public Scenario {
 public:
  StopSignUnprotectedScenario(
      const ScenarioConfig& config, const ScenarioContext* context,
      const std::shared_ptr<DependencyInjector>& injector)
      : Scenario(config, context, injector) {}

  void Init() override;

  std::unique_ptr<Stage> CreateStage(
      const ScenarioConfig::StageConfig& stage_config,
      const std::shared_ptr<DependencyInjector>& injector);

  StopSignUnprotectedContext* GetContext() { return &context_; }

 private:
  static void RegisterStages();
  bool GetScenarioConfig();
  int GetAssociatedLanes(const hdmap::StopSignInfo& stop_sign_info);

 private:
  static apollo::common::util::Factory<
      ScenarioConfig::StageType, Stage,
      Stage* (*)(const ScenarioConfig::StageConfig& stage_config,
                 const std::shared_ptr<DependencyInjector>& injector)>
      s_stage_factory_;
  bool init_ = false;
  StopSignUnprotectedContext context_;
};

}  // namespace stop_sign
}  // namespace scenario
}  // namespace planning
}  // namespace apollo


text:
<?xml version="1.0" encoding="UTF-8"?>
<BucketLoggingStatus xmlns="http://doc.s3.amazonaws.com/2006-03-01">
  <LoggingEnabled>
    <TargetBucket>mybucketlogs</TargetBucket>
    <TargetPrefix>mybucket-access_log-/</TargetPrefix>
    <TargetGrants>
      <Grant>
        <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:type="AmazonCustomerByEmail">
          <EmailAddress>user@company.com</EmailAddress>
        </Grantee>
        <Permission>READ</Permission>
      </Grant>
    </TargetGrants>
  </LoggingEnabled>
</BucketLoggingStatus>


text:
package com.sqisland.nfc.hunt.retrofit;

import retrofit.Callback;
import retrofit.http.GET;
import retrofit.http.Query;

/**
 * Created by brenda on 8/1/15.
 */
public interface HarmanService {
    @GET("/init_session")
    void getSession(@Query("Priority") int priority, Callback<Session> cb);

    @GET("/close_session")
    void closeSession(@Query("SessionID") String sessionId, Callback<CloseSessionResponse> cb);

    @GET("/device_list")
    void getDevices(@Query("SessionID") String sessionId, Callback<DeviceList> cb);

    @GET("/add_device_to_session")
    void addDeviceToSession(@Query("SessionID") String sessionId, @Query("DeviceID") String deviceId, Callback<GenericBooleanResponse> cb);

    @GET("/play_web_media")
    void playFromUrl(@Query("SessionID") String sessionId, @Query("MediaUrl") String url, Callback<GenericBooleanResponse> cb);

    @GET("/play_web_media_party_mode")
    void playFromUrlToAllConnectedSpeakers(@Query("SessionID") String sessionId, @Query("MediaUrl") String url, Callback<GenericBooleanResponse> cb);

    @GET("/play_web_media_selected_speakers")
    void playFromUrlToASelectedSpeaker(@Query("SessionID") String sessionId,
                                       @Query("MediaUrl") String url,
                                       @Query("DeviceIDList") String deviceId,
                                       Callback<GenericBooleanResponse> cb);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/author"
        android:paddingLeft="10dp"
        android:paddingTop="10dp"
        android:text="Author"
        android:textColor="@color/colorPrimary"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/content"
        android:paddingLeft="10dp"
        android:paddingTop="10dp"
        android:text="hum magar ye dil ka tohfa dene use aye hain,.. vo ladki jo sabse alag h vo ladki jo sabse juda h"/>
</LinearLayout>