CRLF -> LF

alex/smoke-test-esbuild
Alex Dima 3 years ago
parent d7ac67dbf8
commit aa75ddccbb
No known key found for this signature in database
GPG Key ID: 39563C1504FDD0C9

@ -1,74 +1,74 @@
/// <reference path="../../references.js" /> /// <reference path="../../references.js" />
(function () { (function () {
"use strict"; "use strict";
var deltaDecorations = function (oldDecorations, newDecorations) { var deltaDecorations = function (oldDecorations, newDecorations) {
/// <summary> /// <summary>
/// Update oldDecorations to match newDecorations. /// Update oldDecorations to match newDecorations.
/// It will remove old decorations which are not found in new decorations /// It will remove old decorations which are not found in new decorations
/// and add only the really new decorations. /// and add only the really new decorations.
/// </summary> /// </summary>
/// <param name="oldDecorations" type="Array"> /// <param name="oldDecorations" type="Array">
/// An array containing ids of existing decorations /// An array containing ids of existing decorations
/// </param> /// </param>
/// <param name="newDecorations" type="Array"> /// <param name="newDecorations" type="Array">
/// An array containing literal objects describing new decorations. A /// An array containing literal objects describing new decorations. A
/// literal contains the following two fields: /// literal contains the following two fields:
/// range /// range
/// options /// options
/// </param> /// </param>
/// <returns type="Array"> /// <returns type="Array">
/// Returns an array of decorations ids /// Returns an array of decorations ids
/// </returns> /// </returns>
var hashFunc = function (range, options) { var hashFunc = function (range, options) {
return range.startLineNumber + "," + range.startColumn + "-" + range.endLineNumber + "," + range.endColumn + return range.startLineNumber + "," + range.startColumn + "-" + range.endLineNumber + "," + range.endColumn +
"-" + options.hoverMessage + "-" + options.className + "-" + options.isOverlay + "-" + options.showInOverviewRuler; "-" + options.hoverMessage + "-" + options.className + "-" + options.isOverlay + "-" + options.showInOverviewRuler;
}; };
return this.changeDecorations(function (changeAccessor) { return this.changeDecorations(function (changeAccessor) {
var i, len, oldDecorationsMap = {}, hash; var i, len, oldDecorationsMap = {}, hash;
// Record old decorations in a map // Record old decorations in a map
// Two decorations can have the same hash // Two decorations can have the same hash
for (i = 0, len = oldDecorations.length; i < len; i++) { for (i = 0, len = oldDecorations.length; i < len; i++) {
hash = hashFunc(this.getDecorationRange(oldDecorations[i]), this.getDecorationOptions(oldDecorations[i])); hash = hashFunc(this.getDecorationRange(oldDecorations[i]), this.getDecorationOptions(oldDecorations[i]));
oldDecorationsMap[hash] = oldDecorationsMap[hash] || []; oldDecorationsMap[hash] = oldDecorationsMap[hash] || [];
oldDecorationsMap[hash].push(oldDecorations[i]); oldDecorationsMap[hash].push(oldDecorations[i]);
} }
// Add only new decorations & mark reused ones // Add only new decorations & mark reused ones
var j, lenJ, result = [], usedOldDecorations = {}, oldDecorationsCandidates, reusedOldDecoration; var j, lenJ, result = [], usedOldDecorations = {}, oldDecorationsCandidates, reusedOldDecoration;
for (i = 0, len = newDecorations.length; i < len; i++) { for (i = 0, len = newDecorations.length; i < len; i++) {
hash = hashFunc(newDecorations[i].range, newDecorations[i].options); hash = hashFunc(newDecorations[i].range, newDecorations[i].options);
reusedOldDecoration = false; reusedOldDecoration = false;
if (oldDecorationsMap.hasOwnProperty(hash)) { if (oldDecorationsMap.hasOwnProperty(hash)) {
oldDecorationsCandidates = oldDecorationsMap[hash]; oldDecorationsCandidates = oldDecorationsMap[hash];
// We can try reusing an old decoration (if it hasn't been reused before) // We can try reusing an old decoration (if it hasn't been reused before)
for (j = 0, lenJ = oldDecorationsCandidates.length; j < lenJ; j++) { for (j = 0, lenJ = oldDecorationsCandidates.length; j < lenJ; j++) {
if (!usedOldDecorations.hasOwnProperty(oldDecorationsCandidates[j])) { if (!usedOldDecorations.hasOwnProperty(oldDecorationsCandidates[j])) {
// Found an old decoration which can be reused & it hasn't been reused before // Found an old decoration which can be reused & it hasn't been reused before
reusedOldDecoration = true; reusedOldDecoration = true;
usedOldDecorations[oldDecorationsCandidates[j]] = true; usedOldDecorations[oldDecorationsCandidates[j]] = true;
result.push(oldDecorationsCandidates[j]); result.push(oldDecorationsCandidates[j]);
break; break;
} }
} }
} }
if (!reusedOldDecoration) { if (!reusedOldDecoration) {
result.push(changeAccessor.addDecoration(newDecorations[i].range, newDecorations[i].options)); result.push(changeAccessor.addDecoration(newDecorations[i].range, newDecorations[i].options));
} }
} }
// Remove unused old decorations // Remove unused old decorations
for (i = 0, len = oldDecorations.length; i < len; i++) { for (i = 0, len = oldDecorations.length; i < len; i++) {
if (!usedOldDecorations.hasOwnProperty(oldDecorations[i])) { if (!usedOldDecorations.hasOwnProperty(oldDecorations[i])) {
changeAccessor.removeDecoration(oldDecorations[i]); changeAccessor.removeDecoration(oldDecorations[i]);
} }
} }
return result; return result;
}.bind(this)); }.bind(this));
}; };
})(); })();

@ -1,61 +1,61 @@
/// <reference path="../../references.js" /> /// <reference path="../../references.js" />
(function () { (function () {
"use strict"; "use strict";
// Some useless comment // Some useless comment
var deltaDecorations = function (oldDecorations, newDecorations) { var deltaDecorations = function (oldDecorations, newDecorations) {
/// <summary> /// <summary>
/// Update oldDecorations to match newDecorations. /// Update oldDecorations to match newDecorations.
/// It will remove old decorations which are not found in new decorations /// It will remove old decorations which are not found in new decorations
/// and add only the really new decorations. /// and add only the really new decorations.
/// </summary> /// </summary>
/// <param name="oldDecorations" type="Array"> /// <param name="oldDecorations" type="Array">
/// An array containing ids of existing decorations /// An array containing ids of existing decorations
/// </param> /// </param>
/// <param name="newDecorations" type="Array"> /// <param name="newDecorations" type="Array">
/// An array containing literal objects describing new decorations. A /// An array containing literal objects describing new decorations. A
/// literal contains the following two fields: /// literal contains the following two fields:
/// range /// range
/// options /// options
/// </param> /// </param>
/// <returns type="Array"> /// <returns type="Array">
/// Returns an array of decorations ids /// Returns an array of decorations ids
/// </returns> /// </returns>
var hashFunc = function (range, options) { var hashFunc = function (range, options) {
return range.startLineNumber + "," + range.startColumn + "-" + range.endLineNumber + "," + range.endColumn + return range.startLineNumber + "," + range.startColumn + "-" + range.endLineNumber + "," + range.endColumn +
"-" + options.hoverMessage + "-" + options.className + "-" + options.isOverlay + "-" + options.showInOverviewRuler; "-" + options.hoverMessage + "-" + options.className + "-" + options.isOverlay + "-" + options.showInOverviewRuler;
}; };
return this.changeDecorations(function (changeAccessor) { return this.changeDecorations(function (changeAccessor) {
var i, len, oldDecorationsMap = {}, hash; var i, len, oldDecorationsMap = {}, hash;
// Record old decorations in a map // Record old decorations in a map
for (i = 0, len = oldDecorations.length; i < len; i++) { for (i = 0, len = oldDecorations.length; i < len; i++) {
hash = hashFunc(this.getDecorationRange(oldDecorations[i]), this.getDecorationOptions(oldDecorations[i])); hash = hashFunc(this.getDecorationRange(oldDecorations[i]), this.getDecorationOptions(oldDecorations[i]));
oldDecorationsMap[hash] = i; oldDecorationsMap[hash] = i;
} }
// Add only new decorations & mark reused ones // Add only new decorations & mark reused ones
var result = [], usedOldDecorationsMap = {}; var result = [], usedOldDecorationsMap = {};
for (i = 0, len = newDecorations.length; i < len; i++) { for (i = 0, len = newDecorations.length; i < len; i++) {
hash = hashFunc(newDecorations[i].range, newDecorations[i].options); hash = hashFunc(newDecorations[i].range, newDecorations[i].options);
if (oldDecorationsMap.hasOwnProperty(hash)) { if (oldDecorationsMap.hasOwnProperty(hash)) {
usedOldDecorationsMap[oldDecorationsMap[hash]] = true; usedOldDecorationsMap[oldDecorationsMap[hash]] = true;
result.push(oldDecorations[oldDecorationsMap[hash]]); result.push(oldDecorations[oldDecorationsMap[hash]]);
} else { } else {
result.push(changeAccessor.addDecoration(newDecorations[i].range, newDecorations[i].options)); result.push(changeAccessor.addDecoration(newDecorations[i].range, newDecorations[i].options));
} }
} }
// Remove unused old decorations // Remove unused old decorations
for (i = 0, len = oldDecorations.length; i < len; i++) { for (i = 0, len = oldDecorations.length; i < len; i++) {
if (!usedOldDecorationsMap.hasOwnProperty(i)) { if (!usedOldDecorationsMap.hasOwnProperty(i)) {
changeAccessor.removeDecoration(oldDecorations[i]); changeAccessor.removeDecoration(oldDecorations[i]);
} }
} }
return result; return result;
}.bind(this)); }.bind(this));
}; };
})(); })();

@ -1,2 +1,2 @@
dist/*.js dist/*.js
dist/*.ttf dist/*.ttf

@ -1,2 +1,2 @@
/dist/*.js /dist/*.js
/dist/*.ttf /dist/*.ttf

@ -1,33 +1,33 @@
"use strict"; "use strict";
function Person(age) { function Person(age) {
if (age) { if (age) {
this.age = age; this.age = age;
} }
} }
Person.prototype.getAge = function () { Person.prototype.getAge = function () {
return this.age; return this.age;
}; };
function Student(age, grade) { function Student(age, grade) {
Person.call(this, age); Person.call(this, age);
this.grade = grade; this.grade = grade;
} }
Student.prototype = new Person(); Student.prototype = new Person();
Student.prototype.getGrade = function () { Student.prototype.getGrade = function () {
return this.grade; return this.grade;
}; };
var s = new Student(24, 5.75); var s = new Student(24, 5.75);
//var age = s. //var age = s.
//delete s.age; //delete s.age;
//s.getAge = function() { return {foo:"bar"}; }; //s.getAge = function() { return {foo:"bar"}; };
//s. //s.
//s.getAge(). //s.getAge().

File diff suppressed because one or more lines are too long

@ -1,10 +1,10 @@
/* /*
전문 전문
유구한 역사와 전통에 빛나는 우리 대한 국민은 3·1 운동으로 건립된 대한민국 임시 정부의 법통과 불의에 항거한 4·19 민주 이념을 계승하고, 조국의 민주 개혁과 평화적 통일의 사명에 입각하여 정의·인도와 동포애로써 민족의 단결을 공고히 하고, 모든 사회적 폐습과 불의를 타파하며, 자율과 조화를 바탕으로 자유 민주적 기본 질서를 더욱 확고히 하여 정치·경제·사회·문화의 모든 영역에 있어서 각인의 기회를 균등히 하고, 능력을 최고도로 발휘하게 하며, 자유와 권리에 따르는 책임과 의무를 완수하게 하여, 안으로는 국민 생활의 균등한 향상을 기하고 밖으로는 항구적인 세계 평화와 인류 공영에 이바지함으로써 우리들과 우리들의 자손의 안전과 자유와 행복을 영원히 확보할 것을 다짐하면서 1948년 7월 12일에 제정되고 8차에 걸쳐 개정된 헌법을 이제 국회의 의결을 거쳐 국민 투표에 의하여 개정한다. 유구한 역사와 전통에 빛나는 우리 대한 국민은 3·1 운동으로 건립된 대한민국 임시 정부의 법통과 불의에 항거한 4·19 민주 이념을 계승하고, 조국의 민주 개혁과 평화적 통일의 사명에 입각하여 정의·인도와 동포애로써 민족의 단결을 공고히 하고, 모든 사회적 폐습과 불의를 타파하며, 자율과 조화를 바탕으로 자유 민주적 기본 질서를 더욱 확고히 하여 정치·경제·사회·문화의 모든 영역에 있어서 각인의 기회를 균등히 하고, 능력을 최고도로 발휘하게 하며, 자유와 권리에 따르는 책임과 의무를 완수하게 하여, 안으로는 국민 생활의 균등한 향상을 기하고 밖으로는 항구적인 세계 평화와 인류 공영에 이바지함으로써 우리들과 우리들의 자손의 안전과 자유와 행복을 영원히 확보할 것을 다짐하면서 1948년 7월 12일에 제정되고 8차에 걸쳐 개정된 헌법을 이제 국회의 의결을 거쳐 국민 투표에 의하여 개정한다.
1987년 10월 29일 1987년 10월 29일
前文 前文
悠久한 歷史와 傳統에 빛나는 우리 大韓國民은 3·1 運動으로 建立된 大韓民國臨時政府의 法統과 不義에 抗拒한 4·19 民主理念을 繼承하고, 祖國의 民主改革과 平和的統一의 使命에 立脚하여 正義·人道와 同胞愛로써 民族의 團結을 鞏固히 하고, 모든 社會的弊習과 不義를 打破하며, 自律과 調和를 바탕으로 自由民主的基本秩序를 더욱 確固히 하여 政治·經濟·社會·文化의 모든 領域에 있어서 各人의 機會를 均等히 하고, 能力을 最高度로 發揮하게 하며, 自由와 權利에 따르는 責任과 義務를 完遂하게 하여, 안으로는 國民生活의 均等한 向上을 基하고 밖으로는 恒久的인 世界平和와 人類共榮에 이바지함으로써 우리들과 우리들의 子孫의 安全과 自由와 幸福을 永遠히 確保할 것을 다짐하면서 1948年 7月 12日에 制定되고 8次에 걸쳐 改正된 憲法을 이제 國會의 議決을 거쳐 國民投票에 依하여 改正한다. 悠久한 歷史와 傳統에 빛나는 우리 大韓國民은 3·1 運動으로 建立된 大韓民國臨時政府의 法統과 不義에 抗拒한 4·19 民主理念을 繼承하고, 祖國의 民主改革과 平和的統一의 使命에 立脚하여 正義·人道와 同胞愛로써 民族의 團結을 鞏固히 하고, 모든 社會的弊習과 不義를 打破하며, 自律과 調和를 바탕으로 自由民主的基本秩序를 더욱 確固히 하여 政治·經濟·社會·文化의 모든 領域에 있어서 各人의 機會를 均等히 하고, 能力을 最高度로 發揮하게 하며, 自由와 權利에 따르는 責任과 義務를 完遂하게 하여, 안으로는 國民生活의 均等한 向上을 基하고 밖으로는 恒久的인 世界平和와 人類共榮에 이바지함으로써 우리들과 우리들의 子孫의 安全과 自由와 幸福을 永遠히 確保할 것을 다짐하면서 1948年 7月 12日에 制定되고 8次에 걸쳐 改正된 憲法을 이제 國會의 議決을 거쳐 國民投票에 依하여 改正한다.
1987年 10月 29日 1987年 10月 29日
*/ */

@ -1,493 +1,493 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Security.Claims; using System.Security.Claims;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Web; using System.Web;
using System.Web.Http; using System.Web.Http;
using System.Web.Http.ModelBinding; using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin; using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security; using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth; using Microsoft.Owin.Security.OAuth;
using WebApplication.Models; using WebApplication.Models;
using WebApplication.Providers; using WebApplication.Providers;
using WebApplication.Results; using WebApplication.Results;
namespace WebApplication.Controllers namespace WebApplication.Controllers
{ {
[Authorize] [Authorize]
[RoutePrefix("api/Account")] [RoutePrefix("api/Account")]
public class AccountController : ApiController public class AccountController : ApiController
{ {
private const string LocalLoginProvider = "Local"; private const string LocalLoginProvider = "Local";
private ApplicationUserManager _userManager; private ApplicationUserManager _userManager;
public AccountController() public AccountController()
{ {
} }
public AccountController(ApplicationUserManager userManager, public AccountController(ApplicationUserManager userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat) ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{ {
UserManager = userManager; UserManager = userManager;
AccessTokenFormat = accessTokenFormat; AccessTokenFormat = accessTokenFormat;
} }
public ApplicationUserManager UserManager public ApplicationUserManager UserManager
{ {
get get
{ {
return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
} }
private set private set
{ {
_userManager = value; _userManager = value;
} }
} }
public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; } public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; }
// GET api/Account/UserInfo // GET api/Account/UserInfo
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UserInfo")] [Route("UserInfo")]
public UserInfoViewModel GetUserInfo() public UserInfoViewModel GetUserInfo()
{ {
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
return new UserInfoViewModel return new UserInfoViewModel
{ {
Email = User.Identity.GetUserName(), Email = User.Identity.GetUserName(),
HasRegistered = externalLogin == null, HasRegistered = externalLogin == null,
LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
}; };
} }
// POST api/Account/Logout // POST api/Account/Logout
[Route("Logout")] [Route("Logout")]
public IHttpActionResult Logout() public IHttpActionResult Logout()
{ {
Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
return Ok(); return Ok();
} }
// GET api/Account/ManageInfo?returnUrl=%2F&generateState=true // GET api/Account/ManageInfo?returnUrl=%2F&generateState=true
[Route("ManageInfo")] [Route("ManageInfo")]
public async Task<ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false) public async Task<ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false)
{ {
IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user == null) if (user == null)
{ {
return null; return null;
} }
List<UserLoginInfoViewModel> logins = new List<UserLoginInfoViewModel>(); List<UserLoginInfoViewModel> logins = new List<UserLoginInfoViewModel>();
foreach (IdentityUserLogin linkedAccount in user.Logins) foreach (IdentityUserLogin linkedAccount in user.Logins)
{ {
logins.Add(new UserLoginInfoViewModel logins.Add(new UserLoginInfoViewModel
{ {
LoginProvider = linkedAccount.LoginProvider, LoginProvider = linkedAccount.LoginProvider,
ProviderKey = linkedAccount.ProviderKey ProviderKey = linkedAccount.ProviderKey
}); });
} }
if (user.PasswordHash != null) if (user.PasswordHash != null)
{ {
logins.Add(new UserLoginInfoViewModel logins.Add(new UserLoginInfoViewModel
{ {
LoginProvider = LocalLoginProvider, LoginProvider = LocalLoginProvider,
ProviderKey = user.UserName, ProviderKey = user.UserName,
}); });
} }
return new ManageInfoViewModel return new ManageInfoViewModel
{ {
LocalLoginProvider = LocalLoginProvider, LocalLoginProvider = LocalLoginProvider,
Email = user.UserName, Email = user.UserName,
Logins = logins, Logins = logins,
ExternalLoginProviders = GetExternalLogins(returnUrl, generateState) ExternalLoginProviders = GetExternalLogins(returnUrl, generateState)
}; };
} }
// POST api/Account/ChangePassword // POST api/Account/ChangePassword
[Route("ChangePassword")] [Route("ChangePassword")]
public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model) public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return BadRequest(ModelState); return BadRequest(ModelState);
} }
IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword,
model.NewPassword); model.NewPassword);
if (!result.Succeeded) if (!result.Succeeded)
{ {
return GetErrorResult(result); return GetErrorResult(result);
} }
return Ok(); return Ok();
} }
// POST api/Account/SetPassword // POST api/Account/SetPassword
[Route("SetPassword")] [Route("SetPassword")]
public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model) public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return BadRequest(ModelState); return BadRequest(ModelState);
} }
IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (!result.Succeeded) if (!result.Succeeded)
{ {
return GetErrorResult(result); return GetErrorResult(result);
} }
return Ok(); return Ok();
} }
// POST api/Account/AddExternalLogin // POST api/Account/AddExternalLogin
[Route("AddExternalLogin")] [Route("AddExternalLogin")]
public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model) public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return BadRequest(ModelState); return BadRequest(ModelState);
} }
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken); AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);
if (ticket == null || ticket.Identity == null || (ticket.Properties != null if (ticket == null || ticket.Identity == null || (ticket.Properties != null
&& ticket.Properties.ExpiresUtc.HasValue && ticket.Properties.ExpiresUtc.HasValue
&& ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow)) && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow))
{ {
return BadRequest("External login failure."); return BadRequest("External login failure.");
} }
ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity); ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity);
if (externalData == null) if (externalData == null)
{ {
return BadRequest("The external login is already associated with an account."); return BadRequest("The external login is already associated with an account.");
} }
IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(),
new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey)); new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey));
if (!result.Succeeded) if (!result.Succeeded)
{ {
return GetErrorResult(result); return GetErrorResult(result);
} }
return Ok(); return Ok();
} }
// POST api/Account/RemoveLogin // POST api/Account/RemoveLogin
[Route("RemoveLogin")] [Route("RemoveLogin")]
public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model) public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return BadRequest(ModelState); return BadRequest(ModelState);
} }
IdentityResult result; IdentityResult result;
if (model.LoginProvider == LocalLoginProvider) if (model.LoginProvider == LocalLoginProvider)
{ {
result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId()); result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId());
} }
else else
{ {
result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(),
new UserLoginInfo(model.LoginProvider, model.ProviderKey)); new UserLoginInfo(model.LoginProvider, model.ProviderKey));
} }
if (!result.Succeeded) if (!result.Succeeded)
{ {
return GetErrorResult(result); return GetErrorResult(result);
} }
return Ok(); return Ok();
} }
// GET api/Account/ExternalLogin // GET api/Account/ExternalLogin
[OverrideAuthentication] [OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)] [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous] [AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")] [Route("ExternalLogin", Name = "ExternalLogin")]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null) public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
{ {
if (error != null) if (error != null)
{ {
return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)); return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
} }
if (!User.Identity.IsAuthenticated) if (!User.Identity.IsAuthenticated)
{ {
return new ChallengeResult(provider, this); return new ChallengeResult(provider, this);
} }
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
if (externalLogin == null) if (externalLogin == null)
{ {
return InternalServerError(); return InternalServerError();
} }
if (externalLogin.LoginProvider != provider) if (externalLogin.LoginProvider != provider)
{ {
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
return new ChallengeResult(provider, this); return new ChallengeResult(provider, this);
} }
ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
externalLogin.ProviderKey)); externalLogin.ProviderKey));
bool hasRegistered = user != null; bool hasRegistered = user != null;
if (hasRegistered) if (hasRegistered)
{ {
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType); OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType); CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
} }
else else
{ {
IEnumerable<Claim> claims = externalLogin.GetClaims(); IEnumerable<Claim> claims = externalLogin.GetClaims();
ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
Authentication.SignIn(identity); Authentication.SignIn(identity);
} }
return Ok(); return Ok();
} }
// GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true
[AllowAnonymous] [AllowAnonymous]
[Route("ExternalLogins")] [Route("ExternalLogins")]
public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false) public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false)
{ {
IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes(); IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>(); List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>();
string state; string state;
if (generateState) if (generateState)
{ {
const int strengthInBits = 256; const int strengthInBits = 256;
state = RandomOAuthStateGenerator.Generate(strengthInBits); state = RandomOAuthStateGenerator.Generate(strengthInBits);
} }
else else
{ {
state = null; state = null;
} }
foreach (AuthenticationDescription description in descriptions) foreach (AuthenticationDescription description in descriptions)
{ {
ExternalLoginViewModel login = new ExternalLoginViewModel ExternalLoginViewModel login = new ExternalLoginViewModel
{ {
Name = description.Caption, Name = description.Caption,
Url = Url.Route("ExternalLogin", new Url = Url.Route("ExternalLogin", new
{ {
provider = description.AuthenticationType, provider = description.AuthenticationType,
response_type = "token", response_type = "token",
client_id = Startup.PublicClientId, client_id = Startup.PublicClientId,
redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
state = state state = state
}), }),
State = state State = state
}; };
logins.Add(login); logins.Add(login);
} }
return logins; return logins;
} }
// POST api/Account/Register // POST api/Account/Register
[AllowAnonymous] [AllowAnonymous]
[Route("Register")] [Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model) public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password); IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded) if (!result.Succeeded)
{ {
return GetErrorResult(result); return GetErrorResult(result);
} }
return Ok(); return Ok();
} }
// POST api/Account/RegisterExternal // POST api/Account/RegisterExternal
[OverrideAuthentication] [OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("RegisterExternal")] [Route("RegisterExternal")]
public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model) public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var info = await Authentication.GetExternalLoginInfoAsync(); var info = await Authentication.GetExternalLoginInfoAsync();
if (info == null) if (info == null)
{ {
return InternalServerError(); return InternalServerError();
} }
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user); IdentityResult result = await UserManager.CreateAsync(user);
if (!result.Succeeded) if (!result.Succeeded)
{ {
return GetErrorResult(result); return GetErrorResult(result);
} }
result = await UserManager.AddLoginAsync(user.Id, info.Login); result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (!result.Succeeded) if (!result.Succeeded)
{ {
return GetErrorResult(result); return GetErrorResult(result);
} }
return Ok(); return Ok();
} }
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing) if (disposing)
{ {
UserManager.Dispose(); UserManager.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Helpers #region Helpers
private IAuthenticationManager Authentication private IAuthenticationManager Authentication
{ {
get { return Request.GetOwinContext().Authentication; } get { return Request.GetOwinContext().Authentication; }
} }
private IHttpActionResult GetErrorResult(IdentityResult result) private IHttpActionResult GetErrorResult(IdentityResult result)
{ {
if (result == null) if (result == null)
{ {
return InternalServerError(); return InternalServerError();
} }
if (!result.Succeeded) if (!result.Succeeded)
{ {
if (result.Errors != null) if (result.Errors != null)
{ {
foreach (string error in result.Errors) foreach (string error in result.Errors)
{ {
ModelState.AddModelError("", error); ModelState.AddModelError("", error);
} }
} }
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
// No ModelState errors are available to send, so just return an empty BadRequest. // No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest(); return BadRequest();
} }
return BadRequest(ModelState); return BadRequest(ModelState);
} }
return null; return null;
} }
private class ExternalLoginData private class ExternalLoginData
{ {
public string LoginProvider { get; set; } public string LoginProvider { get; set; }
public string ProviderKey { get; set; } public string ProviderKey { get; set; }
public string UserName { get; set; } public string UserName { get; set; }
public IList<Claim> GetClaims() public IList<Claim> GetClaims()
{ {
IList<Claim> claims = new List<Claim>(); IList<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider)); claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider));
if (UserName != null) if (UserName != null)
{ {
claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider)); claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider));
} }
return claims; return claims;
} }
public static ExternalLoginData FromIdentity(ClaimsIdentity identity) public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
{ {
if (identity == null) if (identity == null)
{ {
return null; return null;
} }
Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier); Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer) if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer)
|| String.IsNullOrEmpty(providerKeyClaim.Value)) || String.IsNullOrEmpty(providerKeyClaim.Value))
{ {
return null; return null;
} }
if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer) if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
{ {
return null; return null;
} }
return new ExternalLoginData return new ExternalLoginData
{ {
LoginProvider = providerKeyClaim.Issuer, LoginProvider = providerKeyClaim.Issuer,
ProviderKey = providerKeyClaim.Value, ProviderKey = providerKeyClaim.Value,
UserName = identity.FindFirstValue(ClaimTypes.Name) UserName = identity.FindFirstValue(ClaimTypes.Name)
}; };
} }
} }
private static class RandomOAuthStateGenerator private static class RandomOAuthStateGenerator
{ {
private static RandomNumberGenerator _random = new RNGCryptoServiceProvider(); private static RandomNumberGenerator _random = new RNGCryptoServiceProvider();
public static string Generate(int strengthInBits) public static string Generate(int strengthInBits)
{ {
const int bitsPerByte = 8; const int bitsPerByte = 8;
if (strengthInBits % bitsPerByte != 0) if (strengthInBits % bitsPerByte != 0)
{ {
throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits"); throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits");
} }
int strengthInBytes = strengthInBits / bitsPerByte; int strengthInBytes = strengthInBits / bitsPerByte;
byte[] data = new byte[strengthInBytes]; byte[] data = new byte[strengthInBytes];
_random.GetBytes(data); _random.GetBytes(data);
return HttpServerUtility.UrlTokenEncode(data); return HttpServerUtility.UrlTokenEncode(data);
} }
} }
#endregion #endregion
} }
} }

@ -1,50 +1,50 @@
[Sun Mar 7 16:02:00 2004] [notice] Apache/1.3.29 (Unix) configured -- resuming normal operations [Sun Mar 7 16:02:00 2004] [notice] Apache/1.3.29 (Unix) configured -- resuming normal operations
[Sun Mar 7 16:02:00 2004] [info] Server built: Feb 27 2004 13:56:37 [Sun Mar 7 16:02:00 2004] [info] Server built: Feb 27 2004 13:56:37
[Sun Mar 7 16:02:00 2004] [notice] Accept mutex: sysvsem (Default: sysvsem) [Sun Mar 7 16:02:00 2004] [notice] Accept mutex: sysvsem (Default: sysvsem)
[Sun Mar 7 16:05:49 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 16:05:49 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 16:45:56 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 16:45:56 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 17:13:50 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 17:13:50 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 17:21:44 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 17:21:44 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 17:23:53 2004] statistics: Use of uninitialized value in concatenation (.) or string at /home/httpd/twiki/lib/TWiki.pm line 528. [Sun Mar 7 17:23:53 2004] statistics: Use of uninitialized value in concatenation (.) or string at /home/httpd/twiki/lib/TWiki.pm line 528.
[Sun Mar 7 17:23:53 2004] statistics: Can't create file /home/httpd/twiki/data/Main/WebStatistics.txt - Permission denied [Sun Mar 7 17:23:53 2004] statistics: Can't create file /home/httpd/twiki/data/Main/WebStatistics.txt - Permission denied
[Sun Mar 7 17:27:37 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 17:27:37 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 17:31:39 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 17:31:39 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 17:58:00 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 17:58:00 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 18:00:09 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 18:00:09 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 18:10:09 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 18:10:09 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 18:19:01 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 18:19:01 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 18:42:29 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 18:42:29 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 18:52:30 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 18:52:30 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 18:58:52 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 18:58:52 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 19:03:58 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 19:03:58 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 19:08:55 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 19:08:55 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 20:04:35 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 20:04:35 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 20:11:33 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 20:11:33 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 20:12:55 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 20:12:55 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 20:25:31 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 20:25:31 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 20:44:48 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 20:44:48 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 20:58:27 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 20:58:27 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 21:16:17 2004] [error] [client xx.xx.xx.xx] File does not exist: /home/httpd/twiki/view/Main/WebHome [Sun Mar 7 21:16:17 2004] [error] [client xx.xx.xx.xx] File does not exist: /home/httpd/twiki/view/Main/WebHome
[Sun Mar 7 21:20:14 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 21:20:14 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 21:31:12 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 21:31:12 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 21:39:55 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 21:39:55 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Sun Mar 7 21:44:10 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 21:44:10 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 01:35:13 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 01:35:13 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 01:47:06 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 01:47:06 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 01:59:13 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 01:59:13 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 02:12:24 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 02:12:24 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 02:54:54 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 02:54:54 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 03:46:27 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 03:46:27 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 03:48:18 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 03:48:18 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 03:52:17 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 03:52:17 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 03:55:09 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 03:55:09 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 04:22:55 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 04:22:55 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 04:24:47 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 04:24:47 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 04:40:32 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 04:40:32 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 04:55:40 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 04:55:40 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 04:59:13 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 04:59:13 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 05:22:57 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 05:22:57 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 05:24:29 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 05:24:29 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
[Mon Mar 8 05:31:47 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed [Mon Mar 8 05:31:47 2004] [info] [client xx.xx.xx.xx] (104)Connection reset by peer: client stopped connection before send body completed
<11>httpd[31628]: [error] [client xx.xx.xx.xx] File does not exist: /usr/local/installed/apache/htdocs/squirrelmail/_vti_inf.html in 29-Mar 15:18:20.50 from xx.xx.xx.xx <11>httpd[31628]: [error] [client xx.xx.xx.xx] File does not exist: /usr/local/installed/apache/htdocs/squirrelmail/_vti_inf.html in 29-Mar 15:18:20.50 from xx.xx.xx.xx
<11>httpd[25859]: [error] [client xx.xx.xx.xx] File does not exist: /usr/local/installed/apache/htdocs/squirrelmail/_vti_bin/shtml.exe/_vti_rpc in 29-Mar 15:18:20.54 from xx.xx.xx.xx <11>httpd[25859]: [error] [client xx.xx.xx.xx] File does not exist: /usr/local/installed/apache/htdocs/squirrelmail/_vti_bin/shtml.exe/_vti_rpc in 29-Mar 15:18:20.54 from xx.xx.xx.xx

File diff suppressed because it is too large Load Diff

@ -1,23 +1,23 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<!-- <!--
Comments are overrated Comments are overrated
--> -->
<html> <html>
<head> <head>
<title>HTML Sample</title> <title>HTML Sample</title>
<style type="text/css"> <style type="text/css">
h1 { h1 {
color: #CCA3A3; color: #CCA3A3;
} }
body { body {
} }
</style> </style>
<script type="text/javascript"> <script type="text/javascript">
window.alert("I am a sample..."); window.alert("I am a sample...");
</script> </script>
</head> </head>
<body> <body>
<h1>Heading No.1</h1> <h1>Heading No.1</h1>
<input disabled type="button" value="Click me" /> <input disabled type="button" value="Click me" />
</body> </body>
</html> </html>

@ -1,222 +1,222 @@
/* /*
© Microsoft. All rights reserved. © Microsoft. All rights reserved.
https://microsoft.com https://microsoft.com
blablahttp://en.wikipedia.org/wiki/Timisoara bla bla blablahttp://en.wikipedia.org/wiki/Timisoara bla bla
blabla http://en.wikipedia.org/wiki/Timisoara bla bla blabla http://en.wikipedia.org/wiki/Timisoara bla bla
This library is supported for use in Windows Tailored Apps only. This library is supported for use in Windows Tailored Apps only.
Build: 6.2.8100.0 Build: 6.2.8100.0
Version: 0.5 Version: 0.5
*/ */
var קודמות = "מיותר קודמות צ'ט של, אם לשון העברית שינויים ויש, אם"; var קודמות = "מיותר קודמות צ'ט של, אם לשון העברית שינויים ויש, אם";
'a string\ 'a string\
on multiple lines'; on multiple lines';
(function (global, undefined) { (function (global, undefined) {
"use strict"; "use strict";
undefinedVariable = {}; undefinedVariable.bar = 5; undefinedVariable = {}; undefinedVariable.bar = 5;
undefinedVariable.foo = 5; undefinedVariable.baz = 10; undefinedVariable.foo = 5; undefinedVariable.baz = 10;
function initializeProperties(target, members) { function initializeProperties(target, members) {
var keys = Object.keys(members); var keys = Object.keys(members);
var properties; var properties;
var i, len; var i, len;
for (i = 0, len = keys.length; i < len; i++) { for (i = 0, len = keys.length; i < len; i++) {
var key = keys[i]; var key = keys[i];
var enumerable = key.charCodeAt(0) !== /*_*/95; var enumerable = key.charCodeAt(0) !== /*_*/95;
var member = members[key]; var member = members[key];
if (member && typeof member === 'object') { if (member && typeof member === 'object') {
if (member.value !== undefined || typeof member.get === 'function' || typeof member.set === 'function') { if (member.value !== undefined || typeof member.get === 'function' || typeof member.set === 'function') {
if (member.enumerable === undefined) { if (member.enumerable === undefined) {
member.enumerable = enumerable; member.enumerable = enumerable;
} }
properties = properties || {}; properties = properties || {};
properties[key] = member; properties[key] = member;
continue; continue;
} }
} }
if (!enumerable) { if (!enumerable) {
properties = properties || {}; properties = properties || {};
properties[key] = { value: member, enumerable: enumerable, configurable: true, writable: true } properties[key] = { value: member, enumerable: enumerable, configurable: true, writable: true }
continue; continue;
} }
target[key] = member; target[key] = member;
} }
if (properties) { if (properties) {
Object.defineProperties(target, properties); Object.defineProperties(target, properties);
} }
} }
(function (rootNamespace) { (function (rootNamespace) {
// Create the rootNamespace in the global namespace // Create the rootNamespace in the global namespace
if (!global[rootNamespace]) { if (!global[rootNamespace]) {
global[rootNamespace] = Object.create(Object.prototype); global[rootNamespace] = Object.create(Object.prototype);
} }
// Cache the rootNamespace we just created in a local variable // Cache the rootNamespace we just created in a local variable
var _rootNamespace = global[rootNamespace]; var _rootNamespace = global[rootNamespace];
if (!_rootNamespace.Namespace) { if (!_rootNamespace.Namespace) {
_rootNamespace.Namespace = Object.create(Object.prototype); _rootNamespace.Namespace = Object.create(Object.prototype);
} }
function defineWithParent(parentNamespace, name, members) { function defineWithParent(parentNamespace, name, members) {
/// <summary locid="1"> /// <summary locid="1">
/// Defines a new namespace with the specified name, under the specified parent namespace. /// Defines a new namespace with the specified name, under the specified parent namespace.
/// </summary> /// </summary>
/// <param name="parentNamespace" type="Object" locid="2"> /// <param name="parentNamespace" type="Object" locid="2">
/// The parent namespace which will contain the new namespace. /// The parent namespace which will contain the new namespace.
/// </param> /// </param>
/// <param name="name" type="String" locid="3"> /// <param name="name" type="String" locid="3">
/// Name of the new namespace. /// Name of the new namespace.
/// </param> /// </param>
/// <param name="members" type="Object" locid="4"> /// <param name="members" type="Object" locid="4">
/// Members in the new namespace. /// Members in the new namespace.
/// </param> /// </param>
/// <returns locid="5"> /// <returns locid="5">
/// The newly defined namespace. /// The newly defined namespace.
/// </returns> /// </returns>
var currentNamespace = parentNamespace, var currentNamespace = parentNamespace,
namespaceFragments = name.split("."); namespaceFragments = name.split(".");
for (var i = 0, len = namespaceFragments.length; i < len; i++) { for (var i = 0, len = namespaceFragments.length; i < len; i++) {
var namespaceName = namespaceFragments[i]; var namespaceName = namespaceFragments[i];
if (!currentNamespace[namespaceName]) { if (!currentNamespace[namespaceName]) {
Object.defineProperty(currentNamespace, namespaceName, Object.defineProperty(currentNamespace, namespaceName,
{ value: {}, writable: false, enumerable: true, configurable: true } { value: {}, writable: false, enumerable: true, configurable: true }
); );
} }
currentNamespace = currentNamespace[namespaceName]; currentNamespace = currentNamespace[namespaceName];
} }
if (members) { if (members) {
initializeProperties(currentNamespace, members); initializeProperties(currentNamespace, members);
} }
return currentNamespace; return currentNamespace;
}; };
function define(name, members) { function define(name, members) {
/// <summary locid="6"> /// <summary locid="6">
/// Defines a new namespace with the specified name. /// Defines a new namespace with the specified name.
/// </summary> /// </summary>
/// <param name="name" type="String" locid="7"> /// <param name="name" type="String" locid="7">
/// Name of the namespace. This could be a dot-separated nested name. /// Name of the namespace. This could be a dot-separated nested name.
/// </param> /// </param>
/// <param name="members" type="Object" locid="4"> /// <param name="members" type="Object" locid="4">
/// Members in the new namespace. /// Members in the new namespace.
/// </param> /// </param>
/// <returns locid="5"> /// <returns locid="5">
/// The newly defined namespace. /// The newly defined namespace.
/// </returns> /// </returns>
return defineWithParent(global, name, members); return defineWithParent(global, name, members);
} }
// Establish members of the "WinJS.Namespace" namespace // Establish members of the "WinJS.Namespace" namespace
Object.defineProperties(_rootNamespace.Namespace, { Object.defineProperties(_rootNamespace.Namespace, {
defineWithParent: { value: defineWithParent, writable: true, enumerable: true }, defineWithParent: { value: defineWithParent, writable: true, enumerable: true },
define: { value: define, writable: true, enumerable: true } define: { value: define, writable: true, enumerable: true }
}); });
})("WinJS"); })("WinJS");
(function (WinJS) { (function (WinJS) {
function define(constructor, instanceMembers, staticMembers) { function define(constructor, instanceMembers, staticMembers) {
/// <summary locid="8"> /// <summary locid="8">
/// Defines a class using the given constructor and with the specified instance members. /// Defines a class using the given constructor and with the specified instance members.
/// </summary> /// </summary>
/// <param name="constructor" type="Function" locid="9"> /// <param name="constructor" type="Function" locid="9">
/// A constructor function that will be used to instantiate this class. /// A constructor function that will be used to instantiate this class.
/// </param> /// </param>
/// <param name="instanceMembers" type="Object" locid="10"> /// <param name="instanceMembers" type="Object" locid="10">
/// The set of instance fields, properties and methods to be made available on the class. /// The set of instance fields, properties and methods to be made available on the class.
/// </param> /// </param>
/// <param name="staticMembers" type="Object" locid="11"> /// <param name="staticMembers" type="Object" locid="11">
/// The set of static fields, properties and methods to be made available on the class. /// The set of static fields, properties and methods to be made available on the class.
/// </param> /// </param>
/// <returns type="Function" locid="12"> /// <returns type="Function" locid="12">
/// The newly defined class. /// The newly defined class.
/// </returns> /// </returns>
constructor = constructor || function () { }; constructor = constructor || function () { };
if (instanceMembers) { if (instanceMembers) {
initializeProperties(constructor.prototype, instanceMembers); initializeProperties(constructor.prototype, instanceMembers);
} }
if (staticMembers) { if (staticMembers) {
initializeProperties(constructor, staticMembers); initializeProperties(constructor, staticMembers);
} }
return constructor; return constructor;
} }
function derive(baseClass, constructor, instanceMembers, staticMembers) { function derive(baseClass, constructor, instanceMembers, staticMembers) {
/// <summary locid="13"> /// <summary locid="13">
/// Uses prototypal inheritance to create a sub-class based on the supplied baseClass parameter. /// Uses prototypal inheritance to create a sub-class based on the supplied baseClass parameter.
/// </summary> /// </summary>
/// <param name="baseClass" type="Function" locid="14"> /// <param name="baseClass" type="Function" locid="14">
/// The class to inherit from. /// The class to inherit from.
/// </param> /// </param>
/// <param name="constructor" type="Function" locid="9"> /// <param name="constructor" type="Function" locid="9">
/// A constructor function that will be used to instantiate this class. /// A constructor function that will be used to instantiate this class.
/// </param> /// </param>
/// <param name="instanceMembers" type="Object" locid="10"> /// <param name="instanceMembers" type="Object" locid="10">
/// The set of instance fields, properties and methods to be made available on the class. /// The set of instance fields, properties and methods to be made available on the class.
/// </param> /// </param>
/// <param name="staticMembers" type="Object" locid="11"> /// <param name="staticMembers" type="Object" locid="11">
/// The set of static fields, properties and methods to be made available on the class. /// The set of static fields, properties and methods to be made available on the class.
/// </param> /// </param>
/// <returns type="Function" locid="12"> /// <returns type="Function" locid="12">
/// The newly defined class. /// The newly defined class.
/// </returns> /// </returns>
if (baseClass) { if (baseClass) {
constructor = constructor || function () { }; constructor = constructor || function () { };
var basePrototype = baseClass.prototype; var basePrototype = baseClass.prototype;
constructor.prototype = Object.create(basePrototype); constructor.prototype = Object.create(basePrototype);
Object.defineProperty(constructor.prototype, "_super", { value: basePrototype }); Object.defineProperty(constructor.prototype, "_super", { value: basePrototype });
Object.defineProperty(constructor.prototype, "constructor", { value: constructor }); Object.defineProperty(constructor.prototype, "constructor", { value: constructor });
if (instanceMembers) { if (instanceMembers) {
initializeProperties(constructor.prototype, instanceMembers); initializeProperties(constructor.prototype, instanceMembers);
} }
if (staticMembers) { if (staticMembers) {
initializeProperties(constructor, staticMembers); initializeProperties(constructor, staticMembers);
} }
return constructor; return constructor;
} else { } else {
return define(constructor, instanceMembers, staticMembers); return define(constructor, instanceMembers, staticMembers);
} }
} }
function mix(constructor) { function mix(constructor) {
/// <summary locid="15"> /// <summary locid="15">
/// Defines a class using the given constructor and the union of the set of instance members /// Defines a class using the given constructor and the union of the set of instance members
/// specified by all the mixin objects. The mixin parameter list can be of variable length. /// specified by all the mixin objects. The mixin parameter list can be of variable length.
/// </summary> /// </summary>
/// <param name="constructor" locid="9"> /// <param name="constructor" locid="9">
/// A constructor function that will be used to instantiate this class. /// A constructor function that will be used to instantiate this class.
/// </param> /// </param>
/// <returns locid="12"> /// <returns locid="12">
/// The newly defined class. /// The newly defined class.
/// </returns> /// </returns>
constructor = constructor || function () { }; constructor = constructor || function () { };
var i, len; var i, len;
for (i = 0, len = arguments.length; i < len; i++) { for (i = 0, len = arguments.length; i < len; i++) {
initializeProperties(constructor.prototype, arguments[i]); initializeProperties(constructor.prototype, arguments[i]);
} }
return constructor; return constructor;
} }
// Establish members of "WinJS.Class" namespace // Establish members of "WinJS.Class" namespace
WinJS.Namespace.define("WinJS.Class", { WinJS.Namespace.define("WinJS.Class", {
define: define, define: define,
derive: derive, derive: derive,
mix: mix mix: mix
}); });
})(WinJS); })(WinJS);
})(this); })(this);

@ -1,2 +1,2 @@
node_modules/monaco-editor/dev node_modules/monaco-editor/dev
node_modules/monaco-editor/esm node_modules/monaco-editor/esm

@ -1,38 +1,38 @@
/* /*
* C# Program to Display All the Prime Numbers Between 1 to 100 * C# Program to Display All the Prime Numbers Between 1 to 100
*/ */
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
namespace VS namespace VS
{ {
class Program class Program
{ {
static void Main(string[] args) static void Main(string[] args)
{ {
bool isPrime = true; bool isPrime = true;
Console.WriteLine("Prime Numbers : "); Console.WriteLine("Prime Numbers : ");
for (int i = 2; i <= 100; i++) for (int i = 2; i <= 100; i++)
{ {
for (int j = 2; j <= 100; j++) for (int j = 2; j <= 100; j++)
{ {
if (i != j && i % j == 0) if (i != j && i % j == 0)
{ {
isPrime = false; isPrime = false;
break; break;
} }
} }
if (isPrime) if (isPrime)
{ {
Console.Write("\t" +i); Console.Write("\t" +i);
} }
isPrime = true; isPrime = true;
} }
Console.ReadKey(); Console.ReadKey();
} }
} }
} }

File diff suppressed because it is too large Load Diff

@ -1,32 +1,32 @@
FROM mono:3.12 FROM mono:3.12
ENV KRE_FEED https://www.myget.org/F/aspnetvnext/api/v2 ENV KRE_FEED https://www.myget.org/F/aspnetvnext/api/v2
ENV KRE_USER_HOME /opt/kre ENV KRE_USER_HOME /opt/kre
RUN apt-get -qq update && apt-get -qqy install unzip RUN apt-get -qq update && apt-get -qqy install unzip
ONBUILD RUN curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/kvminstall.sh | sh ONBUILD RUN curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/kvminstall.sh | sh
ONBUILD RUN bash -c "source $KRE_USER_HOME/kvm/kvm.sh \ ONBUILD RUN bash -c "source $KRE_USER_HOME/kvm/kvm.sh \
&& kvm install latest -a default \ && kvm install latest -a default \
&& kvm alias default | xargs -i ln -s $KRE_USER_HOME/packages/{} $KRE_USER_HOME/packages/default" && kvm alias default | xargs -i ln -s $KRE_USER_HOME/packages/{} $KRE_USER_HOME/packages/default"
# Install libuv for Kestrel from source code (binary is not in wheezy and one in jessie is still too old) # Install libuv for Kestrel from source code (binary is not in wheezy and one in jessie is still too old)
RUN apt-get -qqy install \ RUN apt-get -qqy install \
autoconf \ autoconf \
automake \ automake \
build-essential \ build-essential \
libtool libtool
RUN LIBUV_VERSION=1.0.0-rc2 \ RUN LIBUV_VERSION=1.0.0-rc2 \
&& curl -sSL https://github.com/joyent/libuv/archive/v${LIBUV_VERSION}.tar.gz | tar zxfv - -C /usr/local/src \ && curl -sSL https://github.com/joyent/libuv/archive/v${LIBUV_VERSION}.tar.gz | tar zxfv - -C /usr/local/src \
&& cd /usr/local/src/libuv-$LIBUV_VERSION \ && cd /usr/local/src/libuv-$LIBUV_VERSION \
&& sh autogen.sh && ./configure && make && make install \ && sh autogen.sh && ./configure && make && make install \
&& rm -rf /usr/local/src/libuv-$LIBUV_VERSION \ && rm -rf /usr/local/src/libuv-$LIBUV_VERSION \
&& ldconfig && ldconfig
ENV PATH $PATH:$KRE_USER_HOME/packages/default/bin ENV PATH $PATH:$KRE_USER_HOME/packages/default/bin
# Extra things to test # Extra things to test
RUN echo "string at end" RUN echo "string at end"
RUN echo must work 'some str' and some more RUN echo must work 'some str' and some more
RUN echo hi this is # not a comment RUN echo hi this is # not a comment
RUN echo 'String with ${VAR} and another $one here' RUN echo 'String with ${VAR} and another $one here'

@ -1,8 +1,8 @@
(* Sample F# application *) (* Sample F# application *)
[<EntryPoint>] [<EntryPoint>]
let main argv = let main argv =
printfn "%A" argv printfn "%A" argv
System.Console.WriteLine("Hello from F#") System.Console.WriteLine("Hello from F#")
0 // return an integer exit code 0 // return an integer exit code
//-------------------------------------------------------- //--------------------------------------------------------

@ -1,111 +1,111 @@
// We often need our programs to perform operations on // We often need our programs to perform operations on
// collections of data, like selecting all items that // collections of data, like selecting all items that
// satisfy a given predicate or mapping all items to a new // satisfy a given predicate or mapping all items to a new
// collection with a custom function. // collection with a custom function.
// In some languages it's idiomatic to use [generic](http://en.wikipedia.org/wiki/Generic_programming) // In some languages it's idiomatic to use [generic](http://en.wikipedia.org/wiki/Generic_programming)
// data structures and algorithms. Go does not support // data structures and algorithms. Go does not support
// generics; in Go it's common to provide collection // generics; in Go it's common to provide collection
// functions if and when they are specifically needed for // functions if and when they are specifically needed for
// your program and data types. // your program and data types.
// Here are some example collection functions for slices // Here are some example collection functions for slices
// of `strings`. You can use these examples to build your // of `strings`. You can use these examples to build your
// own functions. Note that in some cases it may be // own functions. Note that in some cases it may be
// clearest to just inline the collection-manipulating // clearest to just inline the collection-manipulating
// code directly, instead of creating and calling a // code directly, instead of creating and calling a
// helper function. // helper function.
package main package main
import "strings" import "strings"
import "fmt" import "fmt"
// Returns the first index of the target string `t`, or // Returns the first index of the target string `t`, or
// -1 if no match is found. // -1 if no match is found.
func Index(vs []string, t string) int { func Index(vs []string, t string) int {
for i, v := range vs { for i, v := range vs {
if v == t { if v == t {
return i return i
} }
} }
return -1 return -1
} }
// Returns `true` if the target string t is in the // Returns `true` if the target string t is in the
// slice. // slice.
func Include(vs []string, t string) bool { func Include(vs []string, t string) bool {
return Index(vs, t) >= 0 return Index(vs, t) >= 0
} }
// Returns `true` if one of the strings in the slice // Returns `true` if one of the strings in the slice
// satisfies the predicate `f`. // satisfies the predicate `f`.
func Any(vs []string, f func(string) bool) bool { func Any(vs []string, f func(string) bool) bool {
for _, v := range vs { for _, v := range vs {
if f(v) { if f(v) {
return true return true
} }
} }
return false return false
} }
// Returns `true` if all of the strings in the slice // Returns `true` if all of the strings in the slice
// satisfy the predicate `f`. // satisfy the predicate `f`.
func All(vs []string, f func(string) bool) bool { func All(vs []string, f func(string) bool) bool {
for _, v := range vs { for _, v := range vs {
if !f(v) { if !f(v) {
return false return false
} }
} }
return true return true
} }
// Returns a new slice containing all strings in the // Returns a new slice containing all strings in the
// slice that satisfy the predicate `f`. // slice that satisfy the predicate `f`.
func Filter(vs []string, f func(string) bool) []string { func Filter(vs []string, f func(string) bool) []string {
vsf := make([]string, 0) vsf := make([]string, 0)
for _, v := range vs { for _, v := range vs {
if f(v) { if f(v) {
vsf = append(vsf, v) vsf = append(vsf, v)
} }
} }
return vsf return vsf
} }
// Returns a new slice containing the results of applying // Returns a new slice containing the results of applying
// the function `f` to each string in the original slice. // the function `f` to each string in the original slice.
func Map(vs []string, f func(string) string) []string { func Map(vs []string, f func(string) string) []string {
vsm := make([]string, len(vs)) vsm := make([]string, len(vs))
for i, v := range vs { for i, v := range vs {
vsm[i] = f(v) vsm[i] = f(v)
} }
return vsm return vsm
} }
func main() { func main() {
// Here we try out our various collection functions. // Here we try out our various collection functions.
var strs = []string{"peach", "apple", "pear", "plum"} var strs = []string{"peach", "apple", "pear", "plum"}
fmt.Println(Index(strs, "pear")) fmt.Println(Index(strs, "pear"))
fmt.Println(Include(strs, "grape")) fmt.Println(Include(strs, "grape"))
fmt.Println(Any(strs, func(v string) bool { fmt.Println(Any(strs, func(v string) bool {
return strings.HasPrefix(v, "p") return strings.HasPrefix(v, "p")
})) }))
fmt.Println(All(strs, func(v string) bool { fmt.Println(All(strs, func(v string) bool {
return strings.HasPrefix(v, "p") return strings.HasPrefix(v, "p")
})) }))
fmt.Println(Filter(strs, func(v string) bool { fmt.Println(Filter(strs, func(v string) bool {
return strings.Contains(v, "e") return strings.Contains(v, "e")
})) }))
// The above examples all used anonymous functions, // The above examples all used anonymous functions,
// but you can also use named functions of the correct // but you can also use named functions of the correct
// type. // type.
fmt.Println(Map(strs, strings.ToUpper)) fmt.Println(Map(strs, strings.ToUpper))
} }

@ -1,48 +1,48 @@
terraform { terraform {
required_providers { required_providers {
aws = { aws = {
source = "hashicorp/aws" source = "hashicorp/aws"
version = "~> 1.0.4" version = "~> 1.0.4"
} }
} }
} }
variable "aws_region" {} variable "aws_region" {}
variable "base_cidr_block" { variable "base_cidr_block" {
description = "A /16 CIDR range definition, such as 10.1.0.0/16, that the VPC will use" description = "A /16 CIDR range definition, such as 10.1.0.0/16, that the VPC will use"
default = "10.1.0.0/16" default = "10.1.0.0/16"
} }
variable "availability_zones" { variable "availability_zones" {
description = "A list of availability zones in which to create subnets" description = "A list of availability zones in which to create subnets"
type = list(string) type = list(string)
} }
provider "aws" { provider "aws" {
region = var.aws_region region = var.aws_region
} }
resource "aws_vpc" "main" { resource "aws_vpc" "main" {
# Referencing the base_cidr_block variable allows the network address # Referencing the base_cidr_block variable allows the network address
# to be changed without modifying the configuration. # to be changed without modifying the configuration.
cidr_block = var.base_cidr_block cidr_block = var.base_cidr_block
} }
resource "aws_subnet" "az" { resource "aws_subnet" "az" {
# Create one subnet for each given availability zone. # Create one subnet for each given availability zone.
count = length(var.availability_zones) count = length(var.availability_zones)
# For each subnet, use one of the specified availability zones. # For each subnet, use one of the specified availability zones.
availability_zone = var.availability_zones[count.index] availability_zone = var.availability_zones[count.index]
# By referencing the aws_vpc.main object, Terraform knows that the subnet # By referencing the aws_vpc.main object, Terraform knows that the subnet
# must be created only after the VPC is created. # must be created only after the VPC is created.
vpc_id = aws_vpc.main.id vpc_id = aws_vpc.main.id
# Built-in functions and operators can be used for simple transformations of # Built-in functions and operators can be used for simple transformations of
# values, such as computing a subnet address. Here we create a /20 prefix for # values, such as computing a subnet address. Here we create a /20 prefix for
# each subnet, using consecutive addresses for each availability zone, # each subnet, using consecutive addresses for each availability zone,
# such as 10.1.16.0/20 . # such as 10.1.16.0/20 .
cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 4, count.index+1) cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 4, count.index+1)
} }

@ -1,100 +1,100 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<!--Example of comments in HTML--> <!--Example of comments in HTML-->
<html> <html>
<head> <head>
<!--This is the head section--> <!--This is the head section-->
<title>HTML Sample</title> <title>HTML Sample</title>
<meta charset="utf-8"> <meta charset="utf-8">
<!--This is the style tag to set style on elements--> <!--This is the style tag to set style on elements-->
<style type="text/css"> <style type="text/css">
h1 h1
{ {
font-family: Tahoma; font-family: Tahoma;
font-size: 40px; font-size: 40px;
font-weight: normal; font-weight: normal;
margin: 50px; margin: 50px;
color: #a0a0a0; color: #a0a0a0;
} }
h2 h2
{ {
font-family: Tahoma; font-family: Tahoma;
font-size: 30px; font-size: 30px;
font-weight: normal; font-weight: normal;
margin: 50px; margin: 50px;
color: #fff; color: #fff;
} }
p p
{ {
font-family: Tahoma; font-family: Tahoma;
font-size: 17px; font-size: 17px;
font-weight: normal; font-weight: normal;
margin: 0px 200px; margin: 0px 200px;
color: #fff; color: #fff;
} }
div.Center div.Center
{ {
text-align: center; text-align: center;
} }
div.Blue div.Blue
{ {
padding: 50px; padding: 50px;
background-color: #7bd2ff; background-color: #7bd2ff;
} }
button.Gray button.Gray
{ {
font-family: Tahoma; font-family: Tahoma;
font-size: 17px; font-size: 17px;
font-weight: normal; font-weight: normal;
margin-top: 100px; margin-top: 100px;
padding: 10px 50px; padding: 10px 50px;
background-color: #727272; background-color: #727272;
color: #fff; color: #fff;
outline: 0; outline: 0;
border: none; border: none;
cursor: pointer; cursor: pointer;
} }
button.Gray:hover button.Gray:hover
{ {
background-color: #898888; background-color: #898888;
} }
button.Gray:active button.Gray:active
{ {
background-color: #636161; background-color: #636161;
} }
</style> </style>
<!--This is the script tag--> <!--This is the script tag-->
<script type="text/javascript"> <script type="text/javascript">
function ButtonClick(){ function ButtonClick(){
// Example of comments in JavaScript // Example of comments in JavaScript
window.alert("I'm an alert sample!"); window.alert("I'm an alert sample!");
} }
</script> </script>
</head> </head>
<body> <body>
<!--This is the body section--> <!--This is the body section-->
<div class="Center"> <div class="Center">
<h1>NAME OF SITE</h1> <h1>NAME OF SITE</h1>
</div> </div>
<div class="Center Blue"> <div class="Center Blue">
<h2>I'm h2 Header! Edit me in &lt;h2&gt;</h2> <h2>I'm h2 Header! Edit me in &lt;h2&gt;</h2>
<p> <p>
I'm a paragraph! Edit me in &lt;p&gt; I'm a paragraph! Edit me in &lt;p&gt;
to add your own content and make changes to the style and font. to add your own content and make changes to the style and font.
It's easy! Just change the text between &lt;p&gt; ... &lt;/p&gt; and change the style in &lt;style&gt;. It's easy! Just change the text between &lt;p&gt; ... &lt;/p&gt; and change the style in &lt;style&gt;.
You can make it as long as you wish. The browser will automatically wrap the lines to accommodate the You can make it as long as you wish. The browser will automatically wrap the lines to accommodate the
size of the browser window. size of the browser window.
</p> </p>
<button class="Gray" onclick="ButtonClick()">Click Me!</button> <button class="Gray" onclick="ButtonClick()">Click Me!</button>
</div> </div>
</body> </body>
</html> </html>

@ -1,15 +1,15 @@
# Example of a .gitconfig file # Example of a .gitconfig file
[core] [core]
repositoryformatversion = 0 repositoryformatversion = 0
filemode = false filemode = false
bare = false bare = false
logallrefupdates = true logallrefupdates = true
symlinks = false symlinks = false
ignorecase = true ignorecase = true
hideDotFiles = dotGitOnly hideDotFiles = dotGitOnly
# Defines the master branch # Defines the master branch
[branch "master"] [branch "master"]
remote = origin remote = origin
merge = refs/heads/master merge = refs/heads/master

@ -1,214 +1,214 @@
/* /*
© Microsoft. All rights reserved. © Microsoft. All rights reserved.
This library is supported for use in Windows Tailored Apps only. This library is supported for use in Windows Tailored Apps only.
Build: 6.2.8100.0 Build: 6.2.8100.0
Version: 0.5 Version: 0.5
*/ */
(function (global, undefined) { (function (global, undefined) {
"use strict"; "use strict";
undefinedVariable = {}; undefinedVariable = {};
undefinedVariable.prop = 5; undefinedVariable.prop = 5;
function initializeProperties(target, members) { function initializeProperties(target, members) {
var keys = Object.keys(members); var keys = Object.keys(members);
var properties; var properties;
var i, len; var i, len;
for (i = 0, len = keys.length; i < len; i++) { for (i = 0, len = keys.length; i < len; i++) {
var key = keys[i]; var key = keys[i];
var enumerable = key.charCodeAt(0) !== /*_*/95; var enumerable = key.charCodeAt(0) !== /*_*/95;
var member = members[key]; var member = members[key];
if (member && typeof member === 'object') { if (member && typeof member === 'object') {
if (member.value !== undefined || typeof member.get === 'function' || typeof member.set === 'function') { if (member.value !== undefined || typeof member.get === 'function' || typeof member.set === 'function') {
if (member.enumerable === undefined) { if (member.enumerable === undefined) {
member.enumerable = enumerable; member.enumerable = enumerable;
} }
properties = properties || {}; properties = properties || {};
properties[key] = member; properties[key] = member;
continue; continue;
} }
} }
if (!enumerable) { if (!enumerable) {
properties = properties || {}; properties = properties || {};
properties[key] = { value: member, enumerable: enumerable, configurable: true, writable: true } properties[key] = { value: member, enumerable: enumerable, configurable: true, writable: true }
continue; continue;
} }
target[key] = member; target[key] = member;
} }
if (properties) { if (properties) {
Object.defineProperties(target, properties); Object.defineProperties(target, properties);
} }
} }
(function (rootNamespace) { (function (rootNamespace) {
// Create the rootNamespace in the global namespace // Create the rootNamespace in the global namespace
if (!global[rootNamespace]) { if (!global[rootNamespace]) {
global[rootNamespace] = Object.create(Object.prototype); global[rootNamespace] = Object.create(Object.prototype);
} }
// Cache the rootNamespace we just created in a local variable // Cache the rootNamespace we just created in a local variable
var _rootNamespace = global[rootNamespace]; var _rootNamespace = global[rootNamespace];
if (!_rootNamespace.Namespace) { if (!_rootNamespace.Namespace) {
_rootNamespace.Namespace = Object.create(Object.prototype); _rootNamespace.Namespace = Object.create(Object.prototype);
} }
function defineWithParent(parentNamespace, name, members) { function defineWithParent(parentNamespace, name, members) {
/// <summary locid="1"> /// <summary locid="1">
/// Defines a new namespace with the specified name, under the specified parent namespace. /// Defines a new namespace with the specified name, under the specified parent namespace.
/// </summary> /// </summary>
/// <param name="parentNamespace" type="Object" locid="2"> /// <param name="parentNamespace" type="Object" locid="2">
/// The parent namespace which will contain the new namespace. /// The parent namespace which will contain the new namespace.
/// </param> /// </param>
/// <param name="name" type="String" locid="3"> /// <param name="name" type="String" locid="3">
/// Name of the new namespace. /// Name of the new namespace.
/// </param> /// </param>
/// <param name="members" type="Object" locid="4"> /// <param name="members" type="Object" locid="4">
/// Members in the new namespace. /// Members in the new namespace.
/// </param> /// </param>
/// <returns locid="5"> /// <returns locid="5">
/// The newly defined namespace. /// The newly defined namespace.
/// </returns> /// </returns>
var currentNamespace = parentNamespace, var currentNamespace = parentNamespace,
namespaceFragments = name.split("."); namespaceFragments = name.split(".");
for (var i = 0, len = namespaceFragments.length; i < len; i++) { for (var i = 0, len = namespaceFragments.length; i < len; i++) {
var namespaceName = namespaceFragments[i]; var namespaceName = namespaceFragments[i];
if (!currentNamespace[namespaceName]) { if (!currentNamespace[namespaceName]) {
Object.defineProperty(currentNamespace, namespaceName, Object.defineProperty(currentNamespace, namespaceName,
{ value: {}, writable: false, enumerable: true, configurable: true } { value: {}, writable: false, enumerable: true, configurable: true }
); );
} }
currentNamespace = currentNamespace[namespaceName]; currentNamespace = currentNamespace[namespaceName];
} }
if (members) { if (members) {
initializeProperties(currentNamespace, members); initializeProperties(currentNamespace, members);
} }
return currentNamespace; return currentNamespace;
} }
function define(name, members) { function define(name, members) {
/// <summary locid="6"> /// <summary locid="6">
/// Defines a new namespace with the specified name. /// Defines a new namespace with the specified name.
/// </summary> /// </summary>
/// <param name="name" type="String" locid="7"> /// <param name="name" type="String" locid="7">
/// Name of the namespace. This could be a dot-separated nested name. /// Name of the namespace. This could be a dot-separated nested name.
/// </param> /// </param>
/// <param name="members" type="Object" locid="4"> /// <param name="members" type="Object" locid="4">
/// Members in the new namespace. /// Members in the new namespace.
/// </param> /// </param>
/// <returns locid="5"> /// <returns locid="5">
/// The newly defined namespace. /// The newly defined namespace.
/// </returns> /// </returns>
return defineWithParent(global, name, members); return defineWithParent(global, name, members);
} }
// Establish members of the "WinJS.Namespace" namespace // Establish members of the "WinJS.Namespace" namespace
Object.defineProperties(_rootNamespace.Namespace, { Object.defineProperties(_rootNamespace.Namespace, {
defineWithParent: { value: defineWithParent, writable: true, enumerable: true }, defineWithParent: { value: defineWithParent, writable: true, enumerable: true },
define: { value: define, writable: true, enumerable: true } define: { value: define, writable: true, enumerable: true }
}); });
})("WinJS"); })("WinJS");
(function (WinJS) { (function (WinJS) {
function define(constructor, instanceMembers, staticMembers) { function define(constructor, instanceMembers, staticMembers) {
/// <summary locid="8"> /// <summary locid="8">
/// Defines a class using the given constructor and with the specified instance members. /// Defines a class using the given constructor and with the specified instance members.
/// </summary> /// </summary>
/// <param name="constructor" type="Function" locid="9"> /// <param name="constructor" type="Function" locid="9">
/// A constructor function that will be used to instantiate this class. /// A constructor function that will be used to instantiate this class.
/// </param> /// </param>
/// <param name="instanceMembers" type="Object" locid="10"> /// <param name="instanceMembers" type="Object" locid="10">
/// The set of instance fields, properties and methods to be made available on the class. /// The set of instance fields, properties and methods to be made available on the class.
/// </param> /// </param>
/// <param name="staticMembers" type="Object" locid="11"> /// <param name="staticMembers" type="Object" locid="11">
/// The set of static fields, properties and methods to be made available on the class. /// The set of static fields, properties and methods to be made available on the class.
/// </param> /// </param>
/// <returns type="Function" locid="12"> /// <returns type="Function" locid="12">
/// The newly defined class. /// The newly defined class.
/// </returns> /// </returns>
constructor = constructor || function () { }; constructor = constructor || function () { };
if (instanceMembers) { if (instanceMembers) {
initializeProperties(constructor.prototype, instanceMembers); initializeProperties(constructor.prototype, instanceMembers);
} }
if (staticMembers) { if (staticMembers) {
initializeProperties(constructor, staticMembers); initializeProperties(constructor, staticMembers);
} }
return constructor; return constructor;
} }
function derive(baseClass, constructor, instanceMembers, staticMembers) { function derive(baseClass, constructor, instanceMembers, staticMembers) {
/// <summary locid="13"> /// <summary locid="13">
/// Uses prototypal inheritance to create a sub-class based on the supplied baseClass parameter. /// Uses prototypal inheritance to create a sub-class based on the supplied baseClass parameter.
/// </summary> /// </summary>
/// <param name="baseClass" type="Function" locid="14"> /// <param name="baseClass" type="Function" locid="14">
/// The class to inherit from. /// The class to inherit from.
/// </param> /// </param>
/// <param name="constructor" type="Function" locid="9"> /// <param name="constructor" type="Function" locid="9">
/// A constructor function that will be used to instantiate this class. /// A constructor function that will be used to instantiate this class.
/// </param> /// </param>
/// <param name="instanceMembers" type="Object" locid="10"> /// <param name="instanceMembers" type="Object" locid="10">
/// The set of instance fields, properties and methods to be made available on the class. /// The set of instance fields, properties and methods to be made available on the class.
/// </param> /// </param>
/// <param name="staticMembers" type="Object" locid="11"> /// <param name="staticMembers" type="Object" locid="11">
/// The set of static fields, properties and methods to be made available on the class. /// The set of static fields, properties and methods to be made available on the class.
/// </param> /// </param>
/// <returns type="Function" locid="12"> /// <returns type="Function" locid="12">
/// The newly defined class. /// The newly defined class.
/// </returns> /// </returns>
if (baseClass) { if (baseClass) {
constructor = constructor || function () { }; constructor = constructor || function () { };
var basePrototype = baseClass.prototype; var basePrototype = baseClass.prototype;
constructor.prototype = Object.create(basePrototype); constructor.prototype = Object.create(basePrototype);
Object.defineProperty(constructor.prototype, "_super", { value: basePrototype }); Object.defineProperty(constructor.prototype, "_super", { value: basePrototype });
Object.defineProperty(constructor.prototype, "constructor", { value: constructor }); Object.defineProperty(constructor.prototype, "constructor", { value: constructor });
if (instanceMembers) { if (instanceMembers) {
initializeProperties(constructor.prototype, instanceMembers); initializeProperties(constructor.prototype, instanceMembers);
} }
if (staticMembers) { if (staticMembers) {
initializeProperties(constructor, staticMembers); initializeProperties(constructor, staticMembers);
} }
return constructor; return constructor;
} else { } else {
return define(constructor, instanceMembers, staticMembers); return define(constructor, instanceMembers, staticMembers);
} }
} }
function mix(constructor) { function mix(constructor) {
/// <summary locid="15"> /// <summary locid="15">
/// Defines a class using the given constructor and the union of the set of instance members /// Defines a class using the given constructor and the union of the set of instance members
/// specified by all the mixin objects. The mixin parameter list can be of variable length. /// specified by all the mixin objects. The mixin parameter list can be of variable length.
/// </summary> /// </summary>
/// <param name="constructor" locid="9"> /// <param name="constructor" locid="9">
/// A constructor function that will be used to instantiate this class. /// A constructor function that will be used to instantiate this class.
/// </param> /// </param>
/// <returns locid="12"> /// <returns locid="12">
/// The newly defined class. /// The newly defined class.
/// </returns> /// </returns>
constructor = constructor || function () { }; constructor = constructor || function () { };
var i, len; var i, len;
for (i = 0, len = arguments.length; i < len; i++) { for (i = 0, len = arguments.length; i < len; i++) {
initializeProperties(constructor.prototype, arguments[i]); initializeProperties(constructor.prototype, arguments[i]);
} }
return constructor; return constructor;
} }
// Establish members of "WinJS.Class" namespace // Establish members of "WinJS.Class" namespace
WinJS.Namespace.define("WinJS.Class", { WinJS.Namespace.define("WinJS.Class", {
define: define, define: define,
derive: derive, derive: derive,
mix: mix mix: mix
}); });
})(WinJS); })(WinJS);
})(this); })(this);

@ -1,68 +1,68 @@
{ {
"type": "team", "type": "team",
"test": { "test": {
"testPage": "tools/testing/run-tests.htm", "testPage": "tools/testing/run-tests.htm",
"enabled": true "enabled": true
}, },
"search": { "search": {
"excludeFolders": [ "excludeFolders": [
".git", ".git",
"node_modules", "node_modules",
"tools/bin", "tools/bin",
"tools/counts", "tools/counts",
"tools/policheck", "tools/policheck",
"tools/tfs_build_extensions", "tools/tfs_build_extensions",
"tools/testing/jscoverage", "tools/testing/jscoverage",
"tools/testing/qunit", "tools/testing/qunit",
"tools/testing/chutzpah", "tools/testing/chutzpah",
"server.net" "server.net"
] ]
}, },
"languages": { "languages": {
"vs.languages.typescript": { "vs.languages.typescript": {
"validationSettings": [{ "validationSettings": [{
"scope":"/", "scope":"/",
"noImplicitAny":true, "noImplicitAny":true,
"noLib":false, "noLib":false,
"extraLibs":[], "extraLibs":[],
"semanticValidation":true, "semanticValidation":true,
"syntaxValidation":true, "syntaxValidation":true,
"codeGenTarget":"ES5", "codeGenTarget":"ES5",
"moduleGenTarget":"", "moduleGenTarget":"",
"lint": { "lint": {
"emptyBlocksWithoutComment": "warning", "emptyBlocksWithoutComment": "warning",
"curlyBracketsMustNotBeOmitted": "warning", "curlyBracketsMustNotBeOmitted": "warning",
"comparisonOperatorsNotStrict": "warning", "comparisonOperatorsNotStrict": "warning",
"missingSemicolon": "warning", "missingSemicolon": "warning",
"unknownTypeOfResults": "warning", "unknownTypeOfResults": "warning",
"semicolonsInsteadOfBlocks": "warning", "semicolonsInsteadOfBlocks": "warning",
"functionsInsideLoops": "warning", "functionsInsideLoops": "warning",
"functionsWithoutReturnType": "warning", "functionsWithoutReturnType": "warning",
"tripleSlashReferenceAlike": "warning", "tripleSlashReferenceAlike": "warning",
"unusedImports": "warning", "unusedImports": "warning",
"unusedVariables": "warning", "unusedVariables": "warning",
"unusedFunctions": "warning", "unusedFunctions": "warning",
"unusedMembers": "warning" "unusedMembers": "warning"
} }
}, },
{ {
"scope":"/client", "scope":"/client",
"baseUrl":"/client", "baseUrl":"/client",
"moduleGenTarget":"amd" "moduleGenTarget":"amd"
}, },
{ {
"scope":"/server", "scope":"/server",
"moduleGenTarget":"commonjs" "moduleGenTarget":"commonjs"
}, },
{ {
"scope":"/build", "scope":"/build",
"moduleGenTarget":"commonjs" "moduleGenTarget":"commonjs"
}, },
{ {
"scope":"/node_modules/nake", "scope":"/node_modules/nake",
"moduleGenTarget":"commonjs" "moduleGenTarget":"commonjs"
}], }],
"allowMultipleWorkers": true "allowMultipleWorkers": true
} }
} }
} }

@ -1,28 +1,28 @@
const val POINTS_X_PASS: Int = 15 const val POINTS_X_PASS: Int = 15
val EZPassAccounts: MutableMap<Int, Int> = mutableMapOf(1 to 100, 2 to 100, 3 to 100) val EZPassAccounts: MutableMap<Int, Int> = mutableMapOf(1 to 100, 2 to 100, 3 to 100)
val EZPassReport: Map<Int, Int> = EZPassAccounts val EZPassReport: Map<Int, Int> = EZPassAccounts
// update points credit // update points credit
fun updatePointsCredit(accountId: Int) { fun updatePointsCredit(accountId: Int) {
if (EZPassAccounts.containsKey(accountId)) { if (EZPassAccounts.containsKey(accountId)) {
println("Updating $accountId...") println("Updating $accountId...")
EZPassAccounts[accountId] = EZPassAccounts.getValue(accountId) + POINTS_X_PASS EZPassAccounts[accountId] = EZPassAccounts.getValue(accountId) + POINTS_X_PASS
} else { } else {
println("Error: Trying to update a non-existing account (id: $accountId)") println("Error: Trying to update a non-existing account (id: $accountId)")
} }
} }
fun accountsReport() { fun accountsReport() {
println("EZ-Pass report:") println("EZ-Pass report:")
EZPassReport.forEach{ EZPassReport.forEach{
k, v -> println("ID $k: credit $v") k, v -> println("ID $k: credit $v")
} }
} }
fun main() { fun main() {
accountsReport() accountsReport()
updatePointsCredit(1) updatePointsCredit(1)
updatePointsCredit(1) updatePointsCredit(1)
updatePointsCredit(5) updatePointsCredit(5)
accountsReport() accountsReport()
} }

@ -1,46 +1,46 @@
@base: #f938ab; @base: #f938ab;
.box-shadow(@style, @c) when (iscolor(@c)) { .box-shadow(@style, @c) when (iscolor(@c)) {
border-radius: @style @c; border-radius: @style @c;
} }
.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) { .box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
.box-shadow(@style, rgba(0, 0, 0, @alpha)); .box-shadow(@style, rgba(0, 0, 0, @alpha));
} }
.box { .box {
color: saturate(@base, 5%); color: saturate(@base, 5%);
border-color: lighten(@base, 30%); border-color: lighten(@base, 30%);
div { div {
.box-shadow((0 0 5px), 30%); .box-shadow((0 0 5px), 30%);
} }
} }
#header { #header {
h1 { h1 {
font-size: 26px; font-size: 26px;
font-weight: bold; font-weight: bold;
} }
p { font-size: 12px; p { font-size: 12px;
a { text-decoration: none; a { text-decoration: none;
&:hover { border-width: 1px } &:hover { border-width: 1px }
} }
} }
} }
@the-border: 1px; @the-border: 1px;
@base-color: #111; @base-color: #111;
@red: #842210; @red: #842210;
#header { #header {
color: (@base-color * 3); color: (@base-color * 3);
border-left: @the-border; border-left: @the-border;
border-right: (@the-border * 2); border-right: (@the-border * 2);
} }
#footer { #footer {
color: (@base-color + #003300); color: (@base-color + #003300);
border-color: desaturate(@red, 10%); border-color: desaturate(@red, 10%);
} }

@ -1,104 +1,104 @@
# Header 1 # # Header 1 #
## Header 2 ## ## Header 2 ##
### Header 3 ### (Hashes on right are optional) ### Header 3 ### (Hashes on right are optional)
## Markdown plus h2 with a custom ID ## {#id-goes-here} ## Markdown plus h2 with a custom ID ## {#id-goes-here}
[Link back to H2](#id-goes-here) [Link back to H2](#id-goes-here)
```js ```js
var x = "string"; var x = "string";
function f() { function f() {
return x; return x;
} }
``` ```
<!-- html madness --> <!-- html madness -->
<div class="custom-class" markdown="1"> <div class="custom-class" markdown="1">
<div> <div>
nested div nested div
</div> </div>
<script type='text/x-koka'> <script type='text/x-koka'>
function( x: int ) { return x*x; } function( x: int ) { return x*x; }
</script> </script>
This is a div _with_ underscores This is a div _with_ underscores
and a & <b class="bold">bold</b> element. and a & <b class="bold">bold</b> element.
<style> <style>
body { font: "Consolas" } body { font: "Consolas" }
</style> </style>
</div> </div>
* Bullet lists are easy too * Bullet lists are easy too
- Another one - Another one
+ Another one + Another one
This is a paragraph, which is text surrounded by This is a paragraph, which is text surrounded by
whitespace. Paragraphs can be on one whitespace. Paragraphs can be on one
line (or many), and can drone on for hours. line (or many), and can drone on for hours.
Now some inline markup like _italics_, **bold**, Now some inline markup like _italics_, **bold**,
and `code()`. Note that underscores and `code()`. Note that underscores
in_words_are ignored. in_words_are ignored.
````application/json ````application/json
{ value: ["or with a mime type"] } { value: ["or with a mime type"] }
```` ````
> Blockquotes are like quoted text in email replies > Blockquotes are like quoted text in email replies
>> And, they can be nested >> And, they can be nested
1. A numbered list 1. A numbered list
2. Which is numbered 2. Which is numbered
3. With periods and a space 3. With periods and a space
And now some code: And now some code:
// Code is just text indented a bit // Code is just text indented a bit
which(is_easy) to_remember(); which(is_easy) to_remember();
And a block And a block
~~~ ~~~
// Markdown extra adds un-indented code blocks too // Markdown extra adds un-indented code blocks too
if (this_is_more_code == true && !indented) { if (this_is_more_code == true && !indented) {
// tild wrapped code blocks, also not indented // tild wrapped code blocks, also not indented
} }
~~~ ~~~
Text with Text with
two trailing spaces two trailing spaces
(on the right) (on the right)
can be used can be used
for things like poems for things like poems
### Horizontal rules ### Horizontal rules
* * * * * * * *
**** ****
-------------------------- --------------------------
![picture alt](/images/photo.jpeg "Title is optional") ![picture alt](/images/photo.jpeg "Title is optional")
## Markdown plus tables ## ## Markdown plus tables ##
| Header | Header | Right | | Header | Header | Right |
| ------ | ------ | -----: | | ------ | ------ | -----: |
| Cell | Cell | $10 | | Cell | Cell | $10 |
| Cell | Cell | $20 | | Cell | Cell | $20 |
* Outer pipes on tables are optional * Outer pipes on tables are optional
* Colon used for alignment (right versus left) * Colon used for alignment (right versus left)
## Markdown plus definition lists ## ## Markdown plus definition lists ##
Bottled water Bottled water
: $ 1.25 : $ 1.25
: $ 1.55 (Large) : $ 1.55 (Large)
Milk Milk
Pop Pop
: $ 1.75 : $ 1.75
* Multiple definitions and terms are possible * Multiple definitions and terms are possible
* Definitions can include multiple paragraphs too * Definitions can include multiple paragraphs too
*[ABBR]: Markdown plus abbreviations (produces an <abbr> tag) *[ABBR]: Markdown plus abbreviations (produces an <abbr> tag)

@ -1,52 +1,52 @@
// //
// Copyright (c) Microsoft Corporation. All rights reserved. // Copyright (c) Microsoft Corporation. All rights reserved.
// //
#import "UseQuotes.h" #import "UseQuotes.h"
#import <Use/GTLT.h> #import <Use/GTLT.h>
/* /*
Multi Multi
Line Line
Comments Comments
*/ */
@implementation Test @implementation Test
- (void) applicationWillFinishLaunching:(NSNotification *)notification - (void) applicationWillFinishLaunching:(NSNotification *)notification
{ {
} }
- (IBAction)onSelectInput:(id)sender - (IBAction)onSelectInput:(id)sender
{ {
NSString* defaultDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0]; NSString* defaultDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0];
NSOpenPanel* panel = [NSOpenPanel openPanel]; NSOpenPanel* panel = [NSOpenPanel openPanel];
[panel setAllowedFileTypes:[[NSArray alloc] initWithObjects:@"ipa", @"xcarchive", @"app", nil]]; [panel setAllowedFileTypes:[[NSArray alloc] initWithObjects:@"ipa", @"xcarchive", @"app", nil]];
[panel beginWithCompletionHandler:^(NSInteger result) [panel beginWithCompletionHandler:^(NSInteger result)
{ {
if (result == NSFileHandlingPanelOKButton) if (result == NSFileHandlingPanelOKButton)
[self.inputTextField setStringValue:[panel.URL path]]; [self.inputTextField setStringValue:[panel.URL path]];
}]; }];
return YES; return YES;
int hex = 0xFEF1F0F; int hex = 0xFEF1F0F;
float ing = 3.14; float ing = 3.14;
ing = 3.14e0; ing = 3.14e0;
ing = 31.4e-2; ing = 31.4e-2;
} }
-(id) initWithParams:(id<anObject>) aHandler withDeviceStateManager:(id<anotherObject>) deviceStateManager -(id) initWithParams:(id<anObject>) aHandler withDeviceStateManager:(id<anotherObject>) deviceStateManager
{ {
// add a tap gesture recognizer // add a tap gesture recognizer
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
NSMutableArray *gestureRecognizers = [NSMutableArray array]; NSMutableArray *gestureRecognizers = [NSMutableArray array];
[gestureRecognizers addObject:tapGesture]; [gestureRecognizers addObject:tapGesture];
[gestureRecognizers addObjectsFromArray:scnView.gestureRecognizers]; [gestureRecognizers addObjectsFromArray:scnView.gestureRecognizers];
scnView.gestureRecognizers = gestureRecognizers; scnView.gestureRecognizers = gestureRecognizers;
return tapGesture; return tapGesture;
return nil; return nil;
} }
@end @end

@ -1,82 +1,82 @@
<?php <?php
// The next line contains a syntax error: // The next line contains a syntax error:
if () { if () {
return "The parser recovers from this type of syntax error"; return "The parser recovers from this type of syntax error";
} }
?> ?>
<html> <html>
<head> <head>
<title>Example page</title> <title>Example page</title>
</head> </head>
<body> <body>
<script type="text/javascript"> <script type="text/javascript">
// Some PHP embedded inside JS // Some PHP embedded inside JS
// Generated <?=date('l, F jS, Y')?> // Generated <?=date('l, F jS, Y')?>
var server_token = <?=rand(5, 10000)?> var server_token = <?=rand(5, 10000)?>
if (typeof server_token === 'number') { if (typeof server_token === 'number') {
alert('token: ' + server_token); alert('token: ' + server_token);
} }
</script> </script>
<div> <div>
Hello Hello
<? if (isset($user)) { ?> <? if (isset($user)) { ?>
<b><?=$user?></b> <b><?=$user?></b>
<? } else { ?> <? } else { ?>
<i>guest</i> <i>guest</i>
<? } ?> <? } ?>
! !
</div> </div>
<?php <?php
/* Example PHP file /* Example PHP file
multiline comment multiline comment
*/ */
$cards = array("ah", "ac", "ad", "as", $cards = array("ah", "ac", "ad", "as",
"2h", "2c", "2d", "2s", "2h", "2c", "2d", "2s",
"3h", "3c", "3d", "3s", "3h", "3c", "3d", "3s",
"4h", "4c", "4d", "4s", "4h", "4c", "4d", "4s",
"5h", "5c", "5d", "5s", "5h", "5c", "5d", "5s",
"6h", "6c", "6d", "6s", "6h", "6c", "6d", "6s",
"7h", "7c", "7d", "7s", "7h", "7c", "7d", "7s",
"8h", "8c", "8d", "8s", "8h", "8c", "8d", "8s",
"9h", "9c", "9d", "9s", "9h", "9c", "9d", "9s",
"th", "tc", "td", "ts", "th", "tc", "td", "ts",
"jh", "jc", "jd", "js", "jh", "jc", "jd", "js",
"qh", "qc", "qd", "qs", "qh", "qc", "qd", "qs",
"kh", "kc", "kd", "ks"); "kh", "kc", "kd", "ks");
srand(time()); srand(time());
for($i = 0; $i < 52; $i++) { for($i = 0; $i < 52; $i++) {
$count = count($cards); $count = count($cards);
$random = (rand()%$count); $random = (rand()%$count);
if($cards[$random] == "") { if($cards[$random] == "") {
$i--; $i--;
} else { } else {
$deck[] = $cards[$random]; $deck[] = $cards[$random];
$cards[$random] = ""; $cards[$random] = "";
} }
} }
srand(time()); srand(time());
$starting_point = (rand()%51); $starting_point = (rand()%51);
print("Starting point for cut cards is: $starting_point<p>"); print("Starting point for cut cards is: $starting_point<p>");
// display shuffled cards (EXAMPLE ONLY) // display shuffled cards (EXAMPLE ONLY)
for ($index = 0; $index < 52; $index++) { for ($index = 0; $index < 52; $index++) {
if ($starting_point == 52) { $starting_point = 0; } if ($starting_point == 52) { $starting_point = 0; }
print("Uncut Point: <strong>$deck[$index]</strong> "); print("Uncut Point: <strong>$deck[$index]</strong> ");
print("Starting Point: <strong>$deck[$starting_point]</strong><br>"); print("Starting Point: <strong>$deck[$starting_point]</strong><br>");
$starting_point++; $starting_point++;
} }
?> ?>
</body> </body>
</html> </html>

@ -1,9 +1,9 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus aliquet sapien, sed rhoncus leo ullamcorper ornare. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus feugiat eleifend nisl, aliquet rhoncus quam scelerisque vel. Morbi eu pellentesque ex. Nam suscipit maximus leo blandit cursus. Aenean sollicitudin nisi luctus, ornare nibh viverra, laoreet ex. Donec eget nibh sit amet dolor ornare elementum. Morbi sollicitudin enim vitae risus pretium vestibulum. Ut pretium hendrerit libero, non vulputate ante volutpat et. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam malesuada turpis vitae est porttitor, id tincidunt neque dignissim. Integer rhoncus vestibulum justo in iaculis. Praesent nec augue ut dui scelerisque gravida vel id velit. Donec vehicula feugiat mollis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus aliquet sapien, sed rhoncus leo ullamcorper ornare. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus feugiat eleifend nisl, aliquet rhoncus quam scelerisque vel. Morbi eu pellentesque ex. Nam suscipit maximus leo blandit cursus. Aenean sollicitudin nisi luctus, ornare nibh viverra, laoreet ex. Donec eget nibh sit amet dolor ornare elementum. Morbi sollicitudin enim vitae risus pretium vestibulum. Ut pretium hendrerit libero, non vulputate ante volutpat et. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam malesuada turpis vitae est porttitor, id tincidunt neque dignissim. Integer rhoncus vestibulum justo in iaculis. Praesent nec augue ut dui scelerisque gravida vel id velit. Donec vehicula feugiat mollis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Praesent diam lorem, luctus quis ullamcorper non, consequat quis orci. Ut vel massa vel nunc sagittis porttitor a vitae ante. Quisque euismod lobortis imperdiet. Vestibulum tincidunt vehicula posuere. Nulla facilisi. Donec sodales imperdiet risus id ullamcorper. Nulla luctus orci tortor, vitae tincidunt urna aliquet nec. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam consequat dapibus massa. Sed ac pharetra magna, in imperdiet neque. Nullam nunc nisi, consequat vel nunc et, sagittis aliquam arcu. Aliquam non orci magna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed id sem ut sem pulvinar rhoncus. Aenean venenatis nunc eget mi ornare, vitae maximus lacus varius. Quisque quis vestibulum justo. Praesent diam lorem, luctus quis ullamcorper non, consequat quis orci. Ut vel massa vel nunc sagittis porttitor a vitae ante. Quisque euismod lobortis imperdiet. Vestibulum tincidunt vehicula posuere. Nulla facilisi. Donec sodales imperdiet risus id ullamcorper. Nulla luctus orci tortor, vitae tincidunt urna aliquet nec. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam consequat dapibus massa. Sed ac pharetra magna, in imperdiet neque. Nullam nunc nisi, consequat vel nunc et, sagittis aliquam arcu. Aliquam non orci magna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed id sem ut sem pulvinar rhoncus. Aenean venenatis nunc eget mi ornare, vitae maximus lacus varius. Quisque quis vestibulum justo.
Donec euismod luctus volutpat. Donec sed lacinia enim. Vivamus aliquam elit cursus, convallis diam at, volutpat turpis. Sed lacinia nisl in auctor dapibus. Nunc turpis mi, mattis ut rhoncus id, lacinia sed lectus. Donec sodales tellus quis libero gravida pretium et quis magna. Etiam ultricies mollis purus, eget consequat velit. Duis vitae nibh vitae arcu tincidunt congue. Maecenas ut velit in ipsum condimentum dictum quis eget urna. Sed mattis nulla arcu, vitae mattis ligula dictum at. Donec euismod luctus volutpat. Donec sed lacinia enim. Vivamus aliquam elit cursus, convallis diam at, volutpat turpis. Sed lacinia nisl in auctor dapibus. Nunc turpis mi, mattis ut rhoncus id, lacinia sed lectus. Donec sodales tellus quis libero gravida pretium et quis magna. Etiam ultricies mollis purus, eget consequat velit. Duis vitae nibh vitae arcu tincidunt congue. Maecenas ut velit in ipsum condimentum dictum quis eget urna. Sed mattis nulla arcu, vitae mattis ligula dictum at.
Praesent at dignissim dolor. Donec quis placerat sem. Cras vitae placerat sapien, eu sagittis ex. Mauris nec luctus risus. Cras imperdiet semper neque suscipit auctor. Mauris nisl massa, commodo sit amet dignissim id, malesuada sed ante. Praesent varius sapien eget eros vehicula porttitor. Praesent at dignissim dolor. Donec quis placerat sem. Cras vitae placerat sapien, eu sagittis ex. Mauris nec luctus risus. Cras imperdiet semper neque suscipit auctor. Mauris nisl massa, commodo sit amet dignissim id, malesuada sed ante. Praesent varius sapien eget eros vehicula porttitor.
Mauris auctor nunc in quam tempor, eget consectetur nisi rhoncus. Donec et nulla imperdiet, gravida dui at, accumsan velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin sollicitudin condimentum auctor. Sed lacinia eleifend nisi, id scelerisque leo laoreet sit amet. Morbi congue augue a malesuada pulvinar. Curabitur nec ante finibus, commodo orci vel, aliquam libero. Morbi molestie purus non nunc placerat fermentum. Pellentesque commodo ligula sed pretium aliquam. Praesent ut nibh ex. Vivamus vestibulum velit in leo suscipit, vitae pellentesque urna vulputate. Suspendisse pretium placerat ligula eu ullamcorper. Nam eleifend mi tellus, ut tristique ante ultricies vitae. Quisque venenatis dapibus tellus sit amet mattis. Donec erat arcu, elementum vel nisl at, sagittis vulputate nisi. Mauris auctor nunc in quam tempor, eget consectetur nisi rhoncus. Donec et nulla imperdiet, gravida dui at, accumsan velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin sollicitudin condimentum auctor. Sed lacinia eleifend nisi, id scelerisque leo laoreet sit amet. Morbi congue augue a malesuada pulvinar. Curabitur nec ante finibus, commodo orci vel, aliquam libero. Morbi molestie purus non nunc placerat fermentum. Pellentesque commodo ligula sed pretium aliquam. Praesent ut nibh ex. Vivamus vestibulum velit in leo suscipit, vitae pellentesque urna vulputate. Suspendisse pretium placerat ligula eu ullamcorper. Nam eleifend mi tellus, ut tristique ante ultricies vitae. Quisque venenatis dapibus tellus sit amet mattis. Donec erat arcu, elementum vel nisl at, sagittis vulputate nisi.

@ -1,13 +1,13 @@
import banana import banana
class Monkey: class Monkey:
# Bananas the monkey can eat. # Bananas the monkey can eat.
capacity = 10 capacity = 10
def eat(self, n): def eat(self, n):
"""Make the monkey eat n bananas!""" """Make the monkey eat n bananas!"""
self.capacity -= n * banana.size self.capacity -= n * banana.size
def feeding_frenzy(self): def feeding_frenzy(self):
self.eat(9.25) self.eat(9.25)
return "Yum yum" return "Yum yum"

@ -1,41 +1,41 @@
# © Microsoft. All rights reserved. # © Microsoft. All rights reserved.
#' Add together two numbers. #' Add together two numbers.
#' #'
#' @param x A number. #' @param x A number.
#' @param y A number. #' @param y A number.
#' @return The sum of \code{x} and \code{y}. #' @return The sum of \code{x} and \code{y}.
#' @examples #' @examples
#' add(1, 1) #' add(1, 1)
#' add(10, 1) #' add(10, 1)
add <- function(x, y) { add <- function(x, y) {
x + y x + y
} }
add(1, 2) add(1, 2)
add(1.0, 2.0) add(1.0, 2.0)
add(-1, -2) add(-1, -2)
add(-1.0, -2.0) add(-1.0, -2.0)
add(1.0e10, 2.0e10) add(1.0e10, 2.0e10)
#' Concatenate together two strings. #' Concatenate together two strings.
#' #'
#' @param x A string. #' @param x A string.
#' @param y A string. #' @param y A string.
#' @return The concatenated string built of \code{x} and \code{y}. #' @return The concatenated string built of \code{x} and \code{y}.
#' @examples #' @examples
#' strcat("one", "two") #' strcat("one", "two")
strcat <- function(x, y) { strcat <- function(x, y) {
paste(x, y) paste(x, y)
} }
paste("one", "two") paste("one", "two")
paste('one', 'two') paste('one', 'two')
paste(NULL, NULL) paste(NULL, NULL)
paste(NA, NA) paste(NA, NA)
paste("multi- paste("multi-
line", line",
'multi- 'multi-
line') line')

@ -1,46 +1,46 @@
@{ @{
var total = 0; var total = 0;
var totalMessage = ""; var totalMessage = "";
@* a multiline @* a multiline
razor comment embedded in csharp *@ razor comment embedded in csharp *@
if (IsPost) { if (IsPost) {
// Retrieve the numbers that the user entered. // Retrieve the numbers that the user entered.
var num1 = Request["text1"]; var num1 = Request["text1"];
var num2 = Request["text2"]; var num2 = Request["text2"];
// Convert the entered strings into integers numbers and add. // Convert the entered strings into integers numbers and add.
total = num1.AsInt() + num2.AsInt(); total = num1.AsInt() + num2.AsInt();
<italic><bold>totalMessage = "Total = " + total;</bold></italic> <italic><bold>totalMessage = "Total = " + total;</bold></italic>
} }
} }
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<title>Add Numbers</title> <title>Add Numbers</title>
<meta charset="utf-8" /> <meta charset="utf-8" />
</head> </head>
<body> <body>
<p>Enter two whole numbers and then click <strong>Add</strong>.</p> <p>Enter two whole numbers and then click <strong>Add</strong>.</p>
<form action="" method="post"> <form action="" method="post">
<p><label for="text1">First Number:</label> <p><label for="text1">First Number:</label>
<input type="text" name="text1" /> <input type="text" name="text1" />
</p> </p>
<p><label for="text2">Second Number:</label> <p><label for="text2">Second Number:</label>
<input type="text" name="text2" /> <input type="text" name="text2" />
</p> </p>
<p><input type="submit" value="Add" /></p> <p><input type="submit" value="Add" /></p>
</form> </form>
@* now we call the totalMessage method @* now we call the totalMessage method
(a multi line razor comment outside code) *@ (a multi line razor comment outside code) *@
<p>@totalMessage</p> <p>@totalMessage</p>
<p>@(totalMessage+"!")</p> <p>@(totalMessage+"!")</p>
An email address (with escaped at character): name@@domain.com An email address (with escaped at character): name@@domain.com
</body> </body>
</html> </html>

@ -1,21 +1,21 @@
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# Copyright (c) Microsoft. All rights reserved. # Copyright (c) Microsoft. All rights reserved.
#-------------------------------------------------------------------------- #--------------------------------------------------------------------------
module Azure module Azure
module Blob module Blob
class Blob class Blob
def initialize def initialize
@properties = {} @properties = {}
@metadata = {} @metadata = {}
yield self if block_given? yield self if block_given?
end end
attr_accessor :name attr_accessor :name
attr_accessor :snapshot attr_accessor :snapshot
attr_accessor :properties attr_accessor :properties
attr_accessor :metadata attr_accessor :metadata
end end
end end
end end

@ -1,37 +1,37 @@
$baseFontSizeInPixels: 14; $baseFontSizeInPixels: 14;
@function px2em ($font_size, $base_font_size: $baseFontSizeInPixels) { @function px2em ($font_size, $base_font_size: $baseFontSizeInPixels) {
@return ($font_size / $base_font_size) + em; @return ($font_size / $base_font_size) + em;
} }
h1 { h1 {
font-size: px2em(36, $baseFontSizeInPixels); font-size: px2em(36, $baseFontSizeInPixels);
} }
h2 { h2 {
font-size: px2em(28, $baseFontSizeInPixels); font-size: px2em(28, $baseFontSizeInPixels);
} }
.class { .class {
font-size: px2em(14, $baseFontSizeInPixels); font-size: px2em(14, $baseFontSizeInPixels);
} }
nav { nav {
ul { ul {
margin: 0; margin: 0;
padding: 0; padding: 0;
list-style: none; list-style: none;
} }
li { display: inline-block; } li { display: inline-block; }
a { a {
display: block; display: block;
padding: 6px 12px; padding: 6px 12px;
text-decoration: none; text-decoration: none;
} }
@each $animal in puma, sea-slug, egret, salamander { @each $animal in puma, sea-slug, egret, salamander {
.#{$animal}-icon { .#{$animal}-icon {
background-image: url('/images/#{$animal}.png'); background-image: url('/images/#{$animal}.png');
} }
} }
} }

@ -1,50 +1,50 @@
import Foundation import Foundation
protocol APIControllerProtocol { protocol APIControllerProtocol {
func didReceiveAPIResults(results: NSArray) func didReceiveAPIResults(results: NSArray)
} }
class APIController { class APIController {
var delegate: APIControllerProtocol var delegate: APIControllerProtocol
init(delegate: APIControllerProtocol) { init(delegate: APIControllerProtocol) {
self.delegate = delegate self.delegate = delegate
} }
func get(path: String) { func get(path: String) {
let url = NSURL(string: path) let url = NSURL(string: path)
let session = NSURLSession.sharedSession() let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
println("Task completed") println("Task completed")
if(error != nil) { if(error != nil) {
// If there is an error in the web request, print it to the console // If there is an error in the web request, print it to the console
println(error.localizedDescription) println(error.localizedDescription)
} }
var err: NSError? var err: NSError?
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary { if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {
if(err != nil) { if(err != nil) {
// If there is an error parsing JSON, print it to the console // If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)") println("JSON Error \(err!.localizedDescription)")
} }
if let results: NSArray = jsonResult["results"] as? NSArray { if let results: NSArray = jsonResult["results"] as? NSArray {
self.delegate.didReceiveAPIResults(results) self.delegate.didReceiveAPIResults(results)
} }
} }
}) })
// The task is just an object with all these properties set // The task is just an object with all these properties set
// In order to actually make the web request, we need to "resume" // In order to actually make the web request, we need to "resume"
task.resume() task.resume()
} }
func searchItunesFor(searchTerm: String) { func searchItunesFor(searchTerm: String) {
// The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs // The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs
let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
// Now escape anything else that isn't URL-friendly // Now escape anything else that isn't URL-friendly
if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music&entity=album" let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music&entity=album"
} }
} }
} }

@ -1,124 +1,124 @@
/* Game of Life /* Game of Life
* Implemented in TypeScript * Implemented in TypeScript
* To learn more about TypeScript, please visit http://www.typescriptlang.org/ * To learn more about TypeScript, please visit http://www.typescriptlang.org/
*/ */
namespace Conway { namespace Conway {
export class Cell { export class Cell {
public row: number; public row: number;
public col: number; public col: number;
public live: boolean; public live: boolean;
constructor(row: number, col: number, live: boolean) { constructor(row: number, col: number, live: boolean) {
this.row = row; this.row = row;
this.col = col; this.col = col;
this.live = live; this.live = live;
} }
} }
export class GameOfLife { export class GameOfLife {
private gridSize: number; private gridSize: number;
private canvasSize: number; private canvasSize: number;
private lineColor: string; private lineColor: string;
private liveColor: string; private liveColor: string;
private deadColor: string; private deadColor: string;
private initialLifeProbability: number; private initialLifeProbability: number;
private animationRate: number; private animationRate: number;
private cellSize: number; private cellSize: number;
private context: CanvasRenderingContext2D; private context: CanvasRenderingContext2D;
private world; private world;
constructor() { constructor() {
this.gridSize = 50; this.gridSize = 50;
this.canvasSize = 600; this.canvasSize = 600;
this.lineColor = '#cdcdcd'; this.lineColor = '#cdcdcd';
this.liveColor = '#666'; this.liveColor = '#666';
this.deadColor = '#eee'; this.deadColor = '#eee';
this.initialLifeProbability = 0.5; this.initialLifeProbability = 0.5;
this.animationRate = 60; this.animationRate = 60;
this.cellSize = 0; this.cellSize = 0;
this.world = this.createWorld(); this.world = this.createWorld();
this.circleOfLife(); this.circleOfLife();
} }
public createWorld() { public createWorld() {
return this.travelWorld( (cell : Cell) => { return this.travelWorld( (cell : Cell) => {
cell.live = Math.random() < this.initialLifeProbability; cell.live = Math.random() < this.initialLifeProbability;
return cell; return cell;
}); });
} }
public circleOfLife() : void { public circleOfLife() : void {
this.world = this.travelWorld( (cell: Cell) => { this.world = this.travelWorld( (cell: Cell) => {
cell = this.world[cell.row][cell.col]; cell = this.world[cell.row][cell.col];
this.draw(cell); this.draw(cell);
return this.resolveNextGeneration(cell); return this.resolveNextGeneration(cell);
}); });
setTimeout( () => {this.circleOfLife()}, this.animationRate); setTimeout( () => {this.circleOfLife()}, this.animationRate);
} }
public resolveNextGeneration(cell : Cell) { public resolveNextGeneration(cell : Cell) {
var count = this.countNeighbors(cell); var count = this.countNeighbors(cell);
var newCell = new Cell(cell.row, cell.col, cell.live); var newCell = new Cell(cell.row, cell.col, cell.live);
if(count < 2 || count > 3) newCell.live = false; if(count < 2 || count > 3) newCell.live = false;
else if(count == 3) newCell.live = true; else if(count == 3) newCell.live = true;
return newCell; return newCell;
} }
public countNeighbors(cell : Cell) { public countNeighbors(cell : Cell) {
var neighbors = 0; var neighbors = 0;
for(var row = -1; row <=1; row++) { for(var row = -1; row <=1; row++) {
for(var col = -1; col <= 1; col++) { for(var col = -1; col <= 1; col++) {
if(row == 0 && col == 0) continue; if(row == 0 && col == 0) continue;
if(this.isAlive(cell.row + row, cell.col + col)) { if(this.isAlive(cell.row + row, cell.col + col)) {
neighbors++; neighbors++;
} }
} }
} }
return neighbors; return neighbors;
} }
public isAlive(row : number, col : number) { public isAlive(row : number, col : number) {
if(row < 0 || col < 0 || row >= this.gridSize || col >= this.gridSize) return false; if(row < 0 || col < 0 || row >= this.gridSize || col >= this.gridSize) return false;
return this.world[row][col].live; return this.world[row][col].live;
} }
public travelWorld(callback) { public travelWorld(callback) {
var result = []; var result = [];
for(var row = 0; row < this.gridSize; row++) { for(var row = 0; row < this.gridSize; row++) {
var rowData = []; var rowData = [];
for(var col = 0; col < this.gridSize; col++) { for(var col = 0; col < this.gridSize; col++) {
rowData.push(callback(new Cell(row, col, false))); rowData.push(callback(new Cell(row, col, false)));
} }
result.push(rowData); result.push(rowData);
} }
return result; return result;
} }
public draw(cell : Cell) { public draw(cell : Cell) {
if(this.context == null) this.context = this.createDrawingContext(); if(this.context == null) this.context = this.createDrawingContext();
if(this.cellSize == 0) this.cellSize = this.canvasSize/this.gridSize; if(this.cellSize == 0) this.cellSize = this.canvasSize/this.gridSize;
this.context.strokeStyle = this.lineColor; this.context.strokeStyle = this.lineColor;
this.context.strokeRect(cell.row * this.cellSize, cell.col*this.cellSize, this.cellSize, this.cellSize); this.context.strokeRect(cell.row * this.cellSize, cell.col*this.cellSize, this.cellSize, this.cellSize);
this.context.fillStyle = cell.live ? this.liveColor : this.deadColor; this.context.fillStyle = cell.live ? this.liveColor : this.deadColor;
this.context.fillRect(cell.row * this.cellSize, cell.col*this.cellSize, this.cellSize, this.cellSize); this.context.fillRect(cell.row * this.cellSize, cell.col*this.cellSize, this.cellSize, this.cellSize);
} }
public createDrawingContext() { public createDrawingContext() {
var canvas = <HTMLCanvasElement> document.getElementById('conway-canvas'); var canvas = <HTMLCanvasElement> document.getElementById('conway-canvas');
if(canvas == null) { if(canvas == null) {
canvas = document.createElement('canvas'); canvas = document.createElement('canvas');
canvas.id = 'conway-canvas'; canvas.id = 'conway-canvas';
canvas.width = this.canvasSize; canvas.width = this.canvasSize;
canvas.height = this.canvasSize; canvas.height = this.canvasSize;
document.body.appendChild(canvas); document.body.appendChild(canvas);
} }
return canvas.getContext('2d'); return canvas.getContext('2d');
} }
} }
} }
var game = new Conway.GameOfLife(); var game = new Conway.GameOfLife();

@ -1,59 +1,59 @@
Imports System Imports System
Imports System.Collections.Generic Imports System.Collections.Generic
Module Module1 Module Module1
Sub Main() Sub Main()
Dim a As New M8Ball Dim a As New M8Ball
Do While True Do While True
Dim q As String = "" Dim q As String = ""
Console.Write("ask me about the future... ") Console.Write("ask me about the future... ")
q = Console.ReadLine() q = Console.ReadLine()
If q.Trim <> "" Then If q.Trim <> "" Then
Console.WriteLine("the answer is... {0}", a.getAnswer(q)) Console.WriteLine("the answer is... {0}", a.getAnswer(q))
Else Else
Exit Do Exit Do
End If End If
Loop Loop
End Sub End Sub
End Module End Module
Class M8Ball Class M8Ball
Public Answers As System.Collections.Generic.Dictionary(Of Integer, String) Public Answers As System.Collections.Generic.Dictionary(Of Integer, String)
Public Sub New() Public Sub New()
Answers = New System.Collections.Generic.Dictionary(Of Integer, String) Answers = New System.Collections.Generic.Dictionary(Of Integer, String)
Answers.Add(0, "It is certain") Answers.Add(0, "It is certain")
Answers.Add(1, "It is decidedly so") Answers.Add(1, "It is decidedly so")
Answers.Add(2, "Without a doubt") Answers.Add(2, "Without a doubt")
Answers.Add(3, "Yes, definitely") Answers.Add(3, "Yes, definitely")
Answers.Add(4, "You may rely on ") Answers.Add(4, "You may rely on ")
Answers.Add(5, "As I see it, yes") Answers.Add(5, "As I see it, yes")
Answers.Add(6, "Most likely") Answers.Add(6, "Most likely")
Answers.Add(7, "Outlook good") Answers.Add(7, "Outlook good")
Answers.Add(8, "Signs point to yes") Answers.Add(8, "Signs point to yes")
Answers.Add(9, "Yes") Answers.Add(9, "Yes")
Answers.Add(10, "Reply hazy, try again") Answers.Add(10, "Reply hazy, try again")
Answers.Add(11, "Ask again later") Answers.Add(11, "Ask again later")
Answers.Add(12, "Better not tell you now") Answers.Add(12, "Better not tell you now")
Answers.Add(13, "Cannot predict now") Answers.Add(13, "Cannot predict now")
Answers.Add(14, "Concentrate and ask again") Answers.Add(14, "Concentrate and ask again")
Answers.Add(15, "Don't count on it") Answers.Add(15, "Don't count on it")
Answers.Add(16, "My reply is no") Answers.Add(16, "My reply is no")
Answers.Add(17, "My sources say no") Answers.Add(17, "My sources say no")
Answers.Add(18, "Outlook not so") Answers.Add(18, "Outlook not so")
Answers.Add(19, "Very doubtful") Answers.Add(19, "Very doubtful")
End Sub End Sub
Public Function getAnswer(theQuestion As String) As String Public Function getAnswer(theQuestion As String) As String
Dim r As New Random Dim r As New Random
Return Answers(r.Next(0, 19)) Return Answers(r.Next(0, 19))
End Function End Function
End Class End Class

@ -1,14 +1,14 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings> <connectionStrings>
<add name="MyDB" <add name="MyDB"
connectionString="value for the deployed Web.config file" connectionString="value for the deployed Web.config file"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings> </connectionStrings>
<system.web> <system.web>
<customErrors defaultRedirect="GenericError.htm" <customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace"> mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/> <error statusCode="500" redirect="InternalError.htm"/>
</customErrors> </customErrors>
</system.web> </system.web>
</configuration> </configuration>

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long
Loading…
Cancel
Save