text:
using MobileDB.Common.Attributes;
using MobileDB.Contracts;
using MobileDB.Stores.Json;

namespace MobileDB.Tests.Common
{
    public class JsonContextWithSimpleIdentity : DbContext
    {
        public JsonContextWithSimpleIdentity(string connectionString)
            : base(connectionString)
        {
        }

        [Store(typeof (JsonStore))]
        public IEntitySet<SimpleEntityWithIdentity> SimpleEntities { get; set; }
    }
}


text:
defineClass('Consoloid.Service.ChainedContainer', 'Consoloid.Service.ServiceContainer',
  {
    __constructor: function(options)
    {
      this.__base();
      $.extend(this, {
        fallback: undefined
      }, options);
    },

    get: function(name)
    {
      if (!(name in this.definitions) && this.fallback) {
        return this.fallback.get(name);
      }

      return this.__base(name);
    },

    getDefinition: function(name)
    {
      if (!(name in this.definitions) && this.fallback) {
        return this.fallback.getDefinition(name);
      }

      return this.__base(name);
    },

    getAllServiceIdsTagged: function(tags)
    {
      var result = this.__base(tags);
      return result.concat(this.fallback.getAllServiceIdsTagged(tags));
    }
  }
);

redpajama_set_name: RedPajamaGithub


text:
'use strict';

eventsApp.controller('EditProfileController', function($scope, gravatarUrlBuilder) {
	$scope.user = {};

	$scope.getGravatarUrl = function (email) {
		return gravatarUrlBuilder.buildGravatarUrl(email);
	}
});


text:
package com.querydsl.core;

import java.util.Calendar;

import com.querydsl.core.types.Constant;
import com.querydsl.core.types.ConstantImpl;
import com.querydsl.core.types.Visitor;
import com.querydsl.core.types.dsl.DateExpression;
import com.querydsl.core.types.dsl.NumberExpression;

/**
 * @author tiwe
 *
 */
public final class DateConstant<D extends java.util.Date> extends DateExpression<D> implements Constant<D> {

    private static final long serialVersionUID = -5745611667058255826L;

    public static <D extends java.util.Date> DateExpression<D> create(D date) {
        return new DateConstant<D>(date);
    }

    private final D date;

    private final Calendar calendar;

    @SuppressWarnings("unchecked")
    public DateConstant(D date) {
        super(ConstantImpl.create(date));
        this.date = (D) date.clone();
        this.calendar = Calendar.getInstance();
        calendar.setTime(date);
    }

    @Override
    public <R,C> R accept(Visitor<R,C> v, C context) {
        return v.visit(this, context);
    }

    @Override
    public NumberExpression<Integer> dayOfMonth() {
        return NumberConstant.create(calendar.get(Calendar.DAY_OF_MONTH));
    }

    @Override
    public NumberExpression<Integer> month() {
        return NumberConstant.create(calendar.get(Calendar.MONTH) + 1);
    }

    @Override
    public NumberExpression<Integer> year() {
        return NumberConstant.create(calendar.get(Calendar.YEAR));
    }

    @Override
    public NumberExpression<Integer> yearMonth() {
        return NumberConstant.create(calendar.get(Calendar.YEAR) * 100 + calendar.get(Calendar.MONTH) + 1);
    }

    @Override
    public NumberExpression<Integer> dayOfWeek() {
        return NumberConstant.create(calendar.get(Calendar.DAY_OF_WEEK));
    }

    @Override
    public NumberExpression<Integer> dayOfYear() {
        return NumberConstant.create(calendar.get(Calendar.DAY_OF_YEAR));
    }

    @Override
    public NumberExpression<Integer> week() {
        return NumberConstant.create(calendar.get(Calendar.WEEK_OF_YEAR));
    }

    @Override
    public D getConstant() {
        return date;
    }

}


text:
import unittest

from hwt.simulator.rtlSimulatorJson import BasicRtlSimulatorJson
from hwtLib.handshaked.fifo_test import HsFifoTC

class HsFifoJsonLogTC(HsFifoTC):
    DEFAULT_SIMULATOR = BasicRtlSimulatorJson
    DEFAULT_LOG_DIR = None

    def runSim(self, until:float, name=None):
        data = {}
        self.rtl_simulator.set_trace_file(data, -1)
        return HsFifoTC.runSim(self, until, name=name)

if __name__ == "__main__":
    suite = unittest.TestSuite()
    # suite.addTest(HsFifoJsonLogTC('test_passdata'))
    suite.addTest(unittest.makeSuite(HsFifoJsonLogTC))
    runner = unittest.TextTestRunner(verbosity=3)
    runner.run(suite)


text:
/**
 * An input field Image Picker utilising the Xinha ImageManager.
 *
 * Hijack the Xinha ImageManager plugin to provide an image URL picker
 * for any form input field in the form of a "Browse" button to the
 * right of the field, in the same manner as a file type input field
 * except it opens the familiar ImageManager dialog to upload/select/edit
 * an image and returns the URL of the image to the field's value.
 *
 * Example Usage:
 *
 *  <script type="text/javascript">_editor_url = '/url/to/xinha';</script>
 *  <script type="text/javascript" src="image-picker.js" />
 *  <script type="text/javascript">
 *   <?php require_once('/path/to/xinha/contrib/php-xinha.php'); ?>
 *   with(ImagePicker.prototype)
 *   {
 *     <?php
 *      $Conf = array
 *       (
 *         'images_dir' => '/path/to/images',
 *         'images_url' => '/url/to/images',
 *         'show_full_options' => false, // Full options are not useful as a URL picker
 *         // See ImageManager for more configuration options !
 *       );
 *      xinha_pass_to_php_backend($Conf);
 *     ?>
 *   }
 *
 *   window.onload = function() { new ImagePicker(document.getElementById('idOfTheInputField')); }
 *  </script>
 *
 *
 * @author $Author$
 * @version $Id$
 * @package ImageManager
 */

function ImagePicker(field)
{
  this.field = field;
  var picker = this;

  var but = document.createElement('input');
  but.type = 'button';
  but.value = 'Browse';
  but.onclick = function() { picker.popup_picker(); }

  field.parentNode.insertBefore(but,field.nextSibling);
  field.size = '20';
  field.style.textAlign = 'right';
};

ImagePicker.prototype.backend             = Xinha.getPluginDir('ImageManager') + '/backend.php?__plugin=ImageManager&';
ImagePicker.prototype.backend_data        = null;

ImagePicker.prototype.popup_picker = function()
{
  var picker = this; // closure for later
  var outparam = null;
  if(picker.field.value)
  {
    outparam =
		{
			f_url    : picker.field.value,
			f_width  : null,
			f_height  : null,

      // None of this stuff is useful to us, we return only a URL.
      f_alt    : picker.field.value,
			f_border : null,
			f_align  : null,
			f_padding: null,
			f_margin : null,
      f_backgroundColor: null,
      f_borderColor: null,
      f_border : null,
      f_padding: null,
      f_margin: null
    };
  }

  var manager = this.backend + '__function=manager';
  if(this.backend_config != null)
  {
    manager += '&backend_config='
      + encodeURIComponent(this.backend_config);
    manager += '&backend_config_hash='
      + encodeURIComponent(this.backend_config_hash);
    manager += '&backend_config_secret_key_location='
      + encodeURIComponent(this.backend_config_secret_key_location);
  }

  if(this.backend_data != null)
  {
    for ( var i in this.backend_data )
    {
      manager += '&' + i + '=' + encodeURIComponent(this.backend_data[i]);
    }
  }

  Dialog(manager, function(param) {
		if (!param) {	// user must have pressed Cancel
			return false;
		}
    picker.field.value = param.f_url;
		}, outparam);
}

// Dialog is part of Xinha, but we'll provide it here incase Xinha's not being
// loaded.
if(typeof Dialog == 'undefined')
{
  // htmlArea v3.0 - Copyright (c) 2003-2004 interactivetools.com, inc.
  // This copyright notice MUST stay intact for use (see license.txt).
  //
  // Portions (c) dynarch.com, 2003-2004
  //
  // A free WYSIWYG editor replacement for <textarea> fields.
  // For full source code and docs, visit http://www.interactivetools.com/
  //
  // Version 3.0 developed by Mihai Bazon.
  //   http://dynarch.com/mishoo
  //
  // $Id: dialog.js 183 2005-05-20 06:11:44Z gogo $

  // Though "Dialog" looks like an object, it isn't really an object.  Instead
  // it's just namespace for protecting global symbols.

  function Dialog(url, action, init) {
    if (typeof init == "undefined") {
      init = window;	// pass this window object by default
    }
    var dlg = window.open(url, "hadialog",
              "toolbar=no,menubar=no,personalbar=no,width=10,height=10," +
              "scrollbars=yes,resizable=yes,modal=yes,dependable=yes");
    Dialog._modal = dlg;
    Dialog._arguments = init;

    // make up a function to be called when the Dialog ends.
    Dialog._return = function (val)
    {
      if (val && action) {
        action(val);
      }

      Dialog._modal = null;
    };
    Dialog._modal.focus();
  };

  // should be a function, the return handler of the currently opened dialog.
  Dialog._return = null;

  // constant, the currently opened dialog
  Dialog._modal = null;

  // the dialog will read it's args from this variable
  Dialog._arguments = null;

}

// Deprecated method for passing config, use above instead!
//---------------------------------------------------------
ImagePicker.prototype.backend_config      = null;
ImagePicker.prototype.backend_config_hash = null;
ImagePicker.prototype.backend_config_secret_key_location = 'Xinha:ImageManager';
//---------------------------------------------------------


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MemoryUsageMeter = void 0;
let os = require('os');
const BenchmarkMeter_1 = require("./BenchmarkMeter");
class MemoryUsageMeter extends BenchmarkMeter_1.BenchmarkMeter {
    constructor() {
        super();
    }
    performMeasurement() {
        return (os.totalmem() - os.freemem()) / 1024 / 1024;
    }
}
exports.MemoryUsageMeter = MemoryUsageMeter;
//# sourceMappingURL=MemoryUsageMeter.js.map


text:
var iot = require('./iot');

var gpio = function(pin) {
	this.pin = pin;

	this.setAsInput = function(pin) {
	}

	this.setAsOutput = function(pin) {
	}

	this.read = function() {
		return -1;
	}

	this.write = function(state) {
	}
}

this.createInput = function(pin) {
	var g = new gpio(pin);
	g.setAsInput();

	return g;
}

this.createOutput = function(pin) {
	var g = new gpio(pin);
	g.setAsOutput();

	return g;
}


text:
namespace Microsoft.OneDrive.Sdk
{
    using System.Collections.Generic;

    /// <summary>
    /// The interface IItemRequestBuilder.
    /// </summary>
    public partial interface IItemRequestBuilder
    {
        /// <summary>
        /// Builds the request.
        /// </summary>
        /// <returns>The built request.</returns>
        IItemRequest Request();

        /// <summary>
        /// Builds the request.
        /// </summary>
        /// <param name="options">The query and header options for the request.</param>
        /// <returns>The built request.</returns>
        IItemRequest Request(IList<Option> options);

        /// <summary>
        /// Gets the request builder for Permissions.
        /// </summary>
        /// <returns>The <see cref="IPermissionsCollectionRequestBuilder"/>.</returns>
        IPermissionsCollectionRequestBuilder Permissions { get; }

        /// <summary>
        /// Gets the request builder for Versions.
        /// </summary>
        /// <returns>The <see cref="IVersionsCollectionRequestBuilder"/>.</returns>
        IVersionsCollectionRequestBuilder Versions { get; }

        /// <summary>
        /// Gets the request builder for Children.
        /// </summary>
        /// <returns>The <see cref="IChildrenCollectionRequestBuilder"/>.</returns>
        IChildrenCollectionRequestBuilder Children { get; }

        /// <summary>
        /// Gets the request builder for Thumbnails.
        /// </summary>
        /// <returns>The <see cref="IThumbnailsCollectionRequestBuilder"/>.</returns>
        IThumbnailsCollectionRequestBuilder Thumbnails { get; }

        /// <summary>
        /// Gets the request builder for Content.
        /// </summary>
        /// <returns>The <see cref="IItemContentRequestBuilder"/>.</returns>
        IItemContentRequestBuilder Content { get; }

        /// <summary>
        /// Gets the request builder for ItemCreateSession.
        /// </summary>
        /// <returns>The <see cref="IItemCreateSessionRequestBuilder"/>.</returns>
        IItemCreateSessionRequestBuilder CreateSession(
            ChunkedUploadSessionDescriptor item);

        /// <summary>
        /// Gets the request builder for ItemCopy.
        /// </summary>
        /// <returns>The <see cref="IItemCopyRequestBuilder"/>.</returns>
        IItemCopyRequestBuilder Copy(
            string name,
            ItemReference parentReference);

        /// <summary>
        /// Gets the request builder for ItemCreateLink.
        /// </summary>
        /// <returns>The <see cref="IItemCreateLinkRequestBuilder"/>.</returns>
        IItemCreateLinkRequestBuilder CreateLink(
            string type);

        /// <summary>
        /// Gets the request builder for ItemAllPhotos.
        /// </summary>
        /// <returns>The <see cref="IItemAllPhotosRequestBuilder"/>.</returns>
        IItemAllPhotosRequestBuilder AllPhotos();

        /// <summary>
        /// Gets the request builder for ItemDelta.
        /// </summary>
        /// <returns>The <see cref="IItemDeltaRequestBuilder"/>.</returns>
        IItemDeltaRequestBuilder Delta(
            string token);

        /// <summary>
        /// Gets the request builder for ItemSearch.
        /// </summary>
        /// <returns>The <see cref="IItemSearchRequestBuilder"/>.</returns>
        IItemSearchRequestBuilder Search(
            string q);

    }
}


text:
package ogletest

import (
	"github.com/glycerine/goconvey/convey/assertions/oglematchers"
)

// AssertEq(e, a) is equivalent to AssertThat(a, oglematchers.Equals(e)).
func AssertEq(expected, actual interface{}, errorParts ...interface{}) ExpectationResult {
	res := ExpectThat(actual, oglematchers.Equals(expected), errorParts...)
	res.SetCaller(getCallerForAlias())

	matcherErr := res.MatchResult()
	if matcherErr != nil {
		panic(&assertThatError{})
	}

	return res
}

// AssertNe(e, a) is equivalent to AssertThat(a, oglematchers.Not(oglematchers.Equals(e))).
func AssertNe(expected, actual interface{}, errorParts ...interface{}) ExpectationResult {
	res := ExpectThat(actual, oglematchers.Not(oglematchers.Equals(expected)), errorParts...)
	res.SetCaller(getCallerForAlias())

	matcherErr := res.MatchResult()
	if matcherErr != nil {
		panic(&assertThatError{})
	}

	return res
}

// AssertLt(x, y) is equivalent to AssertThat(x, oglematchers.LessThan(y)).
func AssertLt(x, y interface{}, errorParts ...interface{}) ExpectationResult {
	res := ExpectThat(x, oglematchers.LessThan(y), errorParts...)
	res.SetCaller(getCallerForAlias())

	matcherErr := res.MatchResult()
	if matcherErr != nil {
		panic(&assertThatError{})
	}

	return res
}

// AssertLe(x, y) is equivalent to AssertThat(x, oglematchers.LessOrEqual(y)).
func AssertLe(x, y interface{}, errorParts ...interface{}) ExpectationResult {
	res := ExpectThat(x, oglematchers.LessOrEqual(y), errorParts...)
	res.SetCaller(getCallerForAlias())

	matcherErr := res.MatchResult()
	if matcherErr != nil {
		panic(&assertThatError{})
	}

	return res
}

// AssertGt(x, y) is equivalent to AssertThat(x, oglematchers.GreaterThan(y)).
func AssertGt(x, y interface{}, errorParts ...interface{}) ExpectationResult {
	res := ExpectThat(x, oglematchers.GreaterThan(y), errorParts...)
	res.SetCaller(getCallerForAlias())

	matcherErr := res.MatchResult()
	if matcherErr != nil {
		panic(&assertThatError{})
	}

	return res
}

// AssertGe(x, y) is equivalent to AssertThat(x, oglematchers.GreaterOrEqual(y)).
func AssertGe(x, y interface{}, errorParts ...interface{}) ExpectationResult {
	res := ExpectThat(x, oglematchers.GreaterOrEqual(y), errorParts...)
	res.SetCaller(getCallerForAlias())

	matcherErr := res.MatchResult()
	if matcherErr != nil {
		panic(&assertThatError{})
	}

	return res
}

// AssertTrue(b) is equivalent to AssertThat(b, oglematchers.Equals(true)).
func AssertTrue(b interface{}, errorParts ...interface{}) ExpectationResult {
	res := ExpectThat(b, oglematchers.Equals(true), errorParts...)
	res.SetCaller(getCallerForAlias())

	matcherErr := res.MatchResult()
	if matcherErr != nil {
		panic(&assertThatError{})
	}

	return res
}

// AssertFalse(b) is equivalent to AssertThat(b, oglematchers.Equals(false)).
func AssertFalse(b interface{}, errorParts ...interface{}) ExpectationResult {
	res := ExpectThat(b, oglematchers.Equals(false), errorParts...)
	res.SetCaller(getCallerForAlias())

	matcherErr := res.MatchResult()
	if matcherErr != nil {
		panic(&assertThatError{})
	}

	return res
}


text:
#include "ecma-globals.h"

#if ENABLED (JERRY_ESNEXT)

#define ECMA_BUILTINS_INTERNAL
#include "ecma-builtins-internal.h"

#define BUILTIN_INC_HEADER_NAME "ecma-builtin-async-function-prototype.inc.h"
#define BUILTIN_UNDERSCORED_ID async_function_prototype
#include "ecma-builtin-internal-routines-template.inc.h"

/** \addtogroup ecma ECMA
 * @{
 *
 * \addtogroup ecmabuiltins
 * @{
 *
 * \addtogroup asyncfunctionprototype ECMA AsyncFunction.prototype object built-in
 * @{
 */

/**
 * @}
 * @}
 * @}
 */

#endif /* ENABLED (JERRY_ESNEXT) */


text:
using System;
using System.Windows.Forms;

namespace NewApiBrowser
{
    public partial class FormTransferProgress : Form
    {
        public System.Threading.CancellationTokenSource CancelTokenSource { get; set; }

        public FormTransferProgress(string filename, TransferDirection direction)
        {
            InitializeComponent();

            switch (direction)
            {
                case TransferDirection.Upload:
                    labelFilename.Text = string.Format("Uploading \"{0}\"...", filename);
                    labelProgressString.Text = "Starting upload...";
                    break;
                case TransferDirection.Download:
                    labelFilename.Text = string.Format("Downloading \"{0}\"...", filename);
                    labelProgressString.Text = "Starting download...";
                    break;
            }

            progressBarPercentComplete.Value = 0;
        }

        public void UpdateProgress(int percentComplete, long bytesTransfered, long totalBytes)
        {
            const double mbconst = 1024.0 * 1024.0;

            Action updateAction = new Action(() =>
                {
                    labelProgressString.Text = string.Format("{0:0.00} of {1:0.00} MB", bytesTransfered / mbconst, totalBytes / mbconst);
                    progressBarPercentComplete.Value = percentComplete;
                });

            if (InvokeRequired)
                BeginInvoke(updateAction);
            else
                updateAction();
        }

        private void FormTransferProgress_Load(object sender, EventArgs e)
        {
            buttonCancel.Visible = (CancelTokenSource != null);
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            if (CancelTokenSource != null)
            {
                CancelTokenSource.Cancel();
            }
        }
    }

    public enum TransferDirection
    {
        Upload,
        Download
    }
}


text:
namespace Fixtures.AcceptanceTestsBodyComplex.Models
{
    using System.Linq;

    public partial class ReadonlyObj
    {
        /// <summary>
        /// Initializes a new instance of the ReadonlyObj class.
        /// </summary>
        public ReadonlyObj() { }

        /// <summary>
        /// Initializes a new instance of the ReadonlyObj class.
        /// </summary>
        public ReadonlyObj(string id = default(string), int? size = default(int?))
        {
            Id = id;
            Size = size;
        }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "id")]
        public string Id { get; private set; }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "size")]
        public int? Size { get; set; }

    }
}


text:
title: "Соединение точка-точка (ad-hoc) по WiFi между Ubuntu Linux и Windows XP"
layout: post
categories: linux
tags: [wifi, linux]
share: true
---

> Рассмотрим случай, когда на одной машине (desktop) стоит все та же Ubuntu, а на другой машине (notebook) стоит Windows XP.

Необходимо соединить оба компьютера по `ad-hoc` wifi. Требуется создать локальную домашнюю сеть, которая называется одноранговой. Другими словами, у нас нет в наличии таких сетевых устройств, как концентратор, коммутатор или маршрутизатор. Соединение между двумя (в нашем случае) компьютерами будет установлено напрямую, `точка-точка`. В первом шаге настроим сеть на десктопе в Ubuntu. Затем повторим настройку на ноутбуке в Windows XP.

И в заключение, протестируем созданную нами сеть.

## Шаг Первый - настройка ad-hoc wifi в Ubuntu Karmic

Открываем NetworkManager правым щелчком мыши на значке в Панели Gnome и выбираем "Edit connections". Появляется окно "Network Connections".

Переходим на вкладку "Wireless" (Беспроводные):

![Start Network Connections]({{site.url}}/images/uploads/2013/06/Start-Network-Connections.png)

Нажимаем Add (Добавить). Появляется окно из четырех вкладок (tabs) для создания нового соединения. В первой вкладке вводим общую информацию о создаваемой нами сети:

  * `Connection name` (имя сети) - это имя сети, которое будет отображаться на компьютере и в списке сетей NetworkManager;
  * `SSID` - реальное имя сети. Каждая сеть Wi-Fi имеет свое имя, по которому сетевые устройства распознают их и подключаются к ним;
  * `Mode` - режим сети. В выпадающем списке выбираем режим сети Ad-hoc;
  * остальные три поля - `BSSID`, `MAC address` и `MTU` оставляем пустыми.

![Ubuntu Editing Windows XP]({{site.url}}/images/uploads/2013/06/Ubuntu-Editing-Windows_XP.png)

Переходим на вкладку "Wireless Security". Оставляем поле "Security" пустым (None):

![Security Editing Windows_XP]({{site.url}}/images/uploads/2013/06/Security-Editing-Windows_XP.png)

Далее, переходим на вкладку "IPv4 Settings". Здесь мы выбираем метод получения IP-адреса компьютером в сети. В нашем случае мы задаем его вручную.

Для этого в выпадающем списке "Method" выбираем "Manual" (Ручной). Затем, в поле "Addresses" (Адреса) нажимаем кнопку Add (Добавить) и последовательно задаем IP-адрес `192.168.0.30`, маску сети "Netmask" `255.255.255.0` и шлюз сети "Gateway" `1.1.1.1`. Поля "DNS servers" и "Search domains" оставляем пустыми:

![IPv4 Settings-Editing Windows_XP]({{site.url}}/images/uploads/2013/06/IPv4-Settings-Editing-Windows_XP.png)

Вкладку "IPv6 Settings" оставляем как есть, ничего не конфигурируя (Method - Ignore):

![IPv6 Settings-Editing Windows_XP]({{site.url}}/images/uploads/2013/06/IPv6-Settings-Editing-Windows_XP.png)

Нажимаем кнопочку Apply (Применить) и видим конечный результат работы - список сетей в "NetworkManager" и нашу Windows_XP среди них:

![Finish Network Connections]({{site.url}}/images/uploads/2013/06/Finish-Network-Connections.png)

Закрываем окно. Вновь нажимаем, теперь уже левой кнопкой мыши, на значке "NetworkManager" в Панели Gnome. Выбираем в выпавшем списке "Connect to hidden wireless network" (Подключиться к скрытой беспроводной сети).

В списке "Connection" выбираем нашу Windows XP и нажимаем Connect (Соединить):

![Connect to hidden wireless network]({{site.url}}/images/uploads/2013/06/Connect-to-Hidden-Wireless-Network1.png)

В эмуляторе терминала набираем команду:

$ sudo ifconfig -a

и видим, что сетевой интерфейс поднят и сеть запущена:

![Ubuntu Desktop]({{site.url}}/images/uploads/2013/06/ubuntu-desktop.png)

## Шаг Второй - Настройка `ad-hoc` wifi в Windows XP

Открываем в "Панели управления" - "Сетевые подключения":

![Network Connections Windows XP]({{site.url}}/uploads/2013/06/Network-Connections-Windows-XP.png)

Кликаем правой кнопкой мыши на значке "Беспроводное сетевое соединение" и в контекстном меню - "Properties" (Свойства). В окне "Свойств" находим в самом низу строку "Протокол Интернета (TCP/IP)":

![TCP IP Windows XP]({{site.url}}/images/uploads/2013/06/TCP_IP_Windows_XP.png)

Нажимаем "Свойства". Открывается окно настроек TCP/IP. Здесь мы задаем IP-адрес, маску сети и шлюз сети так же, как и в NetworkManager, за исключением того, что IP-адрес у нас будет несколько иной - `192.168.0.31`:

![Properties TCP IP Windows XP]({{site.url}}/images/uploads/2013/06/Properties-TCP_IP-Windows-XP.png)

Нажимаем OK. Далее кликаем левой кнопкой мыши на значке "Беспроводное сетевое соединение" в "Сетевые подключения" "Панели управления". Открывается окно со списком беспроводных сетей, находящихся в зоне доступа компьютера:

![Start Wireless Networks Windows XP]({{site.url}}/images/uploads/2013/06/Start-Wireless-Networks-Windows-XP.png)

Выбираем "Установить беспроводную сеть" для создания сети `ad-hoc`. Запускается "Мастер беспроводной сети", пошагово проведущий по несложной настройке новой сети windows:

![Step1 Windows XP]({{site.url}}/images/uploads/2013/06/Step1.png)

![Step2 Windows XP]({{site.url}}/images/uploads/2013/06/Step2.png)

![Step3 Windows XP]({{site.url}}/images/uploads/2013/06/Step3.png)

![Step4 Windows XP]({{site.url}}/images/uploads/2013/06/Step4.png)

![Step5 Windows XP]({{site.url}}/images/uploads/2013/06/Step5.png)

Нажимаем "Готово". Вновь открывается окно со списков доступных беспроводных сетей. В этом списке появилась и наша windows:

![Step6 Windows XP]({{site.url}}/images/uploads/2013/06/Step6-Windows-XP.png)

Выбираем сеть windows и нажимаем "Подключить":

![Step7 Windows XP]({{site.url}}/images/uploads/2013/06/Step7-Windows-Xp.png)

![Step8 Windows XP]({{site.url}}/images/uploads/2013/06/Step8-Windows-XP.png)

В итоге получаем подключение к сети windows:

![Step9 Windows XP]({{site.url}}/images/uploads/2013/06/Step9-Windows-XP.png)

## Шаг Третий - тестирование сети из Ubuntu

Ping самих себя:

![Ping Self - Network Tools]({{site.url}}/images/uploads/2013/06/Ping-Self-Network-Tools.png)

Ping Windows XP:

![Ping Windows - Network Tools]({{site.url}}/images/uploads/2013/06/Ping-Windows-Network-Tools.png)

Трассировка Windows XP:

![Traceroute Windows - Network Tools]({{site.url}}/images/uploads/2013/06/Traceroute-Windows-Network-Tools.png)

Сканирование портов Windows XP:

![Port Scan Windows - Network Tools]({{site.url}}/images/uploads/2013/06/Port-Scan-Windows-Network-Tools.png)

На этом все.

---


text:
// TurinMachine.scala
//
//

package turingmachine

import scala.annotation.tailrec

class TuringMachine {

     type Symbol = Char
     type State  = Char
     type Move   = Tape => Tape

     val A: Char = 'A'
     val B: Char = 'B'
     val C: Char = 'C'

     val one:   Char ='1'            /* Write '1' */
	   val blank: Char = ' '           /* Blank */
     val zero:  Char = '0'           /* Zero */
	   val halt:  Char = '#'           /* Halt */

     val R = right _
     val L = left _

    //                     state 1                 state 2                state 3

    //  symbol 1   (symbol, state, move ) (symbol, state, move ) (symbol, state, move )
    //  symbol 2

    //  Map( state -> Map( symbol -> ( symbol, state, move )))

  	 type TrnsMtrx= Map[State, Map[Symbol, (Symbol, State, Move)]]

	 /* <--- left ----><-- head --><--- right ---> */

	 case class Tape(l: List[Symbol],head:Symbol, r: List[Symbol]){

	   /* 'reverse' - reverse the list */
	   /* 'trim' - removes spaces at the beginning and end of the tape */

       override def toString = ( l.reverse ++ (head::r)  ).mkString.trim

      /* length of tape = number of Char in left and right List + head */

      def print = println(l:::head::r)

       def length: Int = l.length + r.length + 1

     }

    /* Converts a String to a Tape */
    /* Example: right("1234") => List(blank)-1-List(1,2,3,4) => "b1234" */

     def tape(s:String)= right(Tape(Nil,blank,s.toList ))

    /* read the tape which is equivalent to returning the head */

	   def read(t:Tape)= t.head

    /* write to tape via the head */

     def write(c:Symbol, t:Tape)=Tape(t.l,c,t.r)

    /* move head to the left and add a blank to extend the tape if required */
    /* Example: tape = "b1234" => List()-b-List(1,2,3,4)                    */

     def left(t:Tape)=t match {
        case Tape(Nil,head,right) =>Tape(Nil,blank,head::right)
        case Tape(left,head,right) =>Tape(left.tail,left.head,head::right)
     }

    /* move head to the right and add a blank to extend the tape if required */

    def right(t:Tape)=t match {
      case Tape(left,head,Nil) =>Tape(head::left,blank,Nil)
      case Tape(left,head,right) =>Tape(head::left,right.head,right.tail)
    }

    /* Interpreter or the Turing Machine                                      */

//    @tailrec
    final def step(q:State, t:Tape, tm:TrnsMtrx, qf:State):Tape =
          if (q == qf ) t else {
            val (c, qnew ,move)=tm(q)(t.head);
            step(qnew, move(write(c,t)), tm, qf) }

}


text:
<#
    .SYNOPSIS
        Automated unit test for DSC_SqlMemory DSC resource.

#>

Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1')

$script:dscModuleName = 'SqlServerDsc'
$script:dscResourceName = 'DSC_SqlMemory'

function Invoke-TestSetup
{
    try
    {
        Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop'
    }
    catch [System.IO.FileNotFoundException]
    {
        throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.'
    }

    $script:testEnvironment = Initialize-TestEnvironment `
        -DSCModuleName $script:dscModuleName `
        -DSCResourceName $script:dscResourceName `
        -ResourceType 'Mof' `
        -TestType 'Unit'

    # Loading mocked classes
    Add-Type -Path (Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Stubs') -ChildPath 'SMO.cs')
}

function Invoke-TestCleanup
{
    Restore-TestEnvironment -TestEnvironment $script:testEnvironment
}

Invoke-TestSetup

try
{
    InModuleScope $script:dscResourceName {
        $mockServerName = 'localhost'
        $mockInstanceName = 'MSSQLSERVER'
        $mockMinServerMemory = 2048
        $mockMaxServerMemory = 10300
        $mockPhysicalMemoryCapacity = 8589934592
        $mockExpectedMinMemoryForAlterMethod = 0
        $mockExpectedMaxMemoryForAlterMethod = 2147483647
        $mockTestActiveNode = $true

        # Default parameters that are used for the It-blocks
        $mockDefaultParameters = @{
            InstanceName = $mockInstanceName
            ServerName   = $mockServerName
            Verbose = $true
        }

        #region Function mocks

        $mockConnectSQL = {
            return @(
                (
                    # New-Object -TypeName Object |
                    New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server |
                        Add-Member -MemberType NoteProperty -Name InstanceName -Value $mockInstanceName -PassThru -Force |
                        Add-Member -MemberType NoteProperty -Name ComputerNamePhysicalNetBIOS -Value $mockServerName -PassThru -Force |
                        Add-Member -MemberType ScriptProperty -Name Configuration -Value {
                        return @( ( New-Object -TypeName Object |
                                    Add-Member -MemberType ScriptProperty -Name MinServerMemory -Value {
                                    return @( ( New-Object -TypeName Object |
                                                Add-Member -MemberType NoteProperty -Name DisplayName -Value 'min server memory (MB)' -PassThru |
                                                Add-Member -MemberType NoteProperty -Name Description -Value 'Minimum size of server memory (MB)' -PassThru |
                                                Add-Member -MemberType NoteProperty -Name RunValue -Value $mockMinServerMemory -PassThru |
                                                Add-Member -MemberType NoteProperty -Name ConfigValue -Value $mockMinServerMemory -PassThru -Force
                                        ) )
                                } -PassThru |
                                    Add-Member -MemberType ScriptProperty -Name MaxServerMemory -Value {
                                    return @( ( New-Object -TypeName Object |
                                                Add-Member -MemberType NoteProperty -Name DisplayName -Value 'max server memory (MB)' -PassThru |
                                                Add-Member -MemberType NoteProperty -Name Description -Value 'Maximum size of server memory (MB)' -PassThru |
                                                Add-Member -MemberType NoteProperty -Name RunValue -Value $mockMaxServerMemory -PassThru |
                                                Add-Member -MemberType NoteProperty -Name ConfigValue -Value $mockMaxServerMemory -PassThru -Force
                                        ) )
                                } -PassThru -Force
                            ) )
                    } -PassThru -Force |
                        Add-Member -MemberType ScriptMethod -Name Alter -Value {
                        if ( $this.Configuration.MinServerMemory.ConfigValue -ne $mockExpectedMinMemoryForAlterMethod )
                        {
                            throw "Called mocked Alter() method without setting the right minimum server memory. Expected '{0}'. But was '{1}'." -f $mockExpectedMinMemoryForAlterMethod, $this.Configuration.MinServerMemory.ConfigValue
                        }
                        if ( $this.Configuration.MaxServerMemory.ConfigValue -ne $mockExpectedMaxMemoryForAlterMethod )
                        {
                            throw "Called mocked Alter() method without setting the right maximum server memory. Expected '{0}'. But was '{1}'." -f $mockExpectedMaxMemoryForAlterMethod, $this.Configuration.MaxServerMemory.ConfigValue
                        }
                    } -PassThru -Force
                )
            )
        }

        #endregion

        Describe "DSC_SqlMemory\Get-TargetResource" -Tag 'Get' {
            Mock -CommandName Connect-SQL -MockWith $mockConnectSQL -Verifiable
            Mock -CommandName Test-ActiveNode -MockWith { return $mockTestActiveNode } -Verifiable

            Context 'When the system is either in the desired state or not in the desired state' {
                $testParameters = $mockDefaultParameters

                $result = Get-TargetResource @testParameters

                It 'Should return the current value for MinMemory' {
                    $result.MinMemory | Should -Be 2048
                }

                It 'Should return the current value for MaxMemory' {
                    $result.MaxMemory | Should -Be 10300
                }

                It 'Should return the same values as passed as parameters' {
                    $result.ServerName | Should -Be $testParameters.ServerName
                    $result.InstanceName | Should -Be $testParameters.InstanceName
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should call the mock function Test-ActiveNode' {
                    Assert-MockCalled -CommandName Test-ActiveNode -Exactly -Times 1 -Scope Context
                }
            }

            Assert-VerifiableMock
        }

        Describe "DSC_SqlMemory\Test-TargetResource" -Tag 'Test' {
            BeforeEach {
                Mock -CommandName Get-SqlDscDynamicMaxMemory -MockWith {
                    return 8192 # MB
                }
                Mock -CommandName Get-SqlDscPercentMemory -MockWith {
                    return 8192 # MB
                }

                Mock -CommandName Get-TargetResource -MockWith {
                    return @{
                        InstanceName = $mockInstanceName
                        ServerName   = $mockServerName
                        MinMemory    = $mockMinServerMemory
                        MaxMemory    = $mockMaxServerMemory
                        IsActiveNode = $mockTestActiveNode
                    }
                }
            }

            $mockMinServerMemory = 0
            $mockMaxServerMemory = 16384

            Context 'When the system is not in the desired state and DynamicAlloc is set to false' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    Ensure       = 'Present'
                    MinMemory    = 1024
                    MaxMemory    = 8192
                    DynamicAlloc = $false
                }

                It 'Should return the state as false when desired MinMemory and MaxMemory are not present' {
                    $result = Test-TargetResource @testParameters
                    $result | Should -Be $false
                }
            }

            Context 'When the system percent memory is not in the desired state and DynamicAlloc is set to false' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    Ensure       = 'Present'
                    MinMemoryPercent    = 80
                    MaxMemoryPercent    = 80
                    DynamicAlloc = $false
                }

                It 'Should return the state as false when desired MinMemory and MaxMemory are not present' {
                    $result = Test-TargetResource @testParameters
                    $result | Should -Be $false
                }
            }

            Context 'When the system is not in the desired state and DynamicAlloc is set to false' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    Ensure       = 'Present'
                    MaxMemory    = 8192
                    DynamicAlloc = $false
                }

                It 'Should return the state as false when desired MaxMemory is not present' {
                    $result = Test-TargetResource @testParameters
                    $result | Should -Be $false
                }
            }

            Context 'When the system is in the desired state and DynamicAlloc is set to false' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    Ensure       = 'Present'
                    MinMemory    = $mockMinServerMemory
                    MaxMemory    = $mockMaxServerMemory
                    DynamicAlloc = $false
                }

                It 'Should return the state as true when desired MinMemory and MaxMemory are present' {
                    $result = Test-TargetResource @testParameters
                    $result | Should -Be $true
                }
            }

            Context 'When the MaxMemory parameter is not null and DynamicAlloc is set to true' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MaxMemory    = 8192
                    DynamicAlloc = $true
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Test-TargetResource @testParameters } | Should -Throw $script:localizedData.MaxMemoryParamMustBeNull
                }
            }

            Context 'When the MaxMemoryPercent parameter is not null and DynamicAlloc is set to true' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MaxMemoryPercent = 80
                    DynamicAlloc = $true
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Test-TargetResource @testParameters } | Should -Throw $script:localizedData.MaxMemoryPercentParamMustBeNull
                }
            }

            Context 'When the MaxMemoryPercent and MaxMemory parameters are not null and DynamicAlloc is set to false' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MaxMemory        = 8192
                    MaxMemoryPercent = 80
                    DynamicAlloc = $false
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Test-TargetResource @testParameters } | Should -Throw $script:localizedData.MaxMemoryPercentParamMustBeNull
                }
            }

            Context 'When the MaxMemory and MaxMemoryPercent parameters are null and DynamicAlloc is set to false' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    DynamicAlloc = $false
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    {Test-TargetResource @testParameters } | Should -Throw $script:localizedData.MaxMemoryParamMustNotBeNull
                }
            }

            Context 'When the MinMemoryPercent and MinMemory parameters are not null and DynamicAlloc is set to true' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MinMemory        = 1024
                    MinMemoryPercent = 80
                    DynamicAlloc = $true
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Test-TargetResource @testParameters } | Should -Throw $script:localizedData.MinMemoryPercentParamMustBeNull
                }
            }

            Context 'When the system is not in the desired state and DynamicAlloc is set to true' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    Ensure       = 'Present'
                    DynamicAlloc = $true
                }

                It 'Should return the state as false when desired MinMemory and MaxMemory are not present' {
                    $result = Test-TargetResource @testParameters
                    $result | Should -Be $false
                }
            }

            Context 'When the system is not in the desired state, DynamicAlloc is set to true and ProcessOnlyOnActiveNode is set to true' {
                AfterAll {
                    $mockTestActiveNode = $true
                }

                BeforeAll {
                    $testParameters = $mockDefaultParameters
                    $testParameters += @{
                        Ensure                  = 'Present'
                        DynamicAlloc            = $true
                        ProcessOnlyOnActiveNode = $true
                    }

                    $mockTestActiveNode = $false
                }

                It 'Should return the state as true' {
                    $result = Test-TargetResource @testParameters
                    $result | Should -Be $true
                }
            }

            $mockMinServerMemory = 8192
            $mockMaxServerMemory = 8192

            Context 'When the system percent memory is in the desired state and DynamicAlloc is set to false' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    Ensure       = 'Present'
                    MinMemoryPercent    = 80
                    MaxMemoryPercent    = 80
                    DynamicAlloc = $false
                }

                It 'Should return the state as true when desired MinMemory and MaxMemory are present' {
                    $result = Test-TargetResource @testParameters
                    $result | Should -Be $true
                }
            }

            $mockMinServerMemory = 0
            $mockMaxServerMemory = 8192

            Context 'When the system is in the desired state and DynamicAlloc is set to true' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    Ensure       = 'Present'
                    DynamicAlloc = $true
                }

                It 'Should return the state as true when desired MinMemory and MaxMemory are present' {
                    $result = Test-TargetResource @testParameters
                    $result | Should -Be $true
                }
            }

            $mockMinServerMemory = 1024
            $mockMaxServerMemory = 8192

            Context 'When the system is not in the desired state and Ensure is set to Absent' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    Ensure = 'Absent'
                }

                It 'Should return the state as false when desired MinMemory and MaxMemory are not set to the default values' {
                    $result = Test-TargetResource @testParameters
                    $result | Should -Be $false
                }
            }

            $mockMinServerMemory = 0
            $mockMaxServerMemory = 2147483647

            Context 'When the system is in the desired state and Ensure is set to Absent' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    Ensure = 'Absent'
                }

                It 'Should return the state as true when desired MinMemory and MaxMemory are present' {
                    $result = Test-TargetResource @testParameters
                    $result | Should -Be $true
                }
            }

            # This is regression test for issue #576
            Context 'When the system is in the desired state and ServerName is not set' {
                $testParameters = $mockDefaultParameters
                $testParameters.Remove('ServerName')
                $testParameters += @{
                    Ensure = 'Absent'
                }

                It 'Should not throw an error' {
                    { Test-TargetResource @testParameters } | Should -Not -Throw
                }
            }

            Assert-VerifiableMock
        }

        Describe "DSC_SqlMemory\Set-TargetResource" -Tag 'Set' {
            $mockMinServerMemory = 0
            $mockMaxServerMemory = 2147483647

            Mock -CommandName Connect-SQL -MockWith $mockConnectSQL -Verifiable
            Mock -CommandName Get-SqlDscDynamicMaxMemory -MockWith {
                return 16384 # MB
            }
            Mock -CommandName Get-SqlDscPercentMemory -MockWith {
                return 16384 # MB
            }

            Context 'When the MaxMemory parameter is not null and DynamicAlloc is set to true' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MaxMemory    = 8192
                    DynamicAlloc = $true
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Set-TargetResource @testParameters } | Should -Throw $script:localizedData.MaxMemoryParamMustBeNull
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscDynamicMaxMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscDynamicMaxMemory -Exactly -Times 0 -Scope Context
                }
            }

            Context 'When the MaxMemoryPercent parameter is not null and DynamicAlloc is set to true' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MaxMemoryPercent = 80
                    DynamicAlloc = $true
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Set-TargetResource @testParameters } | Should -Throw $script:localizedData.MaxMemoryPercentParamMustBeNull
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscPercentMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscPercentMemory -Exactly -Times 0 -Scope Context
                }
            }

            Context 'When the MaxMemoryPercent and MaxMemory parameters are not null and DynamicAlloc is set to false' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MaxMemory = 8192
                    MaxMemoryPercent = 80
                    DynamicAlloc = $false
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Set-TargetResource @testParameters } | Should -Throw $script:localizedData.MaxMemoryPercentParamMustBeNull
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscPercentMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscPercentMemory -Exactly -Times 0 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscDynamicMaxMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscDynamicMaxMemory -Exactly -Times 0 -Scope Context
                }
            }

            Context 'When the MinMemoryPercent and MinMemory parameters are not null and MaxMemory is not null' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MinMemory = 1024
                    MinMemoryPercent = 80
                    MaxMemory = 8192
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Set-TargetResource @testParameters } | Should -Throw $script:localizedData.MinMemoryPercentParamMustBeNull
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscPercentMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscPercentMemory -Exactly -Times 0 -Scope Context
                }
            }

            Context 'When the parameters MaxMemory and MaxMemoryPercent are null and DynamicAlloc is set to false' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    DynamicAlloc = $false
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Set-TargetResource @testParameters } | Should -Throw $script:localizedData.MaxMemoryParamMustNotBeNull
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscDynamicMaxMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscDynamicMaxMemory -Exactly -Times 0 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscPercentMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscPercentMemory -Exactly -Times 0 -Scope Context
                }
            }

            Context 'When the system is not in the desired state and Ensure is set to Absent' {
                $mockExpectedMinMemoryForAlterMethod = 0
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    Ensure = 'Absent'
                }

                It 'Should set the MinMemory and MaxMemory to the default values' {
                    { Set-TargetResource @testParameters } | Should -Not -Throw
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscDynamicMaxMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscDynamicMaxMemory -Exactly -Times 0 -Scope Context
                }
            }

            Context 'When the system is not in the desired state and Ensure is set to Present, and DynamicAlloc is set to false' {
                $mockMinServerMemory = 1024
                $mockMaxServerMemory = 8192

                Mock -CommandName Connect-SQL -MockWith $mockConnectSQL -Verifiable

                $mockExpectedMinMemoryForAlterMethod = 1024
                $mockExpectedMaxMemoryForAlterMethod = 8192
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MaxMemory    = 8192
                    MinMemory    = 1024
                    DynamicAlloc = $false
                    Ensure       = 'Present'
                }

                It 'Should set the MinMemory and MaxMemory to the correct values when Ensure parameter is set to Present and DynamicAlloc is set to false' {
                    { Set-TargetResource @testParameters } | Should -Not -Throw
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscDynamicMaxMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscDynamicMaxMemory -Exactly -Times 0 -Scope Context
                }
            }

            Context 'When the system is not in the desired state and Ensure is set to Present, Max/MinMemoryPercent specified and DynamicAlloc is set to false' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    DynamicAlloc = $false
                    Ensure       = 'Present'
                    MaxMemoryPercent = 80
                    MinMemoryPercent = 80
                }

                It 'Should set the MaxMemoryPercent and MinMemoryPercent to the correct values when Ensure parameter is set to Present and DynamicAlloc is set to false' {
                    { Set-TargetResource @testParameters } | Should -Not -Throw
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should call the mock function Get-SqlDscPercentMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscPercentMemory -Exactly -Times 2 -Scope Context
                }
            }

            Context 'When the system (OS IA64-bit) is not in the desired state and Ensure is set to Present, and DynamicAlloc is set to true' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    DynamicAlloc = $true
                    Ensure       = 'Present'
                    MinMemory    = 2048
                }

                It 'Should set the MaxMemory to the correct values when Ensure parameter is set to Present and DynamicAlloc is set to true' {
                    { Set-TargetResource @testParameters } | Should -Not -Throw
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should call the mock function Get-SqlDscDynamicMaxMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscDynamicMaxMemory -Exactly -Times 1 -Scope Context
                }
            }

            Mock -CommandName Connect-SQL -MockWith {
                $mockSqlServerObject = [PSCustomObject]@{
                    InstanceName                = $mockInstanceName
                    ComputerNamePhysicalNetBIOS = $mockServerName
                    Configuration               = @{
                        MinServerMemory = @{
                            DisplayName = 'min server memory (MB)'
                            Description = 'Minimum size of server memory (MB)'
                            RunValue    = 0
                            ConfigValue = 0
                        }
                        MaxServerMemory = @{
                            DisplayName = 'max server memory (MB)'
                            Description = 'Maximum size of server memory (MB)'
                            RunValue    = 10300
                            ConfigValue = 10300
                        }
                    }
                }

                # Add the Alter method
                $mockSqlServerObject | Add-Member -MemberType ScriptMethod -Name Alter -Value {
                    throw 'Mock Alter Method was called with invalid operation.'
                }

                $mockSqlServerObject
            } -Verifiable

            Context 'When the desired MinMemory and MaxMemory fails to be set' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MaxMemory    = 8192
                    MinMemory    = 1024
                    DynamicAlloc = $false
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Set-TargetResource @testParameters } | Should -Throw ($script:localizedData.AlterServerMemoryFailed -f $env:COMPUTERNAME, $mockInstanceName)
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscDynamicMaxMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscDynamicMaxMemory -Exactly -Times 0 -Scope Context
                }
            }

            Context 'When the desired MinMemoryPercent and MaxMemoryPercent fails to be set' {
                $testParameters = $mockDefaultParameters
                $testParameters += @{
                    MaxMemoryPercent    = 80
                    MinMemoryPercent    = 80
                    DynamicAlloc = $false
                    Ensure       = 'Present'
                }

                It 'Should throw the correct error' {
                    { Set-TargetResource @testParameters } | Should -Throw ($script:localizedData.AlterServerMemoryFailed -f $env:COMPUTERNAME, $mockInstanceName)
                }

                It 'Should call the mock function Connect-SQL' {
                    Assert-MockCalled -CommandName Connect-SQL -Exactly -Times 1 -Scope Context
                }

                It 'Should not call the mock function Get-SqlDscDynamicMaxMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscDynamicMaxMemory -Exactly -Times 0 -Scope Context
                }

                It 'Should call the mock function Get-SqlDscPercentMemory' {
                    Assert-MockCalled -CommandName Get-SqlDscPercentMemory -Exactly -Times 2 -Scope Context
                }
            }

            Assert-VerifiableMock
        }

        Describe 'DSC_SqlMemory\Get-SqlDscDynamicMaxMemory' -Tag 'Helper' {
            Context 'When the physical memory should be calculated' {
                BeforeEach {
                    Mock -CommandName Get-CimInstance -MockWith {
                        return New-Object -TypeName PSObject -Property @{
                            TotalPhysicalMemory = $mockTotalPhysicalMemory
                        }
                    } -ParameterFilter { $ClassName -eq 'Win32_ComputerSystem' }

                    Mock -CommandName Get-CimInstance -MockWith {
                        return  [PSCustomObject]@{
                            NumberOfCores = $mockNumberOfCores
                        }
                    } -ParameterFilter { $ClassName -eq 'Win32_Processor' }

                    Mock -CommandName Get-CimInstance -MockWith {
                        return [PSCustomObject]@{
                            OSArchitecture = $mockOSArchitecture
                        }
                    } -ParameterFilter { $ClassName -eq 'Win32_OperatingSystem' }
                }

                Context 'When number of cores is 2' {
                    $mockNumberOfCores = 2

                    Context 'When OS Architecture is 64-bit' {
                        $mockOSArchitecture = '64-bit'

                        context 'When physical memory is less than 20480MB' {
                            $mockTotalPhysicalMemory = 20426260480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 14560
                            }
                        }

                        context 'When physical memory is equal to 20480MB' {
                            $mockTotalPhysicalMemory = 21474836480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 16896
                            }
                        }

                        context 'When physical memory is more than 20480MB' {
                            $mockTotalPhysicalMemory = 31960596480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 25646
                            }
                        }

                    }

                    Context 'When OS Architecture is 32-bit' {
                        $mockOSArchitecture = '32-bit'

                        context 'When physical memory is less than 20480MB' {
                            # Dynamically set the mock return value.
                            $mockTotalPhysicalMemory = 20426260480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 14560
                            }
                        }

                        context 'When physical memory is equal to 20480MB' {
                            $mockTotalPhysicalMemory = 21474836480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 16896
                            }
                        }

                        context 'When physical memory is more than 20480MB' {
                            $mockTotalPhysicalMemory = 31960596480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 25646
                            }
                        }
                    }

                    Context 'When OS Architecture is IA64-bit' {
                        $mockOSArchitecture = 'IA64-bit'

                        context 'When physical memory is less than 20480MB' {
                            # Dynamically set the mock return value.
                            $mockTotalPhysicalMemory = 20426260480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 14560
                            }
                        }

                        context 'When physical memory is equal to 20480MB' {
                            $mockTotalPhysicalMemory = 21474836480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 16896
                            }
                        }

                        context 'When physical memory is more than 20480MB' {
                            $mockTotalPhysicalMemory = 31960596480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 25646
                            }
                        }
                    }
                }

                Context 'When number of cores is 4' {
                    $mockNumberOfCores = 4
                    Context 'When OS Architecture is 64-bit' {
                        $mockOSArchitecture = '64-bit'

                        context 'When physical memory is more than 20480MB' {
                            $mockTotalPhysicalMemory = 31960596480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 25134
                            }
                        }
                    }

                    Context 'When OS Architecture is 32-bit' {
                        $mockOSArchitecture = '32-bit'

                        context 'When physical memory is more than 20480MB' {
                            # Dynamically set the mock return value.
                            $mockTotalPhysicalMemory = 31960596480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 25390
                            }
                        }
                    }

                    Context 'When OS Architecture is IA64-bit' {
                        $mockOSArchitecture = 'IA64-bit'

                        context 'When physical memory is more than 20480MB' {
                            # Dynamically set the mock return value.
                            $mockTotalPhysicalMemory = 31960596480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 24622
                            }
                        }
                    }
                }

                Context 'When number of cores is 6' {
                    $mockNumberOfCores = 6
                    Context 'When OS Architecture is 64-bit' {
                        $mockOSArchitecture = '64-bit'

                        context 'When physical memory is more than 20480MB' {
                            $mockTotalPhysicalMemory = 31960596480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 24078
                            }
                        }
                    }

                    Context 'When OS Architecture is 32-bit' {
                        $mockOSArchitecture = '32-bit'

                        context 'When physical memory is more than 20480MB' {
                            # Dynamically set the mock return value.
                            $mockTotalPhysicalMemory = 31960596480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 24350
                            }
                        }
                    }

                    Context 'When OS Architecture is IA64-bit' {
                        $mockOSArchitecture = 'IA64-bit'

                        context 'When physical memory is more than 20480MB' {
                            # Dynamically set the mock return value.
                            $mockTotalPhysicalMemory = 31960596480

                            It 'Should return the correct max memory (in megabytes) value' {
                                $result = Get-SqlDscDynamicMaxMemory
                                $result | Should -Be 23534
                            }
                        }
                    }
                }
            }

            Context 'When the physical memory fails to be calculated' {
                BeforeAll {
                    Mock -CommandName Get-CimInstance -MockWith {
                        throw 'mocked unkown error'
                    }
                }

                It 'Should throw the correct error' {
                    { Get-SqlDscDynamicMaxMemory } | Should -Throw $script:localizedData.ErrorGetDynamicMaxMemory
                }
            }
        }

        Describe 'DSC_SqlMemory\Get-SqlDscPercentMemory' -Tag 'Helper' {
            Context 'When the physical memory should be calculated' {
                BeforeEach {
                    Mock -CommandName Get-CimInstance -MockWith {
                        return New-Object -TypeName PSObject -Property @{
                            TotalPhysicalMemory = $mockTotalPhysicalMemory
                        }
                    } -ParameterFilter { $ClassName -eq 'Win32_ComputerSystem' }
                }

                Context 'When physical memory is equal to 20480MB' {
                    $mockTotalPhysicalMemory = 21474836480

                    It 'Should return the correct memory (in megabytes) value' {
                        $result = Get-SqlDscPercentMemory -PercentMemory 80
                        $result | Should -Be 16384
                    }
                }

                Context 'When physical memory is equal to 1218.4MB' {
                    $mockTotalPhysicalMemory = 1596981248

                    It 'Should return the correct rounded memory (in megabytes) value' {
                        $result = Get-SqlDscPercentMemory -PercentMemory 50
                        $result | Should -Be 762
                    }
                }
            }

            Context 'When percentage of physical memory fails to be calculated' {
                BeforeAll {
                    Mock -CommandName Get-CimInstance -MockWith {
                        throw 'mocked unkown error'
                    }
                }

                It 'Should throw the correct error' {
                    { Get-SqlDscPercentMemory -PercentMemory 80 } | Should -Throw $script:localizedData.ErrorGetPercentMemory
                }
            }
        }
    }
}
finally
{
    Invoke-TestCleanup
}


text:
namespace OneDream.Models
{
    using System;
    using System.Collections.Generic;

    public partial class OD_Award
    {
        public int ID { get; set; }
        public int TermID { get; set; }
        public string Code { get; set; }
        public int UserID { get; set; }
        public bool DelFlag { get; set; }
        public System.DateTime CreateTime { get; set; }
    }
}


text:
const {User} = require('../models')
const jwt = require('jsonwebtoken')
const config = require('../config/config')

function jwtSignUser (user) {
  const ONE_WEEK = 60 * 60 * 24 * 7
  return jwt.sign(user, config.authentication.jwtSecret, {
    expiresIn: ONE_WEEK
  })
}

module.exports = {
  async register (req, res) {
    try {
      const user = await User.create(req.body)
      const userJson = user.toJSON()
      res.send({
        user: userJson,
        token: jwtSignUser(userJson)
      })
    } catch (err) {
      res.status(400).send({
        error: 'This email account is already in use.'
      })
    }
  },
  async login (req, res) {
    try {
      const {email, password} = req.body
      const user = await User.findOne({
        where: {
          email: email
        }
      })
      if (!user) {
        return res.status(403).send({
          error: 'The login info was incorrect'
        })
      }
      const isPasswordValid = await user.comparePassword(password)
      if (!isPasswordValid) {
        return res.status(403).send({
          error: 'The login info was incorrect'
        })
      }
      const userJson = user.toJSON()
      res.send({
        user: userJson,
        token: jwtSignUser(userJson)
      })
    } catch (err) {
      res.status(500).send({
        error: 'An error has occured trying to log in. '
      })
    }
  }
}


text:
package org.jetbrains.plugins.cucumber.java.run;

import gherkin.formatter.Formatter;
import gherkin.formatter.Reporter;
import gherkin.formatter.model.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;

import static org.jetbrains.plugins.cucumber.java.run.CucumberJvmSMFormatterUtil.*;

public class CucumberJvmSMFormatter implements Formatter, Reporter {
  public static final int MILLION = 1000000;
  private int scenarioCount;
  private int passedScenarioCount;
  private boolean scenarioPassed = true;

  private int stepCount;
  private int passedStepCount;
  private int skippedStepCount;
  private int pendingStepCount;
  private int failedStepCount;
  private int undefinedStepCount;
  private boolean endedByNewLine = true;

  public static final String RESULT_STATUS_PENDING = "pending";

  private final Appendable appendable;

  private final Queue<String> queue;

  private String uri;
  private String currentFeatureName;

  private boolean beforeExampleSection;

  private ScenarioOutline currentScenarioOutline;

  private Scenario currentScenario;

  private final Queue<Step> currentSteps;

  @SuppressWarnings("UnusedDeclaration")
  public CucumberJvmSMFormatter(Appendable appendable) {
    this.appendable = System.err;
    queue = new ArrayDeque<String>();
    currentSteps = new ArrayDeque<Step>();
    outCommand(String.format(TEMPLATE_ENTER_THE_MATRIX, getCurrentTime()));
    outCommand(String.format(TEMPLATE_SCENARIO_COUNTING_STARTED, 0, getCurrentTime()));
  }

  @Override
  public void feature(Feature feature) {
    if (currentFeatureName != null) {
      done();
    }
    currentFeatureName = "Feature: " + getName(feature);
    outCommand(String.format(TEMPLATE_TEST_SUITE_STARTED, getCurrentTime(), uri + ":" + feature.getLine(), currentFeatureName));
  }

  private static boolean isRealScenario(final Scenario scenario) {
    return scenario.getKeyword().equals("Scenario");
  }

  @Override
  public void scenario(Scenario scenario) {
    closeScenario();
    outCommand(String.format(TEMPLATE_SCENARIO_STARTED, getCurrentTime()));
    if (isRealScenario(scenario)) {
      scenarioCount++;
      closeScenarioOutline();
      currentSteps.clear();
    }
    currentScenario = scenario;
    beforeExampleSection = false;
    outCommand(String.format(TEMPLATE_TEST_SUITE_STARTED, getCurrentTime(), uri + ":" + scenario.getLine(), getName(currentScenario)));

    while (queue.size() > 0) {
      String smMessage = queue.poll();
      outCommand(smMessage);
    }
  }

  @Override
  public void scenarioOutline(ScenarioOutline outline) {
    scenarioCount++;
    queue.clear();
    currentSteps.clear();

    closePreviousScenarios();
    currentScenarioOutline = outline;
    currentScenario = null;
    beforeExampleSection = true;
    outCommand(
      String.format(TEMPLATE_TEST_SUITE_STARTED, getCurrentTime(), uri + ":" + outline.getLine(), getName(currentScenarioOutline)));
  }

  @Override
  public void examples(Examples examples) {
    beforeExampleSection = false;
    outCommand(String.format(TEMPLATE_TEST_SUITE_STARTED, getCurrentTime(), uri + ":" + examples.getLine(), "Examples:"));
  }

  @Override
  public void startOfScenarioLifeCycle(Scenario scenario) {

  }

  @Override
  public void step(Step step) {
    if (beforeExampleSection) {
      return;
    }
    currentSteps.add(step);
  }

  @Override
  public void endOfScenarioLifeCycle(Scenario scenario) {
  }

  @Override
  public void result(Result result) {
    stepCount++;
    Step currentStep = currentSteps.poll();
    outCommand(String.format(TEMPLATE_TEST_STARTED, getCurrentTime(), uri + ":" + currentStep.getLine(), getName(currentStep)), true);
    String stepFullName = getName(currentStep);
    if (result.getStatus().equals(Result.FAILED)) {
      failedStepCount++;
      scenarioPassed = false;
      String fullMessage = result.getErrorMessage().replace("\r", "").replace("\t", "  ");
      String[] messageInfo = fullMessage.split("\n", 2);
      final String message;
      final String details;
      if (messageInfo.length == 2) {
        message = messageInfo[0].trim();
        details = messageInfo[1].trim();
      }
      else {
        message = fullMessage;
        details = "";
      }

      outCommand(String.format(TEMPLATE_TEST_FAILED, getCurrentTime(), escape(details), escape(message), stepFullName, ""), true);
    }
    else if (result.getStatus().equals(RESULT_STATUS_PENDING)) {
      pendingStepCount++;
      scenarioPassed = false;
      outCommand(String.format(TEMPLATE_TEST_PENDING, stepFullName, getCurrentTime()), true);
    }
    else if (result.equals(Result.UNDEFINED)) {
      undefinedStepCount++;
      scenarioPassed = false;
      String message = "Undefined step: " + getName(currentStep);
      String details = "";
      outCommand(String.format(TEMPLATE_TEST_FAILED, getCurrentTime(), escape(details), escape(message), stepFullName, "error = 'true'"), true);
    }
    else if (result.equals(Result.SKIPPED)) {
      skippedStepCount++;
      scenarioPassed = false;
      outCommand(String.format(TEMPLATE_TEST_PENDING, stepFullName, getCurrentTime()), true);
    }
    else {
      passedStepCount++;
    }

    final String currentTime = getCurrentTime();
    final Long duration = result.getDuration();
    outCommand(String.format(TEMPLATE_TEST_FINISHED, currentTime, (duration == null ? 0 : duration.longValue()) / MILLION, stepFullName), true);
  }

  private void closeScenario() {
    if (currentScenario != null) {
      if (isRealScenario(currentScenario)) {
        if (scenarioPassed) {
          passedScenarioCount++;
        }
      }

      if (!scenarioPassed) {
        outCommand(String.format(TEMPLATE_SCENARIO_FAILED, getCurrentTime()), true);
      }
      outCommand(String.format(TEMPLATE_SCENARIO_FINISHED, getCurrentTime()), true);
      outCommand(String.format(TEMPLATE_TEST_SUITE_FINISHED, getCurrentTime(), getName(currentScenario)));
    }
    scenarioPassed = true;
    currentScenario = null;
  }

  private void closeScenarioOutline() {
    if (currentScenarioOutline != null) {
      if (scenarioPassed) {
        passedScenarioCount++;
      }
      if (!beforeExampleSection) {
        outCommand(String.format(TEMPLATE_TEST_SUITE_FINISHED, getCurrentTime(), "Examples:"));
      }
      outCommand(String.format(TEMPLATE_TEST_SUITE_FINISHED, getCurrentTime(), getName(currentScenarioOutline)));
    }
    currentScenarioOutline = null;
  }

  private void closePreviousScenarios() {
    closeScenario();
    closeScenarioOutline();
  }

  @Override
  public void background(Background background) {
    closeScenario();
    currentScenario = null;
  }

  @Override
  public void done() {
    closePreviousScenarios();
    outCommand(String.format(TEMPLATE_TEST_SUITE_FINISHED, getCurrentTime(), currentFeatureName));
  }

  @Override
  public void uri(String s) {
    String currentDir = System.getProperty("org.jetbrains.run.directory");
    if (currentDir != null) {
      uri = FILE_RESOURCE_PREFIX + currentDir + File.separator + s;
    }
    else {
      uri = FILE_RESOURCE_PREFIX + s;
    }
  }

  @Override
  public void eof() {
  }

  @Override
  public void syntaxError(String s, String s1, List<String> strings, String s2, Integer integer) {
    outCommand("Syntax error\n");
  }

  @Override
  public void after(Match match, Result result) {
  }

  @Override
  public void match(Match match) {
  }

  @SuppressWarnings("UnusedDeclaration")
  public void embedding(String mimeType, byte[] data) {
    outCommand("embedding\n");
  }

  @SuppressWarnings("UnusedDeclaration")
  public void embedding(String s, InputStream inputStream) {
    outCommand("embedding\n");
  }

  @Override
  public void write(String s) {
    out(s);
  }

  @Override
  public void close() {
    outCommand(String.format(TEMPLATE_SCENARIO_COUNTING_FINISHED, getCurrentTime()));
  }

  @Override
  public void before(Match match, Result result) {
  }

  private void outCommand(String s) {
    outCommand(s, false);
  }

  private void outCommand(String s, boolean waitForScenario) {
    if (currentScenario == null && waitForScenario) {
      queue.add(s);
    }
    else {
      try {
        if (!endedByNewLine) {
          appendable.append("\n");
        }
        appendable.append(s);
        appendable.append("\n");
        endedByNewLine = true;
      }
      catch (IOException ignored) {
      }
    }
  }

  private void out(String s) {
    try {
      appendable.append(s);
      endedByNewLine = s.endsWith("\n");
    }
    catch (IOException ignored) {
    }
  }

  private static String getName(Scenario scenario) {
    if (scenario.getKeyword().equals("Scenario Outline")) {
      return escape("Scenario: Line: " + scenario.getLine());
    }
    else {
      return escape("Scenario: " + scenario.getName());
    }
  }

  private static String getName(ScenarioOutline outline) {
    return escape("Scenario Outline: " + outline.getName());
  }

  private static String getName(Step step) {
    return escape(step.getKeyword() + " " + step.getName());
  }

  private static String getName(Feature feature) {
    return escape(feature.getName());
  }
}


text:
dir="/tmp/foo-bar/"
cd "$dir"

echo -e "GSA Adaptor Data Version 1 [\n]"
echo id-list
# Note: \n delimiter requires no file names contain it.
find . -type f


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Audiodoc = mongoose.model('Audiodoc'),
    _ = require('lodash'),
    express = require('express'),
    needle = require('needle'),
    fs = require('fs'),
    S = require('string'),
     mv = require('mv');

var app = express();
/**
 * Get the error message from error object
 */
var getErrorMessage = function (err) {
    var message = '';

    if (err.code) {
        switch (err.code) {
            case 11000:
            case 11001:
                message = 'Audiodoc already exists';
                break;
            default:
                message = 'Something went wrong';
        }
    } else {
        for (var errName in err.errors) {
            if (err.errors[errName].message) message = err.errors[errName].message;
        }
    }

    return message;
};

/**
 * Create a Audiodoc
 */
exports.create = function (req, res) {
    var audiodoc = new Audiodoc(req.body);
    audiodoc.user = req.user;

    audiodoc.save(function (err) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(audiodoc);
        }
    });
};

/**
 * Show the current Audiodoc
 */
exports.read = function (req, res) {
    res.jsonp(req.audiodoc);
};

/**
 * Update a Audiodoc
 */
exports.update = function (req, res) {
    var audiodoc = req.audiodoc;

    audiodoc = _.extend(audiodoc, req.body);

    audiodoc.save(function (err) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(audiodoc);
        }
    });
};

/**
 * Delete an Audiodoc
 */
exports.delete = function (req, res) {
    var audiodoc = req.audiodoc;

    audiodoc.remove(function (err) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(audiodoc);
        }
    });
};

/**
 * List of Audiodocs
 */
exports.list = function (req, res) {
    Audiodoc.find().sort('-created').populate('user', 'displayName').exec(function (err, audiodocs) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(audiodocs);
        }
    });
};

exports.audiodocFTSearch = function (req, res) {
    if (!req.param('query')) {

        return res.send(400, {

            message: 'Empty query'
        });
    }
    Audiodoc.textSearch(req.param('query'), function (err, audiodocs) {
        if (err) {
            console.log("I'm here" + err);
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            //use lodash to filter for the user relevent only
            var results = _.pluck(audiodocs.results, 'obj');
            var retval = {
                owned: [],
                shared: []
            };
            _.each(results, function (value, key, list) {
                value.content = S(value.content).truncate(580);
            });
            for (var i = 0; i<results.length; i++) {
                if (String(results[i].user) === String(req.user._id)) {
                    retval.owned.push(results[i]);
                } else if (results[i].sharedUser.indexOf(String(req.user._id)) > -1) {
                    retval.shared.push(results[i]);
                }
            }
            res.jsonp(retval);
        }

    });

};

/**
 * Audiodoc middleware
 */

exports.audiodocByID = function (req, res, next, id) {
    Audiodoc.findById(id).populate('user', 'displayName').exec(function (err, audiodoc) {
        if (err) return next(err);
        if (!audiodoc) return next(new Error('Failed to load Audiodoc ' + id));
        req.audiodoc = audiodoc;
        next();
    });
};

/**
 * Audiodoc authorization middleware
 */
exports.hasAuthorization = function (req, res, next) {
    if (req.audiodoc.user.id !== req.user.id) {
        return res.send(403, 'User is not authorized');
    }
    next();
};

exports.sharedoc = function (req, res, next) {
    var sharedWithUser = req.body.sharedWithUser;
    var sharedDoc = req.body.sharedDoc;
    Audiodoc.findById(sharedDoc._id).exec(function (err, audiodoc) {
        if (err) {
            res.send(400, {
                message: getErrorMessage(err)
            });
        }

        if (!audiodoc) {
            res.send(400, {
                message: getErrorMessage('no doc found')
            });
        }

        audiodoc.sharedUser.push(sharedWithUser.id);
        audiodoc.sharedUser = _.uniq(audiodoc.sharedUser);
        audiodoc.save(function (err) {
            if (err) {
                return res.send(400, {
                    message: getErrorMessage(err)
                });
            } else {
                res.jsonp("success");
            }
        });

    });

}

exports.uploadRecordedFile = function (req,res,next)
{
    var buf = new Buffer(req.body.data.blob, 'base64'); // decode
    fs.writeFile('public/uploads/'+req.body.subject+'.wav', buf, function(err) {
        if(err) {
            console.log("err", err);
        }
        mv('public/uploads/'+req.body.subject+'.wav', 'public/uploads/'+req.user._id+'/'+req.body.subject+'.wav',{mkdirp: true}, function(err) {
        });

        var audiodoc = new Audiodoc();
        audiodoc.user = req.user;
        audiodoc.subject = req.body.subject;
        audiodoc.content = req.body.content;
        audiodoc.filepath = 'uploads/'+req.user._id+'/'+req.body.subject+'.wav';

        console.log(audiodoc);
        audiodoc.save(function (err) {
            if (err) {
                return res.send(400, {
                    message: getErrorMessage(err)
                });
            }
        });
    })

}

exports.uploadFile = function (req, res, next) {
    res._headers['x-frame-options'] = 'SAMEORIGIN';
    console.log(req.files);
    console.log('inside uploadFile'); // <-- never reached using IE9
    var originalName = req.files.file.originalname;

    var options = {
        headers: {
            'Content-Type': 'audio/x-flac; rate=44100'
        }
    }
    var file = fs.createReadStream(req.files.file.path);
    needle.post('http://www.google.com/speech-api/v2/recognize?output=json&maxresults=1&lang=en-us&key=AIzaSyD5rlPiYhD3p-0rRoUQ9QCleq-aN_ZlyGY',
        file, options,
        function (err, resp) {
            if (err) {
                console.log('error');
                res.jsonp("error");
            }

            var parsedResult = JSON.parse(resp.body.substring(14));

            var jsonDoc = req.body;
            jsonDoc.content = parsedResult.result[0]['alternative'][0]['transcript'];

            var newFilePath = 'public/uploads/'+req.user._id+'/'+originalName;
            var newFilePath1 = 'uploads/'+req.user._id+'/'+originalName;
            jsonDoc.filepath = newFilePath1;
            mv(req.files.file.path, newFilePath,{mkdirp: true}, function(err) {});
            var audiodoc = new Audiodoc(jsonDoc);
            audiodoc.user = req.user;
            audiodoc.save(function (err) {
                if (err) {
                    return res.send(400, {
                        message: getErrorMessage(err)
                    });
                }
            });

            res.jsonp(jsonDoc);

        });

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 334762 $ -->
<appendix xml:id="datetime.constants" xmlns="http://docbook.org/ns/docbook">
 &reftitle.constants;
 <para>
  The <link linkend="datetime.constants.types"><literal>DATE_</literal>
  constants</link> are defined since PHP 5.1.1 and they offer standard
  date representations, which can be used along with the date format functions
  (like <function>date</function>).
 </para>
 <para>
  Following constants exists since PHP 5.1.2 and specify a format returned by
  functions <function>date_sunrise</function> and
  <function>date_sunset</function>.
 </para>
 <variablelist>
  <varlistentry xml:id="constant.sunfuncs-ret-timestamp">
   <term>
    <constant>SUNFUNCS_RET_TIMESTAMP</constant>
     (<type>integer</type>)
   </term>
   <listitem>
    <simpara>
     Timestamp
    </simpara>
   </listitem>
  </varlistentry>
  <varlistentry xml:id="constant.sunfuncs-ret-string">
   <term>
    <constant>SUNFUNCS_RET_STRING</constant>
     (<type>integer</type>)
   </term>
   <listitem>
    <simpara>
     Hours:minutes (example: 08:02)
    </simpara>
   </listitem>
  </varlistentry>
  <varlistentry xml:id="constant.sunfuncs-ret-double">
   <term>
    <constant>SUNFUNCS_RET_DOUBLE</constant>
     (<type>integer</type>)
   </term>
   <listitem>
    <simpara>
     Hours as floating point number (example 8.75)
    </simpara>
   </listitem>
  </varlistentry>
 </variablelist>
</appendix>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
/*written by kimikan, 2017-7-12*/
use mio::{Events, Poll, Token, Ready, PollOpt, Evented};
use std::io;

/* just a wrapper */
pub struct Poller {
    pub _poll: Poll,
}

impl Poller {
    pub fn new() -> io::Result<Poller> {
        let poll = Poll::new()?;

        return Ok(Poller { _poll: poll });
    }

    pub fn poll_once(&self, events: &mut Events) -> io::Result<usize> {
        //println!("poll: {:?} {:?}", self._poll, events);
        self._poll.poll(events, None)
    }

    pub fn deregister<E:?Sized>(&self, handle:&E)->io::Result<()>
        where E:Evented {
            self._poll.deregister(handle)
    }

    pub fn register_read<E: ?Sized>(&self, handle: &E, token: Token) -> io::Result<()>
        where E: Evented
    {
        self.register(handle, token, Ready::readable(), PollOpt::edge())
    }

    pub fn register_both<E: ?Sized>(&self, handle: &E, token: Token) -> io::Result<()>
        where E: Evented
    {
        let mut ready = Ready::readable();
        ready.insert(Ready::writable());
        self.register(handle, token, ready, PollOpt::edge())
    }

    pub fn register<E: ?Sized>(&self,
                               handle: &E,
                               token: Token,
                               interest: Ready,
                               opts: PollOpt)
                               -> io::Result<()>
        where E: Evented
    {
        let result = self._poll.register(handle, token, interest, opts)?;
        println!("regist: {:?}, {:?}, {:?}", token, interest, opts);
        Ok(result)
    }
}

/*
impl Deref<Poll> for Poller {

} */


text: REPLAY = "replay"


text:
namespace Bookshelf.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class rentals : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Rentals",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        StudentId = c.Int(nullable: false),
                        BookId = c.Int(nullable: false),
                        CreatedAt = c.DateTime(nullable: false),
                        DueDate = c.DateTime(nullable: false),
                        Student_Id = c.String(nullable: false, maxLength: 128),
                        Library_Id = c.Int(),
                    })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.Books", t => t.BookId)
                .ForeignKey("dbo.AspNetUsers", t => t.Student_Id)
                .ForeignKey("dbo.Libraries", t => t.Library_Id)
                .Index(t => t.BookId)
                .Index(t => t.Student_Id)
                .Index(t => t.Library_Id);

            AddColumn("dbo.Books", "TotalCopies", c => c.Int(nullable: false));
            AddColumn("dbo.Books", "AvailableCopies", c => c.Int(nullable: false));
        }

        public override void Down()
        {
            DropForeignKey("dbo.Rentals", "Library_Id", "dbo.Libraries");
            DropForeignKey("dbo.Rentals", "Student_Id", "dbo.AspNetUsers");
            DropForeignKey("dbo.Rentals", "BookId", "dbo.Books");
            DropIndex("dbo.Rentals", new[] { "Library_Id" });
            DropIndex("dbo.Rentals", new[] { "Student_Id" });
            DropIndex("dbo.Rentals", new[] { "BookId" });
            DropColumn("dbo.Books", "AvailableCopies");
            DropColumn("dbo.Books", "TotalCopies");
            DropTable("dbo.Rentals");
        }
    }
}


text:
<!DOCTYPE html>

    <title></title>

Selamat anda telah terdaftar sebagai pengguna API OCFA !

Anda dapat mengakses API OCFA dengan menggunakan API KEY:

<?= $user->auth_key ?>


text:
module AwsSdkCodeGenerator
  class ResourceHasManyAssociationCode

    def initialize(options)
      @assoc = options.fetch(:assoc)
      @paginators = options.fetch(:paginators, nil)
      @collection_class = "#{options.fetch(:assoc)['resource']['type']}::Collection"
    end

    def build
      if paginated?
        paginated_request
      else
        non_paginated_request
      end
    end

    private

    def paginated_request
      <<-CODE.rstrip
batches = Enumerator.new do |y|
  #{client_request}
  resp.each_page do |page|
    batch = []
    #{batch_builder(resp_var_name: 'page', indent: '    ')}
    y.yield(batch)
  end
end
#{@collection_class}.new(batches)
      CODE
    end

    def non_paginated_request
      <<-CODE.rstrip
batches = Enumerator.new do |y|
  batch = []
  #{client_request}
  #{batch_builder(indent: '  ')}
  y.yield(batch)
end
#{@collection_class}.new(batches)
      CODE
    end

    def client_request
      Docstring.indent(ResourceClientRequest.build(
        request: @assoc['request'],
        merge: true,
        resp: true,
      ), '  ')
    end

    def batch_builder(options)
      Docstring.indent(
        ResourceBatchBuilder.new(
          resource: @assoc['resource'],
          resp_var_name: options.fetch(:resp_var_name, 'resp'),
        ).build,
      options[:indent])
    end

    def paginated?
      @paginators &&
      @paginators['pagination'][operation_name] &&
      @paginators['pagination'][operation_name]['input_token']
    end

    def operation_name
      @assoc['request']['operation']
    end

  end
end


text:
/*@ngInject*/
export default class ResultsService {

  constructor($http) {
    this.$http = $http;
  }

  getHotels() {
    return this.$http.get('http://localhost:3000/api/hotel').then((object) => {
      return object.data;
    }, function (error) {
      return [];
    });
  }
}