text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.areen.jlib.gui;

import java.awt.*;
import java.beans.*;
import java.util.HashMap;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.text.*;

/**
 *  This class will display line numbers for a related text component. The text
 *  component must use the same line height for each line. TextLineNumber
 *  supports wrapped lines and will highlight the line number of the current
 *  line in the text component.
 *
 *  This class was designed to be used as a component added to the row header
 *  of a JScrollPane.

 * Author: Rob Camick
 * URL: http://tips4java.wordpress.com/2009/05/23/text-component-line-number/
 */
public class TextLineNumber extends JPanel
        implements CaretListener, DocumentListener, PropertyChangeListener {

    public static final float LEFT = 0.0f;
    public static final float CENTER = 0.5f;
    public static final float RIGHT = 1.0f;

    private static final Border OUTER = new MatteBorder(0, 0, 0, 2, Color.GRAY);

    private static final int HEIGHT = Integer.MAX_VALUE - 1000000;

	//  Text component this TextTextLineNumber component is in sync with
    private JTextComponent component;

	//  Properties that can be changed
    private boolean updateFont;
    private int borderGap;
    private Color currentLineForeground;
    private float digitAlignment;
    private int minimumDisplayDigits;

	//  Keep history information to reduce the number of times the component
    //  needs to be repainted
    private int lastDigits;
    private int lastHeight;
    private int lastLine;

    private HashMap<String, FontMetrics> fonts;

    /**
     * Create a line number component for a text component. This minimum display width will be based on 3
     * digits.
     *
     * @param argComponent the related text component
     */
    public TextLineNumber(JTextComponent argComponent) {
        this(argComponent, 3);
    }

    /**
     * Create a line number component for a text component.
     *
     * @param argComponent the related text component
     * @param argMinimumDisplayDigits the number of digits used to calculate the minimum width of the
     * component.
     */
    public TextLineNumber(JTextComponent argComponent, int argMinimumDisplayDigits) {
        component = argComponent;

        setFont(argComponent.getFont());

        setBorderGap(5);
        setCurrentLineForeground(Color.RED);
        setDigitAlignment(RIGHT);
        setMinimumDisplayDigits(argMinimumDisplayDigits);

        argComponent.getDocument().addDocumentListener(this);
        argComponent.addCaretListener(this);
        argComponent.addPropertyChangeListener("font", this);
    }

    /**
     * Gets the update font property
     *
     * @return the update font property
     */
    public boolean getUpdateFont() {
        return updateFont;
    }

    /**
     * Set the update font property. Indicates whether this Font should be updated automatically when the Font
     * of the related text component is changed.
     *
     * @param argUpdateFont when true update the Font and repaint the line numbers, otherwise just repaint the
     * line numbers.
     */
    public void setUpdateFont(boolean argUpdateFont) {
        updateFont = argUpdateFont;
    }

    /**
     * Gets the border gap
     *
     * @return the border gap in pixels
     */
    public int getBorderGap() {
        return borderGap;
    }

    /**
     * The border gap is used in calculating the left and right insets of the border. Default value is 5.
     *
     * @param argBorderGap the gap in pixels
     */
    public void setBorderGap(int argBorderGap) {
        borderGap = argBorderGap;
        Border inner = new EmptyBorder(0, argBorderGap, 0, argBorderGap);
        setBorder(new CompoundBorder(OUTER, inner));
        lastDigits = 0;
        setPreferredWidth();
    }

    /**
     * Gets the current line rendering Color
     *
     * @return the Color used to render the current line number
     */
    public Color getCurrentLineForeground() {
        return currentLineForeground == null ? getForeground() : currentLineForeground;
    }

    /**
     * The Color used to render the current line digits. Default is Coolor.RED.
     *
     * @param argCurrentLineForeground the Color used to render the current line
     */
    public void setCurrentLineForeground(Color argCurrentLineForeground) {
        currentLineForeground = argCurrentLineForeground;
    }

    /**
     * Gets the digit alignment
     *
     * @return the alignment of the painted digits
     */
    public float getDigitAlignment() {
        return digitAlignment;
    }

    /**
     * Specify the horizontal alignment of the digits within the component. Common values would be:
     *

     *
TextLineNumber.LEFT
     *
TextLineNumber.CENTER
     *
TextLineNumber.RIGHT (default)
     *

     *
     * @param currentLineForeground the Color used to render the current line
     */
    public void setDigitAlignment(float argDigitAlignment) {
        digitAlignment = argDigitAlignment > 1.0f ? 1.0f
                                                  : argDigitAlignment < 0.0f ? -1.0f
                                                                             : argDigitAlignment;
    }

    /**
     * Gets the minimum display digits
     *
     * @return the minimum display digits
     */
    public int getMinimumDisplayDigits() {
        return minimumDisplayDigits;
    }

    /**
     * Specify the mimimum number of digits used to calculate the preferred width of the component.
     * Default is 3.
     *
     * @param argMinimumDisplayDigits the number digits used in the preferred width calculation
     */
    public void setMinimumDisplayDigits(int argMinimumDisplayDigits) {
        minimumDisplayDigits = argMinimumDisplayDigits;
        setPreferredWidth();
    }

    /**
     * Calculate the width needed to display the maximum line number
     */
    private void setPreferredWidth() {
        Element root = component.getDocument().getDefaultRootElement();
        int lines = root.getElementCount();
        int digits = Math.max(String.valueOf(lines).length(), minimumDisplayDigits);

		//  Update sizes when number of digits in the line number changes
        if (lastDigits != digits) {
            lastDigits = digits;
            FontMetrics fontMetrics = getFontMetrics(getFont());
            int width = fontMetrics.charWidth('0') * digits;
            Insets insets = getInsets();
            int preferredWidth = insets.left + insets.right + width;

            Dimension d = getPreferredSize();
            d.setSize(preferredWidth, HEIGHT);
            setPreferredSize(d);
            setSize(d);
        }
    }

    /**
     * Draw the line numbers
     */
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

		//	Determine the width of the space available to draw the line number
        FontMetrics fontMetrics = component.getFontMetrics(component.getFont());
        Insets insets = getInsets();
        int availableWidth = getSize().width - insets.left - insets.right;

		//  Determine the rows to draw within the clipped bounds.
        Rectangle clip = g.getClipBounds();
        int rowStartOffset = component.viewToModel(new Point(0, clip.y));
        int endOffset = component.viewToModel(new Point(0, clip.y + clip.height));

        while (rowStartOffset <= endOffset) {
            try {
                if (isCurrentLine(rowStartOffset)) {
                    g.setColor(getCurrentLineForeground());
                } else {
                    g.setColor(getForeground());
                }

    			//  Get the line number as a string and then determine the
                //  "X" and "Y" offsets for drawing the string.
                String lineNumber = getTextLineNumber(rowStartOffset);
                int stringWidth = fontMetrics.stringWidth(lineNumber);
                int x = getOffsetX(availableWidth, stringWidth) + insets.left;
                int y = getOffsetY(rowStartOffset, fontMetrics);
                g.drawString(lineNumber, x, y);

    			//  Move to the next row
                rowStartOffset = Utilities.getRowEnd(component, rowStartOffset) + 1;
            } catch (Exception e) {
                break;
            }
        }
    }

    /*
     *  We need to know if the caret is currently positioned on the line we
     *  are about to paint so the line number can be highlighted.
     */
    private boolean isCurrentLine(int rowStartOffset) {
        int caretPosition = component.getCaretPosition();
        Element root = component.getDocument().getDefaultRootElement();

        return root.getElementIndex(rowStartOffset) == root.getElementIndex(caretPosition);
    }

    /*
     *	Get the line number to be drawn. The empty string will be returned
     *  when a line of text has wrapped.
     */
    protected String getTextLineNumber(int rowStartOffset) {
        Element root = component.getDocument().getDefaultRootElement();
        int index = root.getElementIndex(rowStartOffset);
        Element line = root.getElement(index);

        if (line.getStartOffset() == rowStartOffset) {
            return String.valueOf(index + 1);
        } else {
            return "";
        }
    }

    /*
     *  Determine the X offset to properly align the line number when drawn
     */
    private int getOffsetX(int availableWidth, int stringWidth) {
        return (int) ((availableWidth - stringWidth) * digitAlignment);
    }

    /*
     *  Determine the Y offset for the current row
     */
    private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics)
            throws BadLocationException {
        //  Get the bounding rectangle of the row

        Rectangle r = component.modelToView(rowStartOffset);
        int lineHeight = fontMetrics.getHeight();
        int y = r.y + r.height;
        int descent = 0;

		//  The text needs to be positioned above the bottom of the bounding
        //  rectangle based on the descent of the font(s) contained on the row.
        if (r.height == lineHeight) {
            // default font is being used
            descent = fontMetrics.getDescent();
        } else {
            // We need to check all the attributes for font changes
            if (fonts == null) {
                fonts = new HashMap<String, FontMetrics>();
            }

            Element root = component.getDocument().getDefaultRootElement();
            int index = root.getElementIndex(rowStartOffset);
            Element line = root.getElement(index);

            for (int i = 0; i < line.getElementCount(); i++) {
                Element child = line.getElement(i);
                AttributeSet as = child.getAttributes();
                String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily);
                Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize);
                String key = fontFamily + fontSize;

                FontMetrics fm = fonts.get(key);

                if (fm == null) {
                    Font font = new Font(fontFamily, Font.PLAIN, fontSize);
                    fm = component.getFontMetrics(font);
                    fonts.put(key, fm);
                }

                descent = Math.max(descent, fm.getDescent());
            }
        }

        return y - descent;
    }

//
//  Implement CaretListener interface
//
    @Override
    public void caretUpdate(CaretEvent e) {
        //  Get the line the caret is positioned on

        int caretPosition = component.getCaretPosition();
        Element root = component.getDocument().getDefaultRootElement();
        int currentLine = root.getElementIndex(caretPosition);

		//  Need to repaint so the correct line number can be highlighted
        if (lastLine != currentLine) {
            repaint();
            lastLine = currentLine;
        }
    }

//
//  Implement DocumentListener interface
//
    @Override
    public void changedUpdate(DocumentEvent e) {
        documentChanged();
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        documentChanged();
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        documentChanged();
    }

    /*
     *  A document change may affect the number of displayed lines of text.
     *  Therefore the lines numbers will also change.
     */
    private void documentChanged() {
		//  View of the component has not been updated at the time
        //  the DocumentEvent is fired

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    int endPos = component.getDocument().getLength();
                    Rectangle rect = component.modelToView(endPos);

                    if (rect != null && rect.y != lastHeight) {
                        setPreferredWidth();
                        repaint();
                        lastHeight = rect.y;
                    }
                } catch (BadLocationException ex) { /* nothing to do */ }
            }
        });
    }

//
//  Implement PropertyChangeListener interface
//
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (evt.getNewValue() instanceof Font) {
            if (updateFont) {
                Font newFont = (Font) evt.getNewValue();
                setFont(newFont);
                lastDigits = 0;
                setPreferredWidth();
            } else {
                repaint();
            }
        }
    }

} // TextLineNumber class

// $Id$


text:
import {AfterViewInit, Directive, ElementRef, OnDestroy, NgZone} from '@angular/core';
import {coerceCssPixelValue} from '@angular/cdk/coercion';
import {Directionality} from '@angular/cdk/bidi';
import {ESCAPE} from '@angular/cdk/keycodes';
import {CdkColumnDef, _CoalescedStyleScheduler} from '@angular/cdk/table';
import {fromEvent, Subject, merge} from 'rxjs';
import {
  distinctUntilChanged,
  filter,
  map,
  mapTo,
  pairwise,
  startWith,
  takeUntil,
} from 'rxjs/operators';

import {_closest} from '@angular/cdk-experimental/popover-edit';

import {HEADER_CELL_SELECTOR} from './selectors';
import {ColumnResizeNotifierSource} from './column-resize-notifier';
import {HeaderRowEventDispatcher} from './event-dispatcher';
import {ResizeRef} from './resize-ref';

// TODO: Take another look at using cdk drag drop. IIRC I ran into a couple
// good reasons for not using it but I don't remember what they were at this point.
/**
 * Base class for a component shown over the edge of a resizable column that is responsible
 * for handling column resize mouse events and displaying any visible UI on the column edge.
 */
@Directive()
export abstract class ResizeOverlayHandle implements AfterViewInit, OnDestroy {
  protected readonly destroyed = new Subject<void>();

  protected abstract readonly columnDef: CdkColumnDef;
  protected abstract readonly document: Document;
  protected abstract readonly directionality: Directionality;
  protected abstract readonly elementRef: ElementRef;
  protected abstract readonly eventDispatcher: HeaderRowEventDispatcher;
  protected abstract readonly ngZone: NgZone;
  protected abstract readonly resizeNotifier: ColumnResizeNotifierSource;
  protected abstract readonly resizeRef: ResizeRef;
  protected abstract readonly styleScheduler: _CoalescedStyleScheduler;

  ngAfterViewInit() {
    this._listenForMouseEvents();
  }

  ngOnDestroy() {
    this.destroyed.next();
    this.destroyed.complete();
  }

  private _listenForMouseEvents() {
    this.ngZone.runOutsideAngular(() => {
      fromEvent<MouseEvent>(this.elementRef.nativeElement!, 'mouseenter').pipe(
          mapTo(this.resizeRef.origin.nativeElement!),
          takeUntil(this.destroyed),
      ).subscribe(cell => this.eventDispatcher.headerCellHovered.next(cell));

      fromEvent<MouseEvent>(this.elementRef.nativeElement!, 'mouseleave').pipe(
          map(event => event.relatedTarget &&
              _closest(event.relatedTarget as Element, HEADER_CELL_SELECTOR)),
          takeUntil(this.destroyed)
      ).subscribe(cell => this.eventDispatcher.headerCellHovered.next(cell));

      fromEvent<MouseEvent>(this.elementRef.nativeElement!, 'mousedown')
          .pipe(takeUntil(this.destroyed)).subscribe(mousedownEvent => {
        this._dragStarted(mousedownEvent);
      });
    });
  }

  private _dragStarted(mousedownEvent: MouseEvent) {
    // Only allow dragging using the left mouse button.
    if (mousedownEvent.button !== 0) {
      return;
    }

    const mouseup = fromEvent<MouseEvent>(this.document, 'mouseup');
    const mousemove = fromEvent<MouseEvent>(this.document, 'mousemove');
    const escape = fromEvent<KeyboardEvent>(this.document, 'keyup')
        .pipe(filter(event => event.keyCode === ESCAPE));

    const startX = mousedownEvent.screenX;

    const initialSize = this._getOriginWidth();
    let overlayOffset = 0;
    let originOffset = this._getOriginOffset();
    let size = initialSize;
    let overshot = 0;

    this.updateResizeActive(true);

    mouseup.pipe(takeUntil(merge(escape, this.destroyed))).subscribe(({screenX}) => {
      this.styleScheduler.scheduleEnd(() => {
        this._notifyResizeEnded(size, screenX !== startX);
      });
    });

    escape.pipe(takeUntil(merge(mouseup, this.destroyed))).subscribe(() => {
      this._notifyResizeEnded(initialSize);
    });

    mousemove.pipe(
        map(({screenX}) => screenX),
        startWith(startX),
        distinctUntilChanged(),
        pairwise(),
        takeUntil(merge(mouseup, escape, this.destroyed))
    ).subscribe(([prevX, currX]) => {
      let deltaX = currX - prevX;

      // If the mouse moved further than the resize was able to match, limit the
      // movement of the overlay to match the actual size and position of the origin.
      if (overshot !== 0) {
        if (overshot < 0 && deltaX < 0 || overshot > 0 && deltaX > 0) {
          overshot += deltaX;
          return;
        } else {
          const remainingOvershot = overshot + deltaX;
          overshot = overshot > 0 ?
              Math.max(remainingOvershot, 0) : Math.min(remainingOvershot, 0);
          deltaX = remainingOvershot - overshot;

          if (deltaX === 0) {
            return;
          }
        }
      }

      let computedNewSize: number = size + (this._isLtr() ? deltaX : -deltaX);
      computedNewSize = Math.min(
          Math.max(computedNewSize, this.resizeRef.minWidthPx, 0), this.resizeRef.maxWidthPx);

      this.resizeNotifier.triggerResize.next({
        columnId: this.columnDef.name,
        size: computedNewSize,
        previousSize: size,
        isStickyColumn: this.columnDef.sticky || this.columnDef.stickyEnd,
      });

      this.styleScheduler.scheduleEnd(() => {
        const originNewSize = this._getOriginWidth();
        const originNewOffset = this._getOriginOffset();
        const originOffsetDeltaX = originNewOffset - originOffset;
        const originSizeDeltaX = originNewSize - size;
        size = originNewSize;
        originOffset = originNewOffset;

        overshot += deltaX + (this._isLtr() ? -originSizeDeltaX : originSizeDeltaX);
        overlayOffset += originOffsetDeltaX + (this._isLtr() ? originSizeDeltaX : 0);

        this._updateOverlayOffset(overlayOffset);
      });
    });
  }

  protected updateResizeActive(active: boolean): void {
    this.eventDispatcher.overlayHandleActiveForCell.next(
        active ? this.resizeRef.origin.nativeElement! : null);
  }

  private _getOriginWidth(): number {
    return this.resizeRef.origin.nativeElement!.offsetWidth;
  }

  private _getOriginOffset(): number {
    return this.resizeRef.origin.nativeElement!.offsetLeft;
  }

  private _updateOverlayOffset(offset: number): void {
    this.resizeRef.overlayRef.overlayElement.style.transform =
        `translateX(${coerceCssPixelValue(offset)})`;
  }

  private _isLtr(): boolean {
    return this.directionality.value === 'ltr';
  }

  private _notifyResizeEnded(size: number, completedSuccessfully = false): void {
    this.updateResizeActive(false);

    this.ngZone.run(() => {
      const sizeMessage = {columnId: this.columnDef.name, size};
      if (completedSuccessfully) {
        this.resizeNotifier.resizeCompleted.next(sizeMessage);
      } else {
        this.resizeNotifier.resizeCanceled.next(sizeMessage);
      }
    });
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web;
using System.Web.Caching;

namespace Ivony.Html.Web
{

  /// <summary>
  /// 提供一些 Web 相关的扩展方法。
  /// </summary>
  public static class WebExtenions
  {

  }
}


text:
layout: post
title: Apresentando o portfólio
date: '2018-10-25 17:10:00 +0530'
published: true
---
Dando continuidade, mostro o projeto de portfólio que será desenvolvido para que possamos listar os nossos projetos principais (os que de fato iremos abordar diversas tecnologias).

É uma aplicação bem simples, desenvolvido com **Spring Boot** e uma página de html estática com as informações de cada projeto e as tecnologias que utilizamos em cada um.

Fizemos também o deploy no Heroku, assim já está disponivél na web para que possamos mostrar aos nossos amigos.

Que saber como ficou, perde tempo não ... Acesse ai e veja o resultado.

[Meu Portifolio, hospedado no Heroku](https://meu-portifolio.herokuapp.com/)

### Não deixe de acompanhar o video no canal do YouTube

[#01- Apresentando o portfólio](https://www.youtube.com/watch?v=DEBsUItDm30)

Até mais !

[]'s


text:
// Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS-IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Unit tests for AddHintModalController.
 */

import { TestBed } from '@angular/core/testing';
import { HintObjectFactory } from 'domain/exploration/HintObjectFactory';
import { StateHintsService } from
  // eslint-disable-next-line max-len
  'components/state-editor/state-editor-properties-services/state-hints.service';
import { GenerateContentIdService } from 'services/generate-content-id.service';

describe('Add Hint Modal Controller', function() {
  var $scope = null;
  var $uibModalInstance = null;
  var ContextService = null;
  var generateContentIdService = null;
  var hintObjectFactory = null;
  var stateHintsService = null;

  var existingHintsContentIds = [];

  beforeEach(angular.mock.module('oppia'));

  beforeEach(function() {
    generateContentIdService = TestBed.get(GenerateContentIdService);
    hintObjectFactory = TestBed.get(HintObjectFactory);
    stateHintsService = TestBed.get(StateHintsService);
  });

  beforeEach(angular.mock.inject(function($injector, $controller) {
    var $rootScope = $injector.get('$rootScope');
    ContextService = $injector.get('ContextService');
    spyOn(ContextService, 'getEntityType').and.returnValue('question');

    stateHintsService.init('State1', new Array(4));

    $uibModalInstance = jasmine.createSpyObj(
      '$uibModalInstance', ['close', 'dismiss']);

    $scope = $rootScope.$new();
    $controller('AddHintModalController', {
      $scope: $scope,
      $uibModalInstance: $uibModalInstance,
      GenerateContentIdService: generateContentIdService,
      HintObjectFactory: hintObjectFactory,
      StateHintsService: stateHintsService,
      existingHintsContentIds: existingHintsContentIds
    });
  }));

  it('should initialize $scope properties after controller is initialized',
    function() {
      expect($scope.tmpHint).toBe('');
      expect($scope.addHintForm).toEqual({});
      expect($scope.hintIndex).toBe(5);
    });

  it('should save hint when closing the modal', function() {
    var contentId = 'cont_1';
    var hintExpected = hintObjectFactory.createNew(contentId, '');

    spyOn(
      generateContentIdService, 'getNextStateId'
    ).and.returnValue(contentId);
    $scope.saveHint();

    expect($uibModalInstance.close).toHaveBeenCalledWith({
      hint: hintExpected,
      contentId: contentId
    });
  });
});


text:
package com.example.myshop.http;

import android.content.Context;

import com.example.myshop.adapter.SimpleAdapter;
import com.example.myshop.utils.ToastUtils;

import dmax.dialog.SpotsDialog;
import okhttp3.Request;
import okhttp3.Response;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;

/**
 * Created by Bei on 2016/9/22.
 * 对缓冲进度条的简单封装
 */

public abstract class SpotsCallBack<T> extends SimpleCallback<T> {

    private SpotsDialog mDialog;

    public SpotsCallBack(Context context) {
        super(context);

        initSpotsDialog();
    }

    private void initSpotsDialog() {

        mDialog = new SpotsDialog(mContext, "拼命加载中...");
    }

    public void showDialog() {
        mDialog.show();
    }

    public void dismissDialog() {
        mDialog.dismiss();
    }

    public void setLoadMessage(int resId) {
        mDialog.setMessage(mContext.getString(resId));
    }

    @Override
    public void onBeforeRequest(Request request) {
        showDialog();
    }

    @Override
    public void onResponse(Response response) {
        dismissDialog();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Eshopworld.Core;
using Eshopworld.DevOps;
using EShopWorld.Tools.Common;
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Azure.Management.Dns.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Newtonsoft.Json.Linq;

namespace EShopWorld.Tools.Commands.AzScan
{
    /// <summary>
    /// DNS scanning command
    /// </summary>
    [Command("dns", Description = "scans DNS set up and projects it into KV")]
    // ReSharper disable once InconsistentNaming
    public class AzScanDNSCommand : AzScanCommandBase
    {
        /// <summary>
        /// secret naming prefix
        /// </summary>
        public const string PlatformPrefix = "Platform";
        /// <summary>
        /// secret name suffix for reverse proxy
        /// </summary>
        public const string ProxySecretSuffix = "Proxy";
        /// <summary>
        /// secret name suffix for ELB level
        /// </summary>
        public const string ClusterSecretSuffix = "Cluster";
        /// <summary>
        /// secret name suffix for FrontDoor level
        /// </summary>
        public const string FrontDoorSecretSuffix = "Global";

        private readonly ServiceFabricDiscoveryFactory _sfDiscoveryFactory;
        private readonly ResourceManagementClient _rmClient;

        //as these are used against each and every LB targeting A-record, let's cache
        private IList<ILoadBalancer> _loadBalancersCache;
        private IList<IPublicIPAddress> _pipCache;

        private IAzure _azClient;
        private IConsole _console;

        /// <inheritdoc />
        public AzScanDNSCommand(Azure.IAuthenticated authenticated, AzScanKeyVaultManager keyVaultManager, IBigBrother bigBrother,
            ServiceFabricDiscoveryFactory sfDiscoveryFactory, ResourceManagementClient rmClient) : base(authenticated, keyVaultManager, bigBrother, PlatformPrefix)
        {
            _sfDiscoveryFactory = sfDiscoveryFactory;
            _rmClient = rmClient;
        }

        /// <inheritdoc />
        protected override async Task<int> RunScanAsync(IAzure client, IConsole console)
        {
            _azClient = client;
            _console = console;
            //scope to V2 (global for now) zone
            var zones = (await client.DnsZones.ListByResourceGroupAsync(NameGenerator.GetPlatformRGName(EnvironmentName)))
                .Where(z => z.Name.EndsWith(".private", StringComparison.Ordinal)); //private = V2

            foreach (var zone in zones)
            {

                /**
                 * two main paths - API and UI
                 *
                 * API routing -> FD (~"Global") -> ELB (~"Cluster") -> Node (~"Proxy" - note that reverse proxy may redirect back to cluster)
                 * UI routing -> FD (~"Global")
                 *
                 */

                //hydrate LB, PIP cache
                _loadBalancersCache = (await _azClient.LoadBalancers.ListAsync()).ToList(); //all pages for now due to old RGs and unclear filtering strategy
                _pipCache = (await _azClient.PublicIPAddresses.ListAsync()).ToList(); //all pages, ditto

                //scan CNAMEs -all global definitions
                var tasks = (await zone.CNameRecordSets.ListAsync()).Select(ProcessCName).ToList();

                var aNames = await zone.ARecordSets.ListAsync();

                //append A name scan tasks
                tasks.AddRange(RegionalPlatformResourceGroups.Select(r =>
                         ScanRegionalANames(r, aNames)
                ));

                await Task.WhenAll(tasks);
            }

            return 0;
        }

        private async Task ProcessCName(ICNameRecordSet cname)
        {
            foreach (var keyVaultName in DomainResourceGroup.TargetKeyVaults)
            {
                await KeyVaultManager.SetKeyVaultSecretAsync(keyVaultName, SecretPrefix, cname.Name, "Global",
                    $"https://{cname.Fqdn.TrimEnd('.')}", "-afd");
            }
        }
        private async Task ScanRegionalANames(ResourceGroupDescriptor r, IEnumerable<IARecordSet> aNames)
        {
            var sfDiscovery = _sfDiscoveryFactory.GetInstance(); //region = separate cluster
            await sfDiscovery.CheckConnectionStatus(_azClient, EnvironmentName, r.Region, _console);

            var regionCode = r.Region.ToRegionCode();

            //scan A(Name)s - regional entries
            var tasks = aNames.Where(a => a.Name.RegionCodeCheck(regionCode)).Select(aName => Task.Run(async () =>
            {
                if (!aName.IPv4Addresses.Any())
                {
                    _console.EmitWarning(GetType(), AppInstance.Options,
                        $"DNS entry {aName.Name} does not have any target IP address");
                    return;
                }

                var ipAddress = aName.IPv4Addresses.First();

                foreach (var keyVault in r.TargetKeyVaults)
                {
                    //lookup backend rule in IP matching LB instance - match the rule by name
                    var lbRule = await LookupLoadBalancerPort(aName.Name, ipAddress);

                    if (!lbRule.HasValue) continue;

                    var port = lbRule.Value.port;
                    var portScheme = lbRule.Value.scheme;

                    var clusterRoute =
                        $"{portScheme.ToLowerInvariant()}://{aName.Fqdn.TrimEnd('.')}:{port.ToString(CultureInfo.InvariantCulture)}";

                    await KeyVaultManager.SetKeyVaultSecretAsync(keyVault,
                        SecretPrefix, aName.Name, "Cluster",
                        clusterRoute,
                        "-lb", "-afd");

                    var reverseProxyDetails = sfDiscovery.GetReverseProxyDetails();

                    if (reverseProxyDetails == null)
                    {
                        _console.EmitWarning(typeof(AzScanDNSCommand), AppInstance.Options,
                            $"Unable to lookup reverse proxy details for Service Fabric cluster - Environment - {EnvironmentName} - Region - {r.Region.ToRegionCode().ToPascalCase()}");
                        continue;
                    }

                    var serviceInstanceName = sfDiscovery.LookupServiceNameByPort(port);

                    if (string.IsNullOrWhiteSpace(serviceInstanceName))
                    {
                        _console.EmitWarning(typeof(AzScanDNSCommand), AppInstance.Options,
                            $"Unable to lookup service instance name for {aName.Name}:{port} under {EnvironmentName} environment - Region - {r.Region.ToRegionCode().ToPascalCase()}");
                        continue;
                    }

                    var (proxyScheme, proxyPort) = reverseProxyDetails.Value;

                    var proxyUrl = new UriBuilder(proxyScheme.ToLowerInvariant(), "localhost", proxyPort,
                        serviceInstanceName.RemoveFabricScheme()).ToString();

                    await KeyVaultManager.SetKeyVaultSecretAsync(keyVault, SecretPrefix, aName.Name,
                        "Proxy", proxyUrl, "-lb");
                }
            }));

            await Task.WhenAll(tasks);
        }

        private async Task<(int port, string scheme)?> LookupLoadBalancerPort(string aName, string ipAddress)
        {
            //public or private
            var publicIp =
                _pipCache.FirstOrDefault(i => !string.IsNullOrWhiteSpace(i.IPAddress) && i.IPAddress.Equals(ipAddress, StringComparison.OrdinalIgnoreCase));

            //if public ip, locate by it's id, otherwise by private ip (internal load balancer)
            var targetLb = publicIp != null
                ? _loadBalancersCache.FirstOrDefault(lb =>
                    lb.PublicIPAddressIds.Any(s => s.Equals(publicIp.Id, StringComparison.OrdinalIgnoreCase)))
                : _loadBalancersCache.FirstOrDefault(lb =>
                    lb.Inner.FrontendIPConfigurations.Any(c => !string.IsNullOrEmpty(c.PrivateIPAddress) &&
                        c.PrivateIPAddress == ipAddress));

            if (targetLb == null)
            {
                //treat as raw IP address for monolith purposes - known to target direct VMs etc. @Colin
                return null;
            }

            //remove region and load balancer suffix from dns record name to derive rule name
            var ruleName = aName.EswTrim("-lb", "-afd");

            //find the rule
            var lbRule =
                targetLb.LoadBalancingRules.FirstOrDefault(r =>
                    r.Key.Equals(ruleName, StringComparison.OrdinalIgnoreCase));

            if (!default(KeyValuePair<string, ILoadBalancingRule>).Equals(lbRule))
            {
                var probe = await _rmClient.Resources.GetByIdAsync(lbRule.Value.Inner.Probe.Id, "2019-04-01" /*not supported in latest */);
                return (lbRule.Value.BackendPort, ((JObject) probe.Properties)["protocol"].Value<string>());
            }

            _console.EmitWarning(GetType(), AppInstance.Options,
                $"No Load balancer rule found for {aName} under {targetLb.Name} load balancer");

            return null;
        }
    }
}


text:
## A Closer Look at `Hello, World!`

Now that we have a program written, compiled and running, its time take a look at its innards and learn what makes the whole thing work. We'll examine the program in two steps to get a better understanding of what is going on:

* **Understanding the Source** : Taking a closer look at the various pieces that make up a C++ *source file* will yeild a deeper insight of the structure of C++ programs and help surface the meaning behind some of the alphabet soup in `hello.cpp`.
* **Debugging the Binary** : Examining the running program is a good first step in introducing debuggers and the debugging process, which is an indispensible tool for diagnosing programs that compile fine but don't quite work the way they're supposed to.

### Understanding the Source

Let's take another look at the `Hello, World!` [program](http://cpp.sh/2vm5q) from the previous chapter:

```cpp
// Hello, World! Program
// File: hello.cpp
// Compile With: g++ --std=c++11 hello.cpp -o a.out
#include <iostream>

int main()
{
  std::cout<<"Hello, World!"<<std::endl;
  return 0;
}
```
As it stands, the above program can be broken down into the following logically pieces, starting with the first line of source:

* The first 3 lines (each starting with a `//`), which are comments. Comments are handy little notes written by programmers, for programmers and are completely ignored by the compiler. Programmers usually use comments to explain the intent or purpose of code they've just written. In the above example however, comments are used to convey additional information (viz. the command for compiling the example). In C++, comments begin with `//` (two forward slashes) and continue upto the end of the line. C++ also supports multi-line comments that begin with `/*` and end with `*/` and span across multiple lines:

    ```cpp
    /* Hello, World! Program
     File: hello.cpp
     Compile With: g++ --std=c++11 hello.cpp -o a.out */
    #include <iostream>
    ```
The change in commenting style makes no difference whatsoever to compiler (remember, compilers simply ignore any comments).

* The `#include` statement, immediately after the comments, is a directive for "pulling-in" code from other files. The filename to be "pulled-in" is enclosed between the two angle brackets (`<` and `>`) just after the `#include` directive. As the source file `hello.cpp` containing the example is processed, code from the file `iostream` gets "pulled-in" and pasted into `hello.cpp`. The compiler then processes code from both `iostream` and `hello.cpp` as if they were a single file. This method of pulling stuff in makes it easy to re-use pre-existing code saving both time and effort required for accomplishing common tasks. In the `Hello, World!` example, the `#include <iostream>` is a directive that "pulls-in" code from `iostream` which contains code allowing the programmer to display text on screen and read input from the keyboard.

* The most important part of the *source file* is the bit following the `#include` statment. The line in question:
    ```cpp
    int main()
    ```
defines the "entry point" for the `Hello, World!` example. An entry point is where a program begins execution. `main()` is by convention the entry point for all C++ programs. If your program does not have a `main()`, the compiler will complain.

* Near the very end of `main()` is the `return` statement:
    ```cpp
    return 0;
    ```
Although not strictly necessary, having a `return` statement at the end of `main()` is a good habit to get into. The `return` marks the end of `main()` and the value `0` following the `return`, indicates a successful run of your program.

#### Miscellaneous Syntax Elements

C++ code usually has a bunch of recurring punctuation marks peppered all over the *source file*. Some really obvious ones are:

* The `;` (semicolons) that appear at the end of each *statement* and since there's usually one *statement* per line, there's usually one at the end of line. These semicolons are the programmer's way of saying "I'm done with this bit, let's move on to the next" to the compiler. Missing out on semicolons will cause the compiler to produce errors.

* The `{` and `}` (curly-braces) specify the extent of statements that make up `main()`. Generally, these are used to group `statement`s into a `block`. A `block` is a just a bunch of instructions that are treated as a single unit. The `block` is then treated as the extent for various other language constructs (such as conditionals, loops and functions).

In C++ *whitspace* (spaces, tabs and newlines) is irrelevant by the compiler (which is different from say Python or Haskell) and therefore these markers are an easy way to indicate the end of a *statement* and for demarcating the beginning and end of a group of *statement*s that need to be treated as a block.

##### Note on Compiler Errors

While compiling the `Hello, World!` example, there might be errors reported by the compiler, `gcc`. Please take a look at [this](misc_gcc_errors.md) note for additional info on some common errors and how to go about understanding and fixing them.

### Debugging the Binary

#### What is Debugging?

*Debugging*, a task that goes hand-in-hand with programming, basically involves running a program binary in a controlled manner with the aim of resolving defects. A *defect* (aka *bug*) is an oddity in program behaviour and occurs when the program does not perform its intended task or behaves unexpected. The controlled environment for debugging can be created with the aid of a special program called a *debugger*. See [here](https://en.wikipedia.org/wiki/Debugging) for a more formal and thorough treatment of *debugging* and [here](https://en.wikipedia.org/wiki/Debugger) for details on debuggers.

In a nutshell, the power and utility of debuggers stems from the fact that they:

* can control the speed of execution of the program being debugged, which allows programmers can pause code exection and jump over parts of code they're not interested. Since computers are so fast, it is near impossible to identify the exact location and cause of *defects* in a program running at its usual speed (the "problem code" will already have executed by the time we realize what is going on). Jumping over parts no related to the problem at hand and pausing at places where the bug may possibly be hiding makes the whole process quicker. Thus, being able to control the speed and length of program execution is real handy when bug-hunting.

* allow looking at the state of the program being debugged, as it is running, which allows programmers to identify when exactly things being to go wrong. Looking at parts of a program, the path of execution that the program takes and the results of calculations it performs are all clues that can help zero-in on the cause of a *defect*. The debugger allows the programmer to take a good look at all these (and more).

Normal program execution doesn't afford this kind of control, although crude work-arounds can be applied to afford some level of control. These (and many, many other advanced) features in debuggers make them a highly indispensible tool.

While the main motivation for *debugging* is to identify (and fix) *defects*, it is also useful for observing how program execution really occurs. This information is really handy in many different situations, such as for identifying areas of improvement.

For the purposes of this tutorial, the [GNU Debugger](https://www.gnu.org/software/gdb/) aka `gdb` will be used for *debugging* the sample code, starting with the "Hello, World!" sample from the previous chapter.

#### Changes to Facilitate Debugging

Before we can begin debugging "Hello, World!" we'll need to pass additional command-line options to the compiler, so that additional information for facilitating debugging is added to the generated binary:
  ```
  g++ --std=c++11 -ggdb -O0 hello.cpp -o a.out`
  ```
A brief description of what these two options do is given below:
* `-ggdb` instructs the compiler to generate and embed detailed information for debugging within the generated binary. Normally, debug information is kept to a minimum in order to reduce the size of generated `a.out` file.
* `-O0` which instructs the compiler not to perform any optimizations. Optimizations are clever little tricks that the compiler pulls behind the scenes to make your code run faster (this flag is not really necessary, since it is usually the default).
  <sup>**PS:** Just to avoid any confusion, this option is the capital alphabet `O` followed by the numeral zero `0`.</sup>

#### A Taste of Debugging

After the *source file* has been re-compiled with the above options, we're ready to go. The debugger can be invoked via the command line by pass the name of the binary to be debugged as a parameter:
  ```
  test@test-desktop:~$ gdb a.out
  ```
After printing a bunch of information, the following prompt is displayed:
  ```
  (gdb)
  ```
Which indicates that the debugger is ready to accept commands, which are simple English words like `start`, `step` and `continue`, from the programmer. These commands instruct the debugger to perform various actions and afford a lot of control over the binary being debugged. For example, typing the command `start` at the prompt will begin running the binary being debugged:

  ```
  (gdb) start
  Breakpoint 1 at 0x80486c5: file hello.cpp, line 7.
  Starting program: /home/test/a.out
  main () at hello.cpp:7

  (gdb)
  ```
However, instead of printing `Hello, World!` and terminating, as it normally would, we see that the debugger has begun executing the program, but stopped just after entering `main()`. This feature of the debugger which allows the programmer to pause the program at a specific place, such as just after entering `main()`, is called a *breakpoint*. True to their name, *breakpoint*s are positions in code (usually identified by a line number: `file hello.cpp, line 7`, in the listing) where the debugger "breaks" (or pauses) program execution and allows the programmer to run more commands (presumably to poke around and look at the state of the running program). We'll see later how to specify and use *breakpoint*s for debugging at a later time. `start` essentially is short hand for "add *breakpoint* in `main()`".

After `start`ing debugging (or pausing at a different `breakpoint`) we can use the command `step` to have the debugger execute one source-line and stop right after that:

```
(gdb) step
Hello, World!
8		return 0;
```
This feature called *single-stepping*, allows running the program "line-by-line", thus giving the programmer an opportunity to analyse what the program does as each line of code executes. This feature is quite useful for identifying excatly where deviations from expected behaviour occur.

We can continue `step`ping thorugh the program till it terminates normally:

```
(gdb) step
9	}
(gdb) step
0xb7d5f775 in __libc_start_main () from /lib/tls/i686/cmov/libc.so.6
(gdb) step
Single stepping until exit from function __libc_start_main,
which has no line number information.

Program exited normally.
(gdb)
```

We can also let the program run to completion, just like when it does without a debugger, via the `continue` command:

```
(gdb) start
Breakpoint 3 at 0x80486c5: file hello.cpp, line 7.
Starting program: /home/seed/a.out
main () at hello.cpp:7
7		std::cout<<"Hello, World!"<<std::endl;
(gdb) continue
Continuing.
Hello, World!

Program exited normally.
(gdb)
```

Although not very useful for this particular instance, the `continue` command resumes normal execution until another *breakpoint* is encountered. This feature thus allows the programmer to "jump" over large portions of the source code which are irrelevant to the problem at hand, because it . We'll take a closer look at this feature in the topics to come.

After *debugging* is complete, we can exit the debugger and return to the command-prompt, via the `quit` command, like so:
   ```
   Program exited normally.
   (gdb) quit
   test@test-desktop:~$
   ```

[Index](../Index.md)


text:
#include <compiler.h>
#include <debug.h>
#include <string.h>
#include <app.h>
#include <arch.h>
#include <platform.h>
#include <target.h>
#include <lib/heap.h>
#include <lib/dpc.h>
#include <lib/fs.h>
#include <lib/bio.h>
#include <kernel/thread.h>
#include <kernel/timer.h>
#include <kernel/debug.h>

extern void *__ctor_list;
extern void *__ctor_end;
extern int __bss_start;
extern int _end;

static int bootstrap2(void *arg);

static void call_constructors(void)
{
	void **ctor;

	ctor = &__ctor_list;
	while (ctor != &__ctor_end) {
		void (*func)(void);

		func = (void (*)())*ctor;

		func();
		ctor++;
	}
}

/* called from crt0.S */
void kmain(void) __NO_RETURN __EXTERNALLY_VISIBLE;
void kmain(void)
{
	inc_critical_section();

	// get us into some sort of thread context
	thread_init_early();

	// early arch stuff
	arch_early_init();

	// do any super early platform initialization
	platform_early_init();

	// do any super early target initialization
	target_early_init();

	dprintf(INFO, "welcome to lk\n\n");

	// deal with any static constructors
	dprintf(SPEW, "calling constructors\n");
	call_constructors();

	// bring up the kernel heap
	dprintf(SPEW, "initializing heap\n");
	heap_init();

	// if enabled, configure the kernel's event log
	kernel_evlog_init();

	// initialize the threading system
	dprintf(SPEW, "initializing threads\n");
	thread_init();

	// initialize kernel timers
	dprintf(SPEW, "initializing timers\n");
	timer_init();

	// create a thread to complete system initialization
	dprintf(SPEW, "creating bootstrap completion thread\n");
	thread_t *t = thread_create("bootstrap2", &bootstrap2, NULL, DEFAULT_PRIORITY, DEFAULT_STACK_SIZE);
	thread_detach(t);
	thread_resume(t);

	// become the idle thread and enable interrupts to start the scheduler
	thread_become_idle();
}

int main(void);

static int bootstrap2(void *arg)
{
	dprintf(SPEW, "top of bootstrap2()\n");

	arch_init();

	// initialize the dpc system
#if WITH_LIB_DPC
	dpc_init();
#endif

	// XXX put this somewhere else
#if WITH_LIB_BIO
	bio_init();
#endif
#if WITH_LIB_FS
	fs_init();
#endif

	// initialize the rest of the platform
	dprintf(SPEW, "initializing platform\n");
	platform_init();

	// initialize the target
	dprintf(SPEW, "initializing target\n");
	target_init();

	dprintf(SPEW, "calling apps_init()\n");
	apps_init();

	return 0;
}


text:
package log

import (
	"fmt"
	"io"
	"os"
	"syscall"
	"unsafe"
)

// Colors.
const (
	ColorBlue    = "\x1b[0;34m"
	ColorGreen   = "\x1b[0;32m"
	ColorYellow  = "\x1b[0;33m"
	ColorRed     = "\x1b[0;31m"
	ColorMegenta = "\x1b[0;35m"

	ColorRST = "\x1b[0;m"
)

func paint(str string, color string) string {
	return fmt.Sprintf("%s%s%s", color, str, ColorRST)
}

// IsTerminal returns true if the given writer supports colored output.
func IsTerminal(w io.Writer) bool {
	var fd int
	switch w {
	case os.Stdout:
		fd = syscall.Stdout
	case os.Stderr:
		fd = syscall.Stderr
	default:
		return false
	}
	var termios syscall.Termios
	_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioCtlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
	return err == 0
}


text:
package storage

import (
	"fmt"
	"sort"
	"strings"
	"sync"
)

// MemStore is an in memory only implementation of the storage.Interface.
// This is intend to be used for testing use cases only.
type MemStore struct {
	mu    sync.Mutex
	Name  string
	store map[string][]byte
}

func NewMemStore(name string) *MemStore {
	return &MemStore{
		Name:  name,
		store: make(map[string][]byte),
	}
}

func (s *MemStore) View(f func(tx ReadOnlyTx) error) error {
	return DoView(s, f)
}

func (s *MemStore) Update(f func(tx Tx) error) error {
	return DoUpdate(s, f)
}

func (s *MemStore) Put(key string, value []byte) error {
	s.mu.Lock()
	s.store[key] = value
	s.mu.Unlock()
	return nil
}

func (s *MemStore) Get(key string) (*KeyValue, error) {
	s.mu.Lock()
	value, ok := s.store[key]
	s.mu.Unlock()
	if !ok {
		return nil, ErrNoKeyExists
	}
	return &KeyValue{
		Key:   key,
		Value: value,
	}, nil
}

func (s *MemStore) Delete(key string) error {
	s.mu.Lock()
	delete(s.store, key)
	s.mu.Unlock()
	return nil
}

func (s *MemStore) Exists(key string) (bool, error) {
	s.mu.Lock()
	_, ok := s.store[key]
	s.mu.Unlock()
	return ok, nil
}

type keySortedKVs []*KeyValue

func (s keySortedKVs) Len() int               { return len(s) }
func (s keySortedKVs) Less(i int, j int) bool { return s[i].Key < s[j].Key }
func (s keySortedKVs) Swap(i int, j int)      { s[i], s[j] = s[j], s[i] }

func (s *MemStore) List(prefix string) ([]*KeyValue, error) {
	s.mu.Lock()
	kvs := make([]*KeyValue, 0, len(s.store))
	for k, v := range s.store {
		if strings.HasPrefix(k, prefix) {
			kvs = append(kvs, &KeyValue{Key: k, Value: v})
		}
	}
	s.mu.Unlock()
	sort.Sort(keySortedKVs(kvs))
	return kvs, nil
}

func (s *MemStore) BeginTx() (Tx, error) {
	return s.newTx()
}

func (s *MemStore) BeginReadOnlyTx() (ReadOnlyTx, error) {
	return s.newTx()
}

func (s *MemStore) newTx() (*memTx, error) {
	// A Tx carries the lock, and must be committed or rolledback before another operation can continue.
	s.mu.Lock()
	store := make(map[string][]byte, len(s.store))
	for k, v := range s.store {
		store[k] = v
	}
	return &memTx{
		m:     s,
		store: store,
	}, nil
}

type memTxState int

const (
	unCommitted memTxState = iota
	committed
	rolledback
)

type memTx struct {
	state memTxState
	m     *MemStore
	store map[string][]byte
}

func (t *memTx) Get(key string) (*KeyValue, error) {
	value, ok := t.store[key]
	if !ok {
		return nil, ErrNoKeyExists
	}
	return &KeyValue{Key: key, Value: value}, nil
}

func (t *memTx) Exists(key string) (bool, error) {
	_, ok := t.store[key]
	return ok, nil
}

func (t *memTx) List(prefix string) ([]*KeyValue, error) {
	kvs := make([]*KeyValue, 0, len(t.store))
	for k, v := range t.store {
		if strings.HasPrefix(k, prefix) {
			kvs = append(kvs, &KeyValue{Key: k, Value: v})
		}
	}
	sort.Sort(keySortedKVs(kvs))
	return kvs, nil
}

func (t *memTx) Put(key string, value []byte) error {
	t.store[key] = value
	return nil
}

func (t *memTx) Delete(key string) error {
	delete(t.store, key)
	return nil
}

func (t *memTx) Commit() error {
	if t.state == unCommitted {
		t.m.store = t.store
		t.state = committed
		t.m.mu.Unlock()
		return nil
	}
	return fmt.Errorf("cannot commit transaction, transaction in state %v", t.state)
}

func (t *memTx) Rollback() error {
	if t.state == unCommitted {
		t.state = rolledback
		t.m.mu.Unlock()
	}
	return nil
}


text:
<?php
	$g_mantis_worklog_table              = plugin_table('results');

	#----------------------------------
	# faq page definitions

	$g_worklog_menu_page                 = plugin_page( 'worklog_menu_page.php' );
	$g_worklog_view_page                 = plugin_page( 'worklog_view_page.php' );

	$g_worklog_edit_page                 = plugin_page( 'worklog_edit_page.php' );
	$g_worklog_add_page                  = plugin_page( 'worklog_add_page.php' );
	$g_worklog_add                       = plugin_page( 'worklog_add.php' );
	$g_worklog_add2                       = plugin_page( 'worklog_add2.php' );
	$g_worklog_delete_page               = plugin_page( 'worklog_delete_page.php' );
	$g_worklog_delete                    = plugin_page( 'worklog_delete.php' );
	$g_worklog_update                    = plugin_page( 'worklog_update.php' );

		#----------------------------------

	###########################################################################
	# faq API
	###########################################################################

	# function worklog_add   ( $p_project_id, $p_poster_id, $p_content, $p_subject, $p_log_type, $p_log_begin, $p_log_end , $p_ref_issue_ids,$p_ref_log_ids );
	# function worklog_delete( $p_id );
	# function worklog_update( $p_id, $p_content,  $p_subject , $p_log_type, $p_log_begin, $p_log_end , $p_ref_issue_ids,$p_ref_log_ids);
	# function worklog_select( $p_id );

	# --------------------
	function worklog_add_query( $p_project_id, $p_poster_id, $p_content, $p_subject, $p_log_type, $p_log_begin, $p_log_end , $p_ref_issue_ids,$p_ref_log_ids, $p_view_level= 10) {
		global $g_mantis_worklog_table;

		# " character poses problem when editting so let's just convert them
		$p_content	= db_prepare_string( $p_content );
		$p_subject	= db_prepare_string( $p_subject );

		# Add item
		$query = "INSERT
				INTO $g_mantis_worklog_table
	    		( id, project_id, poster_id, date_posted, last_modified, content, subject, log_type,log_begin,log_end,ref_issue_ids,ref_log_ids, view_access )
				VALUES
				( null, '$p_project_id', '$p_poster_id', NOW(), NOW(), '$p_content', '$p_subject','$p_log_type','$p_log_begin','$p_log_end',
				 '$p_ref_issue_ids','$p_ref_log_ids',
				'$p_view_level' )";
	    return db_query_bound( $query );
	}
	# --------------------
	# Delete the faq entry
	function worklog_delete_query( $p_id ) {
		global $g_mantis_worklog_table;

		$query = "DELETE
				FROM $g_mantis_worklog_table
	    		WHERE id='$p_id'";
	    return db_query_bound( $query );
	}
	# --------------------
	# Update faq item
	function worklog_update_query( $p_id, $p_content, $p_subject, $p_log_type, $p_log_begin, $p_log_end, $p_project_id ,$p_ref_issue_ids,$p_ref_log_ids,$p_view_level) {
		global $g_mantis_worklog_table;

		# " character poses problem when editting so let's just convert them to '
		$p_content	= db_prepare_string( $p_content );
		$p_subject		= db_prepare_string( $p_subject );

		# Update entry
		$query = "UPDATE $g_mantis_worklog_table
				SET content='$p_content',
				subject='$p_subject',
				log_type='$p_log_type',
				log_begin='$p_log_begin',
				log_end='$p_log_end',
				ref_issue_ids='$p_ref_issue_ids',
				ref_log_ids='$p_ref_log_ids',
					project_id='$p_project_id', view_access='$p_view_level', last_modified=NOW()
	    		WHERE id='$p_id'";
	    return db_query_bound( $query );
	}
	# --------------------
	# Selects the faq item associated with the specified id
	function worklog_select_query( $p_id ) {
		global $g_mantis_worklog_table;

		$query = "SELECT *
			FROM $g_mantis_worklog_table
			WHERE id='$p_id'";
	    $result = db_query_bound( $query );
		return db_fetch_array( $result );
	}
	# --------------------
	# get faq count (selected project plus sitewide posts)
	function worklog_count_query( $p_project_id ) {
		global $g_mantis_worklog_table;

		$query = "SELECT COUNT(*)
				FROM $g_mantis_worklog_table";
//				;WHERE project_id='$p_project_id' OR project_id='0000000'";
		$result = db_query_bound( $query );
	    return db_result( $result, 0, 0 );
	}

    function worklog_type_display($p_log_type) {
		switch($p_log_type){
			case 0:return plugin_lang_get('log_type_day');
			case 1:return plugin_lang_get('log_type_week');
			case 2:return plugin_lang_get('log_type_month');
			case 3:return plugin_lang_get('log_type_year');
		}
		return '';
    }


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Xerces-C++: File Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Xerces-C++
    3.1.2

Main Page

Related Pages

Classes

Files

File List

File Members

All

Functions

Variables

Typedefs

Macros

c

d

f

g

l

m

p

s

t

u

v

x

Here is a list of all file members with links to the files they belong to:

- l -

LocationHint
: XMLSchemaDescription.hpp

<address class="footer">
Generated on Wed Mar 18 2015 10:43:39 for Xerces-C++ by

 1.8.9.1
</address>


text:
{% macro render_files(post_item) %}
    {% if post_item.files %}
        {% for file in post_item.files %}

        {% endfor %}
    {% endif %}
{% endmacro %}

{% macro render(post_item, thread, board=None, snippet=False, link_refno=False,
                board_info=False, with_divider=False, checkbox=False,
                file_position='bottom', is_locked=False, is_sticky=False) %}
    {# NOTE: keep this in line with the javascript post html builder #}

            {% if post_item.subject %}

                    {{ post_item.subject }}

            {% endif %}
            #{{ post_item.refno }}

                {{ post_item.name|post_name }}

            {% if post_item.mod_code %}
                {{ post_item.mod_code }}
            {% endif %}

                {{ post_item.date|post_time }}

            {% if is_locked %}[locked] {% endif %}
            {% if is_sticky %}[sticky]{% endif %}
            {% if checkbox %}

                <input type="checkbox" name="post_id" value="{{ post_item.id }}">

            {% endif %}

            {% if post_item.files %}

                {% for file in post_item.files %}
                    File: {{ file.original_name }} {{ '(' ~ file.size|filesizeformat ~ ', ' ~ file.width ~ 'x' ~ file.height ~ ')' }}{% if not loop.last %}
{% endif %}
                {% endfor %}
            {% endif %}

        {% if file_position == 'top' %}
            {{ render_files(post_item) }}
        {% endif %}
        {% if post_item.html_text %}

                {{ post_item.html_text|safe }}

        {% endif %}
        {% if file_position == 'bottom' %}
            {{ render_files(post_item) }}
        {% endif %}
        {% if board_info %}

                {% if thread.omitted_count %}
                    {{ thread.omitted_count ~ ' ' ~ thread.omitted_count|pluralize('reply', 'replies') }} omitted
                {% endif %}
                [View thread]

        {% endif %}

{% endmacro %}


text:
FOUNDATION_EXPORT double Pods_BeeFunVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_BeeFunVersionString[];


text: Watch the Prolific synchronous message temporary directory.


text:
var util = require('../util');
var Rest = require('./rest');
var Json = require('./json');
var JsonBuilder = require('../json/builder');
var JsonParser = require('../json/parser');

function populateBody(req) {
    var builder = new JsonBuilder();
    var operation = req.service.api.operations[req.operation];
    var input = operation.input;
    var inputShape = input;
    var params = {};
    var defaultTarget = (req.service.api.targetPrefix + '.' + operation.name);

    var json_body = {
        method: operation.httpTarget || defaultTarget,
        version: req.service.api.apiVersion
    };

    if (input.payload) {
        var payloadShape = input.members[input.payload];
        if (req.params[input.payload] === undefined) return;

        if (payloadShape.type === 'structure') {
            inputShape = payloadShape;
            params = req.params[input.payload];
        } else { // non-JSON payload
        }
    } else {
        params = req.params;
    }

    if (params.hasOwnProperty('requestId') && params.requestId) {
        json_body.id = params.requestId;
        delete params.requestId;
    }

    json_body.params = JSON.parse(builder.build(params, inputShape));
    req.httpRequest.body = JSON.stringify(json_body);
}

function buildRequest(req) {
    var operation = req.service.api.operations[req.operation];
    // var defaultTarget = (req.service.api.targetPrefix + '.' + operation.name);

    Rest.buildRequest(req);
    req.httpRequest.method = 'POST';
    req.httpRequest.headers['Content-Type'] = 'application/json';
    // req.httpRequest.headers['X-Hive-Target'] = operation.httpTarget || defaultTarget;
    populateBody(req);
}

function extractError(resp) {
    var error = {};
    var httpResponse = resp.httpResponse;

    error.code = httpResponse.headers['x-hive-errortype'] || 'UnknownError';
    if (typeof error.code === 'string') {
        error.code = error.code.split(':')[0];
    }

    if (httpResponse.body.length > 0) {
        var r = JSON.parse(httpResponse.body.toString());
        if (r.error) {
            error.code = (r.error.code).toString().split('#').pop();
        }
        if (error.code === 'RequestEntityTooLarge') {
            error.message = 'Request body must be less than 1 MB';
        } else {
            error.message = (r.error.message || r.error.Message || null);
        }
        if (r.id) {
            error.requestId = r.id;
        }
    } else {
        error.statusCode = httpResponse.statusCode;
        error.message = httpResponse.statusCode.toString();
    }

    resp.error = util.error(new Error(), error);
}

function extractData(resp) {
    Rest.extractData(resp);

    var json = JSON.parse(resp.httpResponse.body.toString() || '{}');
    if (!util.isEmpty(json) && json.hasOwnProperty('error')) {
        extractError(resp);
        return;
    }

    var req = resp.request;
    var rules = req.service.api.operations[req.operation].output || {};
    if (rules.payload) {
        var payloadMember = rules.members[rules.payload];
        var body = resp.httpResponse.body;
        if (payloadMember.isStreaming) {
            resp.data[rules.payload] = body;
        } else if (payloadMember.type === 'structure' || payloadMember.type === 'list') {
            var parser = new JsonParser();
            resp.data[rules.payload] = parser.parse(body, payloadMember);
        } else {
            resp.data[rules.payload] = body.toString();
        }
    } else {
        var data = resp.data;
        Json.extractData(resp);
        if (!util.isEmpty(data)) {
            resp.data = util.merge(data, resp.data);
        }
    }
    if (!util.isEmpty(resp.data) && resp.data.hasOwnProperty('result')) {
        resp.data = resp.data.result;
    }
}

module.exports = {
    buildRequest: buildRequest,
    extractError: extractError,
    extractData: extractData
};


text:
<meta charset=utf-8>
<iframe src=//{{domains[élève]}}:{{location[port]}}/html/browsers/windows/resources/opener-cross-origin.html></iframe>


text:
Creating new pages
~~~~~~~~~~~~~~~~~~

.. image:: ../_static/images/screen08_add_page_button.png

Create new pages by clicking the **Add child page** button. This creates a child page of the section you are currently in. In this case a child page of the 'School of Fine Art' page.

.. ADD IN OTHER WAYS A CHILD PAGE CAN BE ADDED?>>

.. toctree::
   :maxdepth: 3

   selecting_a_page_type
   creating_body_content
   inserting_images
   inserting_links
   inserting_videos
   inserting_documents
   adding_multiple_items
   required_fields
   Edit Page tabs <the_promote_tab>
   previewing_and_submitting_for_moderation


text:
@interface NSDate (Helper)

- (NSUInteger)daysAgo;
- (NSUInteger)daysAgoAgainstMidnight;
- (NSString *)stringDaysAgo;
- (NSString *)stringDaysAgoAgainstMidnight:(BOOL)flag;
- (NSUInteger)weekday;
- (NSString*)weekdayString;

+ (NSDate *)dateFromString:(NSString *)string;
+ (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format;
+ (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)string;
+ (NSString *)stringFromDate:(NSDate *)date;
+ (NSString *)stringForDisplayFromDate:(NSDate *)date;
+ (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed;
+ (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed alwaysDisplayTime:(BOOL)displayTime;

- (NSString *)string;
- (NSString *)stringWithFormat:(NSString *)format;
- (NSString *)stringWithDateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle;

- (NSDate *)beginningOfWeek;
- (NSDate *)beginningOfDay;
- (NSDate *)endOfWeek;

+ (NSString *)dateFormatString; //@"yyyy-MM-dd"
+ (NSString *)timeFormatString;
+ (NSString *)timestampFormatString;
+ (NSString *)dbFormatString;

-(NSString *)prettyDateWithReference:(NSDate *)reference;
@end


text:
""" p2p-streams  (c)  2014 enen92 fightnight

    This file contains functions to link acestream or sopcast depending on the given argument (id or url).
    It is used for the items in the main menu

    Functions:

    go_to_id(p2p_type) -> Receives the type of stream (sop or ace) and activates the keyboard to receive the next argument. This can be the sop id, the acestream hash or the sop url.

"""

import xbmc,sys
from peertopeerutils.pluginxbmc import *
import sopcast as sop
import acestream as ace

def go_to_id(p2p_type):
	if p2p_type=='ace':
		keyb = xbmc.Keyboard('', translate(40033))
		keyb.doModal()
		if (keyb.isConfirmed()):
			search = keyb.getText()
			if search=='': sys.exit(0)
			else:
				channel_id = search
				ace.acestreams(translate(40035) + ' ( ' + str(channel_id) + ')','',str(channel_id))
	elif p2p_type=='sop_id':
		channel_id = xbmcgui.Dialog().numeric(0, translate(40033))
		sop.sopstreams(translate(40035) + ' ( ' + str(channel_id) + ')','',str(channel_id))
	elif p2p_type=='sop_url':
		keyb = xbmc.Keyboard('sop://', translate(40034) + ' sop://')
		keyb.doModal()
		if (keyb.isConfirmed()):
			search = keyb.getText()
			if search=='': sys.exit(0)
			else:
				channel_id = search
				sop.sopstreams(translate(40036) + ' ( ' + str(channel_id) + ')','',str(channel_id))


text:
require 'log4r'

require 'vagrant/util/busy'
require 'vagrant/util/network_ip'
require 'vagrant/util/platform'
require 'vagrant/util/subprocess'
require 'vagrant/util/which'

module VagrantPlugins
  module Parallels
    module Driver
      # Base class for all Parallels drivers.
      #
      # This class provides useful tools for things such as executing
      # PrlCtl and handling SIGINTs and so on.
      class Base
        # Include this so we can use `Subprocess` more easily.
        include Vagrant::Util::Retryable
        include Vagrant::Util::NetworkIP

        def initialize(uuid)
          @uuid = uuid
          @logger = Log4r::Logger.new('vagrant_parallels::driver::base')

          # This flag is used to keep track of interrupted state (SIGINT)
          @interrupted = false

          @prlctl_path    = util_path('prlctl')
          @prlsrvctl_path = util_path('prlsrvctl')
          @prldisktool_path = util_path('prl_disk_tool')

          if !@prlctl_path
            # This means that Parallels Desktop was not found, so we raise this
            # error here.
            raise VagrantPlugins::Parallels::Errors::ParallelsNotDetected
          end

          @logger.info("prlctl path: #{@prlctl_path}")
          @logger.info("prlsrvctl path: #{@prlsrvctl_path}")
        end

        # Removes all port forwarding rules for the virtual machine.
        def clear_forwarded_ports
          raise NotImplementedError
        end

        # Clears the shared folders that have been set on the virtual machine.
        def clear_shared_folders
          share_ids = read_shared_folders.keys
          share_ids.each do |id|
            execute_prlctl('set', @uuid, '--shf-host-del', id)
          end
        end

        # Makes a clone of the virtual machine.
        #
        # @param [String] src_name Name or UUID of the source VM or template.
        # @param [String] dst_name Name of the destination VM.
        # @param [<String => String>] options Options to clone virtual machine.
        # @return [String] UUID of the new VM.
        def clone_vm(src_name, dst_name, options={})
          args = ['clone', src_name, '--name', dst_name]
          args << '--template' if options[:template]
          args.concat(['--dst', options[:dst]]) if options[:dst]

          # Linked clone options
          args << '--linked' if options[:linked]
          args.concat(['--id', options[:snapshot_id]]) if options[:snapshot_id]

          execute_prlctl(*args) do |_, data|
            lines = data.split('\r')
            # The progress of the clone will be in the last line. Do a greedy
            # regular expression to find what we're looking for.
            if lines.last =~ /Copying hard disk.+?(\d{,3}) ?%/
              yield $1.to_i if block_given?
            end
          end
          read_vms[dst_name]
        end

        # Compacts all disk drives of virtual machine
        def compact(uuid)
          hw_info = read_settings(uuid).fetch('Hardware', {})
          used_drives = hw_info.select do |name, _|
            name.start_with? 'hdd'
          end
          used_drives.each_value do |drive_params|
            execute(@prldisktool_path, 'compact', '--hdd', drive_params['image']) do |_, data|
              lines = data.split('\r')
              # The progress of the compact will be in the last line. Do a greedy
              # regular expression to find what we're looking for.
              if lines.last =~ /.+?(\d{,3}) ?%/
                yield $1.to_i if block_given?
              end
            end
          end
        end

        # Creates a host only network with the given options.
        #
        # @param [<Symbol => String>] options Hostonly network options.
        # @return [<Symbol => String>] The details of the host only network,
        # including keys `:name`, `:ip`, `:netmask` and `:dhcp`
        # @param [<Symbol => String>] options
        def create_host_only_network(options)
          # Create the interface
          execute_prlsrvctl('net', 'add', options[:network_id], '--type', 'host-only')

          # Configure it
          args = ['--ip', "#{options[:adapter_ip]}/#{options[:netmask]}"]
          if options[:dhcp]
            args.concat(['--dhcp-ip', options[:dhcp][:ip],
                         '--ip-scope-start', options[:dhcp][:lower],
                         '--ip-scope-end', options[:dhcp][:upper]])
          end

          execute_prlsrvctl('net', 'set', options[:network_id], *args)

          # Return the details
          {
            name:    options[:network_id],
            ip:      options[:adapter_ip],
            netmask: options[:netmask],
            dhcp:    options[:dhcp]
          }
        end

        # Creates a snapshot for the specified virtual machine.
        #
        # @param [String] uuid Name or UUID of the target VM.
        # @param [<Symbol => String, Boolean>] options Snapshot options.
        # @return [String] ID of the created snapshot.
        def create_snapshot(uuid, options)
          raise NotImplementedError
        end

        # Deletes the virtual machine references by this driver.
        def delete
          execute_prlctl('delete', @uuid)
        end

        # Deletes all disabled network adapters from the VM configuration
        def delete_disabled_adapters
          read_settings.fetch('Hardware', {}).each do |adapter, params|
            if adapter.start_with?('net') and !params.fetch('enabled', true)
              execute_prlctl('set', @uuid, '--device-del', adapter)
            end
          end
        end

        # Deletes any host only networks that aren't being used for anything.
        def delete_unused_host_only_networks
          raise NotImplementedError
        end

        # Disables requiring password on such operations as creating, adding,
        # removing or cloning the virtual machine.
        #
        def disable_password_restrictions
          raise NotImplementedError
        end

        # Enables network adapters on the VM.
        #
        # The format of each adapter specification should be like so:
        #
        # {
        #   :type     => :hostonly,
        #   :hostonly => "vagrant-vnet0",
        #   :name     => "vnic2",
        #   :nic_type => "virtio"
        # }
        #
        # This must support setting up both host only and bridged networks.
        #
        # @param [Array<Symbol => Symbol, String>] adapters
        # Array of adapters to be enabled.
        def enable_adapters(adapters)
          raise NotImplementedError
        end

        # Create a set of port forwarding rules for a virtual machine.
        #
        # This will not affect any previously set forwarded ports,
        # so be sure to delete those if you need to.
        #
        # The format of each port hash should be the following:
        #
        #     {
        #       guestport: 80,
        #       hostport: 8500,
        #       name: "foo",
        #       protocol: "tcp"
        #     }
        #
        # Note that "protocol" is optional and will default to "tcp".
        #
        # @param [Array<Hash>] ports An array of ports to set. See documentation
        # for more information on the format.
        def forward_ports(ports)
          raise NotImplementedError
        end

        # Halts the virtual machine (pulls the plug).
        def halt(force=false)
          args = ['stop', @uuid]
          args << '--kill' if force
          execute_prlctl(*args)
        end

        # Returns a list of bridged interfaces.
        #
        # @return [Array<Symbol => String>]
        def read_bridged_interfaces
          host_hw_info = read_host_info.fetch('Hardware info', {})
          net_list = host_hw_info.select do |name, attrs|
            # Get all network interfaces except 'vnicXXX'
            attrs.fetch('type') == 'net' and name !~ /^(vnic(.+?))$/
          end

          bridged_ifaces = []
          net_list.keys.each do |iface|
            info = {}
            ifconfig = execute('ifconfig', iface)
            # Assign default values
            info[:name]    = iface
            info[:ip]      = '0.0.0.0'
            info[:netmask] = '0.0.0.0'
            info[:status]  = 'Down'

            if ifconfig =~ /(?<=inet\s)(\S*)/
              info[:ip] = $1.to_s
            end
            if ifconfig =~ /(?<=netmask\s)(\S*)/
              # Netmask will be converted from hex to dec:
              # '0xffffff00' -> '255.255.255.0'
              info[:netmask] = $1.hex.to_s(16).scan(/../).each.map{|octet| octet.hex}.join('.')
            end
            if ifconfig =~ /\W(UP)\W/ and ifconfig !~ /(?<=status:\s)inactive$/
              info[:status] = 'Up'
            end

            bridged_ifaces << info
          end
          bridged_ifaces
        end

        # Returns current snapshot ID for the specified VM. Returns nil if
        # the VM doesn't have any snapshot.
        #
        # @param [String] uuid Name or UUID of the target VM.
        # @return [String]
        def read_current_snapshot(uuid)
          raise NotImplementedError
        end

        def read_forwarded_ports(global=false)
          raise NotImplementedError
        end

        # Returns an IP of the virtual machine. It requires that Shared network
        # adapter is configured for this VM and it obtains an IP via DHCP.
        #
        # @return [String] IP address leased by DHCP server in "Shared" network
        def read_guest_ip
          mac_addr = read_mac_address.downcase
          leases_file = '/Library/Preferences/Parallels/parallels_dhcp_leases'
          leases = {}
          begin
            File.open(leases_file).grep(/#{mac_addr}/) do |line|
              _, ip, exp, dur, _, _ = line.split /([\d.]*)="(\d*),(\d*),(\w*),(\w*)".*/
              leases[ip] = exp.to_i - dur.to_i
            end
          rescue Errno::EACCES
            raise Errors::DhcpLeasesNotAccessible, :leases_file => leases_file.to_s
          rescue Errno::ENOENT
            # File does not exist
            # Perhaps, it is the fist start of Parallels Desktop
            return nil
          end

          return nil if leases.empty?

          # Get the most resent lease and return an associated IP
          leases.sort_by { |_ip, lease_time| lease_time }.last.first
        end

        # Returns path to the Parallels Tools ISO file.
        #
        # @param [String] guest_os Guest os type: "linux", "darwin" or "windows"
        # @return [String] Path to the ISO.
        def read_guest_tools_iso_path(guest_os)
          guest_os = guest_os.to_sym
          iso_name ={
            linux: 'prl-tools-lin.iso',
            darwin: 'prl-tools-mac.iso',
            windows: 'prl-tools-win.iso'
          }
          return nil if !iso_name[guest_os]

          bundle_id =  'com.parallels.desktop.console'
          bundle_path = execute('mdfind', "kMDItemCFBundleIdentifier == #{bundle_id}")
          iso_path = File.expand_path("./Contents/Resources/Tools/#{iso_name[guest_os]}",
                                      bundle_path.split("\n")[0])

          if !File.exist?(iso_path)
            raise Errors::ParallelsToolsIsoNotFound, :iso_path => iso_path
          end

          iso_path
        end

        # Returns the state of guest tools that is installed on this VM.
        # Can be any of:
        # * :installed
        # * :not_installed
        # * :possibly_installed
        # * :outdated
        #
        # @return [Symbol]
        def read_guest_tools_state
          state = read_settings.fetch('GuestTools', {}).fetch('state', nil)
          state = 'not_installed' if !state
          state.to_sym
        end

        # Returns Parallels Desktop properties and common information about
        # the host machine.
        #
        # @return [<Symbol => String>]
        def read_host_info
          json { execute_prlctl('server', 'info', '--json') }
        end

        # Returns a list of available host only interfaces.
        #
        # @return [Array<Symbol => String>]
        def read_host_only_interfaces
          raise NotImplementedError
        end

        # Returns the MAC address of the first Shared network interface.
        #
        # @return [String]
        def read_mac_address
          hw_info = read_settings.fetch('Hardware', {})
          shared_ifaces = hw_info.select do |name, params|
            name.start_with?('net') && params['type'] == 'shared'
          end

          if shared_ifaces.empty?
            raise Errors::SharedAdapterNotFound
          end

          shared_ifaces.values.first.fetch('mac', nil)
        end

        # Returns the array of network interface card MAC addresses
        #
        # @return [Array<String>]
        def read_mac_addresses
          read_vm_option('mac').strip.gsub(':', '').split(' ')
        end

        # Returns a list of network interfaces of the VM.
        #
        # @return [<Integer => Hash>]
        def read_network_interfaces
          raise NotImplementedError
        end

        # Returns virtual machine settings
        #
        # @return [<String => String, Hash>]
        def read_settings(uuid=@uuid)
          vm = json { execute_prlctl('list', uuid, '--info', '--no-header', '--json')  }
          vm.last
        end

        # Returns the unique name (e.q. "ID") on the first Shared network in
        # Parallels Desktop configuration.
        # By default there is only one called "Shared".
        #
        # @return [String] Shared network ID
        def read_shared_network_id
          # There should be only one Shared interface
          shared_net = read_virtual_networks.detect do |net|
            net['Type'] == 'shared'
          end
          shared_net.fetch('Network ID')
        end

        # Returns info about shared network interface.
        #
        # @return [<Symbol => String, Hash>]
        def read_shared_interface
          raise NotImplementedError
        end

        # Returns a list of shared folders in format:
        # { id => hostpath, ... }
        #
        # @return [<String => String>]
        def read_shared_folders
          shf_info = read_settings.fetch('Host Shared Folders', {})
          list = {}
          shf_info.delete_if { |k,v| k == 'enabled' }.each do |id, data|
            list[id] = data.fetch('path')
          end

          list
        end

        # Returns the current state of this VM.
        #
        # @return [Symbol] Virtual machine state
        def read_state
          read_vm_option('status').strip.to_sym
        end

        # Returns a list of all forwarded ports in use by active
        # virtual machines.
        #
        # @return [Array]
        def read_used_ports
        end

        # Returns the configuration of all virtual networks in Parallels Desktop.
        #
        # @return [Array<String => String>]
        def read_virtual_networks
          json { execute_prlsrvctl('net', 'list', '--json') }
        end

        # Returns a value of specified VM option. Raises an exception if value
        # is not available
        #
        # @param [String] option Name of option (See all: `prlctl list -L`)
        # @param [String] uuid Virtual machine UUID
        # @return [String]
        def read_vm_option(option, uuid=@uuid)
          out = execute_prlctl('list', uuid,'--no-header', '-o', option).strip
          if out.empty?
            raise Errors::ParallelsVMOptionNotFound, vm_option: option
          end

          out
        end

        # Returns names and ids of all virtual machines and templates.
        #
        # @return [<String => String>]
        def read_vms
          args = %w(list --all --no-header --json -o name,uuid)
          vms_arr = json([]) { execute_prlctl(*args) }
          templates_arr = json([]) { execute_prlctl(*args, '--template') }

          vms = vms_arr | templates_arr
          Hash[vms.map { |i| [i.fetch('name'), i.fetch('uuid')] }]
        end

        # Returns the configuration of all VMs and templates.
        #
        # @return [Array <String => String>]
        def read_vms_info
          args = %w(list --all --info --no-header --json)
          vms_arr = json([]) { execute_prlctl(*args) }
          templates_arr = json([]) { execute_prlctl(*args, '--template') }

          vms_arr | templates_arr
        end

        # Regenerates 'SourceVmUuid' to avoid SMBIOS UUID collision [GH-113]
        #
        def regenerate_src_uuid
          settings = read_settings
          vm_config = File.join(settings.fetch('Home'), 'config.pvs')

          # Generate and put new SourceVmUuid
          xml = Nokogiri::XML(File.open(vm_config))
          p = '//ParallelsVirtualMachine/Identification/SourceVmUuid'
          xml.xpath(p).first.content = "{#{SecureRandom.uuid}}"

          File.open(vm_config, 'w') do |f|
            f.write xml.to_xml
          end
        end

        # Registers the virtual machine
        #
        # @param [String] pvm_file Path to the machine image (*.pvm)
        def register(pvm_file)
          args = [@prlctl_path, 'register', pvm_file]

          3.times do
            result = raw(*args)
            # Exit if everything is OK
            return if result.exit_code == 0

            # It may occur in the race condition with other Vagrant processes.
            # It is OK, just exit.
            return if result.stderr.include?('is already registered.')

            # Sleep a bit though to give Parallels Desktop time to fix itself
            sleep 2
          end

          # If we reach this point, it means that we consistently got the
          # failure, do a standard execute now. This will raise an
          # exception if it fails again.
          execute(*args)
        end

        # Checks that specified virtual machine is registered
        #
        # @return [Boolean]
        def registered?(uuid)
          args = %w(list --all --info --no-header -o uuid)

          execute_prlctl(*args).include?(uuid) ||
            execute_prlctl(*args, '--template').include?(uuid)
        end

        # Resumes the virtual machine.
        #
        def resume
          execute_prlctl('resume', @uuid)
        end

        # Sets the name of the virtual machine.
        #
        # @param [String] name New VM name.
        def set_name(name)
          execute_prlctl('set', @uuid, '--name', name)
        end

        # Sets Power Consumption method.
        #
        # @param [Boolean] optimized Use "Longer Battery Life"
        # instead "Better Performance"
        def set_power_consumption_mode(optimized)
          raise NotImplementedError
        end

        # Share a set of folders on this VM.
        #
        # @param [Array<Symbol => String>] folders
        def share_folders(folders)
          folders.each do |folder|
            # Add the shared folder
            execute_prlctl('set', @uuid,
                           '--shf-host-add', folder[:name],
                           '--path', folder[:hostpath])
          end
        end

        # Reads the SSH IP of this VM.
        #
        # @return [String] IP address to use for SSH connection to the VM.
        def ssh_ip
          read_guest_ip
        end

        # Reads the SSH port of this VM.
        #
        # @param [Integer] expected Expected guest port of SSH.
        # @return [Integer] Port number to use for SSH connection to the VM.
        def ssh_port(expected)
          expected
        end

        # Starts the virtual machine.
        #
        def start
          execute_prlctl('start', @uuid)
        end

        # Suspends the virtual machine.
        def suspend
          execute_prlctl('suspend', @uuid)
        end

        # Performs un-registeration of the specified VM in Parallels Desktop.
        # Virtual machine will be removed from the VM list, but its image will
        # not be deleted from the disk. So, it can be registered again.
        def unregister(uuid)
          args = [@prlctl_path, 'unregister', uuid]
          3.times do
            result = raw(*args)
            # Exit if everything is OK
            return if result.exit_code == 0

            # It may occur in the race condition with other Vagrant processes.
            # Both are OK, just exit.
            return if result.stderr.include?('is not registered')
            return if result.stderr.include?('is being cloned')

            # Sleep a bit though to give Parallels Desktop time to fix itself
            sleep 2
          end

          # If we reach this point, it means that we consistently got the
          # failure, do a standard execute now. This will raise an
          # exception if it fails again.
          execute(*args)
        end

        # Unshare folders.
        def unshare_folders(names)
          names.each do |name|
            execute_prlctl('set', @uuid, '--shf-host-del', name)
          end
        end

        # Checks if a VM with the given UUID exists.
        #
        # @return [Boolean]
        def vm_exists?(uuid)
          5.times do
            result = raw(@prlctl_path, 'list', uuid)
            return true if result.exit_code == 0

            # Sometimes this happens. In this case, retry.
            # If we don't see this text, the VM really doesn't exist.
            return false if !result.stderr.include?('Login failed:')

            # Sleep a bit though to give Parallels Desktop time to fix itself
            sleep 2
          end

          # If we reach this point, it means that we consistently got the
          # failure, do a standard prlctl now. This will raise an
          # exception if it fails again.
          execute_prlctl('list', uuid)
          true
        end

        private

        # Wraps 'execute' and returns the output of given 'prlctl' subcommand.
        def execute_prlctl(*command, &block)
          execute(@prlctl_path, *command, &block)
        end

        #Wraps 'execute' and returns the output of given 'prlsrvctl' subcommand.
        def execute_prlsrvctl(*command, &block)
          execute(@prlsrvctl_path, *command, &block)
        end

        # Execute the given command and return the output.
        def execute(*command, &block)
          r = raw(*command, &block)

          # If the command was a failure, then raise an exception that is
          # nicely handled by Vagrant.
          if r.exit_code != 0
            if @interrupted
              @logger.info('Exit code != 0, but interrupted. Ignoring.')
            else
              # If there was an error running command, show the error and the
              # output.
              raise VagrantPlugins::Parallels::Errors::ExecutionError,
                :command => command.inspect,
                :stderr  => r.stderr
            end
          end
          r.stdout
        end

        # Parses given block (JSON string) to object
        def json(default=nil)
          data = yield
          JSON.parse(data) rescue default
        end

        # Executes a command and returns the raw result object.
        def raw(*command, &block)
          int_callback = lambda do
            @interrupted = true

            # We have to execute this in a thread due to trap contexts
            # and locks.
            Thread.new { @logger.info('Interrupted.') }
          end

          # Append in the options for subprocess
          command << {notify: [:stdout, :stderr]}

          Vagrant::Util::Busy.busy(int_callback) do
            Vagrant::Util::Subprocess.execute(*command, &block)
          end
        end

        def util_path(bin)
          path = Vagrant::Util::Which.which(bin)
          return path if path

          ['/usr/local/bin', '/usr/bin'].each do |folder|
            path = File.join(folder, bin)
            return path if File.file?(path)
          end
          nil
        end

      end
    end
  end
end


text:
{% extends "base.html" %}
{% block menu %}
{% include "org/menu.html" %}
{% endblock %}
{% block content %}
{% include "org/leftmenu.html" %}

{% for notify in notifies %}

    {{notify.text}}
    {{notify.start_date|date:"j E"}} по {{notify.end_date|date:"j E"}}
    {% for house in notify.houses.all %}{{house}}{% if not forloop.last %}, {% endif %}{% endfor %}
    <form action="{% url "delete_notification" %}" method="POST">{% csrf_token %}<input type="hidden" name="notify" value="{{notify.id}}"><button type="submit" class="btn btn-danger">Удалить</button></form>

{% endfor %}

<form role="form" method="POST">
{% csrf_token %}

    <input type="radio" name="note_type" value="0" checked> Отключение воды

    <input type="radio" name="note_type" value="1"> Отключение света

    <input type="radio" name="note_type" value="2"> Собрание

    <input type="radio" name="note_type" value="3"> Другое

    Отправить жильцам домов:
    <select id="houses"  multiple class="form-control" name="houses">
        {% for house in houses %}
        <option value="{{house.id}}">{{house}}</option>
        {% endfor %}
    </select>

    Начиная с:

      <input class="form-control" id="from" name="start_date" placeholder="введите нач. дату">

    Заканчивая:

      <input class="form-control" id="to" name="end_date" placeholder="введите кон. дату">

    Текст
    <textarea type="email" class="form-control" name="text" id="text" placeholder="Например, время"></textarea>

    <button type="submit" class="btn btn-success">Отправить</button>

</form>

{% endblock %}
{% block scripts %}

{% endblock %}