repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
markvincze/Stubbery | test/Stubbery.IntegrationTests/StateTest.cs | 529 | using System;
using Xunit;
namespace Stubbery.IntegrationTests
{
public class StateTest
{
[Fact]
public void Start_StartTwice_Exception()
{
var sut = new ApiStub();
sut.Start();
Assert.Throws<InvalidOperationException>(() => sut.Start());
}
[Fact]
public void Address_NotStarted_Exception()
{
var sut = new ApiStub();
Assert.Throws<InvalidOperationException>(() => sut.Address);
}
}
}
| mit |
Adrianacmy/Classic-Interesting-CS-Mini-Programs | old/reverse_dict.py | 2014 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Created on Sun May 15
@author: Adrianacmy
Create a function reverse that takes in a dictionary and reverses it, such that
all of the values become keys and all of the keys become values. Be careful: we
do not wish to lose any information. Consider what to do if the original
dictionary has lists of values for a particular key, or has duplicate values
for some keys.
'''
# def format_dic_value(dict):
# '''format the single elements value list if it is necessary'''
# nw_dict = {}
# for k, v in dict.items():
# if len(v) == 1 and type(v) == list:
# nw_dict[k] = ''.join(v)
# else:
# nw_dict[k] = v
# return nw_dict
def convert_to_simple_list(lst, nw_list=[]):
'''
Convert a muti-dimentinal list to one dimention list.
lst: any list
nw_list: one dimentiona list, could start as empty
return: a one dimention list
'''
for a in lst:
if type(a) == list:
convert_to_simple_list(a)
else:
nw_list.append(a)
return nw_list
# lst = ['a', 'b', 'c', [1,2,3], 'abc']
# print(convert_to_simple_list(lst))
def add_dic_val(dic, k, v):
'''
add elements or values to a dictionary.
dic: an empty dictionary
k: a key
v: a value
'''
dic[k] = dic.get(k, [])
if not v in dic[k]:
dic[k].append(v)
def reverse_dict(d):
'''reverse keys and values in a dictionary'''
r = {} #reversed dictionary
for k, v in d.items():
nw_lst = []
if type(v) == list:
value_list = convert_to_simple_list(v, nw_lst)
# if value_list:
for val in value_list:
add_dic_val(r, val, k)
else:
add_dic_val(r, v, k)
return r
def main():
d = {1: 'a', 4: ['abc', 'egf'], 5: '',(1, 6): 'abc', 2:[1, 2, 3, [1, 2]], 8: ['', 2]}
print(reverse_dict(d))
if __name__ == "__main__":
main()
| mit |
mawax/InfoBridge.SuperLinq | src/InfoBridge.SuperLinq.CodeGen/Program.cs | 263 | using SuperOffice;
namespace InfoBridge.SuperLinq.CodeGen
{
class Program
{
static void Main(string[] args)
{
var gen = new Generator();
string generatedCode = gen.GenerateString(gen.Build());
}
}
}
| mit |
rokka-io/rokka-client-php | src/LocalImage/StringContent.php | 1137 | <?php
namespace Rokka\Client\LocalImage;
/**
* Creates a LocalImage object with the content of an image as input.
*
* For images on a accessible file system, better use \Rokka\Client\LocalImage\FileInfo
*
* Example:
*
* ```language-php
* $image = new StringContent($content, $identifier, $context);
* ```
*
* @see \Rokka\Client\LocalImage\FileInfo
* @since 1.3.0
*/
class StringContent extends AbstractLocalImage
{
/**
* @var string|null
*/
private $content = null;
/**
* @param string|null $image
* @param string|null $identifier
* @param mixed|null $context
*/
public function __construct($image, $identifier = null, $context = null)
{
parent::__construct($identifier);
$this->content = $image;
$this->context = $context;
}
public function getIdentifier()
{
if (null !== $this->identifier) {
return $this->identifier;
}
$this->identifier = md5((string) $this->getContent());
return $this->identifier;
}
public function getContent()
{
return $this->content;
}
}
| mit |
sapioit/nw-sample-apps | notifications/app.js | 5159 | var NW = require('nw.gui');
// Extend application menu for Mac OS
if (process.platform == "darwin") {
var menu = new NW.Menu({type: "menubar"});
menu.createMacBuiltin && menu.createMacBuiltin(window.document.title);
NW.Window.get().menu = menu;
}
var $ = function (selector) {
return document.querySelector(selector);
}
document.addEventListener('DOMContentLoaded', function() {
$('#simple-coffee').addEventListener('click', function (event) {
showNotification("./icons/coffee.png", "Your coffee", 'is ready...')
});
$('#simple-camera').addEventListener('click', function (event) {
var notif = showNotification("./icons/camera.png", "Camera", 'example notification');
setTimeout(function () {
notif.close();
}, 1200);
});
$('#simple-car').addEventListener('click', function (event) {
showNotification('./icons/car.png', "Taxi is arrived", 'hurry up');
});
$('#node-notifier-coffee').addEventListener('click', function (event) {
showNativeNotification("./icons/coffee.png", "Your coffee", 'is ready...', 'default')
});
$('#node-notifier-camera').addEventListener('click', function (event) {
showNativeNotification("./icons/camera.png", "Camera", 'example notification', 'Glass');
});
$('#node-notifier-car').addEventListener('click', function (event) {
showNativeNotification(false, "Taxi is arrived", 'hurry up', false, './icons/car.png');
});
$('#nw-notify-coffee').addEventListener('click', function (event) {
showHtmlNotification("./icons/coffee.png", "Your coffee", 'is ready...');
});
$('#nw-notify-camera').addEventListener('click', function (event) {
showHtmlNotification("./icons/camera.png", "Camera", 'example notification', function (event) {
setTimeout(function () {
console.log("closing notification on timeout", event)
event.closeNotification();
}, 1200);
});
});
$('#nw-notify-car').addEventListener('click', function (event) {
showHtmlNotification('./icons/car.png', "Taxi is arrived", 'hurry up');
});
// bring window to front when open via terminal
NW.Window.get().focus();
// for nw-notify frameless windows
NW.Window.get().on('close', function() {
NW.App.quit();
});
});
var writeLog = function (msg) {
var logElement = $("#output");
logElement.innerHTML += msg + "<br>";
logElement.scrollTop = logElement.scrollHeight;
};
// NW.JS Notification
var showNotification = function (icon, title, body) {
if (icon && icon.match(/^\./)) {
icon = icon.replace('.', 'file://' + process.cwd());
}
var notification = new Notification(title, {icon: icon, body: body});
notification.onclick = function () {
writeLog("Notification clicked");
};
notification.onclose = function () {
writeLog("Notification closed");
NW.Window.get().focus();
};
notification.onshow = function () {
writeLog("-----<br>" + title);
};
return notification;
}
// NODE-NOTIFIER
var showNativeNotification = function (icon, title, message, sound, image) {
var notifier;
try {
notifier = require('node-notifier');
} catch (error) {
console.error(error);
if (error.message == "Cannot find module 'node-notifier'") {
window.alert("Can not load module 'node-notifier'.\nPlease run 'npm install'");
}
return false;
}
var path = require('path');
icon = icon ? path.join(process.cwd(), icon) : undefined;
image = image ? path.join(process.cwd(), image) : undefined;
notifier.notify({
title: title,
message: message,
icon: icon,
appIcon: icon,
contentImage: image,
sound: sound,
wait: false,
sender: 'org.nwjs.sample.notifications'
}, function (err, response) {
if (response == "Activate\n") {
writeLog("node-notifier: notification clicked");
NW.Window.get().focus();
}
});
writeLog("-----<br>node-notifier: " + title);
};
// NW-NOTIFY
var showHtmlNotification = function (icon, title, body, callback) {
var notifier;
try {
notifier = require('nw-notify');
} catch (error) {
console.error(error);
if (error.message == "Cannot find module 'nw-notify'") {
window.alert("Can not load module 'nw-notify'.\nPlease run 'npm install'");
return false;
}
}
// give it nice look
notifier.setConfig({
defaultStyleContainer: {
border: '1px solid #9D9D9D',
borderRadius: '6px',
backgroundColor: 'rgba(245, 245, 245, 0.94)',
fontFamily: 'Helvetica Neue',
boxShadow: '0px 0px 11px rgba(0, 0, 0, 0.4)',
fontSize: 12,
position: 'relative',
lineHeight: '17px',
padding: '8px 12px 8px 14px'
}
});
if (icon) icon = notifier.getAppPath() + icon;
notifier.notify({
title: title,
text: body,
iconPath: icon,
onShowFunc: function (event) {
if (callback) callback(event);
writeLog("-----<br>nw-notify: " + title);
},
onClickFunc: function (event) {
writeLog("nw-notify notification clicked");
},
onCloseFunc: function (event) {
if (event.event == 'close') {
writeLog("nw-notify notification closed ");
}
}
});
}; | mit |
silhouette/Angular2Quickstart | app/app.component.ts | 220 | import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
styleUrls: ['app/app.component.css']
})
export class AppComponent {
title = 'Tour of Heroes';
} | mit |
AzureDay/2016-WebSite | TeamSpark.AzureDay.WebSite.Host/Controllers/ProfileController.cs | 11099 | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Security;
using Kaznachey.KaznacheyPayment;
using TeamSpark.AzureDay.WebSite.App;
using TeamSpark.AzureDay.WebSite.App.Entity;
using TeamSpark.AzureDay.WebSite.Config;
using TeamSpark.AzureDay.WebSite.Data.Enum;
using TeamSpark.AzureDay.WebSite.Host.Filter;
using TeamSpark.AzureDay.WebSite.Host.Models.Profile;
using TeamSpark.AzureDay.WebSite.Notification;
using TeamSpark.AzureDay.WebSite.Notification.Email.Model;
namespace TeamSpark.AzureDay.WebSite.Host.Controllers
{
public class ProfileController : Controller
{
private readonly string _host = "https://azureday.net";
[Authorize]
public async Task<ActionResult> My()
{
var email = User.Identity.Name;
var attendeeTask = AppFactory.AttendeeService.Value.GetAttendeeByEmailAsync(email);
var ticketTask = AppFactory.TicketService.Value.GetTicketByEmailAsync(email);
await Task.WhenAll(attendeeTask, ticketTask);
var attendee = attendeeTask.Result;
var ticket = ticketTask.Result;
var model = new MyProfileModel
{
Email = attendee.EMail,
LastName = attendee.LastName,
FirstName = attendee.FirstName,
Company = attendee.Company
};
model.Tickets = new List<TicketModel>();
if (ticket == null)
{
if (DateTime.UtcNow.Month <= 5 && DateTime.UtcNow.Day <= 31 && DateTime.UtcNow.Year == 2016)
{
model.Tickets.Add(new TicketModel
{
TicketType = TicketType.EarlyBird,
TicketName = "Ранняя регистрация",
TicketNotes = ""
});
}
else
{
model.Tickets.Add(new TicketModel
{
TicketType = TicketType.Regular,
TicketName = "Стандартный",
TicketNotes = ""
});
}
model.Tickets.Add(new TicketModel
{
TicketType = TicketType.Educational,
TicketName = "Студенческий",
TicketNotes = "Для получения бейджа необходимо предъявить действующий студенческий билет в момент регистрации на конференцию."
});
}
else
{
model.PayedTicket = ticket;
}
return View(model);
}
[Authorize]
[HttpPost]
public async Task<ActionResult> My(MyProfileModel model)
{
var email = User.Identity.Name;
var attendee = await AppFactory.AttendeeService.Value.GetAttendeeByEmailAsync(email);
attendee.EMail = email;
attendee.LastName = model.LastName;
attendee.FirstName = model.FirstName;
attendee.Company = model.Company;
if (!string.IsNullOrEmpty(model.Password))
{
var salt = AppFactory.AttendeeService.Value.GenerateSalt();
var passwordHash = AppFactory.AttendeeService.Value.Hash(model.Password, salt);
attendee.Salt = salt;
attendee.PasswordHash = passwordHash;
}
await AppFactory.AttendeeService.Value.UpdateProfileAsync(attendee);
return RedirectToAction("My");
}
[NonAuthorize]
public ActionResult Registration()
{
return View(new RegistrationModel());
}
[NonAuthorize]
[HttpPost]
public async Task<ActionResult> Registration(RegistrationModel model)
{
var attendeeExisted = await AppFactory.AttendeeService.Value.GetAttendeeByEmailAsync(model.Email);
if (attendeeExisted != null)
{
model.ErrorMessage = "Пользователь с таким адресом электронной почты уже есть в системе. Если вы забыли пароль, то воспользуйтесь функцией восстановления пароля на странице входа в личный кабинет.";
model.Password = string.Empty;
return View(model);
}
var salt = AppFactory.AttendeeService.Value.GenerateSalt();
var passwordHash = AppFactory.AttendeeService.Value.Hash(model.Password, salt);
var attendee = new Attendee
{
EMail = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
Company = model.Company,
Salt = salt,
PasswordHash = passwordHash
};
await AppFactory.AttendeeService.Value.RegisterAsync(attendee);
return RedirectToAction("ConfirmRegistration");
}
[NonAuthorize]
public async Task<ActionResult> ConfirmRegistration(string token)
{
if (string.IsNullOrEmpty(token))
{
return View("ConfirmEmail");
}
var authToken = await AppFactory.QuickAuthTokenService.Value.GetQuickAuthTokenByValueAsync(token, false);
if (authToken == null)
{
return Redirect("~/");
}
await AppFactory.AttendeeService.Value.ConfirmRegistrationByTokenAsync(token);
return View("ConfirmRegistration");
}
[NonAuthorize]
public ActionResult LogIn()
{
var model = new LoginModel();
return View(model);
}
[NonAuthorize]
[HttpPost]
public async Task<ActionResult> LogIn(LoginModel model)
{
var attendee = await AppFactory.AttendeeService.Value.GetAttendeeByEmailAsync(model.Email);
if (attendee == null)
{
model.Password = string.Empty;
model.ErrorMessage = "Неверный email или пароль";
return View(model);
}
if (attendee.IsConfirmed && AppFactory.AttendeeService.Value.IsPasswordValid(attendee, model.Password))
{
FormsAuthentication.SetAuthCookie(attendee.EMail, true);
var url = FormsAuthentication.GetRedirectUrl(attendee.EMail, true);
return Redirect(url);
}
else
{
model.Password = string.Empty;
model.ErrorMessage = "Неверный email или пароль";
return View(model);
}
}
[Authorize]
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
return Redirect("~/");
}
[Authorize]
public async Task<ActionResult> Pay(Ticket ticket)
{
if (ticket == null)
{
return RedirectToAction("My");
}
if (ticket.Attendee == null)
{
var email = User.Identity.Name;
ticket.Attendee = await AppFactory.AttendeeService.Value.GetAttendeeByEmailAsync(email);
}
var model = GetPaymentForm(ticket);
return View("PayForm", model);
}
private PayFormModel GetPaymentForm(Ticket ticket)
{
KaznacheyPaymentSystem kaznachey;
int paySystemId;
switch (ticket.PaymentType.ToLowerInvariant())
{
case "kaznackey":
kaznachey = new KaznacheyPaymentSystem(Configuration.KaznackeyMerchantId, Configuration.KaznackeyMerchantSecreet);
paySystemId = kaznachey.GetMerchantInformation().PaySystems[0].Id;
break;
case "liqpay":
kaznachey = new KaznacheyPaymentSystem(Configuration.LiqPayMerchantId, Configuration.LiqPayMerchantSecreet);
paySystemId = kaznachey.GetMerchantInformation().PaySystems[3].Id;
break;
default:
kaznachey = new KaznacheyPaymentSystem(Configuration.KaznackeyMerchantId, Configuration.KaznackeyMerchantSecreet);
paySystemId = kaznachey.GetMerchantInformation().PaySystems[0].Id;
break;
}
var paymentRequest = new PaymentRequest(paySystemId);
paymentRequest.Language = "RU";
paymentRequest.Currency = "UAH";
paymentRequest.PaymentDetail = new PaymentDetails
{
EMail = ticket.Attendee.EMail,
MerchantInternalUserId = ticket.Attendee.EMail,
MerchantInternalPaymentId = string.Format("{0}-{1}", ticket.Attendee.EMail, ticket.TicketType),
BuyerFirstname = ticket.Attendee.FirstName,
BuyerLastname = ticket.Attendee.LastName,
ReturnUrl = string.Format("{0}/profile/my", _host),
StatusUrl = string.Format("{0}/api/tickets/paymentconfirm", _host)
};
paymentRequest.Products = new List<Product>
{
new Product
{
ProductId = ticket.TicketType.ToString(),
ProductItemsNum = 1,
ProductName = string.Format("{0} {1} билет на AzureDay {2} ({3})",
ticket.Attendee.FirstName,
ticket.Attendee.LastName,
Configuration.Year,
ticket.TicketType.ToDisplayString()),
ProductPrice = (decimal) ticket.Price
}
};
var form = kaznachey.CreatePayment(paymentRequest).ExternalFormHtml;
var model = new PayFormModel
{
Form = form
};
return model;
}
[Authorize]
[HttpPost]
public async Task<ActionResult> Pay(PayModel model)
{
decimal ticketPrice = AppFactory.TicketService.Value.GetTicketPrice(model.TicketType);
var ticket = new Ticket
{
Price = (double)ticketPrice,
TicketType = model.TicketType,
PaymentType = model.PaymentType
};
if (!string.IsNullOrEmpty(model.PromoCode))
{
var coupon = await AppFactory.CouponService.Value.GetValidCouponByCodeAsync(model.PromoCode);
if (coupon != null)
{
ticketPrice = AppFactory.CouponService.Value.GetPriceWithCoupon(ticketPrice, coupon);
await AppFactory.CouponService.Value.UseCouponByCodeAsync(model.PromoCode);
ticket.Price = (double)ticketPrice;
ticket.Coupon = coupon;
}
}
ticket.IsPayed = ticket.Price <= 0;
if (ticket.Attendee == null)
{
var email = User.Identity.Name;
ticket.Attendee = await AppFactory.AttendeeService.Value.GetAttendeeByEmailAsync(email);
}
await AppFactory.TicketService.Value.AddTicketAsync(ticket);
if (ticket.IsPayed)
{
return RedirectToAction("My");
}
else
{
return RedirectToAction("Pay", ticket);
}
}
[Authorize]
public async Task<ActionResult> PayAgain()
{
var email = User.Identity.Name;
var ticketTask = AppFactory.TicketService.Value.GetTicketByEmailAsync(email);
var attendeeTask = AppFactory.AttendeeService.Value.GetAttendeeByEmailAsync(email);
await Task.WhenAll(ticketTask, attendeeTask);
var ticket = ticketTask.Result;
ticket.Attendee = attendeeTask.Result;
var model = GetPaymentForm(ticket);
return View("PayForm", model);
}
[Authorize]
public async Task<ActionResult> DeleteTicket()
{
var email = User.Identity.Name;
var ticket = await AppFactory.TicketService.Value.GetTicketByEmailAsync(email);
await Task.WhenAll(
AppFactory.TicketService.Value.DeleteTicketAsync(email),
AppFactory.CouponService.Value.RestoreCouponByCodeAsync(ticket.Coupon == null ? string.Empty : ticket.Coupon.Code)
);
return RedirectToAction("My");
}
[NonAuthorize]
[HttpPost]
public async Task<ActionResult> RestorePassword(LoginModel model)
{
var user = await AppFactory.AttendeeService.Value.GetAttendeeByEmailAsync(model.Email);
if (user != null)
{
var token = new QuickAuthToken
{
Email = user.EMail,
Token = Guid.NewGuid().ToString("N")
};
var notification = new RestorePasswordMessage
{
Email = user.EMail,
FullName = user.FullName,
Token = token.Token
};
await Task.WhenAll(
AppFactory.QuickAuthTokenService.Value.AddQuickAuthTokenAsync(token),
NotificationFactory.AttendeeNotificationService.Value.SendRestorePasswordEmailAsync(notification)
);
}
return View();
}
//[Authorize]
//public ActionResult Quiz()
//{
// return View();
//}
//[Authorize]
//public ActionResult Feedback()
//{
// return View();
//}
}
} | mit |
fixrb/fix | test/matcher/comparisons/be_within_spec.rb | 233 | # frozen_string_literal: true
require_relative File.join("..", "..", "..", "lib", "fix")
Fix { it MUST be_within(2).of(42) }.against { 40 }
# test/matcher/comparisons/be_within_spec.rb:5 Success: expected 40 to be within 2 of 42.
| mit |
mdejean/Chkdraft | Chkdraft/src/WindowsUI/GroupBoxControl.cpp | 562 | #include "GroupBoxControl.h"
#include <string>
bool GroupBoxControl::CreateThis(HWND hParent, s32 x, s32 y, s32 width, s32 height, const char* initText, u32 id)
{
return WindowControl::CreateControl( 0, "BUTTON", initText, WS_CHILD|WS_VISIBLE|BS_GROUPBOX,
x, y, width, height, hParent, (HMENU)id, false );
}
bool GroupBoxControl::SetText(const std::string& newText)
{
return SetWindowText(getHandle(), newText.c_str()) == TRUE;
}
bool GroupBoxControl::SetText(const char* newText)
{
return SetWindowText(getHandle(), (LPCSTR)newText) == TRUE;
}
| mit |
alexpisquared/Windows-universal-samples | Samples/BackgroundTask/cs/BackgroundTask/Views/BlankPage1.xaml.cs | 775 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace SDKTemplate.Views
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class BlankPage1 : Page
{
public BlankPage1()
{
this.InitializeComponent();
}
}
}
| mit |
Squashy83/meanjs-medical | app/routes/anamnesis.server.routes.js | 704 | 'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var anamnesis = require('../../app/controllers/anamnesis.server.controller');
// Anamnesis Routes
app.route('/anamnesis')
.get(anamnesis.list)
.post(users.requiresLogin, anamnesis.create);
app.route('/anamnesis/:anamnesiId')
.get(anamnesis.read)
.put(users.requiresLogin, anamnesis.hasAuthorization, anamnesis.update)
.delete(users.requiresLogin, anamnesis.hasAuthorization, anamnesis.delete);
app.route('/anamnesist')
.get(anamnesis.listByAnagrafica);
// Finish by binding the Anamnesi middleware
app.param('anamnesiId', anamnesis.anamnesiByID);
};
| mit |
DbUp/DbUp | src/dbup-sqlserver/AzureSqlServerExtensions.cs | 4239 | using System;
using DbUp.Builder;
using DbUp.SqlServer;
#if SUPPORTS_AZURE_AD
/// <summary>Configuration extension methods for Azure SQL Server.</summary>
// NOTE: DO NOT MOVE THIS TO A NAMESPACE
// Since the class just contains extension methods, we leave it in the global:: namespace so that it is always available
// ReSharper disable CheckNamespace
public static class AzureSqlServerExtensions
{
/// <summary>Creates an upgrader for SQL Server databases.</summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="schema">The SQL schema name to use. Defaults to 'dbo' if <see langword="null" />.</param>
/// <param name="useAzureSqlIntegratedSecurity">Whether to use Azure SQL Integrated Security</param>
/// <returns>A builder for a database upgrader designed for SQL Server databases.</returns>
[Obsolete("Use \"AzureSqlDatabaseWithIntegratedSecurity(this SupportedDatabases, string, string)\" if passing \"true\" to \"useAzureSqlIntegratedSecurity\".")]
public static UpgradeEngineBuilder SqlDatabase(this SupportedDatabases supported, string connectionString, string schema, bool useAzureSqlIntegratedSecurity)
{
if (useAzureSqlIntegratedSecurity)
{
return AzureSqlDatabaseWithIntegratedSecurity(supported, connectionString, schema);
}
return supported.SqlDatabase(new SqlConnectionManager(connectionString), schema);
}
/// <summary>Creates an upgrader for Azure SQL Databases using Azure AD Integrated Security.</summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="schema">The SQL schema name to use. Defaults to 'dbo' if <see langword="null" />.</param>
/// <returns>A builder for a database upgrader designed for Azure SQL Server databases.</returns>
public static UpgradeEngineBuilder AzureSqlDatabaseWithIntegratedSecurity(this SupportedDatabases supported, string connectionString, string schema)
{
return supported.SqlDatabase(new AzureSqlConnectionManager(connectionString), schema);
}
/// <summary>Creates an upgrader for Azure SQL Databases using Azure AD Integrated Security.</summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="schema">The SQL schema name to use. Defaults to 'dbo' if <see langword="null" />.</param>
/// <returns>A builder for a database upgrader designed for Azure SQL Server databases.</returns>
public static UpgradeEngineBuilder AzureSqlDatabaseWithIntegratedSecurity(this SupportedDatabases supported, string connectionString, string schema, string resource)
{
return AzureSqlDatabaseWithIntegratedSecurity(supported, connectionString, schema, resource, null);
}
/// <summary>Creates an upgrader for Azure SQL Databases using Azure AD Integrated Security.</summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="schema">The SQL schema name to use. Defaults to 'dbo' if <see langword="null" />.</param>
/// <param name="resource">Resource to access. e.g. https://management.azure.com/.</param>
/// <param name="tenantId">If not specified, default tenant is used. Managed Service Identity REST protocols do not accept tenantId, so this can only be used with certificate and client secret based authentication.</param>
/// <param name="azureAdInstance">Specify a value for clouds other than the Public Cloud.</param>
/// <returns>A builder for a database upgrader designed for Azure SQL Server databases.</returns>
public static UpgradeEngineBuilder AzureSqlDatabaseWithIntegratedSecurity(this SupportedDatabases supported, string connectionString, string schema, string resource, string tenantId, string azureAdInstance = "https://login.microsoftonline.com/")
{
return supported.SqlDatabase(new AzureSqlConnectionManager(connectionString, resource, tenantId, azureAdInstance), schema);
}
}
#endif
| mit |
awahid101/Mist | docs/src/elementlist.js | 335 |
var ApiGen = ApiGen || {};
ApiGen.elements = [["c","Mist\\Core\\Controller\\Controller"],["c","Mist\\Core\\Controller\\Error"],["c","Mist\\Core\\Model\\Model"],["c","Mist\\Core\\Routing\\Router"],["c","Mist\\Core\\Template\\View"],["c","Mist\\Helpers\\Configurations"],["c","Mist\\Helpers\\Database"],["c","Mist\\Helpers\\Session"]];
| mit |
danielwippermann/resol-vbus | test/specs/configuration-optimizers/resol-deltasol-bs4v2-103-configuration-optimizer.spec.js | 2890 | /*! resol-vbus | Copyright (c) 2013-2018, Daniel Wippermann | MIT license */
'use strict';
const {
ConfigurationOptimizerFactory,
} = require('../resol-vbus');
const expect = require('../expect');
const _ = require('../lodash');
const testUtils = require('../test-utils');
const { wrapAsPromise } = testUtils;
const optimizerPromise = ConfigurationOptimizerFactory.createOptimizerByDeviceAddress(0x427B);
describe('ResolDeltaSolBs4V2103ConfigurationOptimizer', () => {
describe('using ConfigurationOptimizerFactory', () => {
it('should work correctly', () => {
return testUtils.expectPromise(optimizerPromise).then((optimizer) => {
expect(optimizer).an('object');
});
});
});
describe('#completeConfiguration', () => {
it('should work correctly', () => {
return optimizerPromise.then((optimizer) => {
return wrapAsPromise(() => {
return testUtils.expectPromise(optimizer.completeConfiguration());
}).then((config) => {
expect(config).an('array').lengthOf(87);
});
});
});
});
describe('#optimizeLoadConfiguration', () => {
it('should work correctly after', () => {
return optimizerPromise.then((optimizer) => {
return wrapAsPromise(() => {
return testUtils.expectPromise(optimizer.completeConfiguration());
}).then((config) => {
return testUtils.expectPromise(optimizer.optimizeLoadConfiguration(config));
}).then((config) => {
expect(config).an('array');
const valueIds = _.reduce(config, (memo, value) => {
if (value.pending) {
memo.push(value.valueId);
}
return memo;
}, []);
expect(valueIds).lengthOf(87);
_.forEach(config, (value) => {
if (value.pending) {
value.pending = false;
value.transceived = true;
value.value = null;
}
});
return testUtils.expectPromise(optimizer.optimizeLoadConfiguration(config));
}).then((config) => {
expect(config).an('array');
const valueIds = _.reduce(config, (memo, value) => {
if (value.pending) {
memo.push(value.valueId);
}
return memo;
}, []);
expect(valueIds).lengthOf(0);
});
});
});
});
});
| mit |
lexbar/colecta | app/stubs/NumberFormatter.php | 969 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Stub implementation for the NumberFormatter class of the intl extension
*
* @author Bernhard Schussek <[email protected]>
* @see Symfony\Component\Locale\Stub\StubNumberFormatter
*/
use Symfony\Component\Locale\Stub\StubNumberFormatter;
class NumberFormatter extends StubNumberFormatter
{
public function getSymbol($attr)
{
switch($attr) {
case NumberFormatter::CURRENCY_SYMBOL:
return '€';
case NumberFormatter::DECIMAL_SEPARATOR_SYMBOL:
return '.';
case NumberFormatter::DIGIT_SYMBOL:
return '#';
case NumberFormatter::EXPONENTIAL_SYMBOL:
return 'E';
case NumberFormatter::GROUPING_SEPARATOR_SYMBOL:
return ',';
;
}
}
}
| mit |
berwin/learn-javascript-design-pattern | chapter28/1.js | 428 | 'use strict';
// bad
var ul = document.getElementById('container');
var li = ul.getElementsByTagName('li');
for (var i = 0; i < li.length; i++) {
li[i].onclick = function() {
this.style.backgroundColor = 'grey';
};
}
// good
ul.onclick = function(e) {
var event = e || event;
var target = e.target || e.srcElement;
if (target.nodeName.toLowerCase() === 'li') {
target.style.backgroundColor = 'grey';
}
}; | mit |
NTaylorMullen/EndGate | EndGate/samples/EndGate.Core.JS.Samples/Content/Samples/Shapes/CustomSlider.ts | 996 | // Wrap in module to keep code out of global scope
module Shapes {
export class CustomSlider {
constructor(private _target: any, private _min: number, private _max: number, private _defaultValue: number, private _onSliderChange: Function) {
var sliderChange = () => {
this.SliderChange();
};
// Build slider with default values
this._target.slider({
orientation: "horizontal",
range: "min",
min: this._min,
max: this._max,
value: this._defaultValue,
animate: true,
slide: sliderChange,
change: sliderChange
});
// This essentially triggers the onSliderChange event with the default values
this.SliderChange();
}
private SliderChange(): void {
this._onSliderChange(parseInt(this._target.slider("value")));
}
}
} | mit |
LePhil/DotNetMiniProj | AutoReservation.Service.Wcf.Testing/Properties/Settings.Designer.cs | 1604 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AutoReservation.Service.Wcf.Testing.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("AutoReservation.BusinessLayer.Test.RemoteServiceCreator, AutoReservation.Business" +
"Layer.Test")]
public string ServiceLayerType {
get {
return ((string)(this["ServiceLayerType"]));
}
}
}
}
| mit |
innogames/gitlabhq | spec/models/group_spec.rb | 92197 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Group do
include ReloadHelpers
let!(:group) { create(:group) }
describe 'associations' do
it { is_expected.to have_many :projects }
it { is_expected.to have_many(:group_members).dependent(:destroy) }
it { is_expected.to have_many(:users).through(:group_members) }
it { is_expected.to have_many(:owners).through(:group_members) }
it { is_expected.to have_many(:requesters).dependent(:destroy) }
it { is_expected.to have_many(:members_and_requesters) }
it { is_expected.to have_many(:project_group_links).dependent(:destroy) }
it { is_expected.to have_many(:shared_projects).through(:project_group_links) }
it { is_expected.to have_many(:notification_settings).dependent(:destroy) }
it { is_expected.to have_many(:labels).class_name('GroupLabel') }
it { is_expected.to have_many(:variables).class_name('Ci::GroupVariable') }
it { is_expected.to have_many(:uploads) }
it { is_expected.to have_one(:chat_team) }
it { is_expected.to have_many(:custom_attributes).class_name('GroupCustomAttribute') }
it { is_expected.to have_many(:badges).class_name('GroupBadge') }
it { is_expected.to have_many(:cluster_groups).class_name('Clusters::Group') }
it { is_expected.to have_many(:clusters).class_name('Clusters::Cluster') }
it { is_expected.to have_many(:container_repositories) }
it { is_expected.to have_many(:milestones) }
it { is_expected.to have_many(:group_deploy_keys) }
it { is_expected.to have_many(:integrations) }
it { is_expected.to have_one(:dependency_proxy_setting) }
it { is_expected.to have_many(:dependency_proxy_blobs) }
it { is_expected.to have_many(:dependency_proxy_manifests) }
it { is_expected.to have_many(:debian_distributions).class_name('Packages::Debian::GroupDistribution').dependent(:destroy) }
it { is_expected.to have_many(:daily_build_group_report_results).class_name('Ci::DailyBuildGroupReportResult') }
describe '#members & #requesters' do
let(:requester) { create(:user) }
let(:developer) { create(:user) }
before do
group.request_access(requester)
group.add_developer(developer)
end
it_behaves_like 'members and requesters associations' do
let(:namespace) { group }
end
end
end
describe 'modules' do
subject { described_class }
it { is_expected.to include_module(Referable) }
end
describe 'validations' do
it { is_expected.to validate_presence_of :name }
it { is_expected.to allow_value('group test_4').for(:name) }
it { is_expected.not_to allow_value('test/../foo').for(:name) }
it { is_expected.not_to allow_value('<script>alert("Attack!")</script>').for(:name) }
it { is_expected.to validate_presence_of :path }
it { is_expected.not_to validate_presence_of :owner }
it { is_expected.to validate_presence_of :two_factor_grace_period }
it { is_expected.to validate_numericality_of(:two_factor_grace_period).is_greater_than_or_equal_to(0) }
context 'validating the parent of a group' do
context 'when the group has no parent' do
it 'allows a group to have no parent associated with it' do
group = build(:group)
expect(group).to be_valid
end
end
context 'when the group has a parent' do
it 'does not allow a group to have a namespace as its parent' do
group = build(:group, parent: build(:namespace))
expect(group).not_to be_valid
expect(group.errors[:parent_id].first).to eq('a group cannot have a user namespace as its parent')
end
it 'allows a group to have another group as its parent' do
group = build(:group, parent: build(:group))
expect(group).to be_valid
end
end
context 'when the feature flag `validate_namespace_parent_type` is disabled' do
before do
stub_feature_flags(validate_namespace_parent_type: false)
end
context 'when the group has no parent' do
it 'allows a group to have no parent associated with it' do
group = build(:group)
expect(group).to be_valid
end
end
context 'when the group has a parent' do
it 'allows a group to have a namespace as its parent' do
group = build(:group, parent: build(:namespace))
expect(group).to be_valid
end
it 'allows a group to have another group as its parent' do
group = build(:group, parent: build(:group))
expect(group).to be_valid
end
end
end
end
describe 'path validation' do
it 'rejects paths reserved on the root namespace when the group has no parent' do
group = build(:group, path: 'api')
expect(group).not_to be_valid
end
it 'allows root paths when the group has a parent' do
group = build(:group, path: 'api', parent: create(:group))
expect(group).to be_valid
end
it 'rejects any wildcard paths when not a top level group' do
group = build(:group, path: 'tree', parent: create(:group))
expect(group).not_to be_valid
end
end
describe '#notification_settings' do
let(:user) { create(:user) }
let(:group) { create(:group) }
let(:sub_group) { create(:group, parent_id: group.id) }
before do
group.add_developer(user)
sub_group.add_maintainer(user)
end
it 'also gets notification settings from parent groups' do
expect(sub_group.notification_settings.size).to eq(2)
expect(sub_group.notification_settings).to include(group.notification_settings.first)
end
context 'when sub group is deleted' do
it 'does not delete parent notification settings' do
expect do
sub_group.destroy
end.to change { NotificationSetting.count }.by(-1)
end
end
end
describe '#notification_email_for' do
let(:user) { create(:user) }
let(:group) { create(:group) }
let(:subgroup) { create(:group, parent: group) }
let(:group_notification_email) { '[email protected]' }
let(:subgroup_notification_email) { '[email protected]' }
before do
create(:email, :confirmed, user: user, email: group_notification_email)
create(:email, :confirmed, user: user, email: subgroup_notification_email)
end
subject { subgroup.notification_email_for(user) }
context 'when both group notification emails are set' do
it 'returns subgroup notification email' do
create(:notification_setting, user: user, source: group, notification_email: group_notification_email)
create(:notification_setting, user: user, source: subgroup, notification_email: subgroup_notification_email)
is_expected.to eq(subgroup_notification_email)
end
end
context 'when subgroup notification email is blank' do
it 'returns parent group notification email' do
create(:notification_setting, user: user, source: group, notification_email: group_notification_email)
create(:notification_setting, user: user, source: subgroup, notification_email: '')
is_expected.to eq(group_notification_email)
end
end
context 'when only the parent group notification email is set' do
it 'returns parent group notification email' do
create(:notification_setting, user: user, source: group, notification_email: group_notification_email)
is_expected.to eq(group_notification_email)
end
end
end
describe '#visibility_level_allowed_by_parent' do
let(:parent) { create(:group, :internal) }
let(:sub_group) { build(:group, parent_id: parent.id) }
context 'without a parent' do
it 'is valid' do
sub_group.parent_id = nil
expect(sub_group).to be_valid
end
end
context 'with a parent' do
context 'when visibility of sub group is greater than the parent' do
it 'is invalid' do
sub_group.visibility_level = Gitlab::VisibilityLevel::PUBLIC
expect(sub_group).to be_invalid
end
end
context 'when visibility of sub group is lower or equal to the parent' do
[Gitlab::VisibilityLevel::INTERNAL, Gitlab::VisibilityLevel::PRIVATE].each do |level|
it 'is valid' do
sub_group.visibility_level = level
expect(sub_group).to be_valid
end
end
end
end
end
describe '#visibility_level_allowed_by_projects' do
let!(:internal_group) { create(:group, :internal) }
let!(:internal_project) { create(:project, :internal, group: internal_group) }
context 'when group has a lower visibility' do
it 'is invalid' do
internal_group.visibility_level = Gitlab::VisibilityLevel::PRIVATE
expect(internal_group).to be_invalid
expect(internal_group.errors[:visibility_level]).to include('private is not allowed since this group contains projects with higher visibility.')
end
end
context 'when group has a higher visibility' do
it 'is valid' do
internal_group.visibility_level = Gitlab::VisibilityLevel::PUBLIC
expect(internal_group).to be_valid
end
end
end
describe '#visibility_level_allowed_by_sub_groups' do
let!(:internal_group) { create(:group, :internal) }
let!(:internal_sub_group) { create(:group, :internal, parent: internal_group) }
context 'when parent group has a lower visibility' do
it 'is invalid' do
internal_group.visibility_level = Gitlab::VisibilityLevel::PRIVATE
expect(internal_group).to be_invalid
expect(internal_group.errors[:visibility_level]).to include('private is not allowed since there are sub-groups with higher visibility.')
end
end
context 'when parent group has a higher visibility' do
it 'is valid' do
internal_group.visibility_level = Gitlab::VisibilityLevel::PUBLIC
expect(internal_group).to be_valid
end
end
end
describe '#two_factor_authentication_allowed' do
let_it_be_with_reload(:group) { create(:group) }
context 'for a parent group' do
it 'is valid' do
group.require_two_factor_authentication = true
expect(group).to be_valid
end
end
context 'for a child group' do
let(:sub_group) { create(:group, parent: group) }
it 'is valid when parent group allows' do
sub_group.require_two_factor_authentication = true
expect(sub_group).to be_valid
end
it 'is invalid when parent group blocks' do
group.namespace_settings.update!(allow_mfa_for_subgroups: false)
sub_group.require_two_factor_authentication = true
expect(sub_group).to be_invalid
expect(sub_group.errors[:require_two_factor_authentication]).to include('is forbidden by a top-level group')
end
end
end
end
context 'traversal_ids on create' do
context 'default traversal_ids' do
let(:group) { build(:group) }
before do
group.save!
group.reload
end
it { expect(group.traversal_ids).to eq [group.id] }
end
context 'has a parent' do
let(:parent) { create(:group) }
let(:group) { build(:group, parent: parent) }
before do
group.save!
reload_models(parent, group)
end
it { expect(parent.traversal_ids).to eq [parent.id] }
it { expect(group.traversal_ids).to eq [parent.id, group.id] }
end
context 'has a parent update before save' do
let(:parent) { create(:group) }
let(:group) { build(:group, parent: parent) }
let!(:new_grandparent) { create(:group) }
before do
parent.update!(parent: new_grandparent)
group.save!
reload_models(parent, group)
end
it 'avoid traversal_ids race condition' do
expect(parent.traversal_ids).to eq [new_grandparent.id, parent.id]
expect(group.traversal_ids).to eq [new_grandparent.id, parent.id, group.id]
end
end
end
context 'traversal_ids on update' do
context 'parent is updated' do
let(:new_parent) { create(:group) }
subject {group.update!(parent: new_parent, name: 'new name') }
it_behaves_like 'update on column', :traversal_ids
end
context 'parent is not updated' do
subject { group.update!(name: 'new name') }
it_behaves_like 'no update on column', :traversal_ids
end
end
context 'traversal_ids on ancestral update' do
context 'update multiple ancestors before save' do
let(:parent) { create(:group) }
let(:group) { create(:group, parent: parent) }
let!(:new_grandparent) { create(:group) }
let!(:new_parent) { create(:group) }
before do
group.parent = new_parent
new_parent.update!(parent: new_grandparent)
group.save!
reload_models(parent, group, new_grandparent, new_parent)
end
it 'avoids traversal_ids race condition' do
expect(parent.traversal_ids).to eq [parent.id]
expect(group.traversal_ids).to eq [new_grandparent.id, new_parent.id, group.id]
expect(new_grandparent.traversal_ids).to eq [new_grandparent.id]
expect(new_parent.traversal_ids).to eq [new_grandparent.id, new_parent.id]
end
end
context 'assign a new parent' do
let!(:group) { create(:group, parent: old_parent) }
let(:recorded_queries) { ActiveRecord::QueryRecorder.new }
subject do
recorded_queries.record do
group.update(parent: new_parent)
end
end
before do
subject
reload_models(old_parent, new_parent, group)
end
context 'within the same hierarchy' do
let!(:root) { create(:group).reload }
let!(:old_parent) { create(:group, parent: root) }
let!(:new_parent) { create(:group, parent: root) }
it 'updates traversal_ids' do
expect(group.traversal_ids).to eq [root.id, new_parent.id, group.id]
end
it_behaves_like 'hierarchy with traversal_ids'
it_behaves_like 'locked row' do
let(:row) { root }
end
end
context 'to another hierarchy' do
let!(:old_parent) { create(:group) }
let!(:new_parent) { create(:group) }
let!(:group) { create(:group, parent: old_parent) }
it 'updates traversal_ids' do
expect(group.traversal_ids).to eq [new_parent.id, group.id]
end
it_behaves_like 'locked rows' do
let(:rows) { [old_parent, new_parent] }
end
context 'old hierarchy' do
let(:root) { old_parent.root_ancestor }
it_behaves_like 'hierarchy with traversal_ids'
end
context 'new hierarchy' do
let(:root) { new_parent.root_ancestor }
it_behaves_like 'hierarchy with traversal_ids'
end
end
context 'from being a root ancestor' do
let!(:old_parent) { nil }
let!(:new_parent) { create(:group) }
it 'updates traversal_ids' do
expect(group.traversal_ids).to eq [new_parent.id, group.id]
end
it_behaves_like 'locked rows' do
let(:rows) { [group, new_parent] }
end
it_behaves_like 'hierarchy with traversal_ids' do
let(:root) { new_parent }
end
end
context 'to being a root ancestor' do
let!(:old_parent) { create(:group) }
let!(:new_parent) { nil }
it 'updates traversal_ids' do
expect(group.traversal_ids).to eq [group.id]
end
it_behaves_like 'locked rows' do
let(:rows) { [old_parent, group] }
end
it_behaves_like 'hierarchy with traversal_ids' do
let(:root) { group }
end
end
end
context 'assigning a new grandparent' do
let!(:old_grandparent) { create(:group) }
let!(:new_grandparent) { create(:group) }
let!(:parent_group) { create(:group, parent: old_grandparent) }
let!(:group) { create(:group, parent: parent_group) }
before do
parent_group.update(parent: new_grandparent)
end
it 'updates traversal_ids for all descendants' do
expect(parent_group.reload.traversal_ids).to eq [new_grandparent.id, parent_group.id]
expect(group.reload.traversal_ids).to eq [new_grandparent.id, parent_group.id, group.id]
end
end
end
context 'traversal queries' do
let_it_be(:group, reload: true) { create(:group, :nested) }
context 'recursive' do
before do
stub_feature_flags(use_traversal_ids: false)
end
it_behaves_like 'namespace traversal'
describe '#self_and_descendants' do
it { expect(group.self_and_descendants.to_sql).not_to include 'traversal_ids @>' }
end
describe '#self_and_descendant_ids' do
it { expect(group.self_and_descendant_ids.to_sql).not_to include 'traversal_ids @>' }
end
describe '#descendants' do
it { expect(group.descendants.to_sql).not_to include 'traversal_ids @>' }
end
describe '#ancestors' do
it { expect(group.ancestors.to_sql).not_to include 'traversal_ids <@' }
end
end
context 'linear' do
it_behaves_like 'namespace traversal'
describe '#self_and_descendants' do
it { expect(group.self_and_descendants.to_sql).to include 'traversal_ids @>' }
end
describe '#self_and_descendant_ids' do
it { expect(group.self_and_descendant_ids.to_sql).to include 'traversal_ids @>' }
end
describe '#descendants' do
it { expect(group.descendants.to_sql).to include 'traversal_ids @>' }
end
describe '#ancestors' do
it { expect(group.ancestors.to_sql).to include "\"namespaces\".\"id\" = #{group.parent_id}" }
it 'hierarchy order' do
expect(group.ancestors(hierarchy_order: :asc).to_sql).to include 'ORDER BY "depth" ASC'
end
context 'ancestor linear queries feature flag disabled' do
before do
stub_feature_flags(use_traversal_ids_for_ancestors: false)
end
it { expect(group.ancestors.to_sql).not_to include 'traversal_ids <@' }
end
end
end
end
describe '.without_integration' do
let(:another_group) { create(:group) }
let(:instance_integration) { build(:jira_service, :instance) }
before do
create(:jira_service, group: group, project: nil)
create(:slack_service, group: another_group, project: nil)
end
it 'returns groups without integration' do
expect(Group.without_integration(instance_integration)).to contain_exactly(another_group)
end
end
describe '.public_or_visible_to_user' do
let!(:private_group) { create(:group, :private) }
let!(:internal_group) { create(:group, :internal) }
subject { described_class.public_or_visible_to_user(user) }
context 'when user is nil' do
let!(:user) { nil }
it { is_expected.to match_array([group]) }
end
context 'when user' do
let!(:user) { create(:user) }
context 'when user does not have access to any private group' do
it { is_expected.to match_array([internal_group, group]) }
end
context 'when user is a member of private group' do
before do
private_group.add_user(user, Gitlab::Access::DEVELOPER)
end
it { is_expected.to match_array([private_group, internal_group, group]) }
end
context 'when user is a member of private subgroup' do
let!(:private_subgroup) { create(:group, :private, parent: private_group) }
before do
private_subgroup.add_user(user, Gitlab::Access::DEVELOPER)
end
it { is_expected.to match_array([private_subgroup, internal_group, group]) }
end
end
end
describe 'scopes' do
let_it_be(:private_group) { create(:group, :private) }
let_it_be(:internal_group) { create(:group, :internal) }
let_it_be(:user1) { create(:user) }
let_it_be(:user2) { create(:user) }
describe 'public_only' do
subject { described_class.public_only.to_a }
it { is_expected.to eq([group]) }
end
describe 'public_and_internal_only' do
subject { described_class.public_and_internal_only.to_a }
it { is_expected.to match_array([group, internal_group]) }
end
describe 'non_public_only' do
subject { described_class.non_public_only.to_a }
it { is_expected.to match_array([private_group, internal_group]) }
end
describe 'with_onboarding_progress' do
subject { described_class.with_onboarding_progress }
it 'joins onboarding_progress' do
create(:onboarding_progress, namespace: group)
expect(subject).to eq([group])
end
end
describe 'for_authorized_group_members' do
let_it_be(:group_member1) { create(:group_member, source: private_group, user_id: user1.id, access_level: Gitlab::Access::OWNER) }
it do
result = described_class.for_authorized_group_members([user1.id, user2.id])
expect(result).to match_array([private_group])
end
end
describe 'for_authorized_project_members' do
let_it_be(:project) { create(:project, group: internal_group) }
let_it_be(:project_member1) { create(:project_member, source: project, user_id: user1.id, access_level: Gitlab::Access::DEVELOPER) }
it do
result = described_class.for_authorized_project_members([user1.id, user2.id])
expect(result).to match_array([internal_group])
end
end
end
describe '#to_reference' do
it 'returns a String reference to the object' do
expect(group.to_reference).to eq "@#{group.name}"
end
end
describe '#users' do
it { expect(group.users).to eq(group.owners) }
end
describe '#human_name' do
it { expect(group.human_name).to eq(group.name) }
end
describe '#add_user' do
let(:user) { create(:user) }
before do
group.add_user(user, GroupMember::MAINTAINER)
end
it { expect(group.group_members.maintainers.map(&:user)).to include(user) }
end
describe '#add_users' do
let(:user) { create(:user) }
before do
group.add_users([user.id], GroupMember::GUEST)
end
it "updates the group permission" do
expect(group.group_members.guests.map(&:user)).to include(user)
group.add_users([user.id], GroupMember::DEVELOPER)
expect(group.group_members.developers.map(&:user)).to include(user)
expect(group.group_members.guests.map(&:user)).not_to include(user)
end
end
describe '#avatar_type' do
let(:user) { create(:user) }
before do
group.add_user(user, GroupMember::MAINTAINER)
end
it "is true if avatar is image" do
group.update_attribute(:avatar, 'uploads/avatar.png')
expect(group.avatar_type).to be_truthy
end
it "is false if avatar is html page" do
group.update_attribute(:avatar, 'uploads/avatar.html')
group.avatar_type
expect(group.errors.added?(:avatar, "file format is not supported. Please try one of the following supported formats: png, jpg, jpeg, gif, bmp, tiff, ico, webp")).to be true
end
end
describe '#avatar_url' do
let!(:group) { create(:group, :with_avatar) }
let(:user) { create(:user) }
context 'when avatar file is uploaded' do
before do
group.add_maintainer(user)
end
it 'shows correct avatar url' do
expect(group.avatar_url).to eq(group.avatar.url)
expect(group.avatar_url(only_path: false)).to eq([Gitlab.config.gitlab.url, group.avatar.url].join)
end
end
end
describe '.search' do
it 'returns groups with a matching name' do
expect(described_class.search(group.name)).to eq([group])
end
it 'returns groups with a partially matching name' do
expect(described_class.search(group.name[0..2])).to eq([group])
end
it 'returns groups with a matching name regardless of the casing' do
expect(described_class.search(group.name.upcase)).to eq([group])
end
it 'returns groups with a matching path' do
expect(described_class.search(group.path)).to eq([group])
end
it 'returns groups with a partially matching path' do
expect(described_class.search(group.path[0..2])).to eq([group])
end
it 'returns groups with a matching path regardless of the casing' do
expect(described_class.search(group.path.upcase)).to eq([group])
end
end
describe '#has_owner?' do
before do
@members = setup_group_members(group)
create(:group_member, :invited, :owner, group: group)
end
it { expect(group.has_owner?(@members[:owner])).to be_truthy }
it { expect(group.has_owner?(@members[:maintainer])).to be_falsey }
it { expect(group.has_owner?(@members[:developer])).to be_falsey }
it { expect(group.has_owner?(@members[:reporter])).to be_falsey }
it { expect(group.has_owner?(@members[:guest])).to be_falsey }
it { expect(group.has_owner?(@members[:requester])).to be_falsey }
it { expect(group.has_owner?(nil)).to be_falsey }
end
describe '#has_maintainer?' do
before do
@members = setup_group_members(group)
create(:group_member, :invited, :maintainer, group: group)
end
it { expect(group.has_maintainer?(@members[:owner])).to be_falsey }
it { expect(group.has_maintainer?(@members[:maintainer])).to be_truthy }
it { expect(group.has_maintainer?(@members[:developer])).to be_falsey }
it { expect(group.has_maintainer?(@members[:reporter])).to be_falsey }
it { expect(group.has_maintainer?(@members[:guest])).to be_falsey }
it { expect(group.has_maintainer?(@members[:requester])).to be_falsey }
it { expect(group.has_maintainer?(nil)).to be_falsey }
end
describe '#last_owner?' do
before do
@members = setup_group_members(group)
end
it { expect(group.last_owner?(@members[:owner])).to be_truthy }
context 'with two owners' do
before do
create(:group_member, :owner, group: group)
end
it { expect(group.last_owner?(@members[:owner])).to be_falsy }
end
context 'with owners from a parent' do
before do
parent_group = create(:group)
create(:group_member, :owner, group: parent_group)
group.update(parent: parent_group)
end
it { expect(group.last_owner?(@members[:owner])).to be_falsy }
end
end
describe '#member_last_blocked_owner?' do
let_it_be(:blocked_user) { create(:user, :blocked) }
let(:member) { blocked_user.group_members.last }
before do
group.add_user(blocked_user, GroupMember::OWNER)
end
context 'when last_blocked_owner is set' do
before do
expect(group).not_to receive(:members_with_parents)
end
it 'returns true' do
member.last_blocked_owner = true
expect(group.member_last_blocked_owner?(member)).to be(true)
end
it 'returns false' do
member.last_blocked_owner = false
expect(group.member_last_blocked_owner?(member)).to be(false)
end
end
context 'when last_blocked_owner is not set' do
it { expect(group.member_last_blocked_owner?(member)).to be(true) }
context 'with another active owner' do
before do
group.add_user(create(:user), GroupMember::OWNER)
end
it { expect(group.member_last_blocked_owner?(member)).to be(false) }
end
context 'with 2 blocked owners' do
before do
group.add_user(create(:user, :blocked), GroupMember::OWNER)
end
it { expect(group.member_last_blocked_owner?(member)).to be(false) }
end
context 'with owners from a parent' do
before do
parent_group = create(:group)
create(:group_member, :owner, group: parent_group)
group.update(parent: parent_group)
end
it { expect(group.member_last_blocked_owner?(member)).to be(false) }
end
end
end
context 'when analyzing blocked owners' do
let_it_be(:blocked_user) { create(:user, :blocked) }
describe '#single_blocked_owner?' do
context 'when there is only one blocked owner' do
before do
group.add_user(blocked_user, GroupMember::OWNER)
end
it 'returns true' do
expect(group.single_blocked_owner?).to eq(true)
end
end
context 'when there are multiple blocked owners' do
let_it_be(:blocked_user_2) { create(:user, :blocked) }
before do
group.add_user(blocked_user, GroupMember::OWNER)
group.add_user(blocked_user_2, GroupMember::OWNER)
end
it 'returns true' do
expect(group.single_blocked_owner?).to eq(false)
end
end
context 'when there are no blocked owners' do
it 'returns false' do
expect(group.single_blocked_owner?).to eq(false)
end
end
end
describe '#blocked_owners' do
let_it_be(:user) { create(:user) }
before do
group.add_user(blocked_user, GroupMember::OWNER)
group.add_user(user, GroupMember::OWNER)
end
it 'has only blocked owners' do
expect(group.blocked_owners.map(&:user)).to match([blocked_user])
end
end
end
describe '#single_owner?' do
let_it_be(:user) { create(:user) }
context 'when there is only one owner' do
before do
group.add_user(user, GroupMember::OWNER)
end
it 'returns true' do
expect(group.single_owner?).to eq(true)
end
end
context 'when there are multiple owners' do
let_it_be(:user_2) { create(:user) }
before do
group.add_user(user, GroupMember::OWNER)
group.add_user(user_2, GroupMember::OWNER)
end
it 'returns true' do
expect(group.single_owner?).to eq(false)
end
end
context 'when there are no owners' do
it 'returns false' do
expect(group.single_owner?).to eq(false)
end
end
end
describe '#member_last_owner?' do
let_it_be(:user) { create(:user) }
let(:member) { group.members.last }
before do
group.add_user(user, GroupMember::OWNER)
end
context 'when last_owner is set' do
before do
expect(group).not_to receive(:last_owner?)
end
it 'returns true' do
member.last_owner = true
expect(group.member_last_owner?(member)).to be(true)
end
it 'returns false' do
member.last_owner = false
expect(group.member_last_owner?(member)).to be(false)
end
end
context 'when last_owner is not set' do
it 'returns true' do
expect(group).to receive(:last_owner?).and_call_original
expect(group.member_last_owner?(member)).to be(true)
end
end
end
describe '#lfs_enabled?' do
context 'LFS enabled globally' do
before do
allow(Gitlab.config.lfs).to receive(:enabled).and_return(true)
end
it 'returns true when nothing is set' do
expect(group.lfs_enabled?).to be_truthy
end
it 'returns false when set to false' do
group.update_attribute(:lfs_enabled, false)
expect(group.lfs_enabled?).to be_falsey
end
it 'returns true when set to true' do
group.update_attribute(:lfs_enabled, true)
expect(group.lfs_enabled?).to be_truthy
end
end
context 'LFS disabled globally' do
before do
allow(Gitlab.config.lfs).to receive(:enabled).and_return(false)
end
it 'returns false when nothing is set' do
expect(group.lfs_enabled?).to be_falsey
end
it 'returns false when set to false' do
group.update_attribute(:lfs_enabled, false)
expect(group.lfs_enabled?).to be_falsey
end
it 'returns false when set to true' do
group.update_attribute(:lfs_enabled, true)
expect(group.lfs_enabled?).to be_falsey
end
end
end
describe '#owners' do
let(:owner) { create(:user) }
let(:developer) { create(:user) }
it 'returns the owners of a Group' do
group.add_owner(owner)
group.add_developer(developer)
expect(group.owners).to eq([owner])
end
end
def setup_group_members(group)
members = {
owner: create(:user),
maintainer: create(:user),
developer: create(:user),
reporter: create(:user),
guest: create(:user),
requester: create(:user)
}
group.add_user(members[:owner], GroupMember::OWNER)
group.add_user(members[:maintainer], GroupMember::MAINTAINER)
group.add_user(members[:developer], GroupMember::DEVELOPER)
group.add_user(members[:reporter], GroupMember::REPORTER)
group.add_user(members[:guest], GroupMember::GUEST)
group.request_access(members[:requester])
members
end
describe '#web_url' do
it 'returns the canonical URL' do
expect(group.web_url).to include("groups/#{group.name}")
end
context 'nested group' do
let(:nested_group) { create(:group, :nested) }
it { expect(nested_group.web_url).to include("groups/#{nested_group.full_path}") }
end
end
describe 'nested group' do
subject { build(:group, :nested) }
it { is_expected.to be_valid }
it { expect(subject.parent).to be_kind_of(described_class) }
end
describe '#max_member_access_for_user' do
let_it_be(:group_user) { create(:user) }
context 'with user in the group' do
before do
group.add_owner(group_user)
end
it 'returns correct access level' do
expect(group.max_member_access_for_user(group_user)).to eq(Gitlab::Access::OWNER)
end
end
context 'when user is nil' do
it 'returns NO_ACCESS' do
expect(group.max_member_access_for_user(nil)).to eq(Gitlab::Access::NO_ACCESS)
end
end
context 'evaluating admin access level' do
let_it_be(:admin) { create(:admin) }
context 'when admin mode is enabled', :enable_admin_mode do
it 'returns OWNER by default' do
expect(group.max_member_access_for_user(admin)).to eq(Gitlab::Access::OWNER)
end
end
context 'when admin mode is disabled' do
it 'returns NO_ACCESS' do
expect(group.max_member_access_for_user(admin)).to eq(Gitlab::Access::NO_ACCESS)
end
end
it 'returns NO_ACCESS when only concrete membership should be considered' do
expect(group.max_member_access_for_user(admin, only_concrete_membership: true))
.to eq(Gitlab::Access::NO_ACCESS)
end
end
context 'group shared with another group' do
let_it_be(:parent_group_user) { create(:user) }
let_it_be(:child_group_user) { create(:user) }
let_it_be(:group_parent) { create(:group, :private) }
let_it_be(:group) { create(:group, :private, parent: group_parent) }
let_it_be(:group_child) { create(:group, :private, parent: group) }
let_it_be(:shared_group_parent) { create(:group, :private) }
let_it_be(:shared_group) { create(:group, :private, parent: shared_group_parent) }
let_it_be(:shared_group_child) { create(:group, :private, parent: shared_group) }
before do
group_parent.add_owner(parent_group_user)
group.add_owner(group_user)
group_child.add_owner(child_group_user)
create(:group_group_link, { shared_with_group: group,
shared_group: shared_group,
group_access: GroupMember::DEVELOPER })
end
context 'with user in the group' do
it 'returns correct access level' do
expect(shared_group_parent.max_member_access_for_user(group_user)).to eq(Gitlab::Access::NO_ACCESS)
expect(shared_group.max_member_access_for_user(group_user)).to eq(Gitlab::Access::DEVELOPER)
expect(shared_group_child.max_member_access_for_user(group_user)).to eq(Gitlab::Access::DEVELOPER)
end
context 'with lower group access level than max access level for share' do
let(:user) { create(:user) }
it 'returns correct access level' do
group.add_reporter(user)
expect(shared_group_parent.max_member_access_for_user(user)).to eq(Gitlab::Access::NO_ACCESS)
expect(shared_group.max_member_access_for_user(user)).to eq(Gitlab::Access::REPORTER)
expect(shared_group_child.max_member_access_for_user(user)).to eq(Gitlab::Access::REPORTER)
end
end
end
context 'with user in the parent group' do
it 'returns correct access level' do
expect(shared_group_parent.max_member_access_for_user(parent_group_user)).to eq(Gitlab::Access::NO_ACCESS)
expect(shared_group.max_member_access_for_user(parent_group_user)).to eq(Gitlab::Access::NO_ACCESS)
expect(shared_group_child.max_member_access_for_user(parent_group_user)).to eq(Gitlab::Access::NO_ACCESS)
end
end
context 'with user in the child group' do
it 'returns correct access level' do
expect(shared_group_parent.max_member_access_for_user(child_group_user)).to eq(Gitlab::Access::NO_ACCESS)
expect(shared_group.max_member_access_for_user(child_group_user)).to eq(Gitlab::Access::NO_ACCESS)
expect(shared_group_child.max_member_access_for_user(child_group_user)).to eq(Gitlab::Access::NO_ACCESS)
end
end
context 'unrelated project owner' do
let(:common_id) { [Project.maximum(:id).to_i, Namespace.maximum(:id).to_i].max + 999 }
let!(:group) { create(:group, id: common_id) }
let!(:unrelated_project) { create(:project, id: common_id) }
let(:user) { unrelated_project.owner }
it 'returns correct access level' do
expect(shared_group_parent.max_member_access_for_user(user)).to eq(Gitlab::Access::NO_ACCESS)
expect(shared_group.max_member_access_for_user(user)).to eq(Gitlab::Access::NO_ACCESS)
expect(shared_group_child.max_member_access_for_user(user)).to eq(Gitlab::Access::NO_ACCESS)
end
end
context 'user without accepted access request' do
let!(:user) { create(:user) }
before do
create(:group_member, :developer, :access_request, user: user, group: group)
end
it 'returns correct access level' do
expect(shared_group_parent.max_member_access_for_user(user)).to eq(Gitlab::Access::NO_ACCESS)
expect(shared_group.max_member_access_for_user(user)).to eq(Gitlab::Access::NO_ACCESS)
expect(shared_group_child.max_member_access_for_user(user)).to eq(Gitlab::Access::NO_ACCESS)
end
end
end
context 'multiple groups shared with group' do
let(:user) { create(:user) }
let(:group) { create(:group, :private) }
let(:shared_group_parent) { create(:group, :private) }
let(:shared_group) { create(:group, :private, parent: shared_group_parent) }
before do
group.add_owner(user)
create(:group_group_link, { shared_with_group: group,
shared_group: shared_group,
group_access: GroupMember::DEVELOPER })
create(:group_group_link, { shared_with_group: group,
shared_group: shared_group_parent,
group_access: GroupMember::MAINTAINER })
end
it 'returns correct access level' do
expect(shared_group.max_member_access_for_user(user)).to eq(Gitlab::Access::MAINTAINER)
end
end
end
describe '#direct_members' do
let_it_be(:group) { create(:group, :nested) }
let_it_be(:maintainer) { group.parent.add_user(create(:user), GroupMember::MAINTAINER) }
let_it_be(:developer) { group.add_user(create(:user), GroupMember::DEVELOPER) }
it 'does not return members of the parent' do
expect(group.direct_members).not_to include(maintainer)
end
it 'returns the direct member of the group' do
expect(group.direct_members).to include(developer)
end
context 'group sharing' do
let!(:shared_group) { create(:group) }
before do
create(:group_group_link, shared_group: shared_group, shared_with_group: group)
end
it 'does not return members of the shared_with group' do
expect(shared_group.direct_members).not_to(
include(developer))
end
end
end
shared_examples_for 'members_with_parents' do
let!(:group) { create(:group, :nested) }
let!(:maintainer) { group.parent.add_user(create(:user), GroupMember::MAINTAINER) }
let!(:developer) { group.add_user(create(:user), GroupMember::DEVELOPER) }
it 'returns parents members' do
expect(group.members_with_parents).to include(developer)
expect(group.members_with_parents).to include(maintainer)
end
context 'group sharing' do
let!(:shared_group) { create(:group) }
before do
create(:group_group_link, shared_group: shared_group, shared_with_group: group)
end
it 'returns shared with group members' do
expect(shared_group.members_with_parents).to(
include(developer))
end
end
end
describe '#members_with_parents' do
it_behaves_like 'members_with_parents'
end
describe '#authorizable_members_with_parents' do
let(:group) { create(:group) }
it_behaves_like 'members_with_parents'
context 'members with associated user but also having invite_token' do
let!(:member) { create(:group_member, :developer, :invited, user: create(:user), group: group) }
it 'includes such members in the result' do
expect(group.authorizable_members_with_parents).to include(member)
end
end
context 'invited members' do
let!(:member) { create(:group_member, :developer, :invited, group: group) }
it 'does not include such members in the result' do
expect(group.authorizable_members_with_parents).not_to include(member)
end
end
context 'members from group shares' do
let(:shared_group) { group }
let(:shared_with_group) { create(:group) }
before do
create(:group_group_link, shared_group: shared_group, shared_with_group: shared_with_group)
end
context 'an invited member that is part of the shared_with_group' do
let!(:member) { create(:group_member, :developer, :invited, group: shared_with_group) }
it 'does not include such members in the result' do
expect(shared_group.authorizable_members_with_parents).not_to(
include(member))
end
end
end
end
describe '#members_from_self_and_ancestors_with_effective_access_level' do
let!(:group_parent) { create(:group, :private) }
let!(:group) { create(:group, :private, parent: group_parent) }
let!(:group_child) { create(:group, :private, parent: group) }
let!(:user) { create(:user) }
let(:parent_group_access_level) { Gitlab::Access::REPORTER }
let(:group_access_level) { Gitlab::Access::DEVELOPER }
let(:child_group_access_level) { Gitlab::Access::MAINTAINER }
before do
create(:group_member, user: user, group: group_parent, access_level: parent_group_access_level)
create(:group_member, user: user, group: group, access_level: group_access_level)
create(:group_member, :minimal_access, user: create(:user), source: group)
create(:group_member, user: user, group: group_child, access_level: child_group_access_level)
end
it 'returns effective access level for user' do
expect(group_parent.members_from_self_and_ancestors_with_effective_access_level.as_json).to(
contain_exactly(
hash_including('user_id' => user.id, 'access_level' => parent_group_access_level)
)
)
expect(group.members_from_self_and_ancestors_with_effective_access_level.as_json).to(
contain_exactly(
hash_including('user_id' => user.id, 'access_level' => group_access_level)
)
)
expect(group_child.members_from_self_and_ancestors_with_effective_access_level.as_json).to(
contain_exactly(
hash_including('user_id' => user.id, 'access_level' => child_group_access_level)
)
)
end
end
context 'members-related methods' do
let!(:group) { create(:group, :nested) }
let!(:sub_group) { create(:group, parent: group) }
let!(:maintainer) { group.parent.add_user(create(:user), GroupMember::MAINTAINER) }
let!(:developer) { group.add_user(create(:user), GroupMember::DEVELOPER) }
let!(:other_developer) { group.add_user(create(:user), GroupMember::DEVELOPER) }
describe '#direct_and_indirect_members' do
it 'returns parents members' do
expect(group.direct_and_indirect_members).to include(developer)
expect(group.direct_and_indirect_members).to include(maintainer)
end
it 'returns descendant members' do
expect(group.direct_and_indirect_members).to include(other_developer)
end
end
describe '#direct_and_indirect_members_with_inactive' do
let!(:maintainer_blocked) { group.parent.add_user(create(:user, :blocked), GroupMember::MAINTAINER) }
it 'returns parents members' do
expect(group.direct_and_indirect_members_with_inactive).to include(developer)
expect(group.direct_and_indirect_members_with_inactive).to include(maintainer)
expect(group.direct_and_indirect_members_with_inactive).to include(maintainer_blocked)
end
it 'returns descendant members' do
expect(group.direct_and_indirect_members_with_inactive).to include(other_developer)
end
end
end
describe '#users_with_descendants' do
let(:user_a) { create(:user) }
let(:user_b) { create(:user) }
let(:group) { create(:group) }
let(:nested_group) { create(:group, parent: group) }
let(:deep_nested_group) { create(:group, parent: nested_group) }
it 'returns member users on every nest level without duplication' do
group.add_developer(user_a)
nested_group.add_developer(user_b)
deep_nested_group.add_maintainer(user_a)
expect(group.users_with_descendants).to contain_exactly(user_a, user_b)
expect(nested_group.users_with_descendants).to contain_exactly(user_a, user_b)
expect(deep_nested_group.users_with_descendants).to contain_exactly(user_a)
end
end
context 'user-related methods' do
let(:user_a) { create(:user) }
let(:user_b) { create(:user) }
let(:user_c) { create(:user) }
let(:user_d) { create(:user) }
let(:group) { create(:group) }
let(:nested_group) { create(:group, parent: group) }
let(:deep_nested_group) { create(:group, parent: nested_group) }
let(:project) { create(:project, namespace: group) }
before do
group.add_developer(user_a)
group.add_developer(user_c)
nested_group.add_developer(user_b)
deep_nested_group.add_developer(user_a)
project.add_developer(user_d)
end
describe '#direct_and_indirect_users' do
it 'returns member users on every nest level without duplication' do
expect(group.direct_and_indirect_users).to contain_exactly(user_a, user_b, user_c, user_d)
expect(nested_group.direct_and_indirect_users).to contain_exactly(user_a, user_b, user_c)
expect(deep_nested_group.direct_and_indirect_users).to contain_exactly(user_a, user_b, user_c)
end
it 'does not return members of projects belonging to ancestor groups' do
expect(nested_group.direct_and_indirect_users).not_to include(user_d)
end
end
describe '#direct_and_indirect_users_with_inactive' do
let(:user_blocked_1) { create(:user, :blocked) }
let(:user_blocked_2) { create(:user, :blocked) }
let(:user_blocked_3) { create(:user, :blocked) }
let(:project_in_group) { create(:project, namespace: nested_group) }
before do
group.add_developer(user_blocked_1)
nested_group.add_developer(user_blocked_1)
deep_nested_group.add_developer(user_blocked_2)
project_in_group.add_developer(user_blocked_3)
end
it 'returns member users on every nest level without duplication' do
expect(group.direct_and_indirect_users_with_inactive).to contain_exactly(user_a, user_b, user_c, user_d, user_blocked_1, user_blocked_2, user_blocked_3)
expect(nested_group.direct_and_indirect_users_with_inactive).to contain_exactly(user_a, user_b, user_c, user_blocked_1, user_blocked_2, user_blocked_3)
expect(deep_nested_group.direct_and_indirect_users_with_inactive).to contain_exactly(user_a, user_b, user_c, user_blocked_1, user_blocked_2)
end
it 'returns members of projects belonging to group' do
expect(nested_group.direct_and_indirect_users_with_inactive).to include(user_blocked_3)
end
end
end
describe '#project_users_with_descendants' do
let(:user_a) { create(:user) }
let(:user_b) { create(:user) }
let(:user_c) { create(:user) }
let(:group) { create(:group) }
let(:nested_group) { create(:group, parent: group) }
let(:deep_nested_group) { create(:group, parent: nested_group) }
let(:project_a) { create(:project, namespace: group) }
let(:project_b) { create(:project, namespace: nested_group) }
let(:project_c) { create(:project, namespace: deep_nested_group) }
it 'returns members of all projects in group and subgroups' do
project_a.add_developer(user_a)
project_b.add_developer(user_b)
project_c.add_developer(user_c)
expect(group.project_users_with_descendants).to contain_exactly(user_a, user_b, user_c)
expect(nested_group.project_users_with_descendants).to contain_exactly(user_b, user_c)
expect(deep_nested_group.project_users_with_descendants).to contain_exactly(user_c)
end
end
describe '#refresh_members_authorized_projects' do
let_it_be(:group) { create(:group, :nested) }
let_it_be(:parent_group_user) { create(:user) }
let_it_be(:group_user) { create(:user) }
before do
group.parent.add_maintainer(parent_group_user)
group.add_developer(group_user)
end
context 'users for which authorizations refresh is executed' do
it 'processes authorizations refresh for all members of the group' do
expect(UserProjectAccessChangedService).to receive(:new).with(contain_exactly(group_user.id, parent_group_user.id)).and_call_original
group.refresh_members_authorized_projects
end
context 'when explicitly specified to run only for direct members' do
it 'processes authorizations refresh only for direct members of the group' do
expect(UserProjectAccessChangedService).to receive(:new).with(contain_exactly(group_user.id)).and_call_original
group.refresh_members_authorized_projects(direct_members_only: true)
end
end
end
end
describe '#users_ids_of_direct_members' do
let_it_be(:group) { create(:group, :nested) }
let_it_be(:parent_group_user) { create(:user) }
let_it_be(:group_user) { create(:user) }
before do
group.parent.add_maintainer(parent_group_user)
group.add_developer(group_user)
end
it 'does not return user ids of the members of the parent' do
expect(group.users_ids_of_direct_members).not_to include(parent_group_user.id)
end
it 'returns the user ids of the direct member of the group' do
expect(group.users_ids_of_direct_members).to include(group_user.id)
end
context 'group sharing' do
let!(:shared_group) { create(:group) }
before do
create(:group_group_link, shared_group: shared_group, shared_with_group: group)
end
it 'does not return the user ids of members of the shared_with group' do
expect(shared_group.users_ids_of_direct_members).not_to(
include(group_user.id))
end
end
end
describe '#user_ids_for_project_authorizations' do
it 'returns the user IDs for which to refresh authorizations' do
maintainer = create(:user)
developer = create(:user)
group.add_user(maintainer, GroupMember::MAINTAINER)
group.add_user(developer, GroupMember::DEVELOPER)
expect(group.user_ids_for_project_authorizations)
.to include(maintainer.id, developer.id)
end
context 'group sharing' do
let_it_be(:group) { create(:group) }
let_it_be(:group_user) { create(:user) }
let_it_be(:shared_group) { create(:group) }
before do
group.add_developer(group_user)
create(:group_group_link, shared_group: shared_group, shared_with_group: group)
end
it 'returns the user IDs for shared with group members' do
expect(shared_group.user_ids_for_project_authorizations).to(
include(group_user.id))
end
end
context 'distinct user ids' do
let_it_be(:subgroup) { create(:group, :nested) }
let_it_be(:user) { create(:user) }
let_it_be(:shared_with_group) { create(:group) }
let_it_be(:other_subgroup_user) { create(:user) }
before do
create(:group_group_link, shared_group: subgroup, shared_with_group: shared_with_group)
subgroup.add_maintainer(other_subgroup_user)
# `user` is added as a direct member of the parent group, the subgroup
# and another group shared with the subgroup.
subgroup.parent.add_maintainer(user)
subgroup.add_developer(user)
shared_with_group.add_guest(user)
end
it 'returns only distinct user ids of users for which to refresh authorizations' do
expect(subgroup.user_ids_for_project_authorizations).to(
contain_exactly(user.id, other_subgroup_user.id))
end
end
end
describe '#update_two_factor_requirement' do
let(:user) { create(:user) }
context 'group membership' do
before do
group.add_user(user, GroupMember::OWNER)
end
it 'is called when require_two_factor_authentication is changed' do
expect_any_instance_of(User).to receive(:update_two_factor_requirement)
group.update!(require_two_factor_authentication: true)
end
it 'is called when two_factor_grace_period is changed' do
expect_any_instance_of(User).to receive(:update_two_factor_requirement)
group.update!(two_factor_grace_period: 23)
end
it 'is not called when other attributes are changed' do
expect_any_instance_of(User).not_to receive(:update_two_factor_requirement)
group.update!(description: 'foobar')
end
it 'calls #update_two_factor_requirement on each group member' do
other_user = create(:user)
group.add_user(other_user, GroupMember::OWNER)
calls = 0
allow_any_instance_of(User).to receive(:update_two_factor_requirement) do
calls += 1
end
group.update!(require_two_factor_authentication: true, two_factor_grace_period: 23)
expect(calls).to eq 2
end
end
context 'sub groups and projects' do
it 'enables two_factor_requirement for group member' do
group.add_user(user, GroupMember::OWNER)
group.update!(require_two_factor_authentication: true)
expect(user.reload.require_two_factor_authentication_from_group).to be_truthy
end
context 'expanded group members' do
let(:indirect_user) { create(:user) }
context 'two_factor_requirement is enabled' do
context 'two_factor_requirement is also enabled for ancestor group' do
it 'enables two_factor_requirement for subgroup member' do
subgroup = create(:group, :nested, parent: group)
subgroup.add_user(indirect_user, GroupMember::OWNER)
group.update!(require_two_factor_authentication: true)
expect(indirect_user.reload.require_two_factor_authentication_from_group).to be_truthy
end
end
context 'two_factor_requirement is disabled for ancestor group' do
it 'enables two_factor_requirement for subgroup member' do
subgroup = create(:group, :nested, parent: group, require_two_factor_authentication: true)
subgroup.add_user(indirect_user, GroupMember::OWNER)
group.update!(require_two_factor_authentication: false)
expect(indirect_user.reload.require_two_factor_authentication_from_group).to be_truthy
end
it 'enable two_factor_requirement for ancestor group member' do
ancestor_group = create(:group)
ancestor_group.add_user(indirect_user, GroupMember::OWNER)
group.update!(parent: ancestor_group)
group.update!(require_two_factor_authentication: true)
expect(indirect_user.reload.require_two_factor_authentication_from_group).to be_truthy
end
end
end
context 'two_factor_requirement is disabled' do
context 'two_factor_requirement is enabled for ancestor group' do
it 'enables two_factor_requirement for subgroup member' do
subgroup = create(:group, :nested, parent: group)
subgroup.add_user(indirect_user, GroupMember::OWNER)
group.update!(require_two_factor_authentication: true)
expect(indirect_user.reload.require_two_factor_authentication_from_group).to be_truthy
end
end
context 'two_factor_requirement is also disabled for ancestor group' do
it 'disables two_factor_requirement for subgroup member' do
subgroup = create(:group, :nested, parent: group)
subgroup.add_user(indirect_user, GroupMember::OWNER)
group.update!(require_two_factor_authentication: false)
expect(indirect_user.reload.require_two_factor_authentication_from_group).to be_falsey
end
it 'disables two_factor_requirement for ancestor group member' do
ancestor_group = create(:group, require_two_factor_authentication: false)
indirect_user.update!(require_two_factor_authentication_from_group: true)
ancestor_group.add_user(indirect_user, GroupMember::OWNER)
group.update!(require_two_factor_authentication: false)
expect(indirect_user.reload.require_two_factor_authentication_from_group).to be_falsey
end
end
end
end
context 'project members' do
it 'does not enable two_factor_requirement for child project member' do
project = create(:project, group: group)
project.add_maintainer(user)
group.update!(require_two_factor_authentication: true)
expect(user.reload.require_two_factor_authentication_from_group).to be_falsey
end
it 'does not enable two_factor_requirement for subgroup child project member' do
subgroup = create(:group, :nested, parent: group)
project = create(:project, group: subgroup)
project.add_maintainer(user)
group.update!(require_two_factor_authentication: true)
expect(user.reload.require_two_factor_authentication_from_group).to be_falsey
end
end
end
end
describe '#path_changed_hook' do
let(:system_hook_service) { SystemHooksService.new }
context 'for a new group' do
let(:group) { build(:group) }
before do
expect(group).to receive(:system_hook_service).and_return(system_hook_service)
end
it 'does not trigger system hook' do
expect(system_hook_service).to receive(:execute_hooks_for).with(group, :create)
group.save!
end
end
context 'for an existing group' do
let(:group) { create(:group, path: 'old-path') }
context 'when the path is changed' do
let(:new_path) { 'very-new-path' }
it 'triggers the rename system hook' do
expect(group).to receive(:system_hook_service).and_return(system_hook_service)
expect(system_hook_service).to receive(:execute_hooks_for).with(group, :rename)
group.update!(path: new_path)
end
end
context 'when the path is not changed' do
it 'does not trigger system hook' do
expect(group).not_to receive(:system_hook_service)
group.update!(name: 'new name')
end
end
end
end
describe '#ci_variables_for' do
let(:project) { create(:project, group: group) }
let(:environment_scope) { '*' }
let!(:ci_variable) do
create(:ci_group_variable, value: 'secret', group: group, environment_scope: environment_scope)
end
let!(:protected_variable) do
create(:ci_group_variable, :protected, value: 'protected', group: group)
end
subject { group.ci_variables_for('ref', project) }
it 'memoizes the result by ref and environment', :request_store do
scoped_variable = create(:ci_group_variable, value: 'secret', group: group, environment_scope: 'scoped')
expect(project).to receive(:protected_for?).with('ref').once.and_return(true)
expect(project).to receive(:protected_for?).with('other').twice.and_return(false)
2.times do
expect(group.ci_variables_for('ref', project, environment: 'production')).to contain_exactly(ci_variable, protected_variable)
expect(group.ci_variables_for('other', project)).to contain_exactly(ci_variable)
expect(group.ci_variables_for('other', project, environment: 'scoped')).to contain_exactly(ci_variable, scoped_variable)
end
end
shared_examples 'ref is protected' do
it 'contains all the variables' do
is_expected.to contain_exactly(ci_variable, protected_variable)
end
end
context 'when the ref is not protected' do
before do
stub_application_setting(
default_branch_protection: Gitlab::Access::PROTECTION_NONE)
end
it 'contains only the CI variables' do
is_expected.to contain_exactly(ci_variable)
end
end
context 'when the ref is a protected branch' do
before do
allow(project).to receive(:protected_for?).with('ref').and_return(true)
end
it_behaves_like 'ref is protected'
end
context 'when the ref is a protected tag' do
before do
allow(project).to receive(:protected_for?).with('ref').and_return(true)
end
it_behaves_like 'ref is protected'
end
context 'when environment name is specified' do
let(:environment) { 'review/name' }
subject do
group.ci_variables_for('ref', project, environment: environment)
end
context 'when environment scope is exactly matched' do
let(:environment_scope) { 'review/name' }
it { is_expected.to contain_exactly(ci_variable) }
end
context 'when environment scope is matched by wildcard' do
let(:environment_scope) { 'review/*' }
it { is_expected.to contain_exactly(ci_variable) }
end
context 'when environment scope does not match' do
let(:environment_scope) { 'review/*/special' }
it { is_expected.not_to contain_exactly(ci_variable) }
end
context 'when environment scope has _' do
let(:environment_scope) { '*_*' }
it 'does not treat it as wildcard' do
is_expected.not_to contain_exactly(ci_variable)
end
context 'when environment name contains underscore' do
let(:environment) { 'foo_bar/test' }
let(:environment_scope) { 'foo_bar/*' }
it 'matches literally for _' do
is_expected.to contain_exactly(ci_variable)
end
end
end
# The environment name and scope cannot have % at the moment,
# but we're considering relaxing it and we should also make sure
# it doesn't break in case some data sneaked in somehow as we're
# not checking this integrity in database level.
context 'when environment scope has %' do
it 'does not treat it as wildcard' do
ci_variable.update_attribute(:environment_scope, '*%*')
is_expected.not_to contain_exactly(ci_variable)
end
context 'when environment name contains a percent' do
let(:environment) { 'foo%bar/test' }
it 'matches literally for %' do
ci_variable.update(environment_scope: 'foo%bar/*')
is_expected.to contain_exactly(ci_variable)
end
end
end
context 'when variables with the same name have different environment scopes' do
let!(:partially_matched_variable) do
create(:ci_group_variable,
key: ci_variable.key,
value: 'partial',
environment_scope: 'review/*',
group: group)
end
let!(:perfectly_matched_variable) do
create(:ci_group_variable,
key: ci_variable.key,
value: 'prefect',
environment_scope: 'review/name',
group: group)
end
it 'puts variables matching environment scope more in the end' do
is_expected.to eq(
[ci_variable,
partially_matched_variable,
perfectly_matched_variable])
end
end
end
context 'when group has children' do
let(:group_child) { create(:group, parent: group) }
let(:group_child_2) { create(:group, parent: group_child) }
let(:group_child_3) { create(:group, parent: group_child_2) }
let(:variable_child) { create(:ci_group_variable, group: group_child) }
let(:variable_child_2) { create(:ci_group_variable, group: group_child_2) }
let(:variable_child_3) { create(:ci_group_variable, group: group_child_3) }
before do
allow(project).to receive(:protected_for?).with('ref').and_return(true)
end
context 'traversal queries' do
shared_examples 'correct ancestor order' do
it 'returns all variables belong to the group and parent groups' do
expected_array1 = [protected_variable, ci_variable]
expected_array2 = [variable_child, variable_child_2, variable_child_3]
got_array = group_child_3.ci_variables_for('ref', project).to_a
expect(got_array.shift(2)).to contain_exactly(*expected_array1)
expect(got_array).to eq(expected_array2)
end
end
context 'recursive' do
before do
stub_feature_flags(use_traversal_ids: false)
end
include_examples 'correct ancestor order'
end
context 'linear' do
before do
stub_feature_flags(use_traversal_ids: true)
group_child_3.reload # make sure traversal_ids are reloaded
end
include_examples 'correct ancestor order'
end
end
end
end
describe '#highest_group_member' do
let(:nested_group) { create(:group, parent: group) }
let(:nested_group_2) { create(:group, parent: nested_group) }
let(:user) { create(:user) }
subject(:highest_group_member) { nested_group_2.highest_group_member(user) }
context 'when the user is not a member of any group in the hierarchy' do
it 'returns nil' do
expect(highest_group_member).to be_nil
end
end
context 'when the user is only a member of one group in the hierarchy' do
before do
nested_group.add_developer(user)
end
it 'returns that group member' do
expect(highest_group_member.access_level).to eq(Gitlab::Access::DEVELOPER)
end
end
context 'when the user is a member of several groups in the hierarchy' do
before do
group.add_owner(user)
nested_group.add_developer(user)
nested_group_2.add_maintainer(user)
end
it 'returns the group member with the highest access level' do
expect(highest_group_member.access_level).to eq(Gitlab::Access::OWNER)
end
end
end
describe '#related_group_ids' do
let(:nested_group) { create(:group, parent: group) }
let(:shared_with_group) { create(:group, parent: group) }
before do
create(:group_group_link, shared_group: nested_group,
shared_with_group: shared_with_group)
end
subject(:related_group_ids) { nested_group.related_group_ids }
it 'returns id' do
expect(related_group_ids).to include(nested_group.id)
end
it 'returns ancestor id' do
expect(related_group_ids).to include(group.id)
end
it 'returns shared with group id' do
expect(related_group_ids).to include(shared_with_group.id)
end
context 'with more than one ancestor group' do
let(:ancestor_group) { create(:group) }
before do
group.update(parent: ancestor_group)
end
it 'returns all ancestor group ids' do
expect(related_group_ids).to(
include(group.id, ancestor_group.id))
end
end
context 'with more than one shared with group' do
let(:another_shared_with_group) { create(:group, parent: group) }
before do
create(:group_group_link, shared_group: nested_group,
shared_with_group: another_shared_with_group)
end
it 'returns all shared with group ids' do
expect(related_group_ids).to(
include(shared_with_group.id, another_shared_with_group.id))
end
end
end
context 'with uploads' do
it_behaves_like 'model with uploads', true do
let(:model_object) { create(:group, :with_avatar) }
let(:upload_attribute) { :avatar }
let(:uploader_class) { AttachmentUploader }
end
end
describe '#first_auto_devops_config' do
using RSpec::Parameterized::TableSyntax
let(:group) { create(:group) }
subject { group.first_auto_devops_config }
where(:instance_value, :group_value, :config) do
# Instance level enabled
true | nil | { status: true, scope: :instance }
true | true | { status: true, scope: :group }
true | false | { status: false, scope: :group }
# Instance level disabled
false | nil | { status: false, scope: :instance }
false | true | { status: true, scope: :group }
false | false | { status: false, scope: :group }
end
with_them do
before do
stub_application_setting(auto_devops_enabled: instance_value)
group.update_attribute(:auto_devops_enabled, group_value)
end
it { is_expected.to eq(config) }
end
context 'with parent groups' do
where(:instance_value, :parent_value, :group_value, :config) do
# Instance level enabled
true | nil | nil | { status: true, scope: :instance }
true | nil | true | { status: true, scope: :group }
true | nil | false | { status: false, scope: :group }
true | true | nil | { status: true, scope: :group }
true | true | true | { status: true, scope: :group }
true | true | false | { status: false, scope: :group }
true | false | nil | { status: false, scope: :group }
true | false | true | { status: true, scope: :group }
true | false | false | { status: false, scope: :group }
# Instance level disable
false | nil | nil | { status: false, scope: :instance }
false | nil | true | { status: true, scope: :group }
false | nil | false | { status: false, scope: :group }
false | true | nil | { status: true, scope: :group }
false | true | true | { status: true, scope: :group }
false | true | false | { status: false, scope: :group }
false | false | nil | { status: false, scope: :group }
false | false | true | { status: true, scope: :group }
false | false | false | { status: false, scope: :group }
end
with_them do
before do
stub_application_setting(auto_devops_enabled: instance_value)
parent = create(:group, auto_devops_enabled: parent_value)
group.update!(
auto_devops_enabled: group_value,
parent: parent
)
end
it { is_expected.to eq(config) }
end
end
end
describe '#auto_devops_enabled?' do
subject { group.auto_devops_enabled? }
context 'when auto devops is explicitly enabled on group' do
let(:group) { create(:group, :auto_devops_enabled) }
it { is_expected.to be_truthy }
end
context 'when auto devops is explicitly disabled on group' do
let(:group) { create(:group, :auto_devops_disabled) }
it { is_expected.to be_falsy }
end
context 'when auto devops is implicitly enabled or disabled' do
before do
stub_application_setting(auto_devops_enabled: false)
group.update!(parent: parent_group)
end
context 'when auto devops is enabled on root group' do
let(:root_group) { create(:group, :auto_devops_enabled) }
let(:subgroup) { create(:group, parent: root_group) }
let(:parent_group) { create(:group, parent: subgroup) }
it { is_expected.to be_truthy }
end
context 'when auto devops is disabled on root group' do
let(:root_group) { create(:group, :auto_devops_disabled) }
let(:subgroup) { create(:group, parent: root_group) }
let(:parent_group) { create(:group, parent: subgroup) }
it { is_expected.to be_falsy }
end
context 'when auto devops is disabled on parent group and enabled on root group' do
let(:root_group) { create(:group, :auto_devops_enabled) }
let(:parent_group) { create(:group, :auto_devops_disabled, parent: root_group) }
it { is_expected.to be_falsy }
end
end
end
describe 'project_creation_level' do
it 'outputs the default one if it is nil' do
group = create(:group, project_creation_level: nil)
expect(group.project_creation_level).to eq(Gitlab::CurrentSettings.default_project_creation)
end
end
describe 'subgroup_creation_level' do
it 'defaults to maintainers' do
expect(group.subgroup_creation_level)
.to eq(Gitlab::Access::MAINTAINER_SUBGROUP_ACCESS)
end
end
describe '#access_request_approvers_to_be_notified' do
let_it_be(:group) { create(:group, :public) }
it 'returns a maximum of ten owners of the group in recent_sign_in descending order' do
limit = 2
stub_const("Member::ACCESS_REQUEST_APPROVERS_TO_BE_NOTIFIED_LIMIT", limit)
users = create_list(:user, limit + 1, :with_sign_ins)
active_owners = users.map do |user|
create(:group_member, :owner, group: group, user: user)
end
active_owners_in_recent_sign_in_desc_order = group.members_and_requesters
.id_in(active_owners)
.order_recent_sign_in.limit(limit)
expect(group.access_request_approvers_to_be_notified).to eq(active_owners_in_recent_sign_in_desc_order)
end
it 'returns active, non_invited, non_requested owners of the group' do
owner = create(:group_member, :owner, source: group)
create(:group_member, :maintainer, group: group)
create(:group_member, :owner, :invited, group: group)
create(:group_member, :owner, :access_request, group: group)
create(:group_member, :owner, :blocked, group: group)
expect(group.access_request_approvers_to_be_notified.to_a).to eq([owner])
end
end
describe '.groups_including_descendants_by' do
it 'returns the expected groups for a group and its descendants' do
parent_group1 = create(:group)
child_group1 = create(:group, parent: parent_group1)
child_group2 = create(:group, parent: parent_group1)
parent_group2 = create(:group)
child_group3 = create(:group, parent: parent_group2)
create(:group)
groups = described_class.groups_including_descendants_by([parent_group2.id, parent_group1.id])
expect(groups).to contain_exactly(parent_group1, parent_group2, child_group1, child_group2, child_group3)
end
end
describe '.preset_root_ancestor_for' do
let_it_be(:rootgroup, reload: true) { create(:group) }
let_it_be(:subgroup, reload: true) { create(:group, parent: rootgroup) }
let_it_be(:subgroup2, reload: true) { create(:group, parent: subgroup) }
it 'does noting for single group' do
expect(subgroup).not_to receive(:self_and_ancestors)
described_class.preset_root_ancestor_for([subgroup])
end
it 'sets the same root_ancestor for multiple groups' do
expect(subgroup).not_to receive(:self_and_ancestors)
expect(subgroup2).not_to receive(:self_and_ancestors)
described_class.preset_root_ancestor_for([rootgroup, subgroup, subgroup2])
expect(subgroup.root_ancestor).to eq(rootgroup)
expect(subgroup2.root_ancestor).to eq(rootgroup)
end
end
describe '#update_shared_runners_setting!' do
context 'enabled' do
subject { group.update_shared_runners_setting!('enabled') }
context 'group that its ancestors have shared runners disabled' do
let_it_be(:parent, reload: true) { create(:group, :shared_runners_disabled) }
let_it_be(:group, reload: true) { create(:group, :shared_runners_disabled, parent: parent) }
let_it_be(:project, reload: true) { create(:project, shared_runners_enabled: false, group: group) }
it 'raises exception' do
expect { subject }
.to raise_error(ActiveRecord::RecordInvalid, 'Validation failed: Shared runners enabled cannot be enabled because parent group has shared Runners disabled')
end
it 'does not enable shared runners' do
expect do
subject rescue nil
parent.reload
group.reload
project.reload
end.to not_change { parent.shared_runners_enabled }
.and not_change { group.shared_runners_enabled }
.and not_change { project.shared_runners_enabled }
end
end
context 'root group with shared runners disabled' do
let_it_be(:group) { create(:group, :shared_runners_disabled) }
let_it_be(:sub_group) { create(:group, :shared_runners_disabled, parent: group) }
let_it_be(:project) { create(:project, shared_runners_enabled: false, group: sub_group) }
it 'enables shared Runners only for itself' do
expect { subject_and_reload(group, sub_group, project) }
.to change { group.shared_runners_enabled }.from(false).to(true)
.and not_change { sub_group.shared_runners_enabled }
.and not_change { project.shared_runners_enabled }
end
end
end
context 'disabled_and_unoverridable' do
let_it_be(:group) { create(:group) }
let_it_be(:sub_group) { create(:group, :shared_runners_disabled, :allow_descendants_override_disabled_shared_runners, parent: group) }
let_it_be(:sub_group_2) { create(:group, parent: group) }
let_it_be(:project) { create(:project, group: group, shared_runners_enabled: true) }
let_it_be(:project_2) { create(:project, group: sub_group_2, shared_runners_enabled: true) }
subject { group.update_shared_runners_setting!('disabled_and_unoverridable') }
it 'disables shared Runners for all descendant groups and projects' do
expect { subject_and_reload(group, sub_group, sub_group_2, project, project_2) }
.to change { group.shared_runners_enabled }.from(true).to(false)
.and not_change { group.allow_descendants_override_disabled_shared_runners }
.and not_change { sub_group.shared_runners_enabled }
.and change { sub_group.allow_descendants_override_disabled_shared_runners }.from(true).to(false)
.and change { sub_group_2.shared_runners_enabled }.from(true).to(false)
.and not_change { sub_group_2.allow_descendants_override_disabled_shared_runners }
.and change { project.shared_runners_enabled }.from(true).to(false)
.and change { project_2.shared_runners_enabled }.from(true).to(false)
end
context 'with override on self' do
let_it_be(:group) { create(:group, :shared_runners_disabled, :allow_descendants_override_disabled_shared_runners) }
it 'disables it' do
expect { subject_and_reload(group) }
.to not_change { group.shared_runners_enabled }
.and change { group.allow_descendants_override_disabled_shared_runners }.from(true).to(false)
end
end
end
context 'disabled_with_override' do
subject { group.update_shared_runners_setting!('disabled_with_override') }
context 'top level group' do
let_it_be(:group) { create(:group, :shared_runners_disabled) }
let_it_be(:sub_group) { create(:group, :shared_runners_disabled, parent: group) }
let_it_be(:project) { create(:project, shared_runners_enabled: false, group: sub_group) }
it 'enables allow descendants to override only for itself' do
expect { subject_and_reload(group, sub_group, project) }
.to change { group.allow_descendants_override_disabled_shared_runners }.from(false).to(true)
.and not_change { group.shared_runners_enabled }
.and not_change { sub_group.allow_descendants_override_disabled_shared_runners }
.and not_change { sub_group.shared_runners_enabled }
.and not_change { project.shared_runners_enabled }
end
end
context 'group that its ancestors have shared Runners disabled but allows to override' do
let_it_be(:parent) { create(:group, :shared_runners_disabled, :allow_descendants_override_disabled_shared_runners) }
let_it_be(:group) { create(:group, :shared_runners_disabled, parent: parent) }
let_it_be(:project) { create(:project, shared_runners_enabled: false, group: group) }
it 'enables allow descendants to override' do
expect { subject_and_reload(parent, group, project) }
.to not_change { parent.allow_descendants_override_disabled_shared_runners }
.and not_change { parent.shared_runners_enabled }
.and change { group.allow_descendants_override_disabled_shared_runners }.from(false).to(true)
.and not_change { group.shared_runners_enabled }
.and not_change { project.shared_runners_enabled }
end
end
context 'when parent does not allow' do
let_it_be(:parent, reload: true) { create(:group, :shared_runners_disabled, allow_descendants_override_disabled_shared_runners: false ) }
let_it_be(:group, reload: true) { create(:group, :shared_runners_disabled, allow_descendants_override_disabled_shared_runners: false, parent: parent) }
it 'raises exception' do
expect { subject }
.to raise_error(ActiveRecord::RecordInvalid, 'Validation failed: Allow descendants override disabled shared runners cannot be enabled because parent group does not allow it')
end
it 'does not allow descendants to override' do
expect do
subject rescue nil
parent.reload
group.reload
end.to not_change { parent.allow_descendants_override_disabled_shared_runners }
.and not_change { parent.shared_runners_enabled }
.and not_change { group.allow_descendants_override_disabled_shared_runners }
.and not_change { group.shared_runners_enabled }
end
end
context 'top level group that has shared Runners enabled' do
let_it_be(:group) { create(:group, shared_runners_enabled: true) }
let_it_be(:sub_group) { create(:group, shared_runners_enabled: true, parent: group) }
let_it_be(:project) { create(:project, shared_runners_enabled: true, group: sub_group) }
it 'enables allow descendants to override & disables shared runners everywhere' do
expect { subject_and_reload(group, sub_group, project) }
.to change { group.shared_runners_enabled }.from(true).to(false)
.and change { group.allow_descendants_override_disabled_shared_runners }.from(false).to(true)
.and change { sub_group.shared_runners_enabled }.from(true).to(false)
.and change { project.shared_runners_enabled }.from(true).to(false)
end
end
end
end
describe "#default_branch_name" do
context "when group.namespace_settings does not have a default branch name" do
it "returns nil" do
expect(group.default_branch_name).to be_nil
end
end
context "when group.namespace_settings has a default branch name" do
let(:example_branch_name) { "example_branch_name" }
before do
allow(group.namespace_settings)
.to receive(:default_branch_name)
.and_return(example_branch_name)
end
it "returns the default branch name" do
expect(group.default_branch_name).to eq(example_branch_name)
end
end
end
describe '#default_owner' do
let(:group) { build(:group) }
context 'the group has owners' do
before do
group.add_owner(create(:user))
group.add_owner(create(:user))
end
it 'is the first owner' do
expect(group.default_owner)
.to eq(group.owners.first)
.and be_a(User)
end
end
context 'the group has a parent' do
let(:parent) { build(:group) }
before do
group.parent = parent
parent.add_owner(create(:user))
end
it 'is the first owner of the parent' do
expect(group.default_owner)
.to eq(parent.default_owner)
.and be_a(User)
end
end
context 'we fallback to group.owner' do
before do
group.owner = build(:user)
end
it 'is the group.owner' do
expect(group.default_owner)
.to eq(group.owner)
.and be_a(User)
end
end
end
describe '#parent_allows_two_factor_authentication?' do
it 'returns true for top-level group' do
expect(group.parent_allows_two_factor_authentication?).to eq(true)
end
context 'for subgroup' do
let(:subgroup) { create(:group, parent: group) }
it 'returns true if parent group allows two factor authentication for its descendants' do
expect(subgroup.parent_allows_two_factor_authentication?).to eq(true)
end
it 'returns true if parent group allows two factor authentication for its descendants' do
group.namespace_settings.update!(allow_mfa_for_subgroups: false)
expect(subgroup.parent_allows_two_factor_authentication?).to eq(false)
end
end
end
describe 'has_project_with_service_desk_enabled?' do
let_it_be(:group) { create(:group, :private) }
subject { group.has_project_with_service_desk_enabled? }
before do
allow(Gitlab::ServiceDesk).to receive(:supported?).and_return(true)
end
context 'when service desk is enabled' do
context 'for top level group' do
let_it_be(:project) { create(:project, group: group, service_desk_enabled: true) }
it { is_expected.to eq(true) }
context 'when service desk is not supported' do
before do
allow(Gitlab::ServiceDesk).to receive(:supported?).and_return(false)
end
it { is_expected.to eq(false) }
end
end
context 'for subgroup project' do
let_it_be(:subgroup) { create(:group, :private, parent: group)}
let_it_be(:project) { create(:project, group: subgroup, service_desk_enabled: true) }
it { is_expected.to eq(true) }
end
end
context 'when none of group child projects has service desk enabled' do
let_it_be(:project) { create(:project, group: group, service_desk_enabled: false) }
before do
project.update(service_desk_enabled: false)
end
it { is_expected.to eq(false) }
end
end
describe 'with Debian Distributions' do
subject { create(:group) }
it_behaves_like 'model with Debian distributions'
end
describe '.ids_with_disabled_email' do
let!(:parent_1) { create(:group, emails_disabled: true) }
let!(:child_1) { create(:group, parent: parent_1) }
let!(:parent_2) { create(:group, emails_disabled: false) }
let!(:child_2) { create(:group, parent: parent_2) }
let!(:other_group) { create(:group, emails_disabled: false) }
subject(:group_ids_where_email_is_disabled) { described_class.ids_with_disabled_email([child_1, child_2, other_group]) }
it { is_expected.to eq(Set.new([child_1.id])) }
end
describe '#to_ability_name' do
it 'returns group' do
group = build(:group)
expect(group.to_ability_name).to eq('group')
end
end
describe '#activity_path' do
it 'returns the group activity_path' do
expected_path = "/groups/#{group.name}/-/activity"
expect(group.activity_path).to eq(expected_path)
end
end
context 'with export' do
let(:group) { create(:group, :with_export) }
it '#export_file_exists? returns true' do
expect(group.export_file_exists?).to be true
end
it '#export_archive_exists? returns true' do
expect(group.export_archive_exists?).to be true
end
end
describe '#open_issues_count', :aggregate_failures do
let(:group) { build(:group) }
it 'provides the issue count' do
expect(group.open_issues_count).to eq 0
end
it 'invokes the count service with current_user' do
user = build(:user)
count_service = instance_double(Groups::OpenIssuesCountService)
expect(Groups::OpenIssuesCountService).to receive(:new).with(group, user).and_return(count_service)
expect(count_service).to receive(:count)
group.open_issues_count(user)
end
it 'invokes the count service with no current_user' do
count_service = instance_double(Groups::OpenIssuesCountService)
expect(Groups::OpenIssuesCountService).to receive(:new).with(group, nil).and_return(count_service)
expect(count_service).to receive(:count)
group.open_issues_count
end
end
describe '#open_merge_requests_count', :aggregate_failures do
let(:group) { build(:group) }
it 'provides the merge request count' do
expect(group.open_merge_requests_count).to eq 0
end
it 'invokes the count service with current_user' do
user = build(:user)
count_service = instance_double(Groups::MergeRequestsCountService)
expect(Groups::MergeRequestsCountService).to receive(:new).with(group, user).and_return(count_service)
expect(count_service).to receive(:count)
group.open_merge_requests_count(user)
end
it 'invokes the count service with no current_user' do
count_service = instance_double(Groups::MergeRequestsCountService)
expect(Groups::MergeRequestsCountService).to receive(:new).with(group, nil).and_return(count_service)
expect(count_service).to receive(:count)
group.open_merge_requests_count
end
end
end
| mit |
josephsavona/valuable | bench/store_core_bench.js | 3161 | var Store = require('../src/store'),
Model = require('../src/model'),
Valuable = require('../valuable/src/index'),
Backbone = require('backbone');
Backbone.sync = function() {};
var createBackbone = function() {
var User = Backbone.Model.extend({url: '/'}),
Users = Backbone.Collection.extend({
model: User,
url: '/'
});
return {
User: User,
Users: Users
};
};
var createValuable = function() {
var User = Valuable.Struct.schema({
id: Valuable.Str,
name: Valuable.Str,
age: Valuable.Decimal,
dev: Valuable.Bool
});
var Users = Valuable.List.of(User);
return {
User: User,
Users: Users
};
};
var createStore = function() {
return new Store({
users: {
name: Model.Str,
age: Model.Decimal,
dev: Model.Bool
}
});
};
suite('Schema Definition', function() {
bench('Backbone', createBackbone);
bench('Valuable', createValuable);
bench('Store', createStore);
});
suite('Object Creation', function() {
var backbone, valuable, store;
before(function() {
backbone = createBackbone();
backbone.collection = new backbone.Users();
valuable = createValuable();
valuable.collection = new valuable.Users();
store = createStore();
});
bench('Backbone - new User()', function() {
var user = new backbone.User();
});
bench('Backbone - users.create()', function() {
var user = backbone.collection.create();
});
bench('Valuable - new Users()', function() {
var user = new valuable.User();
});
bench('Valuable - users.push()', function() {
var user = valuable.collection.push({});
});
bench('Store - (private) new User()', function() {
var user = new store._models.users({});
});
bench('Store - store.create(users)', function() {
var user = store.create('users', {});
});
});
suite('Object Property Access', function() {
var object, backbone, valuable, store;
before(function() {
object = {name: 'hello'};
backbone = new (createBackbone()).User({name: 'hello'});
valuable = new (createValuable()).User({name: 'hello'});
store = (createStore()).create('users', {name: 'hello'});
});
bench('Native', function() {
return object.name;
});
bench('Backbone', function() {
return backbone.get('name');
});
bench('Valuable', function() {
return valuable.val('name');
});
bench('Store - object.name.val', function() {
return store.name.val;
});
bench('Store - object.val(name)', function() {
return store.val('name');
});
});
suite('Collection Creation', function() {
var backbone, valuable, store;
before(function() {
backbone = createBackbone();
valuable = createValuable();
store = createStore();
});
bench('Backbone - new Users()', function() {
var users = new backbone.Users();
});
bench('Valuable - new Users()', function() {
var users = new valuable.Users();
});
bench('Store - store.get(users))', function() {
var users = store.get('users');
});
bench('Store - store.snapshot.get(users)', function() {
var users = store.snapshot().get('users');
});
}); | mit |
Spazz/discord-bot | node_modules/pokedex-promise-v2/index.js | 6773 | const rp = require('request-promise');
const cache = require('memory-cache');
const CACHE_LIMIT = 1000000 * 1000 //11 days
const pokeUrl = 'http://pokeapi.co';
getJSON = function(url) {
const cachedResult = cache.get(url);
if (cachedResult !== null) {
return cachedResult;
} else {
const options = {
url: url,
json: true,
};
return rp.get(options)
.catch(function(error) {
throw error;
})
.then(function(response) {
if (response.statusCode !== undefined && response.statusCode !== 200) {
throw response;
}
cache.put(url, response, CACHE_LIMIT);
return response;
});
}
};
const Pokedex = (function() {
function Pokedex() {}
Pokedex.prototype.getBerryByName = function(name) {
return getJSON(pokeUrl + '/api/v2/berry/' + name);
};
Pokedex.prototype.getBerryFirmnessByName = function(name) {
return getJSON(pokeUrl + '/api/v2/berry-firmness/' + name);
};
Pokedex.prototype.getBerryFlavorByName = function(name) {
return getJSON(pokeUrl + '/api/v2/berry-flavor/' + name);
};
Pokedex.prototype.getContestTypeByName = function(name) {
return getJSON(pokeUrl + '/api/v2/contest-type/' + name);
};
Pokedex.prototype.getContestEffectById = function(id) {
return getJSON(pokeUrl + '/api/v2/contest-effect/' + id);
};
Pokedex.prototype.getSuperContestEffectById = function(id) {
return getJSON(pokeUrl + '/api/v2/super-contest-effect/' + id);
};
Pokedex.prototype.getEncounterMethodByName = function(name) {
return getJSON(pokeUrl + '/api/v2/encounter-method/' + name);
};
Pokedex.prototype.getEncounterConditionByName = function(name) {
return getJSON(pokeUrl + '/api/v2/encounter-condition/' + name);
};
Pokedex.prototype.getEncounterConditionValueByName = function(name) {
return getJSON(pokeUrl + '/api/v2/encounter-condition-value/' + name);
};
Pokedex.prototype.getEvolutionChainById = function(id) {
return getJSON(pokeUrl + '/api/v2/evolution-chain/' + id);
};
Pokedex.prototype.getEvolutionTriggerByName = function(name) {
return getJSON(pokeUrl + '/api/v2/evolution-trigger/' + name);
};
Pokedex.prototype.getGenerationByName = function(name) {
return getJSON(pokeUrl + '/api/v2/generation/' + name);
};
Pokedex.prototype.getPokedexByName = function(name) {
return getJSON(pokeUrl + '/api/v2/pokedex/' + name);
};
Pokedex.prototype.getVersionByName = function(name) {
return getJSON(pokeUrl + '/api/v2/version/' + name);
};
Pokedex.prototype.getVersionGroupByName = function(name) {
return getJSON(pokeUrl + '/api/v2/version-group/' + name);
};
Pokedex.prototype.getItemByName = function(name) {
return getJSON(pokeUrl + '/api/v2/item/' + name);
};
Pokedex.prototype.getItemAttributeByName = function(name) {
return getJSON(pokeUrl + '/api/v2/item-attribute/' + name);
};
Pokedex.prototype.getItemCategoryByName = function(name) {
return getJSON(pokeUrl + '/api/v2/item-category/' + name);
};
Pokedex.prototype.getItemFlingEffectByName = function(name) {
return getJSON(pokeUrl + '/api/v2/item-fling-effect/' + name);
};
Pokedex.prototype.getItemPocketByName = function(name) {
return getJSON(pokeUrl + '/api/v2/item-pocket/' + name);
};
Pokedex.prototype.getMoveByName = function(name) {
return getJSON(pokeUrl + '/api/v2/move/' + name);
};
Pokedex.prototype.getMoveAilmentByName = function(name) {
return getJSON(pokeUrl + '/api/v2/move-ailment/' + name);
};
Pokedex.prototype.getMoveBattleStyleByName = function(name) {
return getJSON(pokeUrl + '/api/v2/move-battle-style/' + name);
};
Pokedex.prototype.getMoveCategoryByName = function(name) {
return getJSON(pokeUrl + '/api/v2/move-category/' + name);
};
Pokedex.prototype.getMoveDamageClassByName = function(name) {
return getJSON(pokeUrl + '/api/v2/move-damage-class/' + name);
};
Pokedex.prototype.getMoveLearnMethodByName = function(name) {
return getJSON(pokeUrl + '/api/v2/move-learn-method/' + name);
};
Pokedex.prototype.getMoveTargetByName = function(name) {
return getJSON(pokeUrl + '/api/v2/move-target/' + name);
};
Pokedex.prototype.getLocationByName = function(name) {
return getJSON(pokeUrl + '/api/v2/location/' + name);
};
Pokedex.prototype.getLocationAreaByName = function(name) {
return getJSON(pokeUrl + '/api/v2/location-area/' + name);
};
Pokedex.prototype.getPalParkAreaByName = function(name) {
return getJSON(pokeUrl + '/api/v2/pal-park-area/' + name);
};
Pokedex.prototype.getRegionByName = function(name) {
return getJSON(pokeUrl + '/api/v2/region/' + name);
};
Pokedex.prototype.getAbilityByName = function(name) {
return getJSON(pokeUrl + '/api/v2/ability/' + name);
};
Pokedex.prototype.getCharacteristicById = function(id) {
return getJSON(pokeUrl + '/api/v2/characteristic/' + id);
};
Pokedex.prototype.getEggGroupByName = function(name) {
return getJSON(pokeUrl + '/api/v2/egg-group/' + name);
};
Pokedex.prototype.getGenderByName = function(name) {
return getJSON(pokeUrl + '/api/v2/gender/' + name);
};
Pokedex.prototype.getGrowthRateByName = function(name) {
return getJSON(pokeUrl + '/api/v2/growth-rate/' + name);
};
Pokedex.prototype.getNatureByName = function(name) {
return getJSON(pokeUrl + '/api/v2/nature/' + name);
};
Pokedex.prototype.getPokeathlonStatByName = function(name) {
return getJSON(pokeUrl + '/api/v2/pokeathlon-stat/' + name);
};
Pokedex.prototype.getPokemonByName = function(name) {
return getJSON(pokeUrl + '/api/v2/pokemon/' + name);
};
Pokedex.prototype.getPokemonColorByName = function(name) {
return getJSON(pokeUrl + '/api/v2/pokemon-color/' + name);
};
Pokedex.prototype.getPokemonFormByName = function(name) {
return getJSON(pokeUrl + '/api/v2/pokemon-form/' + name);
};
Pokedex.prototype.getPokemonHabitatByName = function(name) {
return getJSON(pokeUrl + '/api/v2/pokemon-habitat/' + name);
};
Pokedex.prototype.getPokemonShapeByName = function(name) {
return getJSON(pokeUrl + '/api/v2/pokemon-shape/' + name);
};
Pokedex.prototype.getPokemonSpeciesByName = function(name) {
return getJSON(pokeUrl + '/api/v2/pokemon-species/' + name);
};
Pokedex.prototype.getStatByName = function(name) {
return getJSON(pokeUrl + '/api/v2/stat/' + name);
};
Pokedex.prototype.getTypeByName = function(name) {
return getJSON(pokeUrl + '/api/v2/type/' + name);
};
Pokedex.prototype.getLanguageByName = function(name) {
return getJSON(pokeUrl + '/api/v2/language/' + name);
};
return Pokedex;
})();
module.exports = Pokedex;
| mit |
XSockets/XSockets.Clients | src/XSockets.Shared.Client/Common/Interfaces/IXSocketObserver.cs | 320 |
namespace XSockets.Common.Interfaces
{
using System;
public interface IXSocketObserver<T>
{
Guid Id { get; }
void OnError(Exception e);
void OnNotify(T value);
void Unsubscribe();
void Subscribe(IXSocketObservable<T> provider);
void OnCompleted();
}
} | mit |
syscyl/SYS_CYL | application/controllers/Publicidad_controller.php | 3026 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Publicidad_controller extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('usuario_model');
}
/************************************************************************************************************************************************************************/
public function index()
{
$this->load->view('publicidad/index.html');
}
/************************************************************************************************************************************************************************/
public function nosotros()
{
$this->load->view('publicidad/nosotros/index.html');
}
/************************************************************************************************************************************************************************/
public function servicios()
{
$this->load->view('publicidad/servicios/index.html');
}
/************************************************************************************************************************************************************************/
public function galeria()
{
$this->load->view('publicidad/galeria/index.html');
}
/************************************************************************************************************************************************************************/
public function contacto()
{
$this->load->view('publicidad/contacto/index.html');
}
/************************************************************************************************************************************************************************/
public function seguimiento()
{
$this->load->view('usuario/header-usuario.html');
$this->load->view('publicidad/seguimiento/index.html');
$this->load->view('usuario/footer-usuario.html');
}
/************************************************************************************************************************************************************************/
public function seguimiento_SE()
{
$guia=$this->input->get('guia');
$usuario=$this->input->get('usuario');
$password=$this->input->get('password');
$data = array('guia'=>$guia);
$schneider = $this->usuario_model->login_usuario($usuario, $password);
if($schneider==TRUE)
{
$this->load->view('usuario/header-usuario.html');
$this->load->view('seguimiento_SE/seguimiento_SE.php',$data);
$this->load->view('usuario/footer-usuario.html');
}
else
{
$this->load->view('vista_SE/acceso_denegado.html');
}
}
/************************************************************************************************************************************************************************/
} | mit |
hyonholee/azure-sdk-for-net | sdk/resources/Azure.Management.Resources/src/Generated/Models/WhatIfResultFormat.Serialization.cs | 1150 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
namespace Azure.Management.Resources.Models
{
internal static class WhatIfResultFormatExtensions
{
public static string ToSerialString(this WhatIfResultFormat value) => value switch
{
WhatIfResultFormat.ResourceIdOnly => "ResourceIdOnly",
WhatIfResultFormat.FullResourcePayloads => "FullResourcePayloads",
_ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown WhatIfResultFormat value.")
};
public static WhatIfResultFormat ToWhatIfResultFormat(this string value)
{
if (string.Equals(value, "ResourceIdOnly", StringComparison.InvariantCultureIgnoreCase)) return WhatIfResultFormat.ResourceIdOnly;
if (string.Equals(value, "FullResourcePayloads", StringComparison.InvariantCultureIgnoreCase)) return WhatIfResultFormat.FullResourcePayloads;
throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown WhatIfResultFormat value.");
}
}
}
| mit |
harpcio/zf2-demo | module/ApplicationFeatureLibrary/config/router.config.php | 2015 | <?php
use Zend\Mvc\Router\Http;
use ApplicationLibrary\Router\Http\SkippableSegment;
return [
'router' => [
'routes' => [
'library' => [
'type' => SkippableSegment::class,
'options' => [
'route' => '[/:lang]/library',
'defaults' => [
'__NAMESPACE__' => 'ApplicationFeatureLibrary\Controller',
'controller' => 'index',
'action' => 'index',
'lang' => '',
],
'constraints' => array(
'lang' => '[a-z]{2}(-[a-zA-Z]{2}){0,1}'
),
'skippable' => [
'lang' => true
]
],
'may_terminate' => true,
'child_routes' => [
'default' => [
'type' => Http\Segment::class,
'options' => [
'route' => '/[:controller[/:action]]',
'constraints' => [
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
],
],
'may_terminate' => true,
'child_routes' => [
'*' => [
'type' => Http\Wildcard::class,
'options' => [
'key_value_delimiter' => '/',
'param_delimiter' => '/',
],
'may_terminate' => true,
],
]
],
],
],
],
],
]; | mit |
marcoazn89/http-wrapper | src/Support/TypeSupport.php | 224 | <?php
namespace HTTP\Support;
class TypeSupport extends ContentSupport {
public static function getDefault() {
return array('text/html','application/xhtml+xml','application/xml', 'text/plain', 'application/json');
}
}
| mit |
Danack/intahwebz-routing | src/Intahwebz/Routing/Router.php | 3813 | <?php
namespace Intahwebz\Routing;
use Intahwebz\ObjectCache;
use Intahwebz\Exception\UnsupportedOperationException;
use Intahwebz\Route;
use Intahwebz\Request;
use Intahwebz\MatchedRoute;
class Router implements \Intahwebz\Router {
use \Intahwebz\SafeAccess;
use \Intahwebz\Cache\KeyName;
/**
* @var $routesByName Route[]
*/
var $routesByName = array();
public $routingInfo;
public $cacheRouteInfo = true;
/**
* @var ObjectCache
*/
var $objectCache;
function __construct(
ObjectCache $objectCache,
$routeCollectionName,
$pathToRouteInfo
){
$this->objectCache = $objectCache;
$this->init($routeCollectionName, $pathToRouteInfo);
}
/**
* Initialise the router if it isn't already cached.
* @param $routeCollectionName
* @param $pathToRouteInfo
*/
function init($routeCollectionName, $pathToRouteInfo) {
$keyname = $this->getClassKey($routeCollectionName);
$this->routesByName = $this->objectCache->get($keyname);
if ($this->routesByName) {
return;
}
if (is_array($pathToRouteInfo)) {
$routingInfo = $pathToRouteInfo;
}
else {
$routingInfo = require $pathToRouteInfo;
}
$this->initRouting($routingInfo);
$this->objectCache->put($keyname, $this->routesByName, 60);
}
/**
* Initializes the router with an array of routes.
*
* @param $routingInfoArray
*/
function initRouting($routingInfoArray){
foreach($routingInfoArray as $routingInfo){
$name = $routingInfo['name'];
$route = new \Intahwebz\Routing\Route($routingInfo);
$this->routesByName[$name] = $route;
}
}
/**
* Find the most appropriate route, and route the request to it.
*
* @param $request
* @return MatchedRoute
*/
function matchRouteForRequest(Request $request){
/** @noinspection PhpUnusedLocalVariableInspection */
foreach ($this->routesByName as $name => $route) {
$params = $route->matchRequest($request);
if($params !== false){
return new MatchedRoute($request, $route, $params);
}
}
throw new \Intahwebz\Routing\RouteMissingException("Failed to match request to route.");
}
/**
* @param $routeName
* @param \Intahwebz\Domain $domain
* @param array $parameters
* @param bool $absolute
* @throws \Intahwebz\Exception\UnsupportedOperationException
* @return mixed|string
*/
function generateURLForRoute(
$routeName,
$parameters = array(),
\Intahwebz\Domain $domain = null,
$absolute = false
) {
foreach ($this->routesByName as $name => $route) {
if($name == $routeName){
return $route->generateURL($parameters, $domain, $absolute);
}
}
throw new UnsupportedOperationException("Could not find route [$routeName] to generateURL for.");
}
/**
* @param $routeName
* @return Route
* @throws UnsupportedOperationException
*/
function getRoute($routeName) {
foreach ($this->routesByName as $name => $route) {
if($name == $routeName){
return $route;
}
}
throw new \Intahwebz\Routing\RouteMissingException("Could not find route [$routeName] to generateURL for.");
}
/**
* @param $pattern
*/
function addRoute($pattern) {
$routingInfo = array();
$routingInfo['pattern'] = $pattern;
$route = new \Intahwebz\Routing\Route($routingInfo);
$this->routesByName[] = $route;
}
}
| mit |
drobbins/couchapp_ace | evently/design_doc_navigation/load_design_doc/selectors/a.file/click.js | 77 | function(){
$(this).trigger("edit_file", $(this).attr("href").slice(1));
}
| mit |
mathiasbynens/unicode-data | 3.2.0/blocks/Tibetan-regex.js | 109 | // Regular expression that matches all symbols in the Tibetan block as per Unicode v3.2.0:
/[\u0F00-\u0FFF]/; | mit |
etundra-bsmith/angular-buyer | src/app/orders/orderDetails/tests/orderDetails.spec.js | 4005 | describe('Component: orderDetails', function() {
var scope,
q,
oc,
_ocOrderDetails,
mockOrderID,
mockBuyerID,
mockCurrentUser,
mockParams,
stateParams
;
beforeEach(module(function($provide) {
mockCurrentUser = 'CurrentUser123';
mockOrderID = 'OrderID123';
mockBuyerID = 'Buyer123';
mockParams = {search:null, page: null, pageSize: null, searchOn: null, sortBy: null, filters: null, from: null, to: null, favorites: null};
stateParams = {buyerid: mockBuyerID, orderid: mockOrderID};
$provide.value('CurrentUser', mockCurrentUser);
$provide.value('Parameters', mockParams);
}));
beforeEach(module('orderCloud'));
beforeEach(module('orderCloud.sdk'));
beforeEach(inject(function($q, $rootScope, OrderCloudSDK, ocParameters, ocOrderDetails) {
q = $q;
scope = $rootScope.$new();
oc = OrderCloudSDK;
_ocOrderDetails = ocOrderDetails;
}));
describe('State: orderDetails', function() {
var state
;
beforeEach(inject(function($state, $stateParams) {
$stateParams.orderid = stateParams.orderid;
$stateParams.buyerid = stateParams.buyerid;
state = $state.get('orderDetail');
spyOn(_ocOrderDetails, 'Get');
spyOn(oc.LineItems, 'List');
}));
it('should resolve SelectedOrder', inject(function($injector){
$injector.invoke(state.resolve.SelectedOrder);
expect(_ocOrderDetails.Get).toHaveBeenCalledWith(mockOrderID);
}));
it('should resolve OrderLineItems', inject(function($injector) {
$injector.invoke(state.resolve.OrderLineItems);
expect(oc.LineItems.List).toHaveBeenCalledWith(mockOrderID, null, 1, null, null, null, null, mockBuyerID);
}));
});
describe('Controller: OrderDetailsCtrl', function(){
var orderDetailsCtrl,
mockMeta,
mockResponse
;
beforeEach(inject(function($controller, $stateParams){
$stateParams = stateParams;
mockMeta = {Page: 2, PageSize: 15};
mockResponse = {Items: [{Name: 'LineItem2'}, {Name:'LineItem3'}], Meta: mockMeta};
orderDetailsCtrl = $controller('OrderDetailsCtrl', {
$stateParams: $stateParams,
OrderCloudSDK: oc,
SelectedOrder: {ID: 'Order123', Name:'mockSelectedOrder'},
OrderLineItems: {Meta: {Page: 1, PageSize: 12}, Items: [{Name: 'LineItem1'}] }
});
var defer = q.defer();
defer.resolve(mockResponse);
spyOn(oc.LineItems, 'List').and.returnValue(defer.promise);
}));
describe('pageChanged', function(){
it('should update results with page from vm.lineItems.Meta.Page', function(){
var mockPage = 3;
orderDetailsCtrl.lineItems.Meta.Page = mockPage;
orderDetailsCtrl.pageChanged();
expect(oc.LineItems.List).toHaveBeenCalledWith(mockOrderID, null, mockPage, 12, null, null, null, mockBuyerID);
scope.$digest();
expect(orderDetailsCtrl.lineItems).toEqual(mockResponse);
});
});
describe('loadMore', function(){
it('should concatenate next page of results with current list items', function(){
var nextPage = orderDetailsCtrl.lineItems.Meta.Page + 1;
orderDetailsCtrl.loadMore();
expect(oc.LineItems.List).toHaveBeenCalledWith(mockOrderID, null, nextPage, 12, null, null, null, mockBuyerID);
scope.$digest();
expect(orderDetailsCtrl.lineItems.Meta.Page).toBe(nextPage);
expect(orderDetailsCtrl.lineItems.Items).toEqual([{Name:'LineItem1'}, {Name: 'LineItem2'}, {Name:'LineItem3'}]);
});
});
});
}); | mit |
Azure/azure-sdk-for-net | sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Utf8JsonWriterExtensions.cs | 2164 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text.Json;
using Azure.Core;
namespace Azure.AI.MetricsAdvisor
{
internal static class Utf8JsonWriterExtensions
{
public static void WriteNullStringValue(this Utf8JsonWriter writer, string propertyName, DateTimeOffset? value, string format) =>
writer.WriteNullObjectValue(propertyName, value != null ? TypeFormatters.ToString(value.Value, format) : null);
public static void WriteNullStringValue<T>(this Utf8JsonWriter writer, string propertyName, T? value) where T : struct =>
writer.WriteNullObjectValue(propertyName, value?.ToString());
public static void WriteNullObjectValue(this Utf8JsonWriter writer, string propertyName, object value)
{
switch (value)
{
case null:
writer.WriteNull(propertyName);
break;
case string s:
writer.WritePropertyName(propertyName);
writer.WriteStringValue(s);
break;
case int i:
writer.WritePropertyName(propertyName);
writer.WriteNumberValue(i);
break;
case long l:
writer.WritePropertyName(propertyName);
writer.WriteNumberValue(l);
break;
case double d:
writer.WritePropertyName(propertyName);
writer.WriteNumberValue(d);
break;
case bool b:
writer.WritePropertyName(propertyName);
writer.WriteBooleanValue(b);
break;
case IUtf8JsonSerializable serializable:
writer.WritePropertyName(propertyName);
writer.WriteObjectValue(serializable);
break;
default:
throw new NotSupportedException("Not supported type " + value.GetType());
}
}
}
}
| mit |
impactlab/oeem-energy-datastore | datastore/migrations/0007_auto_20150917_1702.py | 701 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('datastore', '0006_auto_20150915_2046'),
]
operations = [
migrations.AddField(
model_name='projectblock',
name='project_owner',
field=models.ForeignKey(to='datastore.ProjectOwner', default=14),
preserve_default=False,
),
migrations.AlterField(
model_name='consumptionmetadata',
name='fuel_type',
field=models.CharField(choices=[('NG', 'natural_gas'), ('E', 'electricity')], max_length=3),
),
]
| mit |
raguay/MyLaunchBarActions | Keyboard Maestro Macros.lbaction/Contents/Scripts/default.js | 966 | function executeMacro(argument) {
if (argument != undefined) {
LaunchBar.executeAppleScript('tell application id "com.stairways.keyboardmaestro.engine" to do script "' + argument + '"');
}
}
function run() {
var output = [];
var macros = Plist.parse(LaunchBar.executeAppleScript('tell application id "com.stairways.keyboardmaestro.engine" to gethotkeys with asstring and getall'));
macros.forEach(function (macroGroup, index, array){
macroGroup['macros'].forEach(function(macro, index, array) {
var name = macro['name'];
if (name == undefined) {
name = macro['namev2'];
}
output.push({
title: name,
actionArgument: macro['uid'],
icon: 'com.stairways.keyboardmaestro.editor',
action: 'executeMacro',
actionRunsInBackground: true
});
});
});
return output;
} | mit |
b091/imbasf | src/Imbax/CMSBundle/Entity/Page.php | 1990 | <?php
namespace Imbax\CMSBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Page
*
* @ORM\Table()
* @ORM\Entity
*/
class Page
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="content", type="text")
*/
private $content;
/**
* @var Category
* @ORM\ManyToOne(targetEntity="Category", inversedBy="pages")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
* @return Page
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set content
*
* @param string $content
* @return Page
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set category
*
* @param \Imbax\CMSBundle\Entity\Category $category
* @return Page
*/
public function setCategory(\Imbax\CMSBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* @return \Imbax\CMSBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
}
| mit |
alipha/FFRK | Stats/Stats/App_Start/RouteConfig.cs | 575 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Stats
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| mit |
NoFearForBeers/BeerMe | public/app/shared/services/exception.service.ts | 348 | import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
export class ExceptionService {
constructor() { }
catchBadResponse<T>(errorResponse: any): Observable<T> {
console.log('this is error: ' + errorResponse);
return Observable.throw(errorResponse.json().error || 'Server error');
};
} | mit |
github/codeql | ruby/ql/test/query-tests/security/cwe-352/railsapp/config/application.rb | 512 | require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Railsapp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
# BAD: Disabling forgery protection may open the application to CSRF attacks
config.action_controller.allow_forgery_protection = false
end
end
| mit |
vlefrere/ProjetBDD | vendor/gedmo/doctrine-extensions/lib/Gedmo/IpTraceable/Mapping/Driver/Yaml.php | 5390 | <?php
namespace Gedmo\IpTraceable\Mapping\Driver;
use Gedmo\Mapping\Driver\File;
use Gedmo\Mapping\Driver;
use Gedmo\Exception\InvalidMappingException;
/**
* This is a yaml mapping driver for IpTraceable
* behavioral extension. Used for extraction of extended
* metadata from yaml specifically for IpTraceable
* extension.
*
* @author Pierre-Charles Bertineau <[email protected]>
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
class Yaml extends File implements Driver {
/**
* File extension
* @var string
*/
protected $_extension = '.dcm.yml';
/**
* List of types which are valid for IP
*
* @var array
*/
private $validTypes = array(
'string',
);
/**
* {@inheritDoc}
*/
public function readExtendedMetadata($meta, array &$config)
{
$mapping = $this->_getMapping($meta->name);
if (isset($mapping['fields'])) {
foreach ($mapping['fields'] as $field => $fieldMapping) {
if (isset($fieldMapping['gedmo']['ipTraceable'])) {
$mappingProperty = $fieldMapping['gedmo']['ipTraceable'];
if (!$this->isValidField($meta, $field)) {
throw new InvalidMappingException("Field - [{$field}] type is not valid and must be 'string' in class - {$meta->name}");
}
if (!isset($mappingProperty['on']) || !in_array($mappingProperty['on'], array('update', 'create', 'change'))) {
throw new InvalidMappingException("Field - [{$field}] trigger 'on' is not one of [update, create, change] in class - {$meta->name}");
}
if ($mappingProperty['on'] == 'change') {
if (!isset($mappingProperty['field'])) {
throw new InvalidMappingException("Missing parameters on property - {$field}, field must be set on [change] trigger in class - {$meta->name}");
}
$trackedFieldAttribute = $mappingProperty['field'];
$valueAttribute = isset($mappingProperty['value']) ? $mappingProperty['value'] : null;
if (is_array($trackedFieldAttribute) && null !== $valueAttribute) {
throw new InvalidMappingException("IpTraceable extension does not support multiple value changeset detection yet.");
}
$field = array(
'field' => $field,
'trackedField' => $trackedFieldAttribute,
'value' => $valueAttribute,
);
}
$config[$mappingProperty['on']][] = $field;
}
}
}
if (isset($mapping['manyToOne'])) {
foreach ($mapping['manyToOne'] as $field => $fieldMapping) {
if (isset($fieldMapping['gedmo']['ipTraceable'])) {
$mappingProperty = $fieldMapping['gedmo']['ipTraceable'];
if (!$meta->isSingleValuedAssociation($field)) {
throw new InvalidMappingException("Association - [{$field}] is not valid, it must be a one-to-many relation or a string field - {$meta->name}");
}
if (!isset($mappingProperty['on']) || !in_array($mappingProperty['on'], array('update', 'create', 'change'))) {
throw new InvalidMappingException("Field - [{$field}] trigger 'on' is not one of [update, create, change] in class - {$meta->name}");
}
if ($mappingProperty['on'] == 'change') {
if (!isset($mappingProperty['field'])) {
throw new InvalidMappingException("Missing parameters on property - {$field}, field must be set on [change] trigger in class - {$meta->name}");
}
$trackedFieldAttribute = $mappingProperty['field'];
$valueAttribute = isset($mappingProperty['value']) ? $mappingProperty['value'] : null;
if (is_array($trackedFieldAttribute) && null !== $valueAttribute) {
throw new InvalidMappingException("IpTraceable extension does not support multiple value changeset detection yet.");
}
$field = array(
'field' => $field,
'trackedField' => $trackedFieldAttribute,
'value' => $valueAttribute,
);
}
$config[$mappingProperty['on']][] = $field;
}
}
}
}
/**
* {@inheritDoc}
*/
protected function _loadMappingFile($file)
{
return \Symfony\Component\Yaml\Yaml::parse($file);
}
/**
* Checks if $field type is valid
*
* @param object $meta
* @param string $field
*
* @return boolean
*/
protected function isValidField($meta, $field)
{
$mapping = $meta->getFieldMapping($field);
return $mapping && in_array($mapping['type'], $this->validTypes);
}
}
| mit |
monsterhunteronline/monsterhunteronline.github.io | monsters/gravios/data.js | 348 | var monsterArray =
{
"name": "铠龙",
"other": [
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
""
],
"weakness": [
{
"data": [
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0"
]
}
]
}; | mit |
panarasi/MobileCenter-ReactNative-Demo | node_modules/mobile-center-analytics/scripts/postlink.js | 1282 | var rnpmlink = require('mobile-center-link-scripts');
var package = require('./../package.json');
return rnpmlink.ios.initMobileCenterConfig().then(function (file) {
console.log('App Secret for iOS written to ' + file);
var prompt = package.rnpm.params[0];
prompt.message = prompt.message.replace(/Android/, 'iOS');
return rnpmlink.inquirer.prompt(prompt);
}).then(function (answer) {
var code = answer.whenToEnableAnalytics === 'ALWAYS_SEND' ?
' [RNAnalytics registerWithInitiallyEnabled:true]; // Initialize Mobile Center analytics' :
' [RNAnalytics registerWithInitiallyEnabled:false]; // Initialize Mobile Center analytics'
return rnpmlink.ios.initInAppDelegate('#import <RNAnalytics/RNAnalytics.h>', code);
}).then(function (file) {
console.log('Added code to initialize iOS Crashes SDK in ' + file);
return rnpmlink.ios.addPodDeps([
{ pod: 'MobileCenter', version: '0.3.0' },
{ pod: 'RNMobileCenter', version: '0.1.0' }
]).catch(function (e) {
console.log(`
Could not install dependencies using CocoaPods.
Please refer the documentation to install dependencies manually.
Error Reason - ${e.message}
`)
return Promise.resolve();
})
}); | mit |
BACRallyApps/IterationBreakdownChart | src/Calculator.js | 6166 | var Ext = window.Ext4 || window.Ext;
var __map = function (mapField, records) {
var map = {};
Ext.Array.each(records, function (record) {
if (record.raw) {
map[record.raw[mapField]] = record.raw;
} else {
map[record[mapField]] = record;
}
});
return map;
};
var __sortByDate = function (dateField, outField, map) {
var arr = Ext.Object.getValues(map);
var sorted = [];
//console.log('__sortByDate:arr', arr);
arr.sort(function (a, b) {
var da = Rally.util.DateTime.fromIsoString(a[dateField]);
var db = Rally.util.DateTime.fromIsoString(b[dateField]);
return Rally.util.DateTime.getDifference(da, db, 'day');
});
Ext.Array.each(arr, function (rec) {
sorted.push(rec[outField]);
});
return sorted;
};
var __sumArray = function (arr, selectorFn) {
var count = 0;
Ext.Array.each(arr, function (item) {
var num = parseInt(selectorFn(item) + '', 10);
if (!isNaN(num)) {
count = count + num;
}
});
return count;
};
Ext.define('IterationBreakdownCalculator', {
extend: 'Rally.data.lookback.calculator.BaseCalculator',
_mapReleasesByName: Ext.bind(__map, this, ['Name'], 0),
_sortReleasesByStartDate: Ext.bind(__sortByDate, this, ['ReleaseStartDate', 'Name'], 0),
_mapIterationsByName: Ext.bind(__map, this, ['Name'], 0),
_sortIterationsByStartDate: Ext.bind(__sortByDate, this, ['StartDate', 'Name'], 0),
_sumArrayByPlanEstimate: Ext.bind(__sumArray, this, [function (item) { return item.PlanEstimate || '0'; }], 1),
prepareChartData: function (stores) {
var snapshots = [];
Ext.Array.each(stores, function (store) {
store.each(function (record) {
snapshots.push(record.raw);
});
});
return this.runCalculation(snapshots);
},
_bucketArtifactsIntoIterations: function (records) {
var me = this;
var rawData = {};
Ext.Array.each(records, function (record) {
if (record._type.toLowerCase().indexOf('iteration') !== -1) {
return;
}
var key = me._getBucketKey(record);
rawData[key] = me._pushRecord(rawData[key], record);
});
return rawData;
},
_bucketStoriesIntoReleases: function (records) {
var bucket = {};
Ext.Array.each(records, function (record) {
if (record._type.toLowerCase().indexOf('portfolioitem') !== -1) { return; }
if (record._type.toLowerCase().indexOf('iteration') !== -1) { return; }
if (!record.Release) { return; }
bucket[record.Release.Name] = bucket[record.Release.Name] || [];
bucket[record.Release.Name].push(record);
});
return bucket;
},
_isIterationInRelease: function (iteration, release) {
var iStart = Rally.util.DateTime.fromIsoString(iteration.StartDate);
var rStart = Rally.util.DateTime.fromIsoString(release.ReleaseStartDate);
var rEnd = Rally.util.DateTime.fromIsoString(release.ReleaseDate);
return !!((Rally.util.DateTime.getDifference(iStart, rStart, 'day') >= 0) &&
(Rally.util.DateTime.getDifference(rEnd, iStart, 'day') >= 1));
},
_getIterations: function (records) {
var iterations = [];
Ext.Array.each(records, function (record) {
if (record._type.toLowerCase() !== 'iteration') { return; }
iterations.push(record);
});
return iterations;
},
_getBucketKey: function (record) {
return this._getIterationKey(record.Iteration);
},
_getIterationKey: function (iteration) {
var rawDate = Rally.util.DateTime.fromIsoString(iteration.EndDate);
var timezone = Rally.util.DateTime.parseTimezoneOffset(iteration.EndDate);
var localDate = Rally.util.DateTime.add(rawDate, 'minute', timezone * -1);
var date = Rally.util.DateTime.formatWithDefault(localDate);
return iteration.Name + '<br>' + date;
},
_sumIterationByField: function (stories, field, values, noValueLabel) {
var sum = {};
var pe;
var v;
Ext.Array.each(values, function (value) {
sum[value] = 0;
});
Ext.Array.each(stories, function (story) {
pe = parseInt('' + story.PlanEstimate, 10);
v = story[field] || noValueLabel;
if (Ext.isObject(v)) { console.log(v); }
if (pe && !isNaN(pe)) {
sum[v] = sum[v] + story.PlanEstimate;
}
});
return sum;
},
_pushRecord: function (arr, itm) {
if (!Ext.isArray(arr)) {
return [itm];
} else {
return arr.concat([itm]);
}
},
runCalculation: function (records) {
//console.log('Running Calculations');
//console.dir(records);
var me = this;
me.iterations = me._getIterations(records);
var iterationMap = me._mapIterationsByName(me.iterations);
var iterationOrder = me._sortIterationsByStartDate(iterationMap);
var rawData = me._bucketArtifactsIntoIterations(records);
var iterationData = {};
var categories;
var series = [];
Ext.Array.each(iterationOrder, function (iteration) {
var key = me._getIterationKey(iterationMap[iteration]);
iterationData[key] = me._sumIterationByField(rawData[key], me.field, me.values, me.noValueLabel);
});
Ext.Array.each(me.values, function (value) {
var v = value || me.noValueLabel;
var data = [];
Ext.Array.each(iterationOrder, function (iteration) {
var key = me._getIterationKey(iterationMap[iteration]);
data.push(iterationData[key][v] || 0);
});
var label = Ext.Array.map(v.split('_'), function (word) {
return Ext.String.capitalize(word.toLowerCase());
}).join(' ');
series.push({
type: 'column',
name: label,
data: data
});
});
categories = [];
Ext.Array.each(iterationOrder, function (iName) {
categories.push(me._getIterationKey(iterationMap[iName]));
});
//debugger;
return {
categories: categories,
series: series
};
},
});
| mit |
mientjan/EaselTS | src/easelts/geom/FluidMeasurementsUnit.js | 416 | define(["require", "exports"], function (require, exports) {
"use strict";
var FluidMeasurementsUnit = (function () {
function FluidMeasurementsUnit(value, unit) {
this.value = value;
this.unit = unit;
}
return FluidMeasurementsUnit;
}());
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = FluidMeasurementsUnit;
});
| mit |
uhlibraries-digital/brays | src/app/app.module.ts | 3616 | import 'zone.js/dist/zone-mix';
import 'reflect-metadata';
import 'polyfills';
import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
/* Components */
import { ActivityComponent } from './components/activity/activity.component';
import { AppComponent } from './app.component';
import { AutofillComponent } from './components/autofill/autofill.component';
import { DigitalObjectsComponent } from './components/digital-objects/digital-objects.component';
import { EdtfHumanizeComponent } from './components/edtf-humanize/edtf-humanize.component';
import { MetadataComponent } from './components/metadata/metadata.component';
import { NotificationComponent } from './components/notification/notification.component';
import { PromptComponent } from './components/prompt/prompt.component';
import { VocabularyAutocompleteComponent } from './components/vocabulary-autocomplete/vocabulary-autocomplete.component';
/* Modules */
// import { AppRoutingModule } from './app-routing.module';
/* Services */
import { ArmandService } from './services/armand.service';
import { AvalonService } from './services/avalon.service';
import { ContentDmService } from './services/content-dm.service';
import { ElectronService } from './services/electron.service';
import { GreensService } from './services/greens.service';
import { LocalStorageService } from './services/local-storage.service';
import { LoggerService } from './services/logger.service';
import { MapService } from './services/map.service';
import { MetadataExportService } from './services/metadata-export.service';
import { MintService } from './services/mint.service';
import { ObjectService } from './services/object.service';
import { PreferencesService } from './services/preferences.service';
import { ProgressBarService } from './services/progress-bar.service';
import { PromptService } from './services/prompt.service';
import { ValidationService } from './services/valication.service';
import { VocabularyService } from './services/vocabulary.service';
import { WatchService } from './services/watch.service';
/* Directives */
import { Autosize } from './directives/autosize.directive';
import { ObligationHighlight } from './directives/obligation-highlight.directive';
import { StatusColor } from './directives/status-color.directive';
import { Validate } from './directives/validate.directive';
import { VocabularyAutocomplete } from './directives/vocabulary-autocomplete.directive';
@NgModule({
declarations: [
ActivityComponent,
AppComponent,
AutofillComponent,
DigitalObjectsComponent,
EdtfHumanizeComponent,
MetadataComponent,
NotificationComponent,
PromptComponent,
VocabularyAutocompleteComponent,
Autosize,
ObligationHighlight,
StatusColor,
Validate,
VocabularyAutocomplete
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
NgbModule.forRoot()
],
providers: [
ArmandService,
AvalonService,
ContentDmService,
ElectronService,
GreensService,
LocalStorageService,
LoggerService,
MapService,
MetadataExportService,
MintService,
ObjectService,
PreferencesService,
ProgressBarService,
PromptService,
ValidationService,
VocabularyService,
WatchService
],
entryComponents: [
VocabularyAutocompleteComponent,
AutofillComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
| mit |
softak098/mReporterLib | mReporter/mReporterLib/MatrixPrinters/Line.cs | 4443 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mReporterLib
{
public class GetDataResult
{
/// <summary>
/// Value to be rendered in place of field
/// </summary>
public string Value;
/// <summary>
/// Indicates word wrap is enabled for field
/// </summary>
public bool WordWrap;
/// <summary>
/// Alignment of value in field boundary
/// </summary>
public Align Alignment;
/// <summary>
/// Font style for field
/// </summary>
public FontStyle Style;
public GetDataResult()
{
WordWrap = false;
Alignment = Align.Left;
Style = FontStyle.Normal;
}
}
public class GetDataArgs
{
/// <summary>
/// Index of field in line, first=0
/// </summary>
public int Index { get; set; }
/// <summary>
/// Data associated with line, if any
/// </summary>
public object Data { get; set; }
/// <summary>
/// Data to render in field
/// </summary>
public GetDataResult Result { get; set; }
}
public delegate void GetDataHandler(GetDataArgs e);
public class Line : ReportItem
{
private LineTemplate _lineTemplate;
string _template;
public string Template
{
get {
return _template;
}
set {
_template = value;
_lineTemplate = new LineTemplate(this, value);
}
}
/// <summary>
/// TRUE to repeat all static text items on line to next lines if some value needs to be splitted to multiple lines
/// </summary>
public bool RepeatStaticItems;
/// <summary>
/// TRUE to generate line on new page (like header for data)
/// </summary>
public bool RepeatOnNewPage;
/// <summary>
/// Sets font style for whole line
/// </summary>
public FontStyle Style;
/// <summary>
/// Sets print style for whole line
/// </summary>
public PrintStyle PrintStyle;
/// <summary>
/// Alignment of the line
/// </summary>
public Align Alignment;
/// <summary>
/// Type of font used
/// </summary>
public FontType FontType;
/// <summary>
/// Controls inserting page break in block generated by line.
/// </summary>
public bool PageBreakInside;
/// <summary>
/// Handler to get all fields values before line is rendered
/// </summary>
public GetDataHandler GetData { get; set; }
public Line(ReportItemType type) : base(type)
{
RepeatStaticItems = false;
RepeatOnNewPage = false;
PageBreakInside = true;
Style = FontStyle.Normal;
PrintStyle = PrintStyle.AsBefore;
Alignment = Align.AsBefore;
FontType = FontType.A;
}
protected virtual GetDataResult GetDataResultInternal(int index)
{
if (this.GetData != null) {
GetDataArgs args = new GetDataArgs {
Index = index,
Data = Data,
Result = new GetDataResult()
};
this.GetData(args);
return args.Result;
}
return null;
}
public override void Render(RenderContext context)
{
if (_lineTemplate == null) return;
GetDataResult[] r = new GetDataResult[_lineTemplate.ValueCount];
for (int i = 0; i < _lineTemplate.ValueCount; i++) {
r[i] = GetDataResultInternal(i);
}
LineElement oLine = new LineElement(context);
_lineTemplate.Build(context, oLine, r);
context.AddToOutput(this, oLine);
if (this.Items != null) {
// process child items
context.SetParentElement(oLine);
Items.ForEach(i => i.Render(context));
context.SetParentElement(oLine.Parent);
}
}
public override string ToString()
{
return this.Type.ToString();
}
}
}
| mit |
joda17/Diorite-API | src/main/java/org/diorite/material/blocks/others/CakeMat.java | 5861 | package org.diorite.material.blocks.others;
import java.util.Map;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.diorite.cfg.magic.MagicNumbers;
import org.diorite.material.BlockMaterialData;
import org.diorite.material.blocks.others.MushroomBlockMat.Type;
import org.diorite.utils.collections.maps.CaseInsensitiveMap;
import gnu.trove.map.TByteObjectMap;
import gnu.trove.map.hash.TByteObjectHashMap;
/**
* Class representing block "Cake" and all its subtypes.
*/
public class CakeMat extends BlockMaterialData
{
/**
* Sub-ids used by diorite/minecraft by default
*/
public static final byte USED_DATA_VALUES = 6;
/**
* Blast resistance of block, can be changed only before server start.
* Final copy of blast resistance from {@link MagicNumbers} class.
*/
public static final float BLAST_RESISTANCE = MagicNumbers.MATERIAL__CAKE__BLAST_RESISTANCE;
/**
* Hardness of block, can be changed only before server start.
* Final copy of hardness from {@link MagicNumbers} class.
*/
public static final float HARDNESS = MagicNumbers.MATERIAL__CAKE__HARDNESS;
public static final CakeMat CAKE_0 = new CakeMat();
public static final CakeMat CAKE_1 = new CakeMat(0x1);
public static final CakeMat CAKE_2 = new CakeMat(0x2);
public static final CakeMat CAKE_3 = new CakeMat(0x3);
public static final CakeMat CAKE_4 = new CakeMat(0x4);
public static final CakeMat CAKE_5 = new CakeMat(0x5);
public static final CakeMat CAKE_6 = new CakeMat(0x6);
private static final Map<String, CakeMat> byName = new CaseInsensitiveMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR);
private static final TByteObjectMap<CakeMat> byID = new TByteObjectHashMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR);
protected final byte piecesEaten;
@SuppressWarnings("MagicNumber")
protected CakeMat()
{
super("CAKE", 92, "minecraft:cake", 1, "0", (byte) 0x00);
this.piecesEaten = 0x0;
}
protected CakeMat(final int piecesEaten)
{
super(CAKE_0.name(), CAKE_0.ordinal(), CAKE_0.getMinecraftId(), Integer.toString(piecesEaten), (byte) piecesEaten);
this.piecesEaten = (byte) piecesEaten;
}
protected CakeMat(final String enumName, final int id, final String minecraftId, final int maxStack, final String typeName, final byte type, final byte piecesEaten)
{
super(enumName, id, minecraftId, maxStack, typeName, type);
this.piecesEaten = piecesEaten;
}
@Override
public float getBlastResistance()
{
return BLAST_RESISTANCE;
}
@Override
public float getHardness()
{
return HARDNESS;
}
@Override
public CakeMat getType(final String name)
{
return getByEnumName(name);
}
@Override
public CakeMat getType(final int id)
{
return getByID(id);
}
@Override
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("piecesEaten", this.piecesEaten).toString();
}
/**
* For vanilla cake blocks should return values from 0 to 6.
*
* @return amount of eated pieces of cake {@literal <3}
*/
public byte getPiecesEaten()
{
return this.piecesEaten;
}
/**
* Return cake with selected amount of eaten pieces.
* Vanilla server will return null for all values above 6.
*
* @param piecesEaten amount of eated pieces of cake.
*
* @return cake with selected amount of eaten pieces or null.
*/
public CakeMat getPiecesEaten(final byte piecesEaten)
{
return getByID(piecesEaten);
}
/**
* Returns one of Cake sub-type based on sub-id, may return null
*
* @param id sub-type id
*
* @return sub-type of Cake or null
*/
public static CakeMat getByID(final int id)
{
return byID.get((byte) id);
}
/**
* Returns one of Cake sub-type based on name (selected by diorite team), may return null
* If block contains only one type, sub-name of it will be this same as name of material.
*
* @param name name of sub-type
*
* @return sub-type of Cake or null
*/
public static CakeMat getByEnumName(final String name)
{
return byName.get(name);
}
/**
* Returns one of Cake sub-type based on amount of eaten pieces.
* It will never return null. (full cake if number is out of range)
*
* @param type amount of eaten pieces.
*
* @return sub-type of Cake
*/
public static CakeMat getCake(final Type type)
{
final CakeMat cake = getByID(type.getFlag());
if (cake == null)
{
return CAKE_0;
}
return cake;
}
/**
* Register new sub-type, may replace existing sub-types.
* Should be used only if you know what are you doing, it will not create fully usable material.
*
* @param element sub-type to register
*/
public static void register(final CakeMat element)
{
byID.put((byte) element.getType(), element);
byName.put(element.name(), element);
}
@Override
public CakeMat[] types()
{
return CakeMat.cakeTypes();
}
/**
* @return array that contains all sub-types of this block.
*/
public static CakeMat[] cakeTypes()
{
return byID.values(new CakeMat[byID.size()]);
}
static
{
CakeMat.register(CAKE_0);
CakeMat.register(CAKE_1);
CakeMat.register(CAKE_2);
CakeMat.register(CAKE_3);
CakeMat.register(CAKE_4);
CakeMat.register(CAKE_5);
CakeMat.register(CAKE_6);
}
}
| mit |
skyrim/hlviewer.js | src/Game.ts | 12216 | import { createNanoEvents, Emitter as EventEmitter } from 'nanoevents'
import { Bsp } from './Bsp'
import * as Time from './Time'
import { Sound } from './Sound'
import { Loader } from './Loader'
import { Config } from './Config'
import { Mouse } from './Input/Mouse'
import { Touch } from './Input/Touch'
import { Replay } from './Replay/Replay'
import { Camera } from './Graphics/Camera'
import { Keyboard } from './Input/Keyboard'
import { SoundSystem } from './SoundSystem'
import { Context } from './Graphics/Context'
import { ReplayPlayer } from './ReplayPlayer'
import { Renderer } from './Graphics/Renderer'
import { SkyScene } from './Graphics/SkyScene'
import { WorldScene } from './Graphics/WorldScene'
export enum PlayerMode {
FREE,
REPLAY
}
type GameInitSuccess = { status: 'success'; game: Game }
type GameInitError = { status: 'error'; message: string }
type GameInit = GameInitSuccess | GameInitError
export class Game {
public static init(config: Config): GameInit {
const status = Context.checkWebGLSupport()
if (!status.hasSupport) {
return {
status: 'error',
message: 'No WebGL support!'
}
}
const canvas = document.createElement('canvas')
if (!canvas) {
return {
status: 'error',
message: 'Failed to create <canvas> element!'
}
}
const context = Context.init(canvas)
if (!context) {
return {
status: 'error',
message: 'Failed to initialize WebGL context'
}
}
const renderer = Renderer.init(context)
if (!renderer) {
return {
status: 'error',
message: 'Failed to initialize renderer'
}
}
const worldScene = WorldScene.init(context)
if (!worldScene) {
return {
status: 'error',
message: 'Failed to initialize world scene'
}
}
const skyScene = SkyScene.init(context)
if (!skyScene) {
return {
status: 'error',
message: 'Failed to initialize sky scene'
}
}
const game = new Game({
canvas,
config,
context,
renderer,
worldScene,
skyScene
})
return {
status: 'success',
game
}
}
config: Config
pauseTime: number = 0
isPaused: boolean = false
lastTime: number = 0
accumTime: number = 0
readonly timeStep: number = 1 / 60
title: string = ''
mode: PlayerMode
pointerLocked: boolean = false
touch: Touch = new Touch()
mouse: Mouse = new Mouse()
keyboard: Keyboard = new Keyboard()
loader: Loader
entities: any[] = []
sounds: Sound[]
soundSystem: SoundSystem
events: EventEmitter
player: ReplayPlayer
canvas: HTMLCanvasElement
mapName: string
context: Context
camera: Camera
renderer: Renderer
worldScene: WorldScene
skyScene: SkyScene
constructor(params: {
config: Config
canvas: HTMLCanvasElement
context: Context
renderer: Renderer
worldScene: WorldScene
skyScene: SkyScene
}) {
this.sounds = []
this.soundSystem = new SoundSystem()
this.config = params.config
this.loader = new Loader(this.config)
this.loader.events.on('loadall', this.onLoadAll)
document.addEventListener('touchstart', this.onTouchStart, false)
document.addEventListener('touchend', this.onTouchEnd, false)
document.addEventListener('touchcancel', this.onTouchEnd, false)
document.addEventListener('touchmove', this.onTouchMove, false)
document.addEventListener('mousemove', this.onMouseMove, false)
window.addEventListener('keydown', this.keyDown)
window.addEventListener('keyup', this.keyUp)
window.addEventListener('visibilitychange', this.onVisibilityChange)
this.canvas = params.canvas
this.camera = Camera.init(this.canvas.width / this.canvas.height)
this.context = params.context
this.renderer = params.renderer
this.worldScene = params.worldScene
this.skyScene = params.skyScene
this.mode = PlayerMode.FREE
this.player = new ReplayPlayer(this)
this.events = createNanoEvents()
this.mapName = ''
}
getCanvas() {
return this.canvas
}
load(name: string) {
this.events.emit('loadstart')
this.loader.load(name)
}
changeMap(map: Bsp) {
if (this.mapName.toLowerCase() === map.name.toLowerCase()) {
return
}
this.mapName = map.name
this.worldScene.changeMap(map)
this.skyScene.changeMap(map)
this.entities = map.entities
const spawn = map.entities.find(e => e['classname'] === 'info_player_start')
if (spawn) {
this.camera.position[0] = spawn.origin[0]
this.camera.position[1] = spawn.origin[1]
this.camera.position[2] = spawn.origin[2]
} else {
this.camera.position[0] = 0
this.camera.position[1] = 0
this.camera.position[2] = 0
}
this.camera.rotation[0] = 0 // Math.PI / 2
this.camera.rotation[1] = 0
this.camera.rotation[2] = 0
}
changeReplay(replay: Replay) {
this.events.emit('prereplaychange', this, replay)
this.player.changeReplay(replay)
this.events.emit('postreplaychange', this, replay)
}
changeMode(mode: PlayerMode) {
this.mode = mode
this.events.emit('modechange', mode)
}
setTitle(title: string) {
this.title = title
this.events.emit('titlechange', title)
}
getTitle() {
return this.title
}
onLoadAll = (loader: Loader) => {
if (loader && loader.replay) {
this.changeReplay(loader.replay.data)
this.changeMode(PlayerMode.REPLAY)
}
if (!loader.map || !loader.map.data) {
return
}
const map = loader.map.data
const skies = loader.skies
let skiesValid = true
skies.forEach(sky => {
skiesValid = skiesValid && sky.isDone()
})
if (skiesValid) {
skies.forEach(sky => (sky.data ? map.skies.push(sky.data) : 0))
}
// add sprites
Object.entries(loader.sprites).forEach(([name, item]) => {
if (item.data) {
map.sprites[name] = item.data
}
})
if (loader.sounds.length > 0) {
loader.sounds.forEach(sound => {
if (sound.data) {
this.sounds.push(sound.data)
}
})
}
this.changeMap(map)
this.events.emit('load', loader)
}
draw = () => {
requestAnimationFrame(this.draw)
const canvas = this.canvas
const parent = canvas.parentElement
if (parent) {
const pw = parent.clientWidth
const ph = parent.clientHeight
if (canvas.width !== pw || canvas.height !== ph) {
canvas.width = pw
canvas.height = ph
this.camera.aspect = canvas.clientWidth / canvas.clientHeight
this.camera.updateProjectionMatrix()
this.context.gl.viewport(
0,
0,
this.context.gl.drawingBufferWidth,
this.context.gl.drawingBufferHeight
)
}
if (
canvas.clientWidth !== canvas.width ||
canvas.clientHeight !== canvas.height
) {
canvas.width = canvas.clientWidth
canvas.height = canvas.clientHeight
this.camera.aspect = canvas.clientWidth / canvas.clientHeight
this.camera.updateProjectionMatrix()
this.context.gl.viewport(
0,
0,
this.context.gl.drawingBufferWidth,
this.context.gl.drawingBufferHeight
)
}
}
const currTime = Time.now() / 1000
const dt = currTime - this.lastTime
this.accumTime += dt
while (this.accumTime > this.timeStep) {
this.update(this.timeStep)
this.accumTime -= this.timeStep
}
this.renderer.draw()
if (this.mapName !== '') {
this.skyScene.draw(this.camera)
this.worldScene.draw(this.camera, this.entities)
}
this.lastTime = currTime
}
update(dt: number) {
this.events.emit('preupdate', this)
const camera = this.camera
const keyboard = this.keyboard
const mouse = this.mouse
const touch = this.touch
if (this.mode === PlayerMode.REPLAY) {
this.player.update(dt)
} else if (this.mode === PlayerMode.FREE) {
if (this.touch.pressed) {
camera.rotation[0] = Math.min(
Math.max(camera.rotation[0] + touch.delta[1] / 100, -Math.PI / 2),
Math.PI / 2
)
camera.rotation[1] -= touch.delta[0] / 100
} else {
camera.rotation[0] = Math.min(
Math.max(camera.rotation[0] + mouse.delta[1] / 100, -Math.PI / 2),
Math.PI / 2
)
camera.rotation[1] -= mouse.delta[0] / 100
}
const speed = 500
const ds = speed * dt
const KEY_W = Keyboard.KEYS.W
const KEY_S = Keyboard.KEYS.S
const KEY_A = Keyboard.KEYS.A
const KEY_D = Keyboard.KEYS.D
const downKey = Keyboard.KEYS.C
const upKey = Keyboard.KEYS.SPACE
if (keyboard.keys[KEY_W] !== keyboard.keys[KEY_S]) {
if (keyboard.keys[KEY_W]) {
camera.position[1] -= Math.cos(camera.rotation[1] + Math.PI / 2) * ds
camera.position[0] += Math.sin(camera.rotation[1] + Math.PI / 2) * ds
} else if (keyboard.keys[KEY_S]) {
camera.position[1] -= Math.cos(camera.rotation[1] - Math.PI / 2) * ds
camera.position[0] += Math.sin(camera.rotation[1] - Math.PI / 2) * ds
}
}
if (keyboard.keys[KEY_A] !== keyboard.keys[KEY_D]) {
if (keyboard.keys[KEY_A]) {
camera.position[1] += Math.cos(camera.rotation[1]) * ds
camera.position[0] -= Math.sin(camera.rotation[1]) * ds
} else if (keyboard.keys[KEY_D]) {
camera.position[1] -= Math.cos(camera.rotation[1]) * ds
camera.position[0] += Math.sin(camera.rotation[1]) * ds
}
}
if (keyboard.keys[upKey] !== keyboard.keys[downKey]) {
if (keyboard.keys[upKey]) {
camera.position[2] += ds
} else if (keyboard.keys[downKey]) {
camera.position[2] -= ds
}
}
}
mouse.delta[0] = 0
mouse.delta[1] = 0
this.events.emit('postupdate', this)
}
onTouchStart = (e: TouchEvent) => {
const touch = e.touches.item(0)
if (touch) {
this.touch.pressed = true
this.touch.position[0] = touch.clientX
this.touch.position[1] = touch.clientY
}
}
onTouchEnd = () => {
this.touch.pressed = false
this.touch.delta[0] = 0
this.touch.delta[1] = 0
}
onTouchMove = (e: TouchEvent) => {
const touch = e.touches.item(0)
if (touch && this.touch.pressed) {
this.touch.delta[0]
this.touch.delta[0] = touch.clientX - this.touch.position[0]
this.touch.delta[1] = touch.clientY - this.touch.position[1]
this.touch.position[0] = touch.clientX
this.touch.position[1] = touch.clientY
}
}
onMouseMove = (e: MouseEvent) => {
if (this.pointerLocked) {
this.mouse.delta[0] = e.movementX * 0.5 // mul 0.5 to lower sensitivity
this.mouse.delta[1] = e.movementY * 0.5 //
this.mouse.position[0] = e.pageX
this.mouse.position[1] = e.pageY
}
}
keyDown = (e: KeyboardEvent) => {
this.keyboard.keys[e.which] = 1
if (this.pointerLocked) {
e.preventDefault()
return false
}
return true
}
keyUp = (e: KeyboardEvent) => {
this.keyboard.keys[e.which] = 0
if (this.pointerLocked) {
e.preventDefault()
return false
}
return true
}
onVisibilityChange = () => {
if (document.hidden) {
if (this.isPaused) {
return
}
this.pauseTime = Time.now() / 1000
this.isPaused = true
} else {
if (!this.isPaused) {
return
}
this.lastTime = Time.now() / 1000 - this.pauseTime + this.lastTime
this.isPaused = false
}
}
}
| mit |
huazh/node-opcua | documentation/lprc.js | 430 | /*global module, require */
module.exports = function(Folder, args) {
if (args.file.length === 0) {
args.file = [
"creating_a_client.md",
"creating_a_server.md",
"create_a_weather_station.md",
"server_with_da_variables.md",
"server_with_method.md"
];
}
args.build = ".";
args.src = ".";
require('litpro-jshint')(Folder, args);
};
| mit |
litepubl/cms | lib/languages/en/admin.js | 381 | /**
* LitePubl CMS
*
* copyright 2010 - 2017 Vladimir Yushko http://litepublisher.com/ http://litepublisher.ru/
* license https://github.com/litepubl/cms/blob/master/LICENSE.txt MIT
* link https://github.com/litepubl\cms
* version 7.08
*/
(function(window) {
window.lang = window.lang || {};
window.lang.admin = {
calendar: 'Calendar'
};
})(window); | mit |
victorsantoss/angular-grid | src/js/paginationController.js | 8087 | var TEMPLATE = [
'<span id="pageRowSummaryPanel" class="ag-paging-row-summary-panel">',
'<span id="firstRowOnPage"></span>',
' [TO] ',
'<span id="lastRowOnPage"></span>',
' [OF] ',
'<span id="recordCount"></span>',
'</span>',
'<span class="ag-paging-page-summary-panel">',
'<button class="ag-paging-button" id="btFirst">[FIRST]</button>',
'<button class="ag-paging-button" id="btPrevious">[PREVIOUS]</button>',
' [PAGE] ',
'<span id="current"></span>',
' [OF] ',
'<span id="total"></span>',
'<button class="ag-paging-button" id="btNext">[NEXT]</button>',
'<button class="ag-paging-button" id="btLast">[LAST]</button>',
'</span>'
].join('');
function PaginationController() {}
PaginationController.prototype.init = function(ePagingPanel, angularGrid, gridOptionsWrapper) {
this.gridOptionsWrapper = gridOptionsWrapper;
this.angularGrid = angularGrid;
this.populatePanel(ePagingPanel);
this.callVersion = 0;
};
PaginationController.prototype.setDatasource = function(datasource) {
this.datasource = datasource;
if (!datasource) {
// only continue if we have a valid datasource to work with
return;
}
this.reset();
};
PaginationController.prototype.reset = function() {
// copy pageSize, to guard against it changing the the datasource between calls
this.pageSize = this.datasource.pageSize;
// see if we know the total number of pages, or if it's 'to be decided'
if (typeof this.datasource.rowCount === 'number' && this.datasource.rowCount >= 0) {
this.rowCount = this.datasource.rowCount;
this.foundMaxRow = true;
this.calculateTotalPages();
} else {
this.rowCount = 0;
this.foundMaxRow = false;
this.totalPages = null;
}
this.currentPage = 0;
// hide the summary panel until something is loaded
this.ePageRowSummaryPanel.style.visibility = 'hidden';
this.setTotalLabels();
this.loadPage();
};
PaginationController.prototype.setTotalLabels = function() {
if (this.foundMaxRow) {
this.lbTotal.innerHTML = this.totalPages.toLocaleString();
this.lbRecordCount.innerHTML = this.rowCount.toLocaleString();
} else {
var moreText = this.gridOptionsWrapper.getLocaleTextFunc()('more', 'more');
this.lbTotal.innerHTML = moreText;
this.lbRecordCount.innerHTML = moreText;
}
};
PaginationController.prototype.calculateTotalPages = function() {
this.totalPages = Math.floor((this.rowCount - 1) / this.pageSize) + 1;
};
PaginationController.prototype.pageLoaded = function(rows, lastRowIndex) {
var firstId = this.currentPage * this.pageSize;
this.angularGrid.setRows(rows, firstId);
// see if we hit the last row
if (!this.foundMaxRow && typeof lastRowIndex === 'number' && lastRowIndex >= 0) {
this.foundMaxRow = true;
this.rowCount = lastRowIndex;
this.calculateTotalPages();
this.setTotalLabels();
// if overshot pages, go back
if (this.currentPage > this.totalPages) {
this.currentPage = this.totalPages - 1;
this.loadPage();
}
}
this.enableOrDisableButtons();
this.updateRowLabels();
};
PaginationController.prototype.updateRowLabels = function() {
var startRow;
var endRow;
if (this.isZeroPagesToDisplay()) {
startRow = 0;
endRow = 0;
} else {
startRow = (this.pageSize * this.currentPage) + 1;
endRow = startRow + this.pageSize - 1;
if (this.foundMaxRow && endRow > this.rowCount) {
endRow = this.rowCount;
}
}
this.lbFirstRowOnPage.innerHTML = (startRow).toLocaleString();
this.lbLastRowOnPage.innerHTML = (endRow).toLocaleString();
// show the summary panel, when first shown, this is blank
this.ePageRowSummaryPanel.style.visibility = null;
};
PaginationController.prototype.loadPage = function() {
this.enableOrDisableButtons();
var startRow = this.currentPage * this.datasource.pageSize;
var endRow = (this.currentPage + 1) * this.datasource.pageSize;
this.lbCurrent.innerHTML = (this.currentPage + 1).toLocaleString();
this.callVersion++;
var callVersionCopy = this.callVersion;
var that = this;
this.angularGrid.showLoadingPanel(true);
this.datasource.getRows(startRow, endRow,
function success(rows, lastRowIndex) {
if (that.isCallDaemon(callVersionCopy)) {
return;
}
that.pageLoaded(rows, lastRowIndex);
},
function fail() {
if (that.isCallDaemon(callVersionCopy)) {
return;
}
// set in an empty set of rows, this will at
// least get rid of the loading panel, and
// stop blocking things
that.angularGrid.setRows([]);
}
);
};
PaginationController.prototype.isCallDaemon = function(versionCopy) {
return versionCopy !== this.callVersion;
};
PaginationController.prototype.onBtNext = function() {
this.currentPage++;
this.loadPage();
};
PaginationController.prototype.onBtPrevious = function() {
this.currentPage--;
this.loadPage();
};
PaginationController.prototype.onBtFirst = function() {
this.currentPage = 0;
this.loadPage();
};
PaginationController.prototype.onBtLast = function() {
this.currentPage = this.totalPages - 1;
this.loadPage();
};
PaginationController.prototype.isZeroPagesToDisplay = function() {
return this.foundMaxRow && this.totalPages === 0;
};
PaginationController.prototype.enableOrDisableButtons = function() {
var disablePreviousAndFirst = this.currentPage === 0;
this.btPrevious.disabled = disablePreviousAndFirst;
this.btFirst.disabled = disablePreviousAndFirst;
var zeroPagesToDisplay = this.isZeroPagesToDisplay();
var onLastPage = this.foundMaxRow && this.currentPage === (this.totalPages - 1);
var disableNext = onLastPage || zeroPagesToDisplay;
this.btNext.disabled = disableNext;
var disableLast = !this.foundMaxRow || zeroPagesToDisplay || this.currentPage === (this.totalPages - 1);
this.btLast.disabled = disableLast;
};
PaginationController.prototype.createTemplate = function() {
var localeTextFunc = this.gridOptionsWrapper.getLocaleTextFunc();
return TEMPLATE
.replace('[PAGE]', localeTextFunc('page', 'Page'))
.replace('[TO]', localeTextFunc('to', 'to'))
.replace('[OF]', localeTextFunc('of', 'of'))
.replace('[OF]', localeTextFunc('of', 'of'))
.replace('[FIRST]', localeTextFunc('first', 'First'))
.replace('[PREVIOUS]', localeTextFunc('previous', 'Previous'))
.replace('[NEXT]', localeTextFunc('next', 'Next'))
.replace('[LAST]', localeTextFunc('last', 'Last'));
};
PaginationController.prototype.populatePanel = function(ePagingPanel) {
ePagingPanel.innerHTML = this.createTemplate();
this.btNext = ePagingPanel.querySelector('#btNext');
this.btPrevious = ePagingPanel.querySelector('#btPrevious');
this.btFirst = ePagingPanel.querySelector('#btFirst');
this.btLast = ePagingPanel.querySelector('#btLast');
this.lbCurrent = ePagingPanel.querySelector('#current');
this.lbTotal = ePagingPanel.querySelector('#total');
this.lbRecordCount = ePagingPanel.querySelector('#recordCount');
this.lbFirstRowOnPage = ePagingPanel.querySelector('#firstRowOnPage');
this.lbLastRowOnPage = ePagingPanel.querySelector('#lastRowOnPage');
this.ePageRowSummaryPanel = ePagingPanel.querySelector('#pageRowSummaryPanel');
var that = this;
this.btNext.addEventListener('click', function() {
that.onBtNext();
});
this.btPrevious.addEventListener('click', function() {
that.onBtPrevious();
});
this.btFirst.addEventListener('click', function() {
that.onBtFirst();
});
this.btLast.addEventListener('click', function() {
that.onBtLast();
});
};
module.exports = PaginationController;
| mit |
AusDTO/gov-au-beta | spec/models/news_article_spec.rb | 887 | require 'rails_helper'
RSpec.describe NewsArticle, type: :model do
it { expect(described_class).to be < Node }
it { is_expected.to respond_to :release_date }
it { is_expected.to validate_presence_of :release_date }
describe '#published_for_section' do
let!(:section) { Fabricate(:section) }
let!(:other_section) { Fabricate(:section) }
let!(:published) { Fabricate(:news_article, section: section, state: 'published') }
let!(:other_published) { Fabricate(:news_article, section: other_section, state: 'published') }
let!(:draft) { Fabricate(:news_article, section: section, state: 'draft') }
it 'should return published news' do
result = NewsArticle.published_for_section(section).all
expect(result).to include(published)
expect(result).to_not include(draft)
expect(result).to_not include(other_published)
end
end
end
| mit |
bhishamtrehan/themedconsult | application/modules/auth/views/change_password_form.php | 5463 | <?php
$old_password = array(
'name' => 'old_password',
'id' => 'old_password',
'value' => set_value('old_password'),
'size' => 30,
);
$new_password = array(
'name' => 'new_password',
'id' => 'new_password',
'maxlength' => $this->config->item('password_max_length', 'tank_auth'),
'size' => 30,
);
$confirm_new_password = array(
'name' => 'confirm_new_password',
'id' => 'confirm_new_password',
'maxlength' => $this->config->item('password_max_length', 'tank_auth'),
'size' => 30,
);
/* ?>
<title><?php echo $this->lang->line('change_password').$this->lang->line('title_universal');?></title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/jquery.dataTables.css">
<style>
.form_error p
{
color: #ff0000;
}
</style>
<body>
<!-- WRAPPER -->
<div class="wrapper">
<!-- TOP BAR -->
<?php
if($role_id==1){
$this->load->view ('inc/top_bar');
}elseif($role_id==2){
$this->load->view ('inc/clinic_top_bar');
}elseif($role_id==3){
$this->load->view ('inc/practitioner_top_bar');
}elseif($role_id==4){
$this->load->view ('inc/patient_top_bar');
}else{
$this->load->view ('inc/clinic_top_bar');
}
?>
<!-- /top -->
<!-- BOTTOM: LEFT NAV AND RIGHT MAIN CONTENT -->
<div class="bottom">
<div class="container">
<div class="row">
<!-- left sidebar -->
<div class="col-md-2 left-sidebar">
<?php
if($role_id==1){
$this->load->view ('inc/admin_left_nav');
}elseif($role_id==2){
$this->load->view ('inc/clinic_left_nav');
}elseif($role_id==3){
$this->load->view ('inc/practitioner_left_nav');
}elseif($role_id==4){
$this->load->view ('inc/patient_left_nav');
}else{
$this->load->view ('inc/clinic_location_left_nav');
}
?>
</div>
<!-- end left sidebar -->
<!-- top general alert -->
<?php if($this->session->flashdata('display_message')) { ?>
<div class="success_message"> <span><?php echo $this->session->flashdata('display_message');?></span></div>
<?php } ?>
<!-- end top general alert -->
<div id="checking_security" class="col-md-10 content-wrapper practitioner_sectn"> <!-- InstanceBeginEditable name="body" -->
<div class="widget">
<div class="widget-header widget_pract">
<h3><i class="fa fa-list"></i>Change Password</h3>
</div>
<div> <?php */ ?>
<div class="widget-content" id="checking_security">
<?php echo form_open($this->uri->uri_string(),array('class' => 'form-horizontal form_health','id' => 'change_password')); ?>
<fieldset>
<legend><?php echo $this->lang->line('general_info');?></legend>
<div class="col-lg-12 ">
<div class="form-group">
<label class="col-sm-3 control-label">Old Password<span class="astrik">*</span></label>
<div class="col-sm-9">
<?php echo form_password($old_password,'',"class='form-control'"); ?>
<span class="form_error"><?php echo form_error($old_password['name']); ?></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">New Password<span class="astrik">*</span></label>
<div class="col-sm-9">
<?php echo form_password($new_password,'',"class='form-control'"); ?>
<span class="form_error"><?php echo form_error($new_password['name']); ?></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Confirm New Password<span class="astrik">*</span></label>
<div class="col-sm-9">
<?php echo form_password($confirm_new_password,'',"class='form-control'"); ?>
<span class="form_error"><?php echo form_error($confirm_new_password['name']); ?></span>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<?php //echo form_hidden('action', $action);
echo form_submit('change', 'Change Password',"class='btn btn-primary btn-block'"); ?>
</div>
</div>
<?php echo form_close();?>
</div>
</fieldset>
</div>
<?php /* ?> </div>
<!-- /content-wrapper -->
</div>
</div>
</div>
<!-- /row -->
</div>
<!-- /container -->
</div>
<!-- END BOTTOM: LEFT NAV AND RIGHT MAIN CONTENT -->
</div>
</div>
<div class="popup">
<button type="button" style="display:none;" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal"></button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content"></div>
</div>
</div>
</div>
<!-- /wrapper -->
<!-- FOOTER -->
<?php $this->load->view ('inc/footer');?>
<script src="<?php echo base_url();?>js/jquery.validate.js"></script>
<script src="<?php echo base_url();?>js/change_password.js"></script>
<!-- FOOTER -->
*
<?php */?>
| mit |
noamiv/cpe_check | main.js | 4548 |
function openGenOverlay() {
var triggerBttn = document.getElementById( 'js-trigger-overlay' ),
overlay = document.querySelector( 'div.overlay' ),
closeBttn = overlay.querySelector( 'button.close' );
transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd',
'transition': 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
support = {
transitions : Modernizr.csstransitions
};
function toggleOverlay() {
if( classie.has( overlay, 'open' ) ) {
classie.remove( overlay, 'open' );
classie.add( overlay, 'close' );
var onEndTransitionFn = function( ev ) {
if( support.transitions ) {
if( ev.propertyName !== 'visibility' ) return;
this.removeEventListener( transEndEventName, onEndTransitionFn );
}
classie.remove( overlay, 'close' );
};
if( support.transitions ) {
overlay.addEventListener( transEndEventName, onEndTransitionFn );
}
else {
onEndTransitionFn();
}
/*location.reload(); NOAM- this will reload the page on close. I prefer to do it nicer and just update the BS ballon*/
/*
var content = document.getElementById('popup-content');
content.innerHTML = "NOAM";
*/
var closer = document.getElementById('popup-closer');
closer.click();
}
else if( !classie.has( overlay, 'close' ) ) {
classie.add( overlay, 'open' );
}
}
toggleOverlay() ;
closeBttn.addEventListener( 'click', toggleOverlay );
}
$(document).ready(function() {
"use-strict";
$('#nav-new-bs').click(function(e)
{
$('#overlayId').html(
'<button type="button" class="close">Close</button>'+
'<iframe id="NewBs" src="new_bs.php" allowfullscreen="true" sandbox="allow-scripts allow-pointer-lock allow-same-origin allow-popups allow-forms" allowtransparency="true" class="result-iframe"></iframe>'
);
openGenOverlay();
});
$('#nav-new-ss').click(function(e)
{
addInteraction();
});
$('#nav-new-user').click(function(e)
{
$('#overlayId').html(
'<button type="button" class="close">Close</button>'+
'<iframe id="newUser" src="register.php" allowfullscreen="true" sandbox="allow-scripts allow-pointer-lock allow-same-origin allow-popups allow-forms" allowtransparency="true" class="result-iframe"></iframe>'
);
openGenOverlay();
});
$('#nav-config').click(function(e)
{
$('#overlayId').html(
'<button type="button" class="close">Close</button>'+
'<iframe id="systemConfig" src="sysConfig.php" allowfullscreen="true" sandbox="allow-scripts allow-pointer-lock allow-same-origin allow-popups allow-forms" allowtransparency="true" class="result-iframe"></iframe>'
);
openGenOverlay();
});
$('#nav-all-bs').click(function(e)
{
$('#overlayId').html(
'<button type="button" class="close">Close</button>'+
'<iframe id="allBs" src="view_allBS.php" allowfullscreen="true" sandbox="allow-scripts allow-pointer-lock allow-same-origin allow-popups allow-forms" allowtransparency="true" class="result-iframe"></iframe>'
);
openGenOverlay();
});
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
| mit |
Jasondou0709/client | app/src/main/java/io/rong/app/activity/ChangeGroupActivity.java | 3491 | package io.rong.app.activity;
import com.sea_monster.resource.Resource;
import io.rong.app.DemoContext;
import io.rong.app.R;
import io.rong.app.utils.Constants;
import io.rong.imkit.widget.AsyncImageView;
import io.rong.imlib.model.Group;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ChangeGroupActivity extends BaseActionBarActivity {
private static final String TAG = "ChangeGroupActivity";
private TextView mComment;
private TextView mGroupName;
private AsyncImageView mImageView;
private Button mSelectButton;
private Button mChooseButton;
private String mClassId;
private RelativeLayout mRelativeLayout;
private Group mGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.change_group);
getSupportActionBar().setTitle(R.string.change_group);
mComment = (TextView) findViewById(R.id.change_group_comment);
mGroupName = (TextView) findViewById(R.id.group_adaper_name);
mImageView = (AsyncImageView) findViewById(R.id.group_adapter_img);
mSelectButton = (Button) findViewById(R.id.group_select);
mChooseButton = (Button) findViewById(R.id.group_choose);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relativelayout);
if (DemoContext.getInstance() != null) {
mClassId = DemoContext.getInstance().getClassId();
Log.d(TAG, "DemoContext.getInstance().getClassId():" + mClassId);
}
initialData();
}
private void initialData() {
if (mClassId == null || mClassId.equalsIgnoreCase("0")) {
mComment.setText("您没有设置朋友圈中的班级,请设置:");
mRelativeLayout.setVisibility(View.GONE);
mChooseButton.setVisibility(View.VISIBLE);
} else {
if (DemoContext.getInstance() != null) {
mGroup = DemoContext.getInstance().getGroupById(mClassId);
}
if (mGroup != null) {
mGroupName.setText(mGroup.getName());
Log.d(TAG, "mGroup.getPortraitUri():" + mGroup.getPortraitUri());
/*if (mGroup.getPortraitUri() != null && !mGroup.getPortraitUri().toString().equalsIgnoreCase("")) {
mImageView.setResource(new Resource(mGroup.getPortraitUri()));
}*/
}
}
if (mChooseButton != null) {
mChooseButton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivityForResult(new Intent(ChangeGroupActivity.this, SelectGroupActivity.class), 20);
}
});
}
if (mSelectButton != null) {
mSelectButton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivityForResult(new Intent(ChangeGroupActivity.this, SelectGroupActivity.class), 20);
}
});
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) {
mGroupName.setText(data.getStringExtra("CLASSNAME"));
//mImageView.setResource(new Resource(data.getStringExtra("CLASSPORTRAIT")));
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| mit |
timmartin/hy-coverage | setup.py | 800 | from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
classifiers = """\
Environment :: Console
Intended Audience :: Developers
License :: OSI Approved :: MIT License
Programming Language :: Python :: 3.4
Topic :: Software Development :: Testing
Development Status :: 4 - Beta
"""
setup(name="hy_coverage_plugin",
version="0.1.0",
description="coverage.py plugin for the Hy language",
long_description=readme(),
url="https://github.com/timmartin/hy-coverage",
author="Tim Martin",
author_email="[email protected]",
license="mit",
packages=["hy_coverage_plugin"],
install_requires=[
"coverage >= 4.0",
"Hy >= 0.11.0",
],
classifiers=classifiers.splitlines()
)
| mit |
Grimace1975/bclcontrib | Web/System.WebEx/Web/UI+Controls/HtmlControls/HtmlAnchorEx.cs | 2932 | #region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Web.UI.WebControls;
namespace System.Web.UI.HtmlControls
{
/// <summary>
/// HtmlAnchorEx
/// </summary>
public class HtmlAnchorEx : HtmlAnchor
{
private static readonly object s_eventCommandKey = new object();
public HtmlAnchorEx()
: base()
{
// singhj: added to force a raise event when clicked
ServerClick += new EventHandler(HtmlButton_ServerClick);
}
public string ClientConfirmationText { get; set; }
public string CommandArgument { get; set; }
public string CommandName { get; set; }
protected void HtmlButton_ServerClick(object sender, EventArgs e) { }
protected override void OnPreRender(EventArgs e)
{
if (!string.IsNullOrEmpty(ClientConfirmationText))
Attributes["onclick"] = "if(!confirm(" + ClientScript.EncodeText(ClientConfirmationText) + "))return(false);";
base.OnPreRender(e);
}
protected override void RaisePostBackEvent(string eventArgument)
{
base.RaisePostBackEvent(eventArgument);
if (!string.IsNullOrEmpty(CommandName))
OnCommand(new CommandEventArgs(CommandName, CommandArgument));
}
public event EventHandler Command
{
add { base.Events.AddHandler(s_eventCommandKey, value); }
remove { base.Events.RemoveHandler(s_eventCommandKey, value); }
}
protected virtual void OnCommand(EventArgs e)
{
var handler = (EventHandler)base.Events[s_eventCommandKey];
if (handler != null)
handler(this, e);
base.RaiseBubbleEvent(this, e);
}
}
} | mit |
NTHINGs/Uhlu | public/app/directives/loading.js | 653 | app.directive('loading', ['$http' ,function ($http)
{
return {
restrict: 'A',
template: '<div class="loading-spiner"><img class="center-block" src="img/loading.gif" /> </div>',
link: function (scope, elm, attrs){
scope.isLoading = function () {
return $http.pendingRequests.length > 0;
};
scope.$watch(scope.isLoading, function (v){
if(v){
jQuery(elm).show();
}else{
jQuery(elm).hide();
}
});
}
};
}]);
| mit |
Jean-GuillaumePonsard/projetWebBDE | bde/src/BCL/UserBundle/Controller/UserController.php | 6507 | <?php
// src/BLC/UserBundle/Controller
namespace BCL\UserBundle\Controller;
use BCL\UserBundle\BCLUserBundle;
use BCL\UserBundle\Entity\Schoolyear;
use BCL\UserBundle\Entity\Status;
use BCL\UserBundle\Entity\Users;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\HttpFoundation\Session\Session;
class UserController extends Controller
{
public function indexAction()
{
return new Response("Erreur");
}
public function removeUserAction($id)
{
}
public function signInAction(Request $request)
{
$user = new Users();
$formBuilder = $this->get('form.factory')->createBuilder(FormType::class, $user)
->add('firstName', TextType::class)
->add('lastName', TextType::class)
->add('email', EmailType::class)
->add('password', PasswordType::class)
->add('confirmPassword', PasswordType::class)
->add('status', ChoiceType::class, array('choices' => $this->getDoctrine()->getManager()->getRepository('BCLUserBundle:Status')->findAll(), 'choice_label' => 'name'))
->add('validate', SubmitType::class)
->getForm();
if($request->isMethod('POST'))
{
$formBuilder->handleRequest($request);
if($formBuilder->isValid())
{
$emailPossible = $this->getDoctrine()->getManager()->getRepository('BCLUserBundle:Users')->findByEmail($user->getEmail());
if(empty($emailPossible) == "empty")
{
if($user->getPassword() === $user->getConfirmPassword())
{
$em = $this->getDoctrine()->getManager();
/*$repo = $em->getRepository("BCLUserBundle:Status");
$status = $repo->findBy(array('name'=>'Student'), $orderBy = null, $limit = 1, $offset = 0);
$user->setStatus($status[0]);*/
$em->persist($user);
$em->flush();
return new RedirectResponse($this->generateUrl('bcl_user_profil', array('id' => $user->getId())));
}
}
echo "<script>alert('Ce compte existe déjà')</script>";
}
}
return $this->render('BCLUserBundle:User:signIn.html.twig', array('form' => $formBuilder->createView()));
}
public function logInAction(Request $request)
{
$user = new Users();
$formBuilder = $this->get('form.factory')->createBuilder(FormType::class, $user)
->add('email', EmailType::class)
->add('password', PasswordType::class)
->add('validate', SubmitType::class)
->getForm();
if($request->isMethod('POST'))
{
$formBuilder->handleRequest($request);
if($formBuilder->isValid())
{
$emailPossible = $this->getDoctrine()->getManager()->getRepository('BCLUserBundle:Users')->findByEmail($user->getEmail());
if(empty($emailPossible) != "empty")
{
if($emailPossible[0]->getPassword() == $user->getPassword())
{
echo "<script>alert('".$emailPossible[0]->getFirstName()."".$emailPossible[0]->getLastName()." tries to connect')</script>";
$ok=$this->get('session');
$ok->set('userId',array($emailPossible[0]->getId()));
$ok->set('status',array($emailPossible[0]->getStatus()->getName()));
return new RedirectResponse($this->generateUrl('bcl_user_profil', array('id' => $emailPossible[0]->getId())));
}
}
echo "<script>alert('This account doesn t exist or wrong password')</script>";
}
}
return $this->render('BCLUserBundle:User:logIn.html.twig', array('form' => $formBuilder->createView()));
}
public function logOutAction()
{
$ok=$this->get('session');
$ok->remove('userId');
$ok->remove('status');
return $this->render('BCLCoreBundle::home.html.twig');
}
public function viewProfilAction(Request $request)
{
$session = $this->get('session');
if(!empty($session->get('userId')))
{
$id = $session->get('userId')[0];
}
else
{
return new RedirectResponse($this->generateUrl('bcl_user_logIn'));
}
$user = new Users();
$user = $this->getDoctrine()->getManager()->getRepository('BCLUserBundle:Users')->find($id);
/*if (!is_null($_SESSION["status"]))
{
echo "<script>alert('bonjour')</script>";
}*/
//Form
$form = $this->get('form.factory')->createBuilder(FormType::class, $user)
->add('urlPicture', TextType::class, array('required'=>false))
->add('firstName', TextType::class)
->add('lastName', TextType::class)
->add('email', EmailType::class)
->add('modify', SubmitType::class)
->getForm();
if($request->isMethod('POST'))
{
// Verifying every form to check what to change
$form->handleRequest($request);
if($form->isSubmitted())
{
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return new RedirectResponse($this->generateUrl('bcl_user_profil', array('id' => $id)));
}
}
return $this->render('BCLUserBundle:User:profil.html.twig', array('profil'=>$user, 'form' => $form->createView()));
}
}
| mit |
DimensionDataCBUSydney/Compute.Api.Client | ComputeClient/Compute.Contracts/Requests/Snapshot/SnapshotServicePlanListOptions.cs | 994 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DD.CBU.Compute.Api.Contracts.Requests.Snapshot
{
using System;
/// <summary>
/// Filtering options for the Snapshot Server Plan List request.
/// </summary>
public sealed class SnapshotServicePlanListOptions : FilterableRequest
{
/// <summary>
/// The "id" field name.
/// </summary>
public const string IdField = "id";
/// <summary>
/// The "available" field name.
/// </summary>
public const string AvailableField = "available";
/// <summary>
/// Identifies an individual Snapshot Service Plan.
/// </summary>
public Guid? Id
{
get { return GetFilter<Guid?>(IdField); }
set { SetFilter(IdField, value); }
}
/// <summary>
/// Gets or sets the available filter.
/// </summary>
public bool? Available
{
get { return GetFilter<bool?>(AvailableField); }
set { SetFilter(AvailableField, value); }
}
}
}
| mit |
DoSomething/northstar | tests/WithMocks.php | 1019 | <?php
namespace Tests;
use Carbon\Carbon;
use Closure;
use Mockery;
trait WithMocks
{
/**
* Mock a class, and register with the IoC container.
*
* @param $class String - Class name to mock
* @return \Mockery\MockInterface
*/
public function mock($class, ?Closure $closure = null)
{
$mock = Mockery::mock($class);
app()->instance($class, $mock);
return $mock;
}
/**
* Spy on a class.
*
* @param $class String - Class name to mock
* @return \Mockery\MockInterface
*/
public function spy($class, ?Closure $closure = null)
{
$spy = Mockery::spy($class);
app()->instance($class, $spy);
return $spy;
}
/**
* "Freeze" time so we can make assertions based on it.
*
* @param string $time
* @return Carbon
*/
public function mockTime($time = 'now')
{
Carbon::setTestNow((string) new Carbon($time));
return Carbon::getTestNow();
}
}
| mit |
joevandyk/monkeycharger | vendor/plugins/monkey_charger/test/monkey_charger_test.rb | 150 | require 'test/unit'
class MonkeyChargerTest < Test::Unit::TestCase
# Replace this with your real tests.
def test_this_plugin
flunk
end
end
| mit |
hugollm/lie2me | tests/test_fields/common_tests.py | 1257 | from unittest import TestCase
from lie2me import Field
class CommonTests(object):
def get_instance(self):
return self.Field()
def test_submitting_empty_value_on_required_field_returns_error(self):
field = self.get_instance()
field.required = True
value, error = field.submit(field.empty_value())
self.assertTrue(error)
def test_submitting_empty_value_on_optional_field_does_not_return_error(self):
field = self.get_instance()
field.required = False
value, error = field.submit(field.empty_value())
self.assertFalse(error)
def test_field_is_required_by_default(self):
field = self.get_instance()
value, error = field.submit(field.empty_value())
self.assertTrue(error)
def test_field_with_default_is_not_required(self):
field = self.get_instance()
field.default = self.valid_default
value, error = field.submit(field.empty_value())
self.assertFalse(error)
def test_field_instance_can_overwrite_specific_messages(self):
field = self.get_instance()
field.messages = {'required': 'Lorem ipsum'}
value, error = field.submit(None)
self.assertIn('Lorem ipsum', str(error))
| mit |
mansonul/events | events/contrib/plugins/form_elements/fields/url/fobi_form_elements.py | 430 | from __future__ import absolute_import
from fobi.base import form_element_plugin_registry
from .base import URLInputPlugin
__title__ = 'fobi.contrib.plugins.form_elements.fields.url.fobi_form_elements'
__author__ = 'Artur Barseghyan <[email protected]>'
__copyright__ = '2014-2017 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('URLInputPlugin',)
form_element_plugin_registry.register(URLInputPlugin)
| mit |
simple-mvc-framework/build-a-blog | app/templates/admin/header.php | 1663 | <!DOCTYPE html>
<html lang="<?php echo LANGUAGE_CODE; ?>">
<head>
<!-- Site meta -->
<meta charset="utf-8">
<title><?php echo $data['title'].' - '.SITETITLE; //SITETITLE defined in app/core/config.php ?></title>
<!-- CSS -->
<?php
helpers\assets::css(array(
'//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css',
helpers\url::admin_template_path() . 'css/style.css',
))
?>
</head>
<body>
<div class="container">
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php echo DIR;?>admin"><?php echo SITETITLE;?></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="<?php echo DIR;?>admin/cats">Categories</a></li>
<li><a href="<?php echo DIR;?>admin/posts">Posts</a></li>
<li><a href="<?php echo DIR;?>admin/users">Users</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="<?php echo DIR;?>admin/logout">Logout</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
| mit |
JosefFriedrich-nodejs/baldr | src/vue/apps/vue2-ts-classcomponent/src/main.ts | 227 | import Vue from 'vue'
import App from './App.vue'
import styleConfigurator from '@bldr/style-configurator'
Vue.use(styleConfigurator as any)
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')
| mit |
brainexe/homie | Tests/UnitTests/Expression/Listener/ClearCacheTest.php | 1381 | <?php
namespace Tests\Homie\Expression\Listener;
use Homie\Expression\Cache;
use Homie\Expression\Entity;
use Homie\Expression\Gateway;
use Homie\Expression\Listener\ClearCache;
use Monolog\Logger;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
use PHPUnit\Framework\TestCase;
class ClearCacheTest extends TestCase
{
/**
* @var ClearCache
*/
private $subject;
/**
* @var Cache|MockObject
*/
private $cache;
/**
* @var Gateway|MockObject
*/
private $gateway;
/**
* @var Logger|MockObject
*/
private $logger;
public function setup()
{
$this->cache = $this->createMock(Cache::class);
$this->gateway = $this->createMock(Gateway::class);
$this->logger = $this->createMock(Logger::class);
$this->subject = new ClearCache(
$this->cache,
$this->gateway,
$this->logger
);
}
public function testRebuild()
{
$entities = [];
$entity1 = $entities[] = new Entity();
$entity1->expressionId = 'sensorCron';
$this->cache
->expects($this->once())
->method('writeCache');
$this->gateway
->expects($this->once())
->method('getAll')
->willReturn($entities);
$this->subject->rebuildCache();
}
}
| mit |
Haseu/legacy-framework | app/Home/Controller/IndexController.php | 2816 | <?php
/**
* Arquivo: IndexController.php (UTF-8)
*
* Data: 16/10/2014
* @author André Luis Rocha Menutole <[email protected]>
*/
namespace Application\Home\Controller;
use Core\AbstractController;
use Core\Helpers\RedirectorHelper;
use Core\Helpers\PdfHelper;
use Application\Login\Model\Usuario;
/**
* Class IndexController
* @package Application\Home\Controller
*/
class IndexController extends AbstractController {
private $db;
public function init() {
}
public function indexAction() {
//$dados = $this->getParams();
//$email = new EmailHelper();
//$email->enviaEmail();
//We add some roles
/*$this->acl->addRole('avô');
$this->acl->addRole('pai', 'avô');
$this->acl->addRole('mãe');
$this->acl->addRole('filho', array('pai', 'mãe'));
//We add some resources
$this->acl->addResource('casa_avo');
$this->acl->addResource('casa_pai');
$this->acl->addResource('casa_mae');
$this->acl->addResource('minha_casa');
//We set some rules
$this->acl->allow('avô', 'casa_avo');
$this->acl->allow('pai', 'casa_pai');
$this->acl->allow('mãe', 'casa_mae');*/
/*echo 'Filho pode entrar na casa do pai?<br />';
var_dump($this->acl->isAllowed('filho', 'casa_avo')); //Deve ser true
echo 'Mãe pode entrar na casa do avô? Ele não gosta dela<br />';
var_dump($this->acl->isAllowed('mãe', 'casa_avo')); //False */
//Testes de queries
$this->db = new Usuario();
$sql = $this->db->select();
//$sql->collumns(array("nome", "login", "senha"));
//$sql->join('posts', 'usuarios.id = posts.usuario_id', array('resumo', 'titulo' => 'teste_titulo'), "LEFT");
//$sql->join(array('telefones' => 't'), 'usuarios.id = t.usuario_id', array('numero' => 'numeroTelefone'), "LEFT");
//$sql->where(array('usuarios.id' => '1'));
//$sql->limit("1");
//$sql->order("usuarios.id DESC");
//echo $sql->getSqlString();
//$usuario = $sql->execute();
//$this->db = new Usuario();
//$sql = $this->db->update();
//echo $sql->getSqlString();
$teste['usuario'] = $usuario;
$teste['acl'] = '';
//Testes de layout
//$this->view->layout('Home/View/layout/layout_1');
//$this->view->setTerminate(true);
$this->view->render('index', $teste);
//$redirector = new RedirectorHelper();
/* $redirector->setUrlParameter('nome','Andre')
->setUrlParameter('idade','33')
->goToUrl('http://www.google.com.br'); */
//echo "Action index";
}
public function testeAction() {
echo "Action Teste";
}
}
| mit |
leader22/simple-pokedex-v2 | _scraping/fetch/191.js | 5090 | module.exports = {
"key": "sunkern",
"moves": [
{
"learn_type": "tutor",
"name": "after-you"
},
{
"learn_type": "machine",
"name": "round"
},
{
"learn_type": "egg move",
"name": "morning-sun"
},
{
"learn_type": "egg move",
"name": "bide"
},
{
"learn_type": "tutor",
"name": "earth-power"
},
{
"learn_type": "tutor",
"name": "uproar"
},
{
"learn_type": "machine",
"name": "grass-knot"
},
{
"learn_type": "machine",
"name": "captivate"
},
{
"learn_type": "machine",
"name": "energy-ball"
},
{
"learn_type": "level up",
"level": 45,
"name": "seed-bomb"
},
{
"learn_type": "level up",
"level": 25,
"name": "worry-seed"
},
{
"learn_type": "machine",
"name": "natural-gift"
},
{
"learn_type": "level up",
"level": 29,
"name": "razor-leaf"
},
{
"learn_type": "tutor",
"name": "substitute"
},
{
"learn_type": "tutor",
"name": "mimic"
},
{
"learn_type": "tutor",
"name": "double-edge"
},
{
"learn_type": "tutor",
"name": "swords-dance"
},
{
"learn_type": "machine",
"name": "bullet-seed"
},
{
"learn_type": "egg move",
"name": "grasswhistle"
},
{
"learn_type": "machine",
"name": "secret-power"
},
{
"learn_type": "level up",
"level": 25,
"name": "endeavor"
},
{
"learn_type": "level up",
"level": 18,
"name": "ingrain"
},
{
"learn_type": "egg move",
"name": "helping-hand"
},
{
"learn_type": "egg move",
"name": "nature-power"
},
{
"learn_type": "machine",
"name": "facade"
},
{
"learn_type": "egg move",
"name": "encore"
},
{
"learn_type": "machine",
"name": "safeguard"
},
{
"learn_type": "machine",
"name": "light-screen"
},
{
"learn_type": "egg move",
"name": "leech-seed"
},
{
"learn_type": "level up",
"level": 19,
"name": "sunny-day"
},
{
"learn_type": "machine",
"name": "hidden-power"
},
{
"learn_type": "level up",
"level": 31,
"name": "synthesis"
},
{
"learn_type": "machine",
"name": "sweet-scent"
},
{
"learn_type": "machine",
"name": "frustration"
},
{
"learn_type": "machine",
"name": "return"
},
{
"learn_type": "machine",
"name": "sleep-talk"
},
{
"learn_type": "machine",
"name": "attract"
},
{
"learn_type": "machine",
"name": "swagger"
},
{
"learn_type": "machine",
"name": "endure"
},
{
"learn_type": "level up",
"level": 46,
"name": "giga-drain"
},
{
"learn_type": "machine",
"name": "sludge-bomb"
},
{
"learn_type": "machine",
"name": "protect"
},
{
"learn_type": "machine",
"name": "curse"
},
{
"learn_type": "machine",
"name": "snore"
},
{
"learn_type": "machine",
"name": "rest"
},
{
"learn_type": "machine",
"name": "flash"
},
{
"learn_type": "machine",
"name": "double-team"
},
{
"learn_type": "machine",
"name": "toxic"
},
{
"learn_type": "machine",
"name": "solarbeam"
},
{
"learn_type": "level up",
"level": 4,
"name": "growth"
},
{
"learn_type": "level up",
"level": 10,
"name": "mega-drain"
},
{
"learn_type": "level up",
"level": 1,
"name": "absorb"
},
{
"learn_type": "machine",
"name": "cut"
}
]
}; | mit |
mybigfriendjo/QuickLaunch | QuickLaunch/LaunchEntryList.cs | 1999 | using System;
using System.Windows.Forms;
using QuickLaunch.storage;
namespace QuickLaunch {
public partial class LaunchEntryList : Form {
public LaunchEntryList() {
InitializeComponent();
foreach (LaunchEntry entry in LaunchRegistry.INSTANCE.Entries) {
if (entry.IsGroup) {
TreeNode group = new TreeNode(entry.Name);
treeViewEntries.Nodes.Add(group);
GenerateChildren(group, entry);
continue;
}
TreeNode item = new TreeNode(entry.Name) {
Tag = entry
};
treeViewEntries.Nodes.Add(item);
}
if (treeViewEntries.Nodes.Count>0) {
treeViewEntries.SelectedNode = treeViewEntries.Nodes[0];
}
}
private static void GenerateChildren(TreeNode current, LaunchEntry entry) {
foreach (LaunchEntry child in entry.Children) {
if (child.IsGroup) {
TreeNode group = new TreeNode(child.Name);
current.Nodes.Add(group);
GenerateChildren(group, child);
continue;
}
TreeNode item = new TreeNode(child.Name) {
Tag = child
};
current.Nodes.Add(item);
}
}
private void buttonAddCategory_Click(object sender, EventArgs e) {
// TODO:
}
private void buttonAddSubCategory_Click(object sender, EventArgs e) {
// TODO:
}
private void buttonDeleteCategory_Click(object sender, EventArgs e) {
// TODO:
}
private void buttonAddEntry_Click(object sender, EventArgs e) {
// TODO:
}
private void buttonDeleteEntry_Click(object sender, EventArgs e) {
// TODO:
}
}
}
| mit |
northdakota/platform | src/Oro/Bundle/EmailBundle/Mailer/Processor.php | 20342 | <?php
namespace Oro\Bundle\EmailBundle\Mailer;
use Doctrine\ORM\EntityManager;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser;
use Oro\Bundle\EmailBundle\Decoder\ContentDecoder;
use Oro\Bundle\EmailBundle\Entity\Email;
use Oro\Bundle\EmailBundle\Entity\EmailAttachment;
use Oro\Bundle\EmailBundle\Entity\EmailAttachmentContent;
use Oro\Bundle\EmailBundle\Entity\EmailOrigin;
use Oro\Bundle\EmailBundle\Form\Model\Email as EmailModel;
use Oro\Bundle\EmailBundle\Builder\EmailEntityBuilder;
use Oro\Bundle\EmailBundle\Model\FolderType;
use Oro\Bundle\EmailBundle\Tools\EmailAddressHelper;
use Oro\Bundle\EmailBundle\Entity\EmailFolder;
use Oro\Bundle\EmailBundle\Entity\EmailUser;
use Oro\Bundle\EmailBundle\Entity\InternalEmailOrigin;
use Oro\Bundle\EmailBundle\Entity\Manager\EmailActivityManager;
use Oro\Bundle\EmailBundle\Entity\Provider\EmailOwnerProvider;
use Oro\Bundle\EmailBundle\Event\EmailBodyAdded;
use Oro\Bundle\EmailBundle\Form\Model\EmailAttachment as EmailAttachmentModel;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;
use Oro\Bundle\EntityConfigBundle\DependencyInjection\Utils\ServiceLink;
use Oro\Bundle\OrganizationBundle\Entity\OrganizationInterface;
use Oro\Bundle\UserBundle\Entity\User;
use Oro\Bundle\SecurityBundle\SecurityFacade;
use Oro\Bundle\ImapBundle\Entity\UserEmailOrigin;
use Oro\Bundle\SecurityBundle\Encoder\Mcrypt;
/**
* Class Processor
*
* @package Oro\Bundle\EmailBundle\Mailer
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*/
class Processor
{
/** @var EntityManager */
protected $em;
/** @var DoctrineHelper */
protected $doctrineHelper;
/** @var \Swift_Mailer */
protected $mailer;
/** @var EmailAddressHelper */
protected $emailAddressHelper;
/** @var EmailEntityBuilder */
protected $emailEntityBuilder;
/** @var EmailOwnerProvider */
protected $emailOwnerProvider;
/** @var EmailActivityManager */
protected $emailActivityManager;
/** @var SecurityFacade */
protected $securityFacade;
/** @var EventDispatcherInterface */
protected $eventDispatcher;
/** @var array */
protected $origins = [];
/** @var Mcrypt */
protected $encryptor;
/**
* @param DoctrineHelper $doctrineHelper
* @param \Swift_Mailer $mailer
* @param EmailAddressHelper $emailAddressHelper
* @param EmailEntityBuilder $emailEntityBuilder
* @param EmailOwnerProvider $emailOwnerProvider
* @param EmailActivityManager $emailActivityManager
* @param ServiceLink $serviceLink
* @param EventDispatcherInterface $eventDispatcher
*/
public function __construct(
DoctrineHelper $doctrineHelper,
\Swift_Mailer $mailer,
EmailAddressHelper $emailAddressHelper,
EmailEntityBuilder $emailEntityBuilder,
EmailOwnerProvider $emailOwnerProvider,
EmailActivityManager $emailActivityManager,
ServiceLink $serviceLink,
EventDispatcherInterface $eventDispatcher,
Mcrypt $encryptor
) {
$this->doctrineHelper = $doctrineHelper;
$this->mailer = $mailer;
$this->emailAddressHelper = $emailAddressHelper;
$this->emailEntityBuilder = $emailEntityBuilder;
$this->emailOwnerProvider = $emailOwnerProvider;
$this->emailActivityManager = $emailActivityManager;
$this->securityFacade = $serviceLink->getService();
$this->eventDispatcher = $eventDispatcher;
$this->encryptor = $encryptor;
}
/**
* Process email model sending.
*
* @param EmailModel $model
*
* @return EmailUser
* @throws \Swift_SwiftException
*/
public function process(EmailModel $model)
{
$this->assertModel($model);
$messageDate = new \DateTime('now', new \DateTimeZone('UTC'));
$parentMessageId = $this->getParentMessageId($model);
/** @var \Swift_Message $message */
$message = $this->mailer->createMessage();
if ($parentMessageId) {
$message->getHeaders()->addTextHeader('References', $parentMessageId);
$message->getHeaders()->addTextHeader('In-Reply-To', $parentMessageId);
}
$message->setDate($messageDate->getTimestamp());
$message->setFrom($this->getAddresses($model->getFrom()));
$message->setTo($this->getAddresses($model->getTo()));
$message->setCc($this->getAddresses($model->getCc()));
$message->setBcc($this->getAddresses($model->getBcc()));
$message->setSubject($model->getSubject());
$message->setBody($model->getBody(), $model->getType() === 'html' ? 'text/html' : 'text/plain');
$this->addAttachments($message, $model);
$this->processEmbeddedImages($message, $model);
$messageId = '<' . $message->generateId() . '>';
$origin = $this->getEmailOrigin($model->getFrom(), $model->getOrganization());
$this->processSend($message, $origin);
$emailUser = $this->emailEntityBuilder->emailUser(
$model->getSubject(),
$model->getFrom(),
$model->getTo(),
$messageDate,
$messageDate,
$messageDate,
Email::NORMAL_IMPORTANCE,
$model->getCc(),
$model->getBcc(),
$origin->getOwner(),
$origin->getOrganization()
);
$emailUser->setFolder($this->getFolder($model->getFrom(), $origin));
$emailUser->getEmail()->setEmailBody(
$this->emailEntityBuilder->body($message->getBody(), $model->getType() === 'html', true)
);
$emailUser->getEmail()->setMessageId($messageId);
$emailUser->setSeen(true);
if ($parentMessageId) {
$emailUser->getEmail()->setRefs($parentMessageId);
}
// persist the email and all related entities such as folders, email addresses etc.
$this->emailEntityBuilder->getBatch()->persist($this->getEntityManager());
$this->persistAttachments($model, $emailUser->getEmail());
// associate the email with the target entity if exist
$contexts = $model->getContexts();
foreach ($contexts as $context) {
$this->emailActivityManager->addAssociation($emailUser->getEmail(), $context);
}
// flush all changes to the database
$this->getEntityManager()->flush();
$event = new EmailBodyAdded($emailUser->getEmail());
$this->eventDispatcher->dispatch(EmailBodyAdded::NAME, $event);
return $emailUser;
}
/**
* Get origin's folder
*
* @param string $email
* @param EmailOrigin $origin
* @return EmailFolder
*/
protected function getFolder($email, EmailOrigin $origin)
{
$folder = $origin->getFolder(FolderType::SENT);
//In case when 'useremailorigin' origin doesn't have folder, get folder from internal origin
if (!$folder && $origin instanceof UserEmailOrigin) {
$originKey = InternalEmailOrigin::BAP.$email;
if (array_key_exists($originKey, $this->origins)) {
unset($this->origins[$originKey]);
}
$origin = $this->getEmailOrigin($email, null, InternalEmailOrigin::BAP, false);
return $origin->getFolder(FolderType::SENT);
}
return $folder;
}
/**
* Process send email message. In case exist custom smtp host/port use it
*
* @param object $message
* @param object $emailOrigin
* @throws \Swift_SwiftException
*/
public function processSend($message, $emailOrigin)
{
if ($emailOrigin instanceof UserEmailOrigin) {
$this->modifySmtpSettings($emailOrigin);
}
if (!$this->mailer->send($message)) {
throw new \Swift_SwiftException('An email was not delivered.');
}
}
/**
* Modify transport smtp settings
*
* @param UserEmailOrigin $userEmailOrigin
*/
protected function modifySmtpSettings(UserEmailOrigin $userEmailOrigin)
{
$transport = $this->mailer->getTransport();
if ($transport instanceof \Swift_Transport_EsmtpTransport) {
$transport->setHost($userEmailOrigin->getSmtpHost());
$transport->setPort($userEmailOrigin->getSmtpPort());
$transport->setUsername($userEmailOrigin->getUser());
$transport->setPassword($this->encryptor->decryptData($userEmailOrigin->getPassword()));
if ($userEmailOrigin->getSmtpEncryption()) {
$transport->setEncryption($userEmailOrigin->getSmtpEncryption());
}
}
}
/**
* Process inline images. Convert it to embedded attachments and update message body.
*
* @param \Swift_Message $message
* @param EmailModel $model
*/
protected function processEmbeddedImages(\Swift_Message $message, EmailModel $model)
{
if ($model->getType() === 'html') {
$guesser = ExtensionGuesser::getInstance();
$body = $message->getBody();
$body = preg_replace_callback(
'/<img(.*)src(\s*)=(\s*)["\'](.*)["\']/U',
function ($matches) use ($message, $guesser, $model) {
if (count($matches) === 5) {
// 1st match contains any data between '<img' and 'src' parts (e.g. 'width=100')
$imgConfig = $matches[1];
// 4th match contains src attribute value
$srcData = $matches[4];
if (strpos($srcData, 'data:image') === 0) {
list($mime, $content) = explode(';', $srcData);
list($encoding, $file) = explode(',', $content);
$mime = str_replace('data:', '', $mime);
$fileName = sprintf('%s.%s', uniqid(), $guesser->guess($mime));
$swiftAttachment = \Swift_Image::newInstance(
ContentDecoder::decode($file, $encoding),
$fileName,
$mime
);
/** @var $message \Swift_Message */
$id = $message->embed($swiftAttachment);
$attachmentContent = new EmailAttachmentContent();
$attachmentContent->setContent($file);
$attachmentContent->setContentTransferEncoding($encoding);
$emailAttachment = new EmailAttachment();
$emailAttachment->setEmbeddedContentId($swiftAttachment->getId());
$emailAttachment->setFileName($fileName);
$emailAttachment->setContentType($mime);
$attachmentContent->setEmailAttachment($emailAttachment);
$emailAttachment->setContent($attachmentContent);
$emailAttachmentModel = new EmailAttachmentModel();
$emailAttachmentModel->setEmailAttachment($emailAttachment);
$model->addAttachment($emailAttachmentModel);
return sprintf('<img%ssrc="%s"', $imgConfig, $id);
}
}
},
$body
);
$message->setBody($body, 'text/html');
}
}
/**
* @param \Swift_Message $message
* @param EmailModel $model
*/
protected function addAttachments(\Swift_Message $message, EmailModel $model)
{
/** @var EmailAttachmentModel $emailAttachmentModel */
foreach ($model->getAttachments() as $emailAttachmentModel) {
$attachment = $emailAttachmentModel->getEmailAttachment();
$swiftAttachment = new \Swift_Attachment(
ContentDecoder::decode(
$attachment->getContent()->getContent(),
$attachment->getContent()->getContentTransferEncoding()
),
$attachment->getFileName(),
$attachment->getContentType()
);
$message->attach($swiftAttachment);
}
}
/**
* @param EmailModel $model
* @param Email $email
*/
protected function persistAttachments(EmailModel $model, Email $email)
{
/** @var EmailAttachmentModel $emailAttachmentModel */
foreach ($model->getAttachments() as $emailAttachmentModel) {
$attachment = $emailAttachmentModel->getEmailAttachment();
if (!$attachment->getId()) {
$this->getEntityManager()->persist($attachment);
} else {
$attachmentContent = clone $attachment->getContent();
$attachment = clone $attachment;
$attachment->setContent($attachmentContent);
$this->getEntityManager()->persist($attachment);
}
$email->getEmailBody()->addAttachment($attachment);
$attachment->setEmailBody($email->getEmailBody());
}
}
/**
* Find existing email origin entity by email string or create and persist new one.
*
* @param string $email
* @param OrganizationInterface $organization
* @param string $originName
* @param boolean $enableUseUserEmailOrigin
*
* @return EmailOrigin
*/
public function getEmailOrigin(
$email,
$organization = null,
$originName = InternalEmailOrigin::BAP,
$enableUseUserEmailOrigin = true
) {
$originKey = $originName . $email;
if (!$organization && $this->securityFacade !== null && $this->securityFacade->getOrganization()) {
$organization = $this->securityFacade->getOrganization();
}
if (!array_key_exists($originKey, $this->origins)) {
$emailOwner = $this->emailOwnerProvider->findEmailOwner(
$this->getEntityManager(),
$this->emailAddressHelper->extractPureEmailAddress($email)
);
if ($emailOwner instanceof User) {
$origin = $this->getPreferedOrigin($enableUseUserEmailOrigin, $emailOwner, $organization);
} else {
$origin = $this->getEntityManager()
->getRepository('OroEmailBundle:InternalEmailOrigin')
->findOneBy(['internalName' => $originName]);
}
$this->origins[$originKey] = $origin;
}
return $this->origins[$originKey];
}
/**
* @param User $emailOwner
* @param OrganizationInterface $organization
*
* @return InternalEmailOrigin
*/
protected function createUserInternalOrigin(User $emailOwner, OrganizationInterface $organization = null)
{
$organization = $organization
? $organization
: $emailOwner->getOrganization();
$originName = InternalEmailOrigin::BAP . '_User_' . $emailOwner->getId();
$outboxFolder = new EmailFolder();
$outboxFolder
->setType(FolderType::SENT)
->setName(FolderType::SENT)
->setFullName(FolderType::SENT);
$origin = new InternalEmailOrigin();
$origin
->setName($originName)
->addFolder($outboxFolder)
->setOwner($emailOwner)
->setOrganization($organization);
$emailOwner->addEmailOrigin($origin);
$this->getEntityManager()->persist($origin);
$this->getEntityManager()->persist($emailOwner);
return $origin;
}
/**
* @param EmailModel $model
*
* @throws \InvalidArgumentException
*/
protected function assertModel(EmailModel $model)
{
if (!$model->getFrom()) {
throw new \InvalidArgumentException('Sender can not be empty');
}
if (!$model->getTo() && !$model->getCc() && !$model->getBcc()) {
throw new \InvalidArgumentException('Recipient can not be empty');
}
}
/**
* Converts emails addresses to a form acceptable to \Swift_Mime_Message class
*
* @param string|string[] $addresses Examples of correct email addresses: [email protected], <[email protected]>,
* John Smith <[email protected]> or "John Smith" <[email protected]>
*
* @return array
* @throws \InvalidArgumentException
*/
protected function getAddresses($addresses)
{
$result = [];
if (is_string($addresses)) {
$addresses = [$addresses];
}
if (!is_array($addresses) && !$addresses instanceof \Iterator) {
throw new \InvalidArgumentException(
'The $addresses argument must be a string or a list of strings (array or Iterator)'
);
}
foreach ($addresses as $address) {
$name = $this->emailAddressHelper->extractEmailAddressName($address);
if (empty($name)) {
$result[] = $this->emailAddressHelper->extractPureEmailAddress($address);
} else {
$result[$this->emailAddressHelper->extractPureEmailAddress($address)] = $name;
}
}
return $result;
}
/**
* @param EmailModel $model
*
* @return string
*/
protected function getParentMessageId(EmailModel $model)
{
$messageId = '';
$parentEmailId = $model->getParentEmailId();
if ($parentEmailId && $model->getMailType() == EmailModel::MAIL_TYPE_REPLY) {
$parentEmail = $this->getEntityManager()
->getRepository('OroEmailBundle:Email')
->find($parentEmailId);
$messageId = $parentEmail->getMessageId();
}
return $messageId;
}
/**
* @return EntityManager
*/
protected function getEntityManager()
{
if (null === $this->em) {
$this->em = $this->doctrineHelper->getEntityManager('OroEmailBundle:Email');
}
return $this->em;
}
/**
* Get imap origin if exists.
*
* @param $enableUseUserEmailOrigin
* @param $emailOwner
* @param $organization
* @return mixed|null|InternalEmailOrigin
*/
protected function getPreferedOrigin($enableUseUserEmailOrigin, $emailOwner, $organization)
{
$origins = new ArrayCollection();
if ($enableUseUserEmailOrigin) {
$origins = $emailOwner->getEmailOrigins()->filter(
$this->getImapEnabledFilter($organization)
);
}
if ($origins->isEmpty()) {
$origins = $emailOwner->getEmailOrigins()->filter(
$this->getInternalFilter($organization)
);
}
$origin = $origins->isEmpty() ? null : $origins->first();
if ($origin === null) {
$origin = $this->createUserInternalOrigin($emailOwner, $organization);
return $origin;
}
return $origin;
}
/**
* @param $organization
* @return \Closure
*/
protected function getImapEnabledFilter($organization)
{
return function ($item) use ($organization) {
return
$item instanceof UserEmailOrigin && $item->isActive() && $item->isSmtpConfigured()
&& (!$organization || $item->getOrganization() === $organization);
};
}
/**
* @param $organization
* @return \Closure
*/
protected function getInternalFilter($organization)
{
return function ($item) use ($organization) {
return
$item instanceof InternalEmailOrigin
&& (!$organization || $item->getOrganization() === $organization);
};
}
}
| mit |
ebeeb/Murmade | src/Murmade.Prototypes.Model.Tests/ValueFieldTypeTests.cs | 131 | using NUnit.Framework;
namespace Murmade.Prototypes.Model.Tests
{
[TestFixture]
public class ValueFieldTypeTests { }
}
| mit |
anseki/plain-overlay | webpack.config.js | 6290 | /* eslint-env node, es6 */
'use strict';
const
BASE_NAME = 'plain-overlay',
OBJECT_NAME = 'PlainOverlay',
LIMIT_TAGS = ['FACE'],
BUILD_MODE = process.env.NODE_ENV === 'production',
LIMIT = process.env.EDITION === 'limit',
SYNC = process.env.SYNC === 'yes', // Enable "sync-mode support"
BUILD_BASE_NAME = `${BASE_NAME}${LIMIT ? '-limit' : ''}${SYNC ? '-sync' : ''}`,
PREPROC_REMOVE_TAGS =
(BUILD_MODE ? ['DEBUG'] : []).concat(LIMIT ? LIMIT_TAGS : [], SYNC ? 'DISABLE-SYNC' : []),
webpack = require('webpack'),
preProc = require('pre-proc'),
pathUtil = require('path'),
fs = require('fs'),
PKG = require('./package'),
SRC_DIR_PATH = pathUtil.resolve(__dirname, 'src'),
BUILD_DIR_PATH = BUILD_MODE ? __dirname : pathUtil.resolve(__dirname, 'test'),
ESM_DIR_PATH = __dirname,
ENTRY_PATH = pathUtil.join(SRC_DIR_PATH, `${BASE_NAME}.js`),
STATIC_ESM_FILES = [], // [{fileName, content}]
STATIC_ESM_CONTENTS = [], // [{path, re, content}]
PostCompile = require('post-compile-webpack-plugin');
function writeFile(filePath, content, messageClass) {
const HL = '='.repeat(48);
fs.writeFileSync(filePath,
`/* ${HL}\n DON'T MANUALLY EDIT THIS FILE\n${HL} */\n\n${content}`);
console.log(`Output (${messageClass}): ${filePath}`);
}
module.exports = {
// optimization: {minimize: false},
mode: BUILD_MODE ? 'production' : 'development',
entry: ENTRY_PATH,
output: {
path: BUILD_DIR_PATH,
filename: `${BUILD_BASE_NAME}${BUILD_MODE ? '.min' : ''}.js`,
library: OBJECT_NAME,
libraryTarget: 'var',
libraryExport: 'default'
},
module: {
rules: [
{
resource: {and: [SRC_DIR_PATH, /\.js$/]},
use: [
// ================================ Static ESM
{
loader: 'skeleton-loader',
options: {
procedure(content) {
if (this.resourcePath === ENTRY_PATH) {
STATIC_ESM_FILES.push(
{fileName: `${BUILD_BASE_NAME}${BUILD_MODE ? '' : '-debug'}.esm.js`, content});
}
return content;
}
}
},
// ================================ Babel
{
loader: 'babel-loader',
options: {presets: [['@babel/preset-env', {targets: 'defaults', modules: false}]]}
},
// ================================ Preprocess
PREPROC_REMOVE_TAGS.length ? {
loader: 'skeleton-loader',
options: {
procedure(content) {
content = preProc.removeTag(PREPROC_REMOVE_TAGS, content);
if (BUILD_MODE && this.resourcePath === ENTRY_PATH) {
writeFile(pathUtil.join(SRC_DIR_PATH, `${BUILD_BASE_NAME}.proc.js`), content, 'PROC');
}
return content;
}
}
} : null
].filter(loader => !!loader)
},
{
resource: {and: [SRC_DIR_PATH, /\.scss$/]},
use: [
// ================================ Static ESM
{
loader: 'skeleton-loader',
options: {
procedure(content) {
if (!this._module.rawRequest) { throw new Error('Can\'t get `rawRequest`'); }
STATIC_ESM_CONTENTS.push({path: this._module.rawRequest, content});
return content;
},
toCode: true
}
},
// ================================ Autoprefixer
{
loader: 'postcss-loader',
options: {postcssOptions: {plugins: [['autoprefixer']]}}
},
// ================================ SASS
{
loader: 'sass-loader',
options: {
implementation: require('sass'),
sassOptions: {
fiber: require('fibers'),
includePaths: [pathUtil.resolve(__dirname, '../../_common/files')],
outputStyle: 'compressed'
}
}
},
// ================================ Preprocess
PREPROC_REMOVE_TAGS.length ? {
loader: 'pre-proc-loader',
options: {removeTag: {tag: PREPROC_REMOVE_TAGS}}
} : null
].filter(loader => !!loader)
},
{
test: pathUtil.resolve(SRC_DIR_PATH, 'face.html'),
use: [
// ================================ Static ESM
{
loader: 'skeleton-loader',
options: {
procedure(content) {
if (!this._module.rawRequest) { throw new Error('Can\'t get `rawRequest`'); }
STATIC_ESM_CONTENTS.push({path: this._module.rawRequest, content});
return content;
},
toCode: true
}
},
// ================================ Minify
'htmlclean-loader',
// ================================ Preprocess
{
loader: 'pre-proc-loader',
options: {pickTag: {}} // `tag` is specified in source code `import`
}
]
}
]
},
devtool: BUILD_MODE ? false : 'source-map',
plugins: [
BUILD_MODE ? new webpack.BannerPlugin(
`${PKG.title || PKG.name} v${PKG.version} (c) ${PKG.author.name} ${PKG.homepage}`) : null,
// Static ESM
new PostCompile(() => {
// Fix STATIC_ESM_CONTENTS
STATIC_ESM_CONTENTS.forEach(content => {
// Member Import is not supported
content.re = new RegExp(`\\bimport\\s+(\\w+)\\s+from\\s+(?:'|")${
content.path.replace(/[\x00-\x7f]/g, // eslint-disable-line no-control-regex
s => `\\x${('00' + s.charCodeAt().toString(16)).substr(-2)}`)}(?:'|")`, 'g');
content.content = JSON.stringify(content.content);
});
STATIC_ESM_FILES.forEach(file => {
STATIC_ESM_CONTENTS.forEach(content => {
file.content = file.content.replace(content.re,
(s, varName) => `/* Static ESM */ /* ${s} */ var ${varName} = ${content.content}`);
});
// Save ESM file
writeFile(pathUtil.join(ESM_DIR_PATH, file.fileName), file.content, 'ESM');
});
})
].filter(plugin => !!plugin)
};
| mit |
vritxii/govirus | cmd/ipfsapp-server/server_test.go | 70 | package main
import (
"testing"
)
func TestServer(t *testing.T) {}
| mit |
pyrocat101/LogoScript | lib/app.js | 276559 | require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Canvas, Turtle, deg2rad, getMathFuncs, rad2deg;
Canvas = require('./canvas');
deg2rad = Math.PI / 180;
rad2deg = 180 / Math.PI;
getMathFuncs = function(cb) {
cb('abs', Math.abs, 1);
cb('acos', (function(x) {
return rad2deg * Math.acos(x);
}), 1);
cb('asin', (function(x) {
return rad2deg * Math.asin(x);
}), 1);
cb('atan', (function(x) {
return rad2deg * Math.atan(x);
}), 1);
cb('atan2', (function(y, x) {
return rad2deg * Math.atan2(y, x);
}), 2);
cb('ceil', Math.ceil, 1);
cb('cos', (function(x) {
return Math.cos(x * deg2rad);
}), 1);
cb('exp', Math.exp, 1);
cb('floor', Math.floor, 1);
cb('log', Math.log, 1);
cb('max', Math.max, 2);
cb('min', Math.min, 2);
cb('pow', Math.pow, 2);
cb('random', Math.random, 0);
cb('round', Math.round, 1);
cb('sin', (function(x) {
return Math.sin(x * deg2rad);
}), 1);
cb('sqrt', Math.sqrt, 1);
return cb('tan', (function(x) {
return Math.tan(x * deg2rad);
}), 1);
};
this.getMathFuncs = getMathFuncs;
Turtle = (function() {
function Turtle(options) {
var height, width;
this._canvas = Canvas();
this._ctx = this._canvas.getContext('2d');
this._ctx.save();
width = this._canvas.width;
height = this._canvas.height;
this._ctx.fillStyle = 'white';
this._ctx.fillRect(-width / 2, -height / 2, width, height);
this._ctx.restore();
this._ctx.moveTo(0, 0);
this._ctx.lineJoin = this._ctx.lineCap = 'round';
this._posx = 0;
this._posy = 0;
this._heading = 0;
this._isPenUp = false;
}
Turtle.prototype.fd = function(step) {
var x, y;
x = this._posx + step * Math.sin(this._heading / 180 * Math.PI);
y = this._posy + step * Math.cos(this._heading / 180 * Math.PI);
return this.setxy(x, y);
};
Turtle.prototype.bk = function(step) {
var x, y;
x = this._posx - step * Math.sin(this._heading / 180 * Math.PI);
y = this._posy - step * Math.cos(this._heading / 180 * Math.PI);
return this.setxy(x, y);
};
Turtle.prototype.lt = function(angle) {
return this._heading -= angle;
};
Turtle.prototype.rt = function(angle) {
return this._heading += angle;
};
Turtle.prototype.pu = function() {
return this._isPenUp = true;
};
Turtle.prototype.pd = function() {
return this._isPenUp = false;
};
Turtle.prototype.home = function() {
this.setxy(0, 0);
return this.seth(0);
};
Turtle.prototype.setx = function(x) {
return this.setxy(x, this._posy);
};
Turtle.prototype.sety = function(y) {
return this.setxy(this._posx, y);
};
Turtle.prototype.seth = function(angle) {
return this._heading = angle;
};
Turtle.prototype.seth2 = function(x, y) {
var dx, dy;
dx = x - this._posx;
dy = y - this._posy;
return this._heading = 90 + rad2deg * Math.atan(dy, dx);
};
Turtle.prototype.geth = function() {
return this._heading % 180;
};
Turtle.prototype.clear = function(c) {
var h, w;
w = this._canvas.width;
h = this._canvas.height;
this._ctx.save();
this._ctx.fillStyle = c;
this._ctx.fillRect(-(w / 2), -(h / 2), w, h);
return this._ctx.restore();
};
Turtle.prototype.setxy = function(x, y) {
if (!this._isPenUp) {
this._ctx.beginPath();
this._ctx.moveTo(this._posx, this._posy);
this._ctx.lineTo(x, y);
this._ctx.stroke();
}
this._posx = x;
return this._posy = y;
};
Turtle.prototype.setpc = function(c) {
this._ctx.strokeStyle = c;
return this._ctx.fillStyle = c;
};
Turtle.prototype.setpw = function(w) {
return this._ctx.lineWidth = w;
};
Turtle.prototype.text = function(t) {
this._ctx.save();
this._ctx.transform(1, 0, 0, -1, 0, 0);
this._ctx.fillText(t, this._posx, this._posy);
return this._ctx.restore();
};
Turtle.prototype.font = function(f) {
return this._ctx.font = f;
};
Turtle.prototype.getFuncs = function(cb) {
cb('fd', this.fd.bind(this), 1);
cb('bk', this.bk.bind(this), 1);
cb('lt', this.lt.bind(this), 1);
cb('rt', this.rt.bind(this), 1);
cb('pu', this.pu.bind(this), 0);
cb('pd', this.pd.bind(this), 0);
cb('home', this.home.bind(this), 0);
cb('setx', this.setx.bind(this), 1);
cb('sety', this.sety.bind(this), 1);
cb('seth', this.seth.bind(this), 1);
cb('seth2', this.seth2.bind(this), 2);
cb('geth', this.geth.bind(this), 0);
cb('setxy', this.setxy.bind(this), 2);
cb('setpc', this.setpc.bind(this), 1);
cb('setpw', this.setpw.bind(this), 1);
return cb('clear', this.clear.bind(this), 1);
};
return Turtle;
})();
this.Turtle = Turtle;
}).call(this);
},{"./canvas":2}],2:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
module.exports = function() {
var canvas, ctx;
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
ctx.restore();
ctx.save();
ctx.setTransform(1, 0, 0, -1, canvas.width / 2, canvas.height / 2);
return canvas;
};
}).call(this);
},{}],3:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var op, symTable, _genStore;
op = require('./opcodes');
symTable = require('./symTable');
_genStore = function(codeObj) {
switch (this.symInfo.flag) {
case symTable.SYM_LOCAL:
return codeObj.emit(op.STLOCAL, this.symInfo.number);
case symTable.SYM_GLOBAL:
return codeObj.emit(op.STGLOBAL, this.symInfo.number);
default:
throw new Error("Invalid symbol: " + this.name);
}
};
this.getGenerator = function(codeObj) {
var gen;
gen = {
genVariable: function() {
switch (this.symInfo.flag) {
case symTable.SYM_LOCAL:
return codeObj.emit(op.LDLOCAL, this.symInfo.number);
case symTable.SYM_GLOBAL:
return codeObj.emit(op.LDGLOBAL, this.symInfo.number);
default:
throw new Error("Invalid symbol: " + this.name);
}
},
genLiteral: function() {
return codeObj.emit(op.LDCONST, this.constNum);
},
genFunctionCall: function() {
var arg, _i, _len, _ref;
_ref = this["arguments"].reverse();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
arg = _ref[_i];
arg.genCode();
}
return codeObj.emit(op.CALL, this.symInfo.number);
},
genPostfixExpression: function() {
this.expression.genCode();
codeObj.emit(op.DUP);
switch (this.operator) {
case '++':
codeObj.emit(op.INC);
break;
case '--':
codeObj.emit(op.DEC);
}
_genStore.call(this.expression, codeObj);
return codeObj.emit(op.POP);
},
genUnaryExpression: function() {
this.expression.genCode();
if (this.operator === 'delete' && (this.expression.symInfo != null)) {
switch (this.symInfo.flag) {
case symTable.SYM_LOCAL:
return codeObj.emit(op.DELLOCAL, this.symInfo.number);
case symTable.SYM_GLOBAL:
return codeObj.emit(op.DELGLOBAL, this.symInfo.number);
default:
throw new Error("Invalid symbol: " + this.name);
}
} else {
switch (this.operator) {
case '++':
return codeObj.emit(op.INC);
case '--':
return codeObj.emit(op.DEC);
case '+':
return codeObj.emit(op.POS);
case '-':
return codeObj.emit(op.NEG);
case '~':
return codeObj.emit(op.BNEG);
case '!':
return codeObj.emit(op.NOT);
case 'typeof':
return codeObj.emit(op.TYPEOF);
}
}
},
genBinaryExpression: function() {
this.left.genCode();
this.right.genCode();
switch (this.operator) {
case '*':
return codeObj.emit(op.MUL);
case '/':
return codeObj.emit(op.DIV);
case '%':
return codeObj.emit(op.MOD);
case '+':
return codeObj.emit(op.ADD);
case '-':
return codeObj.emit(op.SUB);
case '<<':
return codeObj.emit(op.LSHIFT);
case '>>>':
return codeObj.emit(op.URSHIFT);
case '>>':
return codeObj.emit(op.RSHIFT);
case '<=':
return codeObj.emit(op.LTE);
case '>=':
return codeObj.emit(op.GTE);
case '<':
return codeObj.emit(op.LT);
case '>':
return codeObj.emit(op.GT);
case '==':
return codeObj.emit(op.EQ);
case '!=':
return codeObj.emit(op.NEQ);
case '&':
return codeObj.emit(op.BAND);
case '^':
return codeObj.emit(op.BXOR);
case '|':
return codeObj.emit(op.BOR);
case '&&':
return codeObj.emit(op.AND);
case '||':
return codeObj.emit(op.OR);
case ',':
return codeObj.emit(op.ROT, op.POP);
}
},
genConditionalExpression: function() {
var slot1, slot2;
this.condition.genCode();
codeObj.emit(op.JF);
slot1 = codeObj.reserveSlot();
this.trueExpression.genCode();
codeObj.emit(op.JMP);
slot2 = codeObj.reserveSlot();
codeObj.patchSlot(slot1, codeObj.peekLabel());
this.falseExpression.genCode();
return codeObj.patchSlot(slot2, codeObj.peekLabel());
},
genAssignmentExpression: function() {
this.left.genCode();
this.right.genCode();
switch (this.operator) {
case '*=':
codeObj.emit(op.MUL);
break;
case '/=':
codeObj.emit(op.DIV);
break;
case '%=':
codeObj.emit(op.MOD);
break;
case '+=':
codeObj.emit(op.ADD);
break;
case '-=':
codeObj.emit(op.SUB);
break;
case '<<=':
codeObj.emit(op.LSHIFT);
break;
case '>>=':
codeObj.emit(op.RSHIFT);
break;
case '>>>=':
codeObj.emit(op.URSHIFT);
break;
case '&=':
codeObj.emit(op.BAND);
break;
case '^=':
codeObj.emit(op.BXOR);
break;
case '|=':
codeObj.emit(op.BOR);
}
return _genStore.call(this.left, codeObj);
},
genBlock: function() {
var stmt, _i, _len, _ref, _results;
_ref = this.statements;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
stmt = _ref[_i];
stmt.genCode();
if (stmt.leaveResult != null) {
_results.push(codeObj.emit(op.POP));
} else {
_results.push(void 0);
}
}
return _results;
},
genVariableStatement: function() {
var decl, _i, _len, _ref;
_ref = this.declarations.splice(0, this.declarations.length - 1);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
decl = _ref[_i];
decl.genCode();
codeObj.emit(op.POP);
}
return this.declarations[this.declarations.length - 1].genCode();
},
genVariableDeclaration: function() {
this.value.genCode();
switch (this.symInfo.flag) {
case symTable.SYM_LOCAL:
return codeObj.emit(op.STLOCAL, this.symInfo.number);
case symTable.SYM_GLOBAL:
return codeObj.emit(op.STGLOBAL, this.symInfo.number);
default:
throw new Error("Invalid symbol: " + this.name);
}
},
genEmptyStatement: function() {},
genIfStatement: function() {
var slot1, slot2;
this.condition.genCode();
codeObj.emit(op.JF);
slot1 = codeObj.reserveSlot();
this.ifStatement.genCode();
if (this.ifStatement.leaveResult != null) {
codeObj.emit(op.POP);
}
if (this.elseStatement != null) {
codeObj.emit(op.JMP);
slot2 = codeObj.reserveSlot();
}
codeObj.patchSlot(slot1, codeObj.peekLabel());
if (this.elseStatement != null) {
this.elseStatement.genCode();
if (this.elseStatement.leaveResult != null) {
codeObj.emit(op.POP);
}
return codeObj.patchSlot(slot2, codeObj.peekLabel());
}
},
genDoWhileStatement: function() {
var label1, label2, label3;
codeObj.scopes.pushScope();
label1 = codeObj.peekLabel();
this.statement.genCode();
if (this.statement.leaveResult != null) {
codeObj.emit(op.POP);
}
label2 = codeObj.peekLabel();
this.condition.genCode();
codeObj.emit(op.JT, label1);
label3 = codeObj.peekLabel();
codeObj.scopes.patchContinue(label2);
codeObj.scopes.patchBreak(label3);
return codeObj.scopes.popScope();
},
genWhileStatement: function() {
var label1, label2, slot2;
codeObj.scopes.pushScope();
label1 = codeObj.peekLabel();
this.condition.genCode();
codeObj.emit(op.JF);
slot2 = codeObj.reserveSlot();
this.statement.genCode();
if (this.statement.leaveResult != null) {
codeObj.emit(op.POP);
}
codeObj.emit(op.JMP, label1);
label2 = codeObj.peekLabel();
codeObj.patchSlot(slot2, label2);
codeObj.scopes.patchContinue(label1);
codeObj.scopes.patchBreak(label2);
return codeObj.scopes.popScope();
},
genForStatement: function() {
var label1, label2, label3, slot3;
codeObj.scopes.pushScope();
if (this.initializer != null) {
this.initializer.genCode();
if (this.initializer.leaveResult != null) {
codeObj.emit(op.POP);
}
}
label1 = codeObj.peekLabel();
if (this.test != null) {
this.test.genCode();
codeObj.emit(op.JF);
slot3 = codeObj.reserveSlot();
}
this.statement.genCode();
if (this.statement.leaveResult != null) {
codeObj.emit(op.POP);
}
label2 = codeObj.peekLabel();
if (this.counter != null) {
this.counter.genCode();
if (this.counter.leaveResult != null) {
codeObj.emit(op.POP);
}
}
codeObj.emit(op.JMP, label1);
label3 = codeObj.peekLabel();
if (this.test != null) {
codeObj.patchSlot(slot3, label3);
}
codeObj.scopes.patchContinue(label2);
codeObj.scopes.patchBreak(label3);
return codeObj.scopes.popScope();
},
genContinueStatement: function() {
codeObj.emit(op.JMP);
return codeObj.scopes.addContinueSlot(codeObj.reserveSlot());
},
genBreakStatement: function() {
codeObj.emit(op.JMP);
return codeObj.scopes.addBreakSlot(codeObj.reserveSlot());
},
genReturnStatement: function() {
if (this.value != null) {
this.value.genCode();
return codeObj.emit(op.RET);
} else {
return codeObj.emit(op.NRET);
}
},
genFunction: function() {
var elem, _i, _len, _ref;
codeObj.startFuncCode(this.symInfo.number);
_ref = this.elements;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
elem = _ref[_i];
elem.genCode();
if (elem.leaveResult != null) {
codeObj.emit(op.POP);
}
}
return codeObj.endFuncCode();
},
genProgram: function() {
var elem, _i, _len, _ref, _results;
_ref = this.elements;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
elem = _ref[_i];
elem.genCode();
if (elem.leaveResult != null) {
_results.push(codeObj.emit(op.POP));
} else {
_results.push(void 0);
}
}
return _results;
}
};
return gen;
};
}).call(this);
},{"./opcodes":8,"./symTable":10}],4:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var BuiltinFunction, LogoFunction, Scope, ScopeChain, UserFunction, op, utils,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
op = require('./opcodes');
utils = require('./utils');
Scope = (function() {
function Scope() {
this.continueSlots = [];
this.breakSlots = [];
}
return Scope;
})();
ScopeChain = (function() {
function ScopeChain(codeObj) {
this.codeObj = codeObj;
this._chain = [];
}
ScopeChain.prototype.pushScope = function() {
return this._chain.push(new Scope);
};
ScopeChain.prototype.popScope = function() {
return this._chain.pop();
};
ScopeChain.prototype.patchContinue = function(label) {
var top;
if (this._chain.length < 1) {
throw new Error('No scope in chain');
}
top = this._chain[this._chain.length - 1];
return top.continueSlots.forEach((function(_this) {
return function(slot) {
return _this.codeObj._currentCode[slot] = label;
};
})(this));
};
ScopeChain.prototype.patchBreak = function(label) {
var top;
if (this._chain.length < 1) {
throw new Error('No scope in chain');
}
top = this._chain[this._chain.length - 1];
return top.breakSlots.forEach((function(_this) {
return function(slot) {
return _this.codeObj._currentCode[slot] = label;
};
})(this));
};
ScopeChain.prototype.addBreakSlot = function(slot) {
var top;
top = this._chain[this._chain.length - 1];
return top.breakSlots.push(slot);
};
ScopeChain.prototype.addContinueSlot = function(slot) {
var top;
top = this._chain[this._chain.length - 1];
return top.continueSlots.push(slot);
};
return ScopeChain;
})();
LogoFunction = (function() {
function LogoFunction(name, argc) {
this.name = name;
this.argc = argc;
}
LogoFunction.prototype.invoke = function(args) {
if (args.length !== this.argc) {
throw new Error("" + name + "() takes exactly " + this.argc + " arguments (" + argc.length + " given)");
}
};
return LogoFunction;
})();
BuiltinFunction = (function(_super) {
__extends(BuiltinFunction, _super);
function BuiltinFunction(name, argc, func) {
this.func = func;
BuiltinFunction.__super__.constructor.call(this, name, argc);
}
BuiltinFunction.prototype.invoke = function(args) {
BuiltinFunction.__super__.invoke.call(this, args);
return this.func.apply(null, args);
};
return BuiltinFunction;
})(LogoFunction);
UserFunction = (function(_super) {
__extends(UserFunction, _super);
function UserFunction(name, argc) {
UserFunction.__super__.constructor.call(this, name, argc);
this.code = [];
}
UserFunction.prototype.invoke = function(visitor, args) {
UserFunction.__super__.invoke.call(this, args);
return visitor(this.code, args);
};
return UserFunction;
})(LogoFunction);
this.BuiltinFunction = BuiltinFunction;
this.UserFunction = UserFunction;
this.CodeObject = (function() {
function CodeObject(consts, globals, funcs, locals) {
this.scopes = new ScopeChain(this);
this.code = [];
this._currentCode = this.code;
this.consts = this._initConsts(consts);
this.globalNames = this._initGlobalNames(globals);
this.funcInfos = this._initFuncInfos(funcs);
this.functions = [];
this.localNames = this._initLocalNames(locals);
}
CodeObject.prototype.startFuncCode = function(funcNum) {
var func;
func = this.funcInfos[funcNum];
this.functions[funcNum] = new UserFunction(func.name, func.argc);
return this._currentCode = this.functions[funcNum].code;
};
CodeObject.prototype.endFuncCode = function(funcNum) {
return this._currentCode = this.code;
};
CodeObject.prototype.addBuiltinFuncs = function(builtins) {
return ([].splice.apply(this.functions, [0, builtins.length - 0].concat(builtins)), builtins);
};
CodeObject.prototype._initConsts = function(consts) {
var x, _array, _i, _len, _results;
_array = [];
consts.forEach(function(obj, nr) {
return _array.push([obj, nr]);
});
_array.sort(function(x, y) {
return x[1] - y[1];
});
_results = [];
for (_i = 0, _len = _array.length; _i < _len; _i++) {
x = _array[_i];
_results.push(x[0]);
}
return _results;
};
CodeObject.prototype._initGlobalNames = function(globals) {
var x, _array, _i, _len, _results;
_array = [];
globals.forEach(function(name, ste) {
return _array.push([name, ste.number]);
});
_array.sort(function(x, y) {
return x[1] - y[1];
});
_results = [];
for (_i = 0, _len = _array.length; _i < _len; _i++) {
x = _array[_i];
_results.push(x[0]);
}
return _results;
};
CodeObject.prototype._initFuncInfos = function(funcs) {
var x, _array, _i, _len, _results;
_array = [];
funcs.forEach(function(name, fe) {
return _array.push([fe.number, fe.argc, name]);
});
_array.sort(function(x, y) {
return x[0] - y[0];
});
_results = [];
for (_i = 0, _len = _array.length; _i < _len; _i++) {
x = _array[_i];
_results.push({
name: x[2],
argc: x[1]
});
}
return _results;
};
CodeObject.prototype._initLocalNames = function(locals) {
var k, v, x, _array, _localNames;
_localNames = {};
for (k in locals) {
if (!__hasProp.call(locals, k)) continue;
v = locals[k];
_array = [];
v.forEach(function(name, ste) {
return _array.push([name, ste.number]);
});
_array.sort(function(x, y) {
return x[1] - y[1];
});
_localNames[k] = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = _array.length; _i < _len; _i++) {
x = _array[_i];
_results.push(x[0]);
}
return _results;
})();
}
return _localNames;
};
CodeObject.prototype.emit = function() {
var bytecode, x, _i, _len, _results;
bytecode = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
_results = [];
for (_i = 0, _len = bytecode.length; _i < _len; _i++) {
x = bytecode[_i];
_results.push(this._currentCode.push(x));
}
return _results;
};
CodeObject.prototype._getOpName = function(opcode) {
var name, num;
for (name in op) {
num = op[name];
if (opcode === num) {
return name;
}
}
};
CodeObject.prototype.dump = function() {
var i, _funcName, _i, _ref, _results;
this._dumpCode(this.code);
_results = [];
for (i = _i = 0, _ref = this.functions.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
if (this.functions[i] instanceof UserFunction) {
_funcName = this.functions[i].name;
utils.printf('%s:', _funcName);
_results.push(this._dumpCode(this.functions[i].code, this.localNames[_funcName]));
} else {
_results.push(void 0);
}
}
return _results;
};
CodeObject.prototype._dumpCode = function(code, localNames) {
var i, len, opname, _const, _funcName, _globalName, _local, _results;
if (localNames == null) {
localNames = this.globalNames;
}
i = 0;
len = code.length;
_results = [];
while (i < len) {
opname = this._getOpName(code[i]);
utils.printf('%-4d%-10s', i, opname);
switch (opname) {
case 'LDCONST':
_const = this.consts[code[++i]];
if (_const.constructor === String) {
utils.printf("%d ('%s')", code[i], _const);
} else {
utils.printf("%d (%s)", code[i], _const);
}
break;
case 'LDLOCAL':
case 'STLOCAL':
case 'DELLOCAL':
if (localNames == null) {
throw new Error("Invalid local var");
}
_local = localNames[code[++i]];
utils.printf('%d (%s)', code[i], _local);
break;
case 'LDGLOBAL':
case 'STGLOBAL':
case 'DELGLOBAL':
_globalName = this.globalNames[code[++i]];
utils.printf('%d (%s)', code[i], _globalName);
break;
case 'CALL':
_funcName = this.funcInfos[code[++i]].name;
utils.printf('%d (%s)', code[i], _funcName);
break;
case 'JT':
case 'JF':
case 'JMP':
utils.printf('%d', code[++i]);
}
_results.push(i++);
}
return _results;
};
CodeObject.prototype.reserveSlot = function() {
this.emit(0);
return this._currentCode.length - 1;
};
CodeObject.prototype.genSlot = function() {
return this._currentCode.length - 1;
};
CodeObject.prototype.patchSlot = function(slot, label) {
return this._currentCode[slot] = label;
};
CodeObject.prototype.genLabel = function() {
return this.genSlot();
};
CodeObject.prototype.peekLabel = function() {
return this.genSlot() + 1;
};
return CodeObject;
})();
}).call(this);
},{"./opcodes":8,"./utils":12}],"logo":[function(require,module,exports){
module.exports=require('Zgbpqn');
},{}],"Zgbpqn":[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var builtins, codeGen, codeObject, logoVM, parser, registerBuiltins, symTab, tree;
parser = require('./parser');
tree = require('./tree');
codeObject = require('./codeObj');
codeGen = require('./codeGen');
symTab = require('./symTable');
logoVM = require('./vm');
builtins = require('./builtins');
this.VERSION = '0.1.0';
registerBuiltins = function(funcTable, builtins) {
var builtin, _i, _len, _results;
_results = [];
for (_i = 0, _len = builtins.length; _i < _len; _i++) {
builtin = builtins[_i];
_results.push(funcTable.add(builtin.name, builtin.argc));
}
return _results;
};
this.run = function(src, options) {
var builtinFuncs, codeGenerator, codeObj, parseTree, print, tabSet, turtle, turtleOpt, vm;
if (options == null) {
options = {};
}
parseTree = parser.parse(src);
tabSet = new symTab.SymTabSet();
builtinFuncs = [];
print = new codeObject.BuiltinFunction('print', 1, console.log);
builtinFuncs.push(print);
builtins.getMathFuncs(function(name, func, argc) {
var f;
f = new codeObject.BuiltinFunction(name, argc, func);
return builtinFuncs.push(f);
});
turtleOpt = {
width: options.width,
height: options.height,
output: options.output,
antialias: options.antialias
};
turtle = new builtins.Turtle(turtleOpt);
turtle.getFuncs(function(name, func, argc) {
var f;
f = new codeObject.BuiltinFunction(name, argc, func);
return builtinFuncs.push(f);
});
registerBuiltins(tabSet.funcs, builtinFuncs);
parseTree.accept(new tree.FirstPassVisitor(tabSet));
if (options.ast) {
console.log(require('util').inspect(parseTree, false, null));
}
codeObj = new codeObject.CodeObject(tabSet.consts, tabSet.globals, tabSet.funcs, tabSet.locals);
codeGenerator = codeGen.getGenerator(codeObj);
parseTree.accept(new tree.SecondPassVisitor(codeGenerator));
codeObj.addBuiltinFuncs(builtinFuncs);
parseTree.genCode();
if (options.dump) {
codeObj.dump();
}
vm = new logoVM.LogoVM(codeObj);
return vm.run();
};
}).call(this);
},{"./builtins":1,"./codeGen":3,"./codeObj":4,"./parser":9,"./symTable":10,"./tree":11,"./vm":13,"util":17}],7:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var Mixins, leaveResult, _binExpression,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Mixins = require('./utils').Mixins;
leaveResult = {
leaveResult: true
};
this.NumericLiteral = (function(_super) {
__extends(NumericLiteral, _super);
NumericLiteral.include(leaveResult);
function NumericLiteral(value) {
this.value = value;
}
NumericLiteral.prototype.accept = function(visitor) {
return visitor.visitNumericLiteral(this);
};
return NumericLiteral;
})(Mixins);
this.StringLiteral = (function(_super) {
__extends(StringLiteral, _super);
StringLiteral.include(leaveResult);
function StringLiteral(value) {
this.value = value;
}
StringLiteral.prototype.accept = function(visitor) {
return visitor.visitStringLiteral(this);
};
return StringLiteral;
})(Mixins);
this.NullLiteral = (function(_super) {
__extends(NullLiteral, _super);
function NullLiteral() {
return NullLiteral.__super__.constructor.apply(this, arguments);
}
NullLiteral.include(leaveResult);
NullLiteral.prototype.accept = function(visitor) {
return visitor.visitNullLiteral(this);
};
return NullLiteral;
})(Mixins);
this.BooleanLiteral = (function(_super) {
__extends(BooleanLiteral, _super);
BooleanLiteral.include(leaveResult);
function BooleanLiteral(value) {
this.value = value;
}
BooleanLiteral.prototype.accept = function(visitor) {
return visitor.visitBooleanLiteral(this);
};
return BooleanLiteral;
})(Mixins);
this.Variable = (function(_super) {
__extends(Variable, _super);
Variable.include(leaveResult);
function Variable(name) {
this.name = name;
}
Variable.prototype.accept = function(visitor) {
return visitor.visitVariable(this);
};
return Variable;
})(Mixins);
this.FunctionCall = (function(_super) {
__extends(FunctionCall, _super);
FunctionCall.include(leaveResult);
function FunctionCall(name, args) {
this.name = name;
this["arguments"] = args;
}
FunctionCall.prototype.accept = function(visitor) {
var arg, _i, _len, _ref;
_ref = this["arguments"];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
arg = _ref[_i];
arg.accept(visitor);
}
return visitor.visitFunctionCall(this);
};
return FunctionCall;
})(Mixins);
this.PostfixExpression = (function(_super) {
__extends(PostfixExpression, _super);
PostfixExpression.include(leaveResult);
function PostfixExpression(operator, expression) {
this.operator = operator;
this.expression = expression;
}
PostfixExpression.prototype.accept = function(visitor) {
this.expression.accept(visitor);
return visitor.visitPostfixExpression(this);
};
return PostfixExpression;
})(Mixins);
this.UnaryExpression = (function(_super) {
__extends(UnaryExpression, _super);
UnaryExpression.include(leaveResult);
function UnaryExpression(operator, expression) {
this.operator = operator;
this.expression = expression;
}
UnaryExpression.prototype.accept = function(visitor) {
this.expression.accept(visitor);
return visitor.visitUnaryExpression(this);
};
return UnaryExpression;
})(Mixins);
_binExpression = function(ctx, op, l, r) {
ctx.operator = op;
ctx.left = l;
ctx.right = r;
};
this.BinaryExpression = (function(_super) {
__extends(BinaryExpression, _super);
BinaryExpression.include(leaveResult);
function BinaryExpression(op, l, r) {
_binExpression(this, op, l, r);
}
BinaryExpression.prototype.accept = function(visitor) {
this.left.accept(visitor);
this.right.accept(visitor);
return visitor.visitBinaryExpression(this);
};
return BinaryExpression;
})(Mixins);
this.ConditionalExpression = (function(_super) {
__extends(ConditionalExpression, _super);
ConditionalExpression.include(leaveResult);
function ConditionalExpression(condition, trueExpression, falseExpression) {
this.condition = condition;
this.trueExpression = trueExpression;
this.falseExpression = falseExpression;
}
ConditionalExpression.prototype.accept = function(visitor) {
this.condition.accept(visitor);
this.trueExpression.accept(visitor);
this.falseExpression.accept(visitor);
return visitor.visitConditionalExpression(this);
};
return ConditionalExpression;
})(Mixins);
this.AssignmentExpression = (function(_super) {
__extends(AssignmentExpression, _super);
AssignmentExpression.include(leaveResult);
function AssignmentExpression(op, l, r) {
_binExpression(this, op, l, r);
}
AssignmentExpression.prototype.accept = function(visitor) {
this.left.accept(visitor);
this.right.accept(visitor);
return visitor.visitAssignmentExpression(this);
};
return AssignmentExpression;
})(Mixins);
this.Block = (function(_super) {
__extends(Block, _super);
function Block(statements) {
this.statements = statements;
}
Block.prototype.accept = function(visitor) {
var stmt, _i, _len, _ref;
_ref = this.statements;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
stmt = _ref[_i];
stmt.accept(visitor);
}
return visitor.visitBlock(this);
};
return Block;
})(Mixins);
this.VariableStatement = (function(_super) {
__extends(VariableStatement, _super);
VariableStatement.include(leaveResult);
function VariableStatement(declarations) {
this.declarations = declarations;
}
VariableStatement.prototype.accept = function(visitor) {
var decl, _i, _len, _ref;
_ref = this.declarations;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
decl = _ref[_i];
decl.accept(visitor);
}
return visitor.visitVariableStatement(this);
};
return VariableStatement;
})(Mixins);
this.VariableDeclaration = (function(_super) {
__extends(VariableDeclaration, _super);
VariableDeclaration.include(leaveResult);
function VariableDeclaration(name, value) {
this.name = name;
this.value = value;
}
VariableDeclaration.prototype.accept = function(visitor) {
this.value.accept(visitor);
return visitor.visitVariableDeclaration(this);
};
return VariableDeclaration;
})(Mixins);
this.EmptyStatement = (function(_super) {
__extends(EmptyStatement, _super);
function EmptyStatement() {
return EmptyStatement.__super__.constructor.apply(this, arguments);
}
EmptyStatement.prototype.accept = function(visitor) {
return visitor.visitEmptyStatement(this);
};
return EmptyStatement;
})(Mixins);
this.IfStatement = (function(_super) {
__extends(IfStatement, _super);
function IfStatement(condition, ifStatement, elseStatement) {
this.condition = condition;
this.ifStatement = ifStatement;
this.elseStatement = elseStatement;
}
IfStatement.prototype.accept = function(visitor) {
var _ref;
this.condition.accept(visitor);
this.ifStatement.accept(visitor);
if ((_ref = this.elseStatement) != null) {
_ref.accept(visitor);
}
return visitor.visitIfStatement(this);
};
return IfStatement;
})(Mixins);
this.DoWhileStatement = (function(_super) {
__extends(DoWhileStatement, _super);
function DoWhileStatement(condition, statement) {
this.condition = condition;
this.statement = statement;
}
DoWhileStatement.prototype.accept = function(visitor) {
this.condition.accept(visitor);
this.statement.accept(visitor);
return visitor.visitDoWhileStatement(this);
};
return DoWhileStatement;
})(Mixins);
this.WhileStatement = (function(_super) {
__extends(WhileStatement, _super);
function WhileStatement(condition, statement) {
this.condition = condition;
this.statement = statement;
}
WhileStatement.prototype.accept = function(visitor) {
this.condition.accept(visitor);
this.statement.accept(visitor);
return visitor.visitWhileStatement(this);
};
return WhileStatement;
})(Mixins);
this.ForStatement = (function(_super) {
__extends(ForStatement, _super);
function ForStatement(initializer, test, counter, statement) {
this.initializer = initializer;
this.test = test;
this.counter = counter;
this.statement = statement;
}
ForStatement.prototype.accept = function(visitor) {
var _ref, _ref1, _ref2;
if ((_ref = this.initializer) != null) {
_ref.accept(visitor);
}
if ((_ref1 = this.test) != null) {
_ref1.accept(visitor);
}
if ((_ref2 = this.counter) != null) {
_ref2.accept(visitor);
}
this.statement.accept(visitor);
return visitor.visitForStatement(this);
};
return ForStatement;
})(Mixins);
this.ContinueStatement = (function(_super) {
__extends(ContinueStatement, _super);
function ContinueStatement() {
return ContinueStatement.__super__.constructor.apply(this, arguments);
}
ContinueStatement.prototype.accept = function(visitor) {
return visitor.visitContinueStatement(this);
};
return ContinueStatement;
})(Mixins);
this.BreakStatement = (function(_super) {
__extends(BreakStatement, _super);
function BreakStatement() {
return BreakStatement.__super__.constructor.apply(this, arguments);
}
BreakStatement.prototype.accept = function(visitor) {
return visitor.visitBreakStatement(this);
};
return BreakStatement;
})(Mixins);
this.ReturnStatement = (function(_super) {
__extends(ReturnStatement, _super);
function ReturnStatement(value) {
this.value = value;
}
ReturnStatement.prototype.accept = function(visitor) {
var _ref;
if ((_ref = this.value) != null) {
_ref.accept(visitor);
}
return visitor.visitReturnStatement(this);
};
return ReturnStatement;
})(Mixins);
this.Function_ = (function(_super) {
__extends(Function_, _super);
function Function_(name, params, elements) {
this.name = name;
this.params = params;
this.elements = elements;
}
Function_.prototype.accept = function(visitor) {
var elem, _i, _len, _ref;
visitor.enter('Function_', this);
visitor.visitParameters(this.params);
_ref = this.elements;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
elem = _ref[_i];
elem.accept(visitor);
}
return visitor.visitFunction_(this);
};
return Function_;
})(Mixins);
this.Program = (function(_super) {
__extends(Program, _super);
function Program(elements) {
this.elements = elements;
}
Program.prototype.accept = function(visitor) {
var elem, _i, _len, _ref;
_ref = this.elements;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
elem = _ref[_i];
elem.accept(visitor);
}
return visitor.visitProgram(this);
};
return Program;
})(Mixins);
}).call(this);
},{"./utils":12}],8:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
this.HALT = 1;
this.POP = 2;
this.LDCONST = 3;
this.LDLOCAL = 4;
this.LDGLOBAL = 5;
this.STLOCAL = 6;
this.STGLOBAL = 7;
this.CALL = 8;
this.RET = 9;
this.JT = 10;
this.JF = 11;
this.JMP = 12;
this.ADD = 13;
this.SUB = 14;
this.MUL = 15;
this.DIV = 16;
this.MOD = 17;
this.DELLOCAL = 18;
this.DELGLOBAL = 19;
this.INC = 20;
this.DEC = 21;
this.POS = 22;
this.NEG = 23;
this.LSHIFT = 24;
this.URSHIFT = 25;
this.RSHIFT = 26;
this.LTE = 27;
this.GTE = 28;
this.LT = 29;
this.GT = 30;
this.EQ = 31;
this.NEQ = 32;
this.NOT = 33;
this.BNEG = 34;
this.BAND = 35;
this.BXOR = 36;
this.BOR = 37;
this.AND = 38;
this.OR = 39;
this.ROT = 40;
this.DUP = 41;
this.TYPEOF = 42;
this.NRET = 43;
}).call(this);
},{}],9:[function(require,module,exports){
module.exports = (function() {
/*
* Generated by PEG.js 0.8.0.
*
* http://pegjs.majda.cz/
*/
function peg$subclass(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function SyntaxError(message, expected, found, offset, line, column) {
this.message = message;
this.expected = expected;
this.found = found;
this.offset = offset;
this.line = line;
this.column = column;
this.name = "SyntaxError";
}
peg$subclass(SyntaxError, Error);
function parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
peg$FAILED = {},
peg$startRuleFunctions = { start: peg$parsestart },
peg$startRuleFunction = peg$parsestart,
peg$c0 = peg$FAILED,
peg$c1 = function(program) { return program; },
peg$c2 = { type: "any", description: "any character" },
peg$c3 = { type: "other", description: "whitespace" },
peg$c4 = /^[\t\x0B\f ]/,
peg$c5 = { type: "class", value: "[\\t\\x0B\\f ]", description: "[\\t\\x0B\\f ]" },
peg$c6 = /^[\n\r\u2028\u2029]/,
peg$c7 = { type: "class", value: "[\\n\\r\\u2028\\u2029]", description: "[\\n\\r\\u2028\\u2029]" },
peg$c8 = { type: "other", description: "end of line" },
peg$c9 = "\n",
peg$c10 = { type: "literal", value: "\n", description: "\"\\n\"" },
peg$c11 = "\r\n",
peg$c12 = { type: "literal", value: "\r\n", description: "\"\\r\\n\"" },
peg$c13 = "\r",
peg$c14 = { type: "literal", value: "\r", description: "\"\\r\"" },
peg$c15 = "\u2028",
peg$c16 = { type: "literal", value: "\u2028", description: "\"\\u2028\"" },
peg$c17 = "\u2029",
peg$c18 = { type: "literal", value: "\u2029", description: "\"\\u2029\"" },
peg$c19 = { type: "other", description: "comment" },
peg$c20 = "/*",
peg$c21 = { type: "literal", value: "/*", description: "\"/*\"" },
peg$c22 = [],
peg$c23 = void 0,
peg$c24 = "*/",
peg$c25 = { type: "literal", value: "*/", description: "\"*/\"" },
peg$c26 = "//",
peg$c27 = { type: "literal", value: "//", description: "\"//\"" },
peg$c28 = { type: "other", description: "identifier" },
peg$c29 = function(name) { return name; },
peg$c30 = function(start, parts) {
return start + parts.join("");
},
peg$c31 = "$",
peg$c32 = { type: "literal", value: "$", description: "\"$\"" },
peg$c33 = "_",
peg$c34 = { type: "literal", value: "_", description: "\"_\"" },
peg$c35 = /^[a-zA-Z]/,
peg$c36 = { type: "class", value: "[a-zA-Z]", description: "[a-zA-Z]" },
peg$c37 = "break",
peg$c38 = { type: "literal", value: "break", description: "\"break\"" },
peg$c39 = "continue",
peg$c40 = { type: "literal", value: "continue", description: "\"continue\"" },
peg$c41 = "delete",
peg$c42 = { type: "literal", value: "delete", description: "\"delete\"" },
peg$c43 = "do",
peg$c44 = { type: "literal", value: "do", description: "\"do\"" },
peg$c45 = "else",
peg$c46 = { type: "literal", value: "else", description: "\"else\"" },
peg$c47 = "for",
peg$c48 = { type: "literal", value: "for", description: "\"for\"" },
peg$c49 = "function",
peg$c50 = { type: "literal", value: "function", description: "\"function\"" },
peg$c51 = "if",
peg$c52 = { type: "literal", value: "if", description: "\"if\"" },
peg$c53 = "in",
peg$c54 = { type: "literal", value: "in", description: "\"in\"" },
peg$c55 = "return",
peg$c56 = { type: "literal", value: "return", description: "\"return\"" },
peg$c57 = "typeof",
peg$c58 = { type: "literal", value: "typeof", description: "\"typeof\"" },
peg$c59 = "while",
peg$c60 = { type: "literal", value: "while", description: "\"while\"" },
peg$c61 = function(value) { return new node.NumericLiteral(value); },
peg$c62 = function(value) { return new node.StringLiteral(value); },
peg$c63 = function() { return new node.NullLiteral(); },
peg$c64 = function() { return new node.BooleanLiteral(true); },
peg$c65 = function() { return new node.BooleanLiteral(false); },
peg$c66 = { type: "other", description: "number" },
peg$c67 = function(literal) {
return literal;
},
peg$c68 = ".",
peg$c69 = { type: "literal", value: ".", description: "\".\"" },
peg$c70 = null,
peg$c71 = function(before, after, exponent) {
return parseFloat(before + "." + after + exponent);
},
peg$c72 = function(after, exponent) {
return parseFloat("." + after + exponent);
},
peg$c73 = function(before, exponent) {
return parseFloat(before + exponent);
},
peg$c74 = "0",
peg$c75 = { type: "literal", value: "0", description: "\"0\"" },
peg$c76 = function(digit, digits) { return digit + digits; },
peg$c77 = function(digits) { return digits.join(""); },
peg$c78 = /^[0-9]/,
peg$c79 = { type: "class", value: "[0-9]", description: "[0-9]" },
peg$c80 = /^[1-9]/,
peg$c81 = { type: "class", value: "[1-9]", description: "[1-9]" },
peg$c82 = function(indicator, integer) {
return indicator + integer;
},
peg$c83 = /^[eE]/,
peg$c84 = { type: "class", value: "[eE]", description: "[eE]" },
peg$c85 = /^[\-+]/,
peg$c86 = { type: "class", value: "[\\-+]", description: "[\\-+]" },
peg$c87 = function(sign, digits) { return sign + digits; },
peg$c88 = /^[xX]/,
peg$c89 = { type: "class", value: "[xX]", description: "[xX]" },
peg$c90 = function(digits) { return parseInt("0x" + digits.join("")); },
peg$c91 = /^[0-9a-fA-F]/,
peg$c92 = { type: "class", value: "[0-9a-fA-F]", description: "[0-9a-fA-F]" },
peg$c93 = { type: "other", description: "string" },
peg$c94 = "\"",
peg$c95 = { type: "literal", value: "\"", description: "\"\\\"\"" },
peg$c96 = "'",
peg$c97 = { type: "literal", value: "'", description: "\"'\"" },
peg$c98 = function(parts) {
return parts[1];
},
peg$c99 = function(chars) { return chars.join(""); },
peg$c100 = "\\",
peg$c101 = { type: "literal", value: "\\", description: "\"\\\\\"" },
peg$c102 = function(char_) { return char_; },
peg$c103 = function(sequence) { return sequence; },
peg$c104 = function(sequence) { return sequence; },
peg$c105 = function() { return "\0"; },
peg$c106 = /^['"\\bfnrtv]/,
peg$c107 = { type: "class", value: "['\"\\\\bfnrtv]", description: "['\"\\\\bfnrtv]" },
peg$c108 = function(char_) {
return char_
.replace("b", "\b")
.replace("f", "\f")
.replace("n", "\n")
.replace("r", "\r")
.replace("t", "\t")
.replace("v", "\x0B") // IE does not recognize "\v".
},
peg$c109 = function(char_) { return char_; },
peg$c110 = "x",
peg$c111 = { type: "literal", value: "x", description: "\"x\"" },
peg$c112 = "u",
peg$c113 = { type: "literal", value: "u", description: "\"u\"" },
peg$c114 = function(h1, h2) {
return String.fromCharCode(parseInt("0x" + h1 + h2));
},
peg$c115 = function(h1, h2, h3, h4) {
return String.fromCharCode(parseInt("0x" + h1 + h2 + h3 + h4));
},
peg$c116 = function() { return "delete"; },
peg$c117 = "false",
peg$c118 = { type: "literal", value: "false", description: "\"false\"" },
peg$c119 = "null",
peg$c120 = { type: "literal", value: "null", description: "\"null\"" },
peg$c121 = "true",
peg$c122 = { type: "literal", value: "true", description: "\"true\"" },
peg$c123 = function() { return "typeof"; },
peg$c124 = ";",
peg$c125 = { type: "literal", value: ";", description: "\";\"" },
peg$c126 = "}",
peg$c127 = { type: "literal", value: "}", description: "\"}\"" },
peg$c128 = function(name) { return new node.Variable(name); },
peg$c129 = "(",
peg$c130 = { type: "literal", value: "(", description: "\"(\"" },
peg$c131 = ")",
peg$c132 = { type: "literal", value: ")", description: "\")\"" },
peg$c133 = function(expression) { return expression; },
peg$c134 = function(name, arguments) {
return new node.FunctionCall(name, arguments);
},
peg$c135 = function(arguments) {
return arguments ? arguments : [];
},
peg$c136 = ",",
peg$c137 = { type: "literal", value: ",", description: "\",\"" },
peg$c138 = function(head, tail) {
var result = [head];
for (var i = 0; i < tail.length; i++) {
result.push(tail[i][3]);
}
return result;
},
peg$c139 = function(expression, operator) {
return new node.PostfixExpression(operator, expression);
},
peg$c140 = "++",
peg$c141 = { type: "literal", value: "++", description: "\"++\"" },
peg$c142 = "--",
peg$c143 = { type: "literal", value: "--", description: "\"--\"" },
peg$c144 = function(operator, expression) {
return new node.UnaryExpression(operator, expression);
},
peg$c145 = "+",
peg$c146 = { type: "literal", value: "+", description: "\"+\"" },
peg$c147 = "-",
peg$c148 = { type: "literal", value: "-", description: "\"-\"" },
peg$c149 = "~",
peg$c150 = { type: "literal", value: "~", description: "\"~\"" },
peg$c151 = "!",
peg$c152 = { type: "literal", value: "!", description: "\"!\"" },
peg$c153 = function(head, tail) {
var result = head;
for (var i = 0; i < tail.length; i++) {
result = new node.BinaryExpression(
tail[i][1], result, tail[i][3]);
}
return result;
},
peg$c154 = "*",
peg$c155 = { type: "literal", value: "*", description: "\"*\"" },
peg$c156 = "/",
peg$c157 = { type: "literal", value: "/", description: "\"/\"" },
peg$c158 = "%",
peg$c159 = { type: "literal", value: "%", description: "\"%\"" },
peg$c160 = "=",
peg$c161 = { type: "literal", value: "=", description: "\"=\"" },
peg$c162 = function(operator) { return operator; },
peg$c163 = function() { return "+"; },
peg$c164 = function() { return "-"; },
peg$c165 = "<<",
peg$c166 = { type: "literal", value: "<<", description: "\"<<\"" },
peg$c167 = ">>>",
peg$c168 = { type: "literal", value: ">>>", description: "\">>>\"" },
peg$c169 = ">>",
peg$c170 = { type: "literal", value: ">>", description: "\">>\"" },
peg$c171 = "<=",
peg$c172 = { type: "literal", value: "<=", description: "\"<=\"" },
peg$c173 = ">=",
peg$c174 = { type: "literal", value: ">=", description: "\">=\"" },
peg$c175 = "<",
peg$c176 = { type: "literal", value: "<", description: "\"<\"" },
peg$c177 = ">",
peg$c178 = { type: "literal", value: ">", description: "\">\"" },
peg$c179 = "==",
peg$c180 = { type: "literal", value: "==", description: "\"==\"" },
peg$c181 = "!=",
peg$c182 = { type: "literal", value: "!=", description: "\"!=\"" },
peg$c183 = "&",
peg$c184 = { type: "literal", value: "&", description: "\"&\"" },
peg$c185 = function() { return "&"; },
peg$c186 = "^",
peg$c187 = { type: "literal", value: "^", description: "\"^\"" },
peg$c188 = function() { return "^"; },
peg$c189 = "|",
peg$c190 = { type: "literal", value: "|", description: "\"|\"" },
peg$c191 = function() { return "|"; },
peg$c192 = "&&",
peg$c193 = { type: "literal", value: "&&", description: "\"&&\"" },
peg$c194 = function() { return "&&"; },
peg$c195 = "||",
peg$c196 = { type: "literal", value: "||", description: "\"||\"" },
peg$c197 = function() { return "||"; },
peg$c198 = "?",
peg$c199 = { type: "literal", value: "?", description: "\"?\"" },
peg$c200 = ":",
peg$c201 = { type: "literal", value: ":", description: "\":\"" },
peg$c202 = function(condition, trueExpression, falseExpression) {
return new node.ConditionalExpression(
condition, trueExpression, falseExpression);
},
peg$c203 = function(left, operator, right) {
return new node.AssignmentExpression(operator, left, right);
},
peg$c204 = "*=",
peg$c205 = { type: "literal", value: "*=", description: "\"*=\"" },
peg$c206 = "/=",
peg$c207 = { type: "literal", value: "/=", description: "\"/=\"" },
peg$c208 = "%=",
peg$c209 = { type: "literal", value: "%=", description: "\"%=\"" },
peg$c210 = "+=",
peg$c211 = { type: "literal", value: "+=", description: "\"+=\"" },
peg$c212 = "-=",
peg$c213 = { type: "literal", value: "-=", description: "\"-=\"" },
peg$c214 = "<<=",
peg$c215 = { type: "literal", value: "<<=", description: "\"<<=\"" },
peg$c216 = ">>=",
peg$c217 = { type: "literal", value: ">>=", description: "\">>=\"" },
peg$c218 = ">>>=",
peg$c219 = { type: "literal", value: ">>>=", description: "\">>>=\"" },
peg$c220 = "&=",
peg$c221 = { type: "literal", value: "&=", description: "\"&=\"" },
peg$c222 = "^=",
peg$c223 = { type: "literal", value: "^=", description: "\"^=\"" },
peg$c224 = "|=",
peg$c225 = { type: "literal", value: "|=", description: "\"|=\"" },
peg$c226 = "{",
peg$c227 = { type: "literal", value: "{", description: "\"{\"" },
peg$c228 = function(statements) {
return new node.Block(statements ? statements[0] : []);
},
peg$c229 = function(head, tail) {
var result = [head];
for (var i = 0; i < tail.length; i++) {
result.push(tail[i][1]);
}
return result;
},
peg$c230 = function(declarations) {
return new node.VariableStatement(declarations);
},
peg$c231 = function(head, tail) {
var result = [head];
for (var i = 0; i < tail.length; i++) {
result.push(tail[i][3]);
}
return result;
},
peg$c232 = function(name, value) {
return new node.VariableDeclaration(name, value);
},
peg$c233 = function() { return new node.EmptyStatement(); },
peg$c234 = function(condition, ifStatement, elseStatement) {
return new node.IfStatement(condition, ifStatement,
elseStatement ? elseStatement[3] : null);
},
peg$c235 = function(statement, condition) {
return new node.DoWhileStatement(condition, statement);
},
peg$c236 = function(condition, statement) {
return new node.WhileStatement(condition, statement);
},
peg$c237 = function(declarations) {
return new node.VariableStatement(declarations);
},
peg$c238 = function(initializer, test, counter, statement) {
return new node.ForStatement(
initializer ? initializer : null,
test ? test : null,
counter ? counter : null,
statement);
},
peg$c239 = function() {
return new node.ContinueStatement();
},
peg$c240 = function() {
return new node.BreakStatement();
},
peg$c241 = function() { return ""; },
peg$c242 = function(value) {
return new node.ReturnStatement(value ? value : null);
},
peg$c243 = function(name, params, elements) {
return new node.Function_(
name, params ? params : [], elements);
},
peg$c244 = function(elements) { return elements ? elements : []; },
peg$c245 = function(elements) {
return new node.Program(elements ? elements : []);
},
peg$currPos = 0,
peg$reportedPos = 0,
peg$cachedPos = 0,
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$reportedPos, peg$currPos);
}
function offset() {
return peg$reportedPos;
}
function line() {
return peg$computePosDetails(peg$reportedPos).line;
}
function column() {
return peg$computePosDetails(peg$reportedPos).column;
}
function expected(description) {
throw peg$buildException(
null,
[{ type: "other", description: description }],
peg$reportedPos
);
}
function error(message) {
throw peg$buildException(message, null, peg$reportedPos);
}
function peg$computePosDetails(pos) {
function advance(details, startPos, endPos) {
var p, ch;
for (p = startPos; p < endPos; p++) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) { details.line++; }
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
}
}
if (peg$cachedPos !== pos) {
if (peg$cachedPos > pos) {
peg$cachedPos = 0;
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };
}
advance(peg$cachedPosDetails, peg$cachedPos, pos);
peg$cachedPos = pos;
}
return peg$cachedPosDetails;
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) { return; }
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, pos) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); })
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); })
.replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); })
.replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); });
}
var expectedDescs = new Array(expected.length),
expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1
? expectedDescs.slice(0, -1).join(", ")
+ " or "
+ expectedDescs[expected.length - 1]
: expectedDescs[0];
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
var posDetails = peg$computePosDetails(pos),
found = pos < input.length ? input.charAt(pos) : null;
if (expected !== null) {
cleanupExpected(expected);
}
return new SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
pos,
posDetails.line,
posDetails.column
);
}
function peg$parsestart() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parse__();
if (s1 !== peg$FAILED) {
s2 = peg$parseProgram();
if (s2 !== peg$FAILED) {
s3 = peg$parse__();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c1(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseSourceCharacter() {
var s0;
if (input.length > peg$currPos) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c2); }
}
return s0;
}
function peg$parseWhiteSpace() {
var s0, s1;
peg$silentFails++;
if (peg$c4.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c5); }
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c3); }
}
return s0;
}
function peg$parseLineTerminator() {
var s0;
if (peg$c6.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c7); }
}
return s0;
}
function peg$parseLineTerminatorSequence() {
var s0, s1;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 10) {
s0 = peg$c9;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c11) {
s0 = peg$c11;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c12); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 13) {
s0 = peg$c13;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c14); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 8232) {
s0 = peg$c15;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c16); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 8233) {
s0 = peg$c17;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c18); }
}
}
}
}
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
return s0;
}
function peg$parseComment() {
var s0, s1;
peg$silentFails++;
s0 = peg$parseMultiLineComment();
if (s0 === peg$FAILED) {
s0 = peg$parseSingleLineComment();
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c19); }
}
return s0;
}
function peg$parseMultiLineComment() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c20) {
s1 = peg$c20;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c21); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c24) {
s5 = peg$c24;
peg$currPos += 2;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c25); }
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c23;
} else {
peg$currPos = s4;
s4 = peg$c0;
}
if (s4 !== peg$FAILED) {
s5 = peg$parseSourceCharacter();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c24) {
s5 = peg$c24;
peg$currPos += 2;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c25); }
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c23;
} else {
peg$currPos = s4;
s4 = peg$c0;
}
if (s4 !== peg$FAILED) {
s5 = peg$parseSourceCharacter();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c24) {
s3 = peg$c24;
peg$currPos += 2;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c25); }
}
if (s3 !== peg$FAILED) {
s1 = [s1, s2, s3];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseMultiLineCommentNoLineTerminator() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c20) {
s1 = peg$c20;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c21); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c24) {
s5 = peg$c24;
peg$currPos += 2;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c25); }
}
if (s5 === peg$FAILED) {
s5 = peg$parseLineTerminator();
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c23;
} else {
peg$currPos = s4;
s4 = peg$c0;
}
if (s4 !== peg$FAILED) {
s5 = peg$parseSourceCharacter();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c24) {
s5 = peg$c24;
peg$currPos += 2;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c25); }
}
if (s5 === peg$FAILED) {
s5 = peg$parseLineTerminator();
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c23;
} else {
peg$currPos = s4;
s4 = peg$c0;
}
if (s4 !== peg$FAILED) {
s5 = peg$parseSourceCharacter();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c24) {
s3 = peg$c24;
peg$currPos += 2;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c25); }
}
if (s3 !== peg$FAILED) {
s1 = [s1, s2, s3];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseSingleLineComment() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c26) {
s1 = peg$c26;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c27); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$parseLineTerminator();
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c23;
} else {
peg$currPos = s4;
s4 = peg$c0;
}
if (s4 !== peg$FAILED) {
s5 = peg$parseSourceCharacter();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$parseLineTerminator();
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c23;
} else {
peg$currPos = s4;
s4 = peg$c0;
}
if (s4 !== peg$FAILED) {
s5 = peg$parseSourceCharacter();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseIdentifier() {
var s0, s1, s2;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
s2 = peg$parseReservedWord();
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c23;
} else {
peg$currPos = s1;
s1 = peg$c0;
}
if (s1 !== peg$FAILED) {
s2 = peg$parseIdentifierName();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c29(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c28); }
}
return s0;
}
function peg$parseIdentifierName() {
var s0, s1, s2, s3;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parseIdentifierStart();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseIdentifierPart();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseIdentifierPart();
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c30(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c28); }
}
return s0;
}
function peg$parseIdentifierStart() {
var s0;
s0 = peg$parseAlphaLetter();
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 36) {
s0 = peg$c31;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c32); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 95) {
s0 = peg$c33;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c34); }
}
}
}
return s0;
}
function peg$parseIdentifierPart() {
var s0;
s0 = peg$parseIdentifierStart();
if (s0 === peg$FAILED) {
s0 = peg$parseDecimalDigit();
}
return s0;
}
function peg$parseAlphaLetter() {
var s0;
if (peg$c35.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c36); }
}
return s0;
}
function peg$parseReservedWord() {
var s0;
s0 = peg$parseKeyword();
if (s0 === peg$FAILED) {
s0 = peg$parseNullLiteral();
if (s0 === peg$FAILED) {
s0 = peg$parseBooleanLiteral();
}
}
return s0;
}
function peg$parseKeyword() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c37) {
s1 = peg$c37;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c38); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 8) === peg$c39) {
s1 = peg$c39;
peg$currPos += 8;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c40); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 6) === peg$c41) {
s1 = peg$c41;
peg$currPos += 6;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c42); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c43) {
s1 = peg$c43;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c44); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 4) === peg$c45) {
s1 = peg$c45;
peg$currPos += 4;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c46); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c47) {
s1 = peg$c47;
peg$currPos += 3;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 8) === peg$c49) {
s1 = peg$c49;
peg$currPos += 8;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c50); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c51) {
s1 = peg$c51;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c52); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c53) {
s1 = peg$c53;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c54); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 6) === peg$c55) {
s1 = peg$c55;
peg$currPos += 6;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c56); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 6) === peg$c57) {
s1 = peg$c57;
peg$currPos += 6;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c58); }
}
if (s1 === peg$FAILED) {
if (input.substr(peg$currPos, 5) === peg$c59) {
s1 = peg$c59;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c60); }
}
}
}
}
}
}
}
}
}
}
}
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseLiteral() {
var s0, s1;
s0 = peg$parseNullLiteral();
if (s0 === peg$FAILED) {
s0 = peg$parseBooleanLiteral();
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseNumericLiteral();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c61(s1);
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseStringLiteral();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c62(s1);
}
s0 = s1;
}
}
}
return s0;
}
function peg$parseNullLiteral() {
var s0, s1;
s0 = peg$currPos;
s1 = peg$parseNullToken();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c63();
}
s0 = s1;
return s0;
}
function peg$parseBooleanLiteral() {
var s0, s1;
s0 = peg$currPos;
s1 = peg$parseTrueToken();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c64();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseFalseToken();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c65();
}
s0 = s1;
}
return s0;
}
function peg$parseNumericLiteral() {
var s0, s1, s2, s3;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parseHexIntegerLiteral();
if (s1 === peg$FAILED) {
s1 = peg$parseDecimalLiteral();
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierStart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c67(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c66); }
}
return s0;
}
function peg$parseDecimalLiteral() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
s1 = peg$parseDecimalIntegerLiteral();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s2 = peg$c68;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c69); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseDecimalDigits();
if (s3 === peg$FAILED) {
s3 = peg$c70;
}
if (s3 !== peg$FAILED) {
s4 = peg$parseExponentPart();
if (s4 === peg$FAILED) {
s4 = peg$c70;
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c71(s1, s3, s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s1 = peg$c68;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c69); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseDecimalDigits();
if (s2 !== peg$FAILED) {
s3 = peg$parseExponentPart();
if (s3 === peg$FAILED) {
s3 = peg$c70;
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c72(s2, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseDecimalIntegerLiteral();
if (s1 !== peg$FAILED) {
s2 = peg$parseExponentPart();
if (s2 === peg$FAILED) {
s2 = peg$c70;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c73(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
}
}
return s0;
}
function peg$parseDecimalIntegerLiteral() {
var s0, s1, s2;
if (input.charCodeAt(peg$currPos) === 48) {
s0 = peg$c74;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseNonZeroDigit();
if (s1 !== peg$FAILED) {
s2 = peg$parseDecimalDigits();
if (s2 === peg$FAILED) {
s2 = peg$c70;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c76(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
}
return s0;
}
function peg$parseDecimalDigits() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
s2 = peg$parseDecimalDigit();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseDecimalDigit();
}
} else {
s1 = peg$c0;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c77(s1);
}
s0 = s1;
return s0;
}
function peg$parseDecimalDigit() {
var s0;
if (peg$c78.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c79); }
}
return s0;
}
function peg$parseNonZeroDigit() {
var s0;
if (peg$c80.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c81); }
}
return s0;
}
function peg$parseExponentPart() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$parseExponentIndicator();
if (s1 !== peg$FAILED) {
s2 = peg$parseSignedInteger();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c82(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseExponentIndicator() {
var s0;
if (peg$c83.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c84); }
}
return s0;
}
function peg$parseSignedInteger() {
var s0, s1, s2;
s0 = peg$currPos;
if (peg$c85.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c86); }
}
if (s1 === peg$FAILED) {
s1 = peg$c70;
}
if (s1 !== peg$FAILED) {
s2 = peg$parseDecimalDigits();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c87(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseHexIntegerLiteral() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 48) {
s1 = peg$c74;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s1 !== peg$FAILED) {
if (peg$c88.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c89); }
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseHexDigit();
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseHexDigit();
}
} else {
s3 = peg$c0;
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c90(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseHexDigit() {
var s0;
if (peg$c91.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c92); }
}
return s0;
}
function peg$parseStringLiteral() {
var s0, s1, s2, s3, s4;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 34) {
s2 = peg$c94;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c95); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseDoubleStringCharacters();
if (s3 === peg$FAILED) {
s3 = peg$c70;
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 34) {
s4 = peg$c94;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c95); }
}
if (s4 !== peg$FAILED) {
s2 = [s2, s3, s4];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c0;
}
} else {
peg$currPos = s1;
s1 = peg$c0;
}
} else {
peg$currPos = s1;
s1 = peg$c0;
}
if (s1 === peg$FAILED) {
s1 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 39) {
s2 = peg$c96;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c97); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseSingleStringCharacters();
if (s3 === peg$FAILED) {
s3 = peg$c70;
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 39) {
s4 = peg$c96;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c97); }
}
if (s4 !== peg$FAILED) {
s2 = [s2, s3, s4];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c0;
}
} else {
peg$currPos = s1;
s1 = peg$c0;
}
} else {
peg$currPos = s1;
s1 = peg$c0;
}
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c98(s1);
}
s0 = s1;
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c93); }
}
return s0;
}
function peg$parseDoubleStringCharacters() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
s2 = peg$parseDoubleStringCharacter();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseDoubleStringCharacter();
}
} else {
s1 = peg$c0;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c99(s1);
}
s0 = s1;
return s0;
}
function peg$parseSingleStringCharacters() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
s2 = peg$parseSingleStringCharacter();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseSingleStringCharacter();
}
} else {
s1 = peg$c0;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c99(s1);
}
s0 = s1;
return s0;
}
function peg$parseDoubleStringCharacter() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 34) {
s2 = peg$c94;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c95); }
}
if (s2 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 92) {
s2 = peg$c100;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c101); }
}
if (s2 === peg$FAILED) {
s2 = peg$parseLineTerminator();
}
}
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c23;
} else {
peg$currPos = s1;
s1 = peg$c0;
}
if (s1 !== peg$FAILED) {
s2 = peg$parseSourceCharacter();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c102(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s1 = peg$c100;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c101); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseEscapeSequence();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c103(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$parseLineContinuation();
}
}
return s0;
}
function peg$parseSingleStringCharacter() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 39) {
s2 = peg$c96;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c97); }
}
if (s2 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 92) {
s2 = peg$c100;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c101); }
}
if (s2 === peg$FAILED) {
s2 = peg$parseLineTerminator();
}
}
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c23;
} else {
peg$currPos = s1;
s1 = peg$c0;
}
if (s1 !== peg$FAILED) {
s2 = peg$parseSourceCharacter();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c102(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s1 = peg$c100;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c101); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseEscapeSequence();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c103(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$parseLineContinuation();
}
}
return s0;
}
function peg$parseLineContinuation() {
var s0, s1, s2;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s1 = peg$c100;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c101); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseLineTerminatorSequence();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c104(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseEscapeSequence() {
var s0, s1, s2, s3;
s0 = peg$parseCharacterEscapeSequence();
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 48) {
s1 = peg$c74;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseDecimalDigit();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c105();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$parseHexEscapeSequence();
if (s0 === peg$FAILED) {
s0 = peg$parseUnicodeEscapeSequence();
}
}
}
return s0;
}
function peg$parseCharacterEscapeSequence() {
var s0;
s0 = peg$parseSingleEscapeCharacter();
if (s0 === peg$FAILED) {
s0 = peg$parseNonEscapeCharacter();
}
return s0;
}
function peg$parseSingleEscapeCharacter() {
var s0, s1;
s0 = peg$currPos;
if (peg$c106.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c107); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c108(s1);
}
s0 = s1;
return s0;
}
function peg$parseNonEscapeCharacter() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
s2 = peg$parseEscapeCharacter();
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c23;
} else {
peg$currPos = s1;
s1 = peg$c0;
}
if (s1 === peg$FAILED) {
s1 = peg$parseLineTerminator();
}
if (s1 !== peg$FAILED) {
s2 = peg$parseSourceCharacter();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c109(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseEscapeCharacter() {
var s0;
s0 = peg$parseSingleEscapeCharacter();
if (s0 === peg$FAILED) {
s0 = peg$parseDecimalDigit();
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 120) {
s0 = peg$c110;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c111); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 117) {
s0 = peg$c112;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c113); }
}
}
}
}
return s0;
}
function peg$parseHexEscapeSequence() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 120) {
s1 = peg$c110;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c111); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseHexDigit();
if (s2 !== peg$FAILED) {
s3 = peg$parseHexDigit();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c114(s2, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseUnicodeEscapeSequence() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 117) {
s1 = peg$c112;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c113); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseHexDigit();
if (s2 !== peg$FAILED) {
s3 = peg$parseHexDigit();
if (s3 !== peg$FAILED) {
s4 = peg$parseHexDigit();
if (s4 !== peg$FAILED) {
s5 = peg$parseHexDigit();
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c115(s2, s3, s4, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseBreakToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c37) {
s1 = peg$c37;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c38); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseContinueToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 8) === peg$c39) {
s1 = peg$c39;
peg$currPos += 8;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c40); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseDeleteToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 6) === peg$c41) {
s1 = peg$c41;
peg$currPos += 6;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c42); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c116();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseDoToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c43) {
s1 = peg$c43;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c44); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseElseToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 4) === peg$c45) {
s1 = peg$c45;
peg$currPos += 4;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c46); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseFalseToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c117) {
s1 = peg$c117;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c118); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseForToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 3) === peg$c47) {
s1 = peg$c47;
peg$currPos += 3;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseFunctionToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 8) === peg$c49) {
s1 = peg$c49;
peg$currPos += 8;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c50); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseIfToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c51) {
s1 = peg$c51;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c52); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseNullToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 4) === peg$c119) {
s1 = peg$c119;
peg$currPos += 4;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c120); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseReturnToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 6) === peg$c55) {
s1 = peg$c55;
peg$currPos += 6;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c56); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseTrueToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 4) === peg$c121) {
s1 = peg$c121;
peg$currPos += 4;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c122); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseTypeofToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 6) === peg$c57) {
s1 = peg$c57;
peg$currPos += 6;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c58); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c123();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseWhileToken() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c59) {
s1 = peg$c59;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c60); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
s3 = peg$parseIdentifierPart();
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseEOS() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parse__();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 59) {
s2 = peg$c124;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c125); }
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
s2 = peg$parseLineTerminatorSequence();
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 125) {
s3 = peg$c126;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c127); }
}
peg$silentFails--;
if (s3 !== peg$FAILED) {
peg$currPos = s2;
s2 = peg$c23;
} else {
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse__();
if (s1 !== peg$FAILED) {
s2 = peg$parseEOF();
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
}
}
}
return s0;
}
function peg$parseEOSNoLineTerminator() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 59) {
s2 = peg$c124;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c125); }
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
s2 = peg$parseLineTerminatorSequence();
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 125) {
s3 = peg$c126;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c127); }
}
peg$silentFails--;
if (s3 !== peg$FAILED) {
peg$currPos = s2;
s2 = peg$c23;
} else {
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parse_();
if (s1 !== peg$FAILED) {
s2 = peg$parseEOF();
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
}
}
}
return s0;
}
function peg$parseEOF() {
var s0, s1;
s0 = peg$currPos;
peg$silentFails++;
if (input.length > peg$currPos) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c2); }
}
peg$silentFails--;
if (s1 === peg$FAILED) {
s0 = peg$c23;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parse_() {
var s0, s1;
s0 = [];
s1 = peg$parseWhiteSpace();
if (s1 === peg$FAILED) {
s1 = peg$parseMultiLineCommentNoLineTerminator();
if (s1 === peg$FAILED) {
s1 = peg$parseSingleLineComment();
}
}
while (s1 !== peg$FAILED) {
s0.push(s1);
s1 = peg$parseWhiteSpace();
if (s1 === peg$FAILED) {
s1 = peg$parseMultiLineCommentNoLineTerminator();
if (s1 === peg$FAILED) {
s1 = peg$parseSingleLineComment();
}
}
}
return s0;
}
function peg$parse__() {
var s0, s1;
s0 = [];
s1 = peg$parseWhiteSpace();
if (s1 === peg$FAILED) {
s1 = peg$parseLineTerminatorSequence();
if (s1 === peg$FAILED) {
s1 = peg$parseComment();
}
}
while (s1 !== peg$FAILED) {
s0.push(s1);
s1 = peg$parseWhiteSpace();
if (s1 === peg$FAILED) {
s1 = peg$parseLineTerminatorSequence();
if (s1 === peg$FAILED) {
s1 = peg$parseComment();
}
}
}
return s0;
}
function peg$parsePrimaryExpression() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseIdentifier();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c128(s1);
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$parseLiteral();
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 40) {
s1 = peg$c129;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c130); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
s3 = peg$parseExpression();
if (s3 !== peg$FAILED) {
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c131;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c132); }
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c133(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
}
}
return s0;
}
function peg$parseCallExpression() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseIdentifier();
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
s3 = peg$parseArguments();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c134(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseArguments() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 40) {
s1 = peg$c129;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c130); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
s3 = peg$parseArgumentList();
if (s3 === peg$FAILED) {
s3 = peg$c70;
}
if (s3 !== peg$FAILED) {
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s5 = peg$c131;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c132); }
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c135(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseArgumentList() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseAssignmentExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c136;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c137); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseAssignmentExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c136;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c137); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseAssignmentExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c138(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseLeftHandSideExpression() {
var s0, s1;
s0 = peg$currPos;
s1 = peg$parseIdentifier();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c128(s1);
}
s0 = s1;
return s0;
}
function peg$parsePostfixExpression() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseLeftHandSideExpression();
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parsePostfixOperator();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c139(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$parseCallExpression();
if (s0 === peg$FAILED) {
s0 = peg$parsePrimaryExpression();
}
}
return s0;
}
function peg$parsePostfixOperator() {
var s0;
if (input.substr(peg$currPos, 2) === peg$c140) {
s0 = peg$c140;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c141); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c142) {
s0 = peg$c142;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c143); }
}
}
return s0;
}
function peg$parseUnaryExpression() {
var s0, s1, s2, s3;
s0 = peg$parsePostfixExpression();
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseUnaryOperator();
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
s3 = peg$parseUnaryExpression();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c144(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
}
return s0;
}
function peg$parseUnaryOperator() {
var s0;
s0 = peg$parseDeleteToken();
if (s0 === peg$FAILED) {
s0 = peg$parseTypeofToken();
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c140) {
s0 = peg$c140;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c141); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c142) {
s0 = peg$c142;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c143); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 43) {
s0 = peg$c145;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c146); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 45) {
s0 = peg$c147;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c148); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 126) {
s0 = peg$c149;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c150); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 33) {
s0 = peg$c151;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c152); }
}
}
}
}
}
}
}
}
return s0;
}
function peg$parseMultiplicativeExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseUnaryExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseMultiplicativeOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseUnaryExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseMultiplicativeOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseUnaryExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseMultiplicativeOperator() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 42) {
s1 = peg$c154;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c155); }
}
if (s1 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 47) {
s1 = peg$c156;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c157); }
}
if (s1 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 37) {
s1 = peg$c158;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c159); }
}
}
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c160;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c161); }
}
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c162(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseAdditiveExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseMultiplicativeExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseAdditiveOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseMultiplicativeExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseAdditiveOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseMultiplicativeExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseAdditiveOperator() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 43) {
s1 = peg$c145;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c146); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 43) {
s3 = peg$c145;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c146); }
}
if (s3 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c160;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c161); }
}
}
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c163();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 45) {
s1 = peg$c147;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c148); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 45) {
s3 = peg$c147;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c148); }
}
if (s3 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c160;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c161); }
}
}
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c164();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
}
return s0;
}
function peg$parseShiftExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseAdditiveExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseShiftOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseAdditiveExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseShiftOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseAdditiveExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseShiftOperator() {
var s0;
if (input.substr(peg$currPos, 2) === peg$c165) {
s0 = peg$c165;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c166); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c167) {
s0 = peg$c167;
peg$currPos += 3;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c168); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c169) {
s0 = peg$c169;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c170); }
}
}
}
return s0;
}
function peg$parseRelationalExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseShiftExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseRelationalOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseShiftExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseRelationalOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseShiftExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseRelationalOperator() {
var s0;
if (input.substr(peg$currPos, 2) === peg$c171) {
s0 = peg$c171;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c172); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c173) {
s0 = peg$c173;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c174); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 60) {
s0 = peg$c175;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c176); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 62) {
s0 = peg$c177;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c178); }
}
}
}
}
return s0;
}
function peg$parseEqualityExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseRelationalExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseEqualityOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseRelationalExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseEqualityOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseRelationalExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseEqualityOperator() {
var s0;
if (input.substr(peg$currPos, 2) === peg$c179) {
s0 = peg$c179;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c180); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c181) {
s0 = peg$c181;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c182); }
}
}
return s0;
}
function peg$parseBitwiseANDExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseEqualityExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseBitwiseANDOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseEqualityExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseBitwiseANDOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseEqualityExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseBitwiseANDOperator() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 38) {
s1 = peg$c183;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c184); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 38) {
s3 = peg$c183;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c184); }
}
if (s3 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c160;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c161); }
}
}
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c185();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseBitwiseXORExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseBitwiseANDExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseBitwiseXOROperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseBitwiseANDExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseBitwiseXOROperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseBitwiseANDExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseBitwiseXOROperator() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 94) {
s1 = peg$c186;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c187); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 94) {
s3 = peg$c186;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c187); }
}
if (s3 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c160;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c161); }
}
}
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c188();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseBitwiseORExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseBitwiseXORExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseBitwiseOROperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseBitwiseXORExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseBitwiseOROperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseBitwiseXORExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseBitwiseOROperator() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 124) {
s1 = peg$c189;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c190); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 124) {
s3 = peg$c189;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c190); }
}
if (s3 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c160;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c161); }
}
}
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c191();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseLogicalANDExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseBitwiseORExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseLogicalANDOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseBitwiseORExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseLogicalANDOperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseBitwiseORExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseLogicalANDOperator() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c192) {
s1 = peg$c192;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c193); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c160;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c161); }
}
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c194();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseLogicalORExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseLogicalANDExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseLogicalOROperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseLogicalANDExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseLogicalOROperator();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseLogicalANDExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseLogicalOROperator() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c195) {
s1 = peg$c195;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c196); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c160;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c161); }
}
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c197();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseConditionalExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;
s0 = peg$currPos;
s1 = peg$parseLogicalORExpression();
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 63) {
s3 = peg$c198;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c199); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseAssignmentExpression();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s7 = peg$c200;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c201); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parse__();
if (s8 !== peg$FAILED) {
s9 = peg$parseAssignmentExpression();
if (s9 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c202(s1, s5, s9);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$parseLogicalORExpression();
}
return s0;
}
function peg$parseAssignmentExpression() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseLeftHandSideExpression();
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
s3 = peg$parseAssignmentOperator();
if (s3 !== peg$FAILED) {
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseAssignmentExpression();
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c203(s1, s3, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$parseConditionalExpression();
}
return s0;
}
function peg$parseAssignmentOperator() {
var s0;
if (input.substr(peg$currPos, 2) === peg$c204) {
s0 = peg$c204;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c205); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c206) {
s0 = peg$c206;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c207); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c208) {
s0 = peg$c208;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c209); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c210) {
s0 = peg$c210;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c211); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c212) {
s0 = peg$c212;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c213); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c214) {
s0 = peg$c214;
peg$currPos += 3;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c215); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c216) {
s0 = peg$c216;
peg$currPos += 3;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c217); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 4) === peg$c218) {
s0 = peg$c218;
peg$currPos += 4;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c219); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c220) {
s0 = peg$c220;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c221); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c222) {
s0 = peg$c222;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c223); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c224) {
s0 = peg$c224;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c225); }
}
}
}
}
}
}
}
}
}
}
}
return s0;
}
function peg$parseExpression() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseAssignmentExpression();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c136;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c137); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseAssignmentExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c136;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c137); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseAssignmentExpression();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c153(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseStatement() {
var s0;
s0 = peg$parseBlock();
if (s0 === peg$FAILED) {
s0 = peg$parseVariableStatement();
if (s0 === peg$FAILED) {
s0 = peg$parseEmptyStatement();
if (s0 === peg$FAILED) {
s0 = peg$parseExpressionStatement();
if (s0 === peg$FAILED) {
s0 = peg$parseIfStatement();
if (s0 === peg$FAILED) {
s0 = peg$parseIterationStatement();
if (s0 === peg$FAILED) {
s0 = peg$parseContinueStatement();
if (s0 === peg$FAILED) {
s0 = peg$parseBreakStatement();
if (s0 === peg$FAILED) {
s0 = peg$parseReturnStatement();
}
}
}
}
}
}
}
}
return s0;
}
function peg$parseBlock() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 123) {
s1 = peg$c226;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c227); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
s4 = peg$parseStatementList();
if (s4 !== peg$FAILED) {
s5 = peg$parse__();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
if (s3 === peg$FAILED) {
s3 = peg$c70;
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 125) {
s4 = peg$c126;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c127); }
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c228(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseStatementList() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseStatement();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseStatement();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseStatement();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c229(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseVariableStatement() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$parseVariableDeclarationList();
if (s1 !== peg$FAILED) {
s2 = peg$parseEOS();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c230(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseVariableDeclarationList() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseVariableDeclaration();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c136;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c137); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseVariableDeclaration();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c136;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c137); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseVariableDeclaration();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c231(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseVariableDeclaration() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseIdentifier();
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
s3 = peg$parseInitialiser();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c232(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseInitialiser() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 61) {
s1 = peg$c160;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c161); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c160;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c161); }
}
peg$silentFails--;
if (s3 === peg$FAILED) {
s2 = peg$c23;
} else {
peg$currPos = s2;
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
s3 = peg$parse__();
if (s3 !== peg$FAILED) {
s4 = peg$parseVariableDeclaration();
if (s4 === peg$FAILED) {
s4 = peg$parseAssignmentExpression();
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c133(s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseEmptyStatement() {
var s0, s1;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 59) {
s1 = peg$c124;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c125); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c233();
}
s0 = s1;
return s0;
}
function peg$parseExpressionStatement() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 123) {
s2 = peg$c226;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c227); }
}
if (s2 === peg$FAILED) {
s2 = peg$parseFunctionToken();
}
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c23;
} else {
peg$currPos = s1;
s1 = peg$c0;
}
if (s1 !== peg$FAILED) {
s2 = peg$parseExpression();
if (s2 !== peg$FAILED) {
s3 = peg$parseEOS();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c133(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseIfStatement() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14;
s0 = peg$currPos;
s1 = peg$parseIfToken();
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 40) {
s3 = peg$c129;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c130); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseExpression();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s7 = peg$c131;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c132); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parse__();
if (s8 !== peg$FAILED) {
s9 = peg$parseStatement();
if (s9 !== peg$FAILED) {
s10 = peg$currPos;
s11 = peg$parse__();
if (s11 !== peg$FAILED) {
s12 = peg$parseElseToken();
if (s12 !== peg$FAILED) {
s13 = peg$parse__();
if (s13 !== peg$FAILED) {
s14 = peg$parseStatement();
if (s14 !== peg$FAILED) {
s11 = [s11, s12, s13, s14];
s10 = s11;
} else {
peg$currPos = s10;
s10 = peg$c0;
}
} else {
peg$currPos = s10;
s10 = peg$c0;
}
} else {
peg$currPos = s10;
s10 = peg$c0;
}
} else {
peg$currPos = s10;
s10 = peg$c0;
}
if (s10 === peg$FAILED) {
s10 = peg$c70;
}
if (s10 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c234(s5, s9, s10);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseIterationStatement() {
var s0;
s0 = peg$parseDoWhileStatement();
if (s0 === peg$FAILED) {
s0 = peg$parseWhileStatement();
if (s0 === peg$FAILED) {
s0 = peg$parseForStatement();
}
}
return s0;
}
function peg$parseDoWhileStatement() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12;
s0 = peg$currPos;
s1 = peg$parseDoToken();
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
s3 = peg$parseStatement();
if (s3 !== peg$FAILED) {
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseWhileToken();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 40) {
s7 = peg$c129;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c130); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parse__();
if (s8 !== peg$FAILED) {
s9 = peg$parseExpression();
if (s9 !== peg$FAILED) {
s10 = peg$parse__();
if (s10 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s11 = peg$c131;
peg$currPos++;
} else {
s11 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c132); }
}
if (s11 !== peg$FAILED) {
s12 = peg$parseEOS();
if (s12 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c235(s3, s9);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseWhileStatement() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;
s0 = peg$currPos;
s1 = peg$parseWhileToken();
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 40) {
s3 = peg$c129;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c130); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseExpression();
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s7 = peg$c131;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c132); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parse__();
if (s8 !== peg$FAILED) {
s9 = peg$parseStatement();
if (s9 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c236(s5, s9);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseForStatement() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17;
s0 = peg$currPos;
s1 = peg$parseForToken();
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 40) {
s3 = peg$c129;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c130); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$currPos;
s6 = peg$parseVariableDeclarationList();
if (s6 !== peg$FAILED) {
peg$reportedPos = s5;
s6 = peg$c237(s6);
}
s5 = s6;
if (s5 === peg$FAILED) {
s5 = peg$parseExpression();
if (s5 === peg$FAILED) {
s5 = peg$c70;
}
}
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 59) {
s7 = peg$c124;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c125); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parse__();
if (s8 !== peg$FAILED) {
s9 = peg$parseExpression();
if (s9 === peg$FAILED) {
s9 = peg$c70;
}
if (s9 !== peg$FAILED) {
s10 = peg$parse__();
if (s10 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 59) {
s11 = peg$c124;
peg$currPos++;
} else {
s11 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c125); }
}
if (s11 !== peg$FAILED) {
s12 = peg$parse__();
if (s12 !== peg$FAILED) {
s13 = peg$parseExpression();
if (s13 === peg$FAILED) {
s13 = peg$c70;
}
if (s13 !== peg$FAILED) {
s14 = peg$parse__();
if (s14 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s15 = peg$c131;
peg$currPos++;
} else {
s15 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c132); }
}
if (s15 !== peg$FAILED) {
s16 = peg$parse__();
if (s16 !== peg$FAILED) {
s17 = peg$parseStatement();
if (s17 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c238(s5, s9, s13, s17);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseContinueStatement() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseContinueToken();
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseEOSNoLineTerminator();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c239();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseBreakStatement() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseBreakToken();
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$parseEOSNoLineTerminator();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c240();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseReturnStatement() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseReturnToken();
if (s1 !== peg$FAILED) {
s2 = peg$parse_();
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
s4 = peg$parseExpression();
if (s4 !== peg$FAILED) {
s5 = peg$parseEOS();
if (s5 !== peg$FAILED) {
peg$reportedPos = s3;
s4 = peg$c133(s4);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
if (s3 === peg$FAILED) {
s3 = peg$currPos;
s4 = peg$parseEOSNoLineTerminator();
if (s4 !== peg$FAILED) {
peg$reportedPos = s3;
s4 = peg$c241();
}
s3 = s4;
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c242(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseFunctionDeclaration() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15;
s0 = peg$currPos;
s1 = peg$parseFunctionToken();
if (s1 !== peg$FAILED) {
s2 = peg$parse__();
if (s2 !== peg$FAILED) {
s3 = peg$parseIdentifier();
if (s3 !== peg$FAILED) {
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 40) {
s5 = peg$c129;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c130); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseFormalParameterList();
if (s7 === peg$FAILED) {
s7 = peg$c70;
}
if (s7 !== peg$FAILED) {
s8 = peg$parse__();
if (s8 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s9 = peg$c131;
peg$currPos++;
} else {
s9 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c132); }
}
if (s9 !== peg$FAILED) {
s10 = peg$parse__();
if (s10 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 123) {
s11 = peg$c226;
peg$currPos++;
} else {
s11 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c227); }
}
if (s11 !== peg$FAILED) {
s12 = peg$parse__();
if (s12 !== peg$FAILED) {
s13 = peg$parseFunctionBody();
if (s13 !== peg$FAILED) {
s14 = peg$parse__();
if (s14 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 125) {
s15 = peg$c126;
peg$currPos++;
} else {
s15 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c127); }
}
if (s15 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c243(s3, s7, s13);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseFormalParameterList() {
var s0, s1, s2, s3, s4, s5, s6, s7;
s0 = peg$currPos;
s1 = peg$parseIdentifier();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c136;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c137); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseIdentifier();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c136;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c137); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parse__();
if (s6 !== peg$FAILED) {
s7 = peg$parseIdentifier();
if (s7 !== peg$FAILED) {
s4 = [s4, s5, s6, s7];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c231(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseFunctionBody() {
var s0, s1;
s0 = peg$currPos;
s1 = peg$parseFunctionElements();
if (s1 === peg$FAILED) {
s1 = peg$c70;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c244(s1);
}
s0 = s1;
return s0;
}
function peg$parseProgram() {
var s0, s1;
s0 = peg$currPos;
s1 = peg$parseSourceElements();
if (s1 === peg$FAILED) {
s1 = peg$c70;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c245(s1);
}
s0 = s1;
return s0;
}
function peg$parseSourceElements() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseSourceElement();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseSourceElement();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseSourceElement();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c229(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseFunctionElements() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseStatement();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseStatement();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parse__();
if (s4 !== peg$FAILED) {
s5 = peg$parseStatement();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c0;
}
} else {
peg$currPos = s3;
s3 = peg$c0;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c229(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseSourceElement() {
var s0;
s0 = peg$parseStatement();
if (s0 === peg$FAILED) {
s0 = peg$parseFunctionDeclaration();
}
return s0;
}
node = require('./node');
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);
}
}
return {
SyntaxError: SyntaxError,
parse: parse
};
})();
},{"./node":7}],10:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var ConstTable, FuncEntry, FuncTable, GlobalVars, LocalVars, SYM_FUNC, SYM_GLOBAL, SYM_LOCAL, SYM_NONE, SymTabEntry, SymTabSet, SymTable, _dictCount,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
SYM_NONE = 0;
SYM_LOCAL = 1;
SYM_GLOBAL = 2;
SYM_FUNC = 3;
this.SYM_NONE = SYM_NONE;
this.SYM_LOCAL = SYM_LOCAL;
this.SYM_GLOBAL = SYM_GLOBAL;
this.SYM_FUNC = SYM_FUNC;
_dictCount = function(obj) {
return Object.keys(obj).length;
};
ConstTable = (function() {
function ConstTable() {
this._set = new (require('./utils').Hashtable);
}
ConstTable.prototype.contains = function(obj) {
return this._set.containsKey(obj);
};
ConstTable.prototype.put = function(obj) {
if (!this._set.containsKey(obj)) {
this._set.put(obj, this._set.size());
}
return this._set.get(obj);
};
ConstTable.prototype.count = function() {
return this._set.size();
};
ConstTable.prototype.get = function(obj) {
return this._set.get(obj);
};
ConstTable.prototype.forEach = function(cb, ctx) {
if (ctx == null) {
ctx = this;
}
return this._set.each(function(k, nr) {
return cb.call(ctx, k, nr);
});
};
return ConstTable;
})();
SymTabEntry = (function() {
function SymTabEntry(flag, number) {
this.flag = flag;
this.number = number;
}
return SymTabEntry;
})();
FuncEntry = (function() {
function FuncEntry(flag, argc, number) {
this.flag = flag;
this.argc = argc;
this.number = number;
}
return FuncEntry;
})();
SymTable = (function() {
function SymTable() {
this._dict = {};
}
SymTable.prototype._add = function(name, flag) {
var ste;
ste = new SymTabEntry(flag, this.count());
return this._dict[name] = ste;
};
SymTable.prototype.count = function() {
return _dictCount(this._dict);
};
SymTable.prototype.contains = function(name) {
return name in this._dict;
};
SymTable.prototype.get = function(name) {
return this._dict[name];
};
SymTable.prototype.forEach = function(cb, ctx) {
var k, ste, _ref, _results;
if (ctx == null) {
ctx = this;
}
_ref = this._dict;
_results = [];
for (k in _ref) {
if (!__hasProp.call(_ref, k)) continue;
ste = _ref[k];
_results.push(cb.call(ctx, k, ste));
}
return _results;
};
return SymTable;
})();
GlobalVars = (function(_super) {
__extends(GlobalVars, _super);
function GlobalVars() {
return GlobalVars.__super__.constructor.apply(this, arguments);
}
GlobalVars.prototype.add = function(name) {
return this._add(name, SYM_GLOBAL);
};
return GlobalVars;
})(SymTable);
LocalVars = (function(_super) {
__extends(LocalVars, _super);
function LocalVars() {
return LocalVars.__super__.constructor.apply(this, arguments);
}
LocalVars.prototype.add = function(name) {
return this._add(name, SYM_LOCAL);
};
return LocalVars;
})(SymTable);
FuncTable = (function(_super) {
__extends(FuncTable, _super);
function FuncTable() {
return FuncTable.__super__.constructor.apply(this, arguments);
}
FuncTable.prototype.add = function(name, argc) {
var fe;
fe = new FuncEntry(SYM_FUNC, argc, this.count());
return this._dict[name] = fe;
};
return FuncTable;
})(SymTable);
SymTabSet = (function() {
function SymTabSet() {
this.globals = new GlobalVars();
this.locals = {};
this.consts = new ConstTable();
this.funcs = new FuncTable();
this.currentTab = this.globals;
}
SymTabSet.prototype.isGlobal = function(name) {
return this.globals.contains(name);
};
SymTabSet.prototype.isFunc = function(name) {
return this.funcs.contains(name);
};
SymTabSet.prototype.enter = function(table) {
return this.currentTab = table;
};
SymTabSet.prototype.enterGlobal = function() {
return this.currentTab = this.globals;
};
SymTabSet.prototype.addLocal = function(name) {
var localTab;
localTab = new LocalVars;
this.locals[name] = localTab;
return this.enter(localTab);
};
return SymTabSet;
})();
this.ConstTable = ConstTable;
this.GlobalVars = GlobalVars;
this.LocalVars = LocalVars;
this.FuncTable = FuncTable;
this.SymTabSet = SymTabSet;
this.SymTabEntry = SymTabEntry;
}).call(this);
},{"./utils":12}],11:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var BaseASTVisitor, ast,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
ast = require('./node');
BaseASTVisitor = (function() {
function BaseASTVisitor() {}
BaseASTVisitor.prototype.visitNumericLiteral = function(node) {};
BaseASTVisitor.prototype.visitStringLiteral = function(node) {};
BaseASTVisitor.prototype.visitNullLiteral = function(node) {};
BaseASTVisitor.prototype.visitBooleanLiteral = function(node) {};
BaseASTVisitor.prototype.visitVariable = function(node) {};
BaseASTVisitor.prototype.visitFunctionCall = function(node) {};
BaseASTVisitor.prototype.visitPostfixExpression = function(node) {};
BaseASTVisitor.prototype.visitUnaryExpression = function(node) {};
BaseASTVisitor.prototype.visitBinaryExpression = function(node) {};
BaseASTVisitor.prototype.visitConditionalExpression = function(node) {};
BaseASTVisitor.prototype.visitAssignmentExpression = function(node) {};
BaseASTVisitor.prototype.visitBlock = function(node) {};
BaseASTVisitor.prototype.visitVariableStatement = function(node) {};
BaseASTVisitor.prototype.visitVariableDeclaration = function(node) {};
BaseASTVisitor.prototype.visitEmptyStatement = function(node) {};
BaseASTVisitor.prototype.visitIfStatement = function(node) {};
BaseASTVisitor.prototype.visitDoWhileStatement = function(node) {};
BaseASTVisitor.prototype.visitWhileStatement = function(node) {};
BaseASTVisitor.prototype.visitForStatement = function(node) {};
BaseASTVisitor.prototype.visitContinueStatement = function(node) {};
BaseASTVisitor.prototype.visitBreakStatement = function(node) {};
BaseASTVisitor.prototype.visitReturnStatement = function(node) {};
BaseASTVisitor.prototype.visitFunction_ = function(node) {};
BaseASTVisitor.prototype.visitProgram = function(node) {};
BaseASTVisitor.prototype.visitParameters = function(array) {};
BaseASTVisitor.prototype.enter = function(nodeName, node) {
var _name;
return typeof this[_name = 'enter' + nodeName] === "function" ? this[_name](node) : void 0;
};
return BaseASTVisitor;
})();
this.FirstPassVisitor = (function(_super) {
__extends(FirstPassVisitor, _super);
function FirstPassVisitor(tabSet) {
this.tabSet = tabSet;
}
FirstPassVisitor.prototype.enterFunction_ = function(node) {
this.tabSet.addLocal(node.name);
this.tabSet.funcs.add(node.name, node.params.length);
return node.symInfo = this.tabSet.funcs.get(node.name);
};
FirstPassVisitor.prototype.visitNumericLiteral = function(node) {
return node.constNum = this.tabSet.consts.put(node.value);
};
FirstPassVisitor.prototype.visitStringLiteral = function(node) {
return node.constNum = this.tabSet.consts.put(node.value);
};
FirstPassVisitor.prototype.visitNullLiteral = function(node) {
return node.constNum = this.tabSet.consts.put(node.value);
};
FirstPassVisitor.prototype.visitBooleanLiteral = function(node) {
return node.constNum = this.tabSet.consts.put(node.value);
};
FirstPassVisitor.prototype.visitVariable = function(node) {
if (!this.tabSet.currentTab.contains(node.name)) {
if (!this.tabSet.isGlobal(node.name)) {
throw new Error("undefined variable '" + node.name + "'");
} else {
return node.symInfo = this.tabSet.globals.get(node.name);
}
} else {
return node.symInfo = this.tabSet.currentTab.get(node.name);
}
};
FirstPassVisitor.prototype.visitFunctionCall = function(node) {
if (!this.tabSet.funcs.contains(node.name)) {
throw new Error("undefined function '" + node.name + "'");
}
return node.symInfo = this.tabSet.funcs.get(node.name);
};
FirstPassVisitor.prototype.visitVariableDeclaration = function(node) {
if (!this.tabSet.currentTab.contains(node.name)) {
if (!this.tabSet.isGlobal(node.name)) {
this.tabSet.currentTab.add(node.name);
node.symInfo = this.tabSet.currentTab.get(node.name);
}
node.symInfo = this.tabSet.globals.get(node.name);
}
return node.symInfo = this.tabSet.currentTab.get(node.name);
};
FirstPassVisitor.prototype.visitFunction_ = function(node) {
return this.tabSet.enterGlobal();
};
FirstPassVisitor.prototype.visitParameters = function(array) {
var param, _i, _len, _results;
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
param = array[_i];
_results.push(this.tabSet.currentTab.add(param));
}
return _results;
};
return FirstPassVisitor;
})(BaseASTVisitor);
this.SecondPassVisitor = (function(_super) {
__extends(SecondPassVisitor, _super);
function SecondPassVisitor(gen) {
this.gen = gen;
}
SecondPassVisitor.prototype.visitVariable = function(node) {
return node.genCode = this.gen.genVariable;
};
SecondPassVisitor.prototype.visitNumericLiteral = function(node) {
return node.genCode = this.gen.genLiteral;
};
SecondPassVisitor.prototype.visitStringLiteral = function(node) {
return node.genCode = this.gen.genLiteral;
};
SecondPassVisitor.prototype.visitNullLiteral = function(node) {
return node.genCode = this.gen.genLiteral;
};
SecondPassVisitor.prototype.visitBooleanLiteral = function(node) {
return node.genCode = this.gen.genLiteral;
};
SecondPassVisitor.prototype.visitFunctionCall = function(node) {
return node.genCode = this.gen.genFunctionCall;
};
SecondPassVisitor.prototype.visitPostfixExpression = function(node) {
return node.genCode = this.gen.genPostfixExpression;
};
SecondPassVisitor.prototype.visitUnaryExpression = function(node) {
return node.genCode = this.gen.genUnaryExpression;
};
SecondPassVisitor.prototype.visitBinaryExpression = function(node) {
return node.genCode = this.gen.genBinaryExpression;
};
SecondPassVisitor.prototype.visitConditionalExpression = function(node) {
return node.genCode = this.gen.genConditionalExpression;
};
SecondPassVisitor.prototype.visitAssignmentExpression = function(node) {
return node.genCode = this.gen.genAssignmentExpression;
};
SecondPassVisitor.prototype.visitBlock = function(node) {
return node.genCode = this.gen.genBlock;
};
SecondPassVisitor.prototype.visitVariableStatement = function(node) {
return node.genCode = this.gen.genVariableStatement;
};
SecondPassVisitor.prototype.visitVariableDeclaration = function(node) {
return node.genCode = this.gen.genVariableDeclaration;
};
SecondPassVisitor.prototype.visitEmptyStatement = function(node) {
return node.genCode = this.gen.genEmptyStatement;
};
SecondPassVisitor.prototype.visitIfStatement = function(node) {
return node.genCode = this.gen.genIfStatement;
};
SecondPassVisitor.prototype.visitDoWhileStatement = function(node) {
return node.genCode = this.gen.genDoWhileStatement;
};
SecondPassVisitor.prototype.visitWhileStatement = function(node) {
return node.genCode = this.gen.genWhileStatement;
};
SecondPassVisitor.prototype.visitForStatement = function(node) {
return node.genCode = this.gen.genForStatement;
};
SecondPassVisitor.prototype.visitContinueStatement = function(node) {
return node.genCode = this.gen.genContinueStatement;
};
SecondPassVisitor.prototype.visitBreakStatement = function(node) {
return node.genCode = this.gen.genBreakStatement;
};
SecondPassVisitor.prototype.visitReturnStatement = function(node) {
return node.genCode = this.gen.genReturnStatement;
};
SecondPassVisitor.prototype.visitFunction_ = function(node) {
return node.genCode = this.gen.genFunction;
};
SecondPassVisitor.prototype.visitProgram = function(node) {
return node.genCode = this.gen.genProgram;
};
return SecondPassVisitor;
})(BaseASTVisitor);
}).call(this);
},{"./node":7}],12:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var HashSet, Hashtable, mixinKeywords, printf, sprintf, vprintf, vsprintf,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
__slice = [].slice;
mixinKeywords = ['extended', 'included'];
this.Mixins = (function() {
function Mixins() {}
Mixins["extends"] = function(obj) {
var key, value, _ref;
for (key in obj) {
value = obj[key];
if (__indexOf.call(mixinKeywords, key) < 0) {
this[key] = value;
}
}
if ((_ref = obj.extended) != null) {
_ref.apply(this);
}
return this;
};
Mixins.include = function(obj) {
var key, value, _ref;
for (key in obj) {
value = obj[key];
if (__indexOf.call(mixinKeywords, key) < 0) {
this.prototype[key] = value;
}
}
if ((_ref = obj.included) != null) {
_ref.apply(this);
}
return this;
};
return Mixins;
})();
sprintf = (function() {
function get_type(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}
function str_repeat(input, multiplier) {
for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
return output.join('');
}
var str_format = function() {
if (!str_format.cache.hasOwnProperty(arguments[0])) {
str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
}
return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
};
str_format.format = function(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
for (i = 0; i < tree_length; i++) {
node_type = get_type(parse_tree[i]);
if (node_type === 'string') {
output.push(parse_tree[i]);
}
else if (node_type === 'array') {
match = parse_tree[i]; // convenience purposes only
if (match[2]) { // keyword argument
arg = argv[cursor];
for (k = 0; k < match[2].length; k++) {
if (!arg.hasOwnProperty(match[2][k])) {
throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
}
arg = arg[match[2][k]];
}
}
else if (match[1]) { // positional argument (explicit)
arg = argv[match[1]];
}
else { // positional argument (implicit)
arg = argv[cursor++];
}
if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
}
switch (match[8]) {
case 'b': arg = arg.toString(2); break;
case 'c': arg = String.fromCharCode(arg); break;
case 'd': arg = parseInt(arg, 10); break;
case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
case 'o': arg = arg.toString(8); break;
case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
case 'u': arg = Math.abs(arg); break;
case 'x': arg = arg.toString(16); break;
case 'X': arg = arg.toString(16).toUpperCase(); break;
}
arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
pad_length = match[6] - String(arg).length;
pad = match[6] ? str_repeat(pad_character, pad_length) : '';
output.push(match[5] ? arg + pad : pad + arg);
}
}
return output.join('');
};
str_format.cache = {};
str_format.parse = function(fmt) {
var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
while (_fmt) {
if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
}
else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
parse_tree.push('%');
}
else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
var field_list = [], replacement_field = match[2], field_match = [];
if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else {
throw('[sprintf] huh?');
}
}
}
else {
throw('[sprintf] huh?');
}
match[2] = field_list;
}
else {
arg_names |= 2;
}
if (arg_names === 3) {
throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
}
parse_tree.push(match);
}
else {
throw('[sprintf] huh?');
}
_fmt = _fmt.substring(match[0].length);
}
return parse_tree;
};
return str_format;
})();;
vsprintf = function(fmt, argv) {
argv.unshift(fmt);
return sprintf.apply(null, argv);
};
printf = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return console.log(this.sprintf.apply(null, args));
};
vprintf = function(fmt, argv) {
return console.log(this.vsprintf.call(null, fmt, argv));
};
this.sprintf = sprintf;
this.vsprintf = vsprintf;
this.printf = printf;
this.vprintf = vprintf;
Hashtable = (function() {
var FUNCTION = "function";
var arrayRemoveAt = (typeof Array.prototype.splice == FUNCTION) ?
function(arr, idx) {
arr.splice(idx, 1);
} :
function(arr, idx) {
var itemsAfterDeleted, i, len;
if (idx === arr.length - 1) {
arr.length = idx;
} else {
itemsAfterDeleted = arr.slice(idx + 1);
arr.length = idx;
for (i = 0, len = itemsAfterDeleted.length; i < len; ++i) {
arr[idx + i] = itemsAfterDeleted[i];
}
}
};
function hashObject(obj) {
var hashCode;
if (typeof obj == "string") {
return obj;
} else if (typeof obj.hashCode == FUNCTION) {
// Check the hashCode method really has returned a string
hashCode = obj.hashCode();
return (typeof hashCode == "string") ? hashCode : hashObject(hashCode);
} else if (typeof obj.toString == FUNCTION) {
return obj.toString();
} else {
try {
return String(obj);
} catch (ex) {
// For host objects (such as ActiveObjects in IE) that have no toString() method and throw an error when
// passed to String()
return Object.prototype.toString.call(obj);
}
}
}
function equals_fixedValueHasEquals(fixedValue, variableValue) {
return fixedValue.equals(variableValue);
}
function equals_fixedValueNoEquals(fixedValue, variableValue) {
return (typeof variableValue.equals == FUNCTION) ?
variableValue.equals(fixedValue) : (fixedValue === variableValue);
}
function createKeyValCheck(kvStr) {
return function(kv) {
if (kv === null) {
throw new Error("null is not a valid " + kvStr);
} else if (typeof kv == "undefined") {
throw new Error(kvStr + " must not be undefined");
}
};
}
var checkKey = createKeyValCheck("key"), checkValue = createKeyValCheck("value");
/*----------------------------------------------------------------------------------------------------------------*/
function Bucket(hash, firstKey, firstValue, equalityFunction) {
this[0] = hash;
this.entries = [];
this.addEntry(firstKey, firstValue);
if (equalityFunction !== null) {
this.getEqualityFunction = function() {
return equalityFunction;
};
}
}
var EXISTENCE = 0, ENTRY = 1, ENTRY_INDEX_AND_VALUE = 2;
function createBucketSearcher(mode) {
return function(key) {
var i = this.entries.length, entry, equals = this.getEqualityFunction(key);
while (i--) {
entry = this.entries[i];
if ( equals(key, entry[0]) ) {
switch (mode) {
case EXISTENCE:
return true;
case ENTRY:
return entry;
case ENTRY_INDEX_AND_VALUE:
return [ i, entry[1] ];
}
}
}
return false;
};
}
function createBucketLister(entryProperty) {
return function(aggregatedArr) {
var startIndex = aggregatedArr.length;
for (var i = 0, len = this.entries.length; i < len; ++i) {
aggregatedArr[startIndex + i] = this.entries[i][entryProperty];
}
};
}
Bucket.prototype = {
getEqualityFunction: function(searchValue) {
return (typeof searchValue.equals == FUNCTION) ? equals_fixedValueHasEquals : equals_fixedValueNoEquals;
},
getEntryForKey: createBucketSearcher(ENTRY),
getEntryAndIndexForKey: createBucketSearcher(ENTRY_INDEX_AND_VALUE),
removeEntryForKey: function(key) {
var result = this.getEntryAndIndexForKey(key);
if (result) {
arrayRemoveAt(this.entries, result[0]);
return result[1];
}
return null;
},
addEntry: function(key, value) {
this.entries[this.entries.length] = [key, value];
},
keys: createBucketLister(0),
values: createBucketLister(1),
getEntries: function(entries) {
var startIndex = entries.length;
for (var i = 0, len = this.entries.length; i < len; ++i) {
// Clone the entry stored in the bucket before adding to array
entries[startIndex + i] = this.entries[i].slice(0);
}
},
containsKey: createBucketSearcher(EXISTENCE),
containsValue: function(value) {
var i = this.entries.length;
while (i--) {
if ( value === this.entries[i][1] ) {
return true;
}
}
return false;
}
};
/*----------------------------------------------------------------------------------------------------------------*/
// Supporting functions for searching hashtable buckets
function searchBuckets(buckets, hash) {
var i = buckets.length, bucket;
while (i--) {
bucket = buckets[i];
if (hash === bucket[0]) {
return i;
}
}
return null;
}
function getBucketForHash(bucketsByHash, hash) {
var bucket = bucketsByHash[hash];
// Check that this is a genuine bucket and not something inherited from the bucketsByHash's prototype
return ( bucket && (bucket instanceof Bucket) ) ? bucket : null;
}
/*----------------------------------------------------------------------------------------------------------------*/
function Hashtable(hashingFunctionParam, equalityFunctionParam) {
var that = this;
var buckets = [];
var bucketsByHash = {};
var hashingFunction = (typeof hashingFunctionParam == FUNCTION) ? hashingFunctionParam : hashObject;
var equalityFunction = (typeof equalityFunctionParam == FUNCTION) ? equalityFunctionParam : null;
this.put = function(key, value) {
checkKey(key);
checkValue(value);
var hash = hashingFunction(key), bucket, bucketEntry, oldValue = null;
// Check if a bucket exists for the bucket key
bucket = getBucketForHash(bucketsByHash, hash);
if (bucket) {
// Check this bucket to see if it already contains this key
bucketEntry = bucket.getEntryForKey(key);
if (bucketEntry) {
// This bucket entry is the current mapping of key to value, so replace old value and we're done.
oldValue = bucketEntry[1];
bucketEntry[1] = value;
} else {
// The bucket does not contain an entry for this key, so add one
bucket.addEntry(key, value);
}
} else {
// No bucket exists for the key, so create one and put our key/value mapping in
bucket = new Bucket(hash, key, value, equalityFunction);
buckets[buckets.length] = bucket;
bucketsByHash[hash] = bucket;
}
return oldValue;
};
this.get = function(key) {
checkKey(key);
var hash = hashingFunction(key);
// Check if a bucket exists for the bucket key
var bucket = getBucketForHash(bucketsByHash, hash);
if (bucket) {
// Check this bucket to see if it contains this key
var bucketEntry = bucket.getEntryForKey(key);
if (bucketEntry) {
// This bucket entry is the current mapping of key to value, so return the value.
return bucketEntry[1];
}
}
return null;
};
this.containsKey = function(key) {
checkKey(key);
var bucketKey = hashingFunction(key);
// Check if a bucket exists for the bucket key
var bucket = getBucketForHash(bucketsByHash, bucketKey);
return bucket ? bucket.containsKey(key) : false;
};
this.containsValue = function(value) {
checkValue(value);
var i = buckets.length;
while (i--) {
if (buckets[i].containsValue(value)) {
return true;
}
}
return false;
};
this.clear = function() {
buckets.length = 0;
bucketsByHash = {};
};
this.isEmpty = function() {
return !buckets.length;
};
var createBucketAggregator = function(bucketFuncName) {
return function() {
var aggregated = [], i = buckets.length;
while (i--) {
buckets[i][bucketFuncName](aggregated);
}
return aggregated;
};
};
this.keys = createBucketAggregator("keys");
this.values = createBucketAggregator("values");
this.entries = createBucketAggregator("getEntries");
this.remove = function(key) {
checkKey(key);
var hash = hashingFunction(key), bucketIndex, oldValue = null;
// Check if a bucket exists for the bucket key
var bucket = getBucketForHash(bucketsByHash, hash);
if (bucket) {
// Remove entry from this bucket for this key
oldValue = bucket.removeEntryForKey(key);
if (oldValue !== null) {
// Entry was removed, so check if bucket is empty
if (!bucket.entries.length) {
// Bucket is empty, so remove it from the bucket collections
bucketIndex = searchBuckets(buckets, hash);
arrayRemoveAt(buckets, bucketIndex);
delete bucketsByHash[hash];
}
}
}
return oldValue;
};
this.size = function() {
var total = 0, i = buckets.length;
while (i--) {
total += buckets[i].entries.length;
}
return total;
};
this.each = function(callback) {
var entries = that.entries(), i = entries.length, entry;
while (i--) {
entry = entries[i];
callback(entry[0], entry[1]);
}
};
this.putAll = function(hashtable, conflictCallback) {
var entries = hashtable.entries();
var entry, key, value, thisValue, i = entries.length;
var hasConflictCallback = (typeof conflictCallback == FUNCTION);
while (i--) {
entry = entries[i];
key = entry[0];
value = entry[1];
// Check for a conflict. The default behaviour is to overwrite the value for an existing key
if ( hasConflictCallback && (thisValue = that.get(key)) ) {
value = conflictCallback(key, thisValue, value);
}
that.put(key, value);
}
};
this.clone = function() {
var clone = new Hashtable(hashingFunctionParam, equalityFunctionParam);
clone.putAll(that);
return clone;
};
}
return Hashtable;
})();;
HashSet = function (hashingFunction, equalityFunction) {
var hashTable = new Hashtable(hashingFunction, equalityFunction);
this.add = function(o) {
hashTable.put(o, true);
};
this.addAll = function(arr) {
var i = arr.length;
while (i--) {
hashTable.put(arr[i], true);
}
};
this.values = function() {
return hashTable.keys();
};
this.remove = function(o) {
return hashTable.remove(o) ? o : null;
};
this.contains = function(o) {
return hashTable.containsKey(o);
};
this.clear = function() {
hashTable.clear();
};
this.size = function() {
return hashTable.size();
};
this.isEmpty = function() {
return hashTable.isEmpty();
};
this.clone = function() {
var h = new HashSet(hashingFunction, equalityFunction);
h.addAll(hashTable.keys());
return h;
};
this.intersection = function(hashSet) {
var intersection = new HashSet(hashingFunction, equalityFunction);
var values = hashSet.values(), i = values.length, val;
while (i--) {
val = values[i];
if (hashTable.containsKey(val)) {
intersection.add(val);
}
}
return intersection;
};
this.union = function(hashSet) {
var union = this.clone();
var values = hashSet.values(), i = values.length, val;
while (i--) {
val = values[i];
if (!hashTable.containsKey(val)) {
union.add(val);
}
}
return union;
};
this.isSubsetOf = function(hashSet) {
var values = hashTable.keys(), i = values.length;
while (i--) {
if (!hashSet.contains(values[i])) {
return false;
}
}
return true;
};
};
this.HashSet = HashSet;
this.Hashtable = Hashtable;
}).call(this);
},{}],13:[function(require,module,exports){
// Generated by CoffeeScript 1.7.1
(function() {
var BuiltinFunction, LogoVM, UserFunction, op;
op = require('./opcodes');
BuiltinFunction = require('./codeObj').BuiltinFunction;
UserFunction = require('./codeObj').UserFunction;
LogoVM = (function() {
function LogoVM(codeObj) {
this.codeObj = codeObj;
this.consts = this.codeObj.consts;
this.globals = this._initGlobals();
}
LogoVM.prototype._initGlobals = function() {
var i, _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = this.codeObj.globalNames.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(void 0);
}
return _results;
};
LogoVM.prototype.run = function() {
return this._run(this.codeObj.code);
};
LogoVM.prototype._run = function(code, localContext, funcName) {
var i, len, pc, stack, _args, _callee, _func, _global, _local, _name, _x, _y;
if (localContext == null) {
localContext = this.globals;
}
stack = [];
pc = 0;
len = code.length;
while (pc < len) {
switch (code[pc]) {
case op.HALT:
return 0;
case op.POP:
stack.pop();
break;
case op.LDCONST:
stack.push(this.consts[code[++pc]]);
break;
case op.LDLOCAL:
_local = localContext[code[++pc]];
if (typeof _local === 'undefined') {
_name = this.codeObj.localNames[funcName][code[pc]];
throw new Error("" + _name + " is not defined");
}
stack.push(_local);
break;
case op.LDGLOBAL:
_global = this.globals[code[++pc]];
if (typeof _global === 'undefined') {
_name = this.codeObj.globalNames[code[pc]];
throw new Error("" + _name + " is not defined");
}
stack.push(_global);
break;
case op.STLOCAL:
localContext[code[++pc]] = stack[stack.length - 1];
break;
case op.STGLOBAL:
this.globals[code[++pc]] = stack[stack.length - 1];
break;
case op.CALL:
_func = this.codeObj.functions[code[++pc]];
_args = (function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = _func.argc; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(stack.pop());
}
return _results;
})();
if (_func instanceof BuiltinFunction) {
stack.push(_func.invoke(_args));
} else if (_func instanceof UserFunction) {
_callee = this.codeObj.funcInfos[code[pc]].name;
_func.invoke(((function(_this) {
return function(code, args) {
var _i, _localContext, _ref;
_localContext = [];
for (i = _i = 0, _ref = _this.codeObj.localNames[_callee].length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_localContext.push(void 0);
}
[].splice.apply(_localContext, [0, _func.argc - 0].concat(args)), args;
return stack.push(_this._run(code, _localContext, _callee));
};
})(this)), _args);
}
break;
case op.RET:
return stack.pop();
case op.JT:
++pc;
if (stack.pop()) {
pc = code[pc];
continue;
}
break;
case op.JF:
++pc;
if (!stack.pop()) {
pc = code[pc];
continue;
}
break;
case op.JMP:
pc = code[++pc];
continue;
case op.ADD:
_y = stack.pop();
_x = stack.pop();
stack.push(_x + _y);
break;
case op.SUB:
_y = stack.pop();
_x = stack.pop();
stack.push(_x - _y);
break;
case op.MUL:
_y = stack.pop();
_x = stack.pop();
stack.push(_x * _y);
break;
case op.DIV:
_y = stack.pop();
_x = stack.pop();
stack.push(_x / _y);
break;
case op.MOD:
_y = stack.pop();
_x = stack.pop();
stack.push(_x % _y);
break;
case op.DELLOCAL:
delete localContext[code[++pc]];
break;
case op.DELGLOBAL:
delete this.globals[code[++pc]];
stack.push(true);
break;
case op.INC:
++stack[stack.length - 1];
break;
case op.DEC:
--stack[stack.length - 1];
break;
case op.POS:
stack[stack.length - 1] = +stack[stack.length - 1];
break;
case op.NEG:
stack[stack.length - 1] = -stack[stack.length - 1];
break;
case op.LSHIFT:
_y = stack.pop();
_x = stack.pop();
stack.push(_x << _y);
break;
case op.URSHIFT:
_y = stack.pop();
_x = stack.pop();
stack.push(_x >>> _y);
break;
case op.RSHIFT:
_y = stack.pop();
_x = stack.pop();
stack.push(_x >> _y);
break;
case op.LTE:
_y = stack.pop();
_x = stack.pop();
stack.push(_x <= _y);
break;
case op.GTE:
_y = stack.pop();
_x = stack.pop();
stack.push(_x >= _y);
break;
case op.LT:
_y = stack.pop();
_x = stack.pop();
stack.push(_x < _y);
break;
case op.GT:
_y = stack.pop();
_x = stack.pop();
stack.push(_x > _y);
break;
case op.EQ:
_y = stack.pop();
_x = stack.pop();
stack.push(_x === _y);
break;
case op.NEQ:
_y = stack.pop();
_x = stack.pop();
stack.push(_x !== _y);
break;
case op.NOT:
stack[stack.length - 1] = !stack[stack.length - 1];
break;
case op.BNEG:
stack[stack.length - 1] = ~stack[stack.length - 1];
break;
case op.BAND:
_y = stack.pop();
_x = stack.pop();
stack.push(_x & _y);
break;
case op.BXOR:
_y = stack.pop();
_x = stack.pop();
stack.push(_x ^ _y);
break;
case op.BOR:
_y = stack.pop();
_x = stack.pop();
stack.push(_x | _y);
break;
case op.AND:
_y = stack.pop();
_x = stack.pop();
stack.push(_x && _y);
break;
case op.OR:
_y = stack.pop();
_x = stack.pop();
stack.push(_x || _y);
break;
case op.ROT:
_x = stack.pop();
_y = stack.pop();
stack.push(_x);
stack.push(_y);
break;
case op.DUP:
stack.push(stack[stack.length - 1]);
break;
case op.TYPEOF:
stack.push(typeof stack.pop);
break;
case op.NRET:
return void 0;
default:
throw new Error("Invalid opcode " + code[pc]);
}
pc++;
}
return 0;
};
return LogoVM;
})();
this.LogoVM = LogoVM;
}).call(this);
},{"./codeObj":4,"./opcodes":8}],14:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],15:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
function noop() {}
process.on = noop;
process.once = noop;
process.off = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],16:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],17:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require("/usr/local/share/npm/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":16,"/usr/local/share/npm/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":15,"inherits":14}]},{},[]) | mit |
SinyooFE/Sinyoo.P0 | src/app/components/user/index.ts | 55 | export * from './user-changePassword-log.component'; | mit |
randyibarrola/lafachada | src/Administracion/ModeloBundle/Entity/Historial.php | 2791 | <?php
namespace Administracion\ModeloBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* @ORM\Entity
*/
class Historial {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;
/**
* @var Usuario $usuario
*
* @ORM\ManyToOne(targetEntity="Usuario", inversedBy="historial")
* @ORM\JoinColumn(nullable=false, onDelete="cascade")
* @Assert\Type(type="Administracion\ModeloBundle\Entity\Usuario")
*/
protected $usuario;
/** @ORM\Column(type="string", length=200) */
protected $proceso;
/**
* @var datetime $created_at
*
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime", nullable=true)
*/
private $created_at;
/**
* @var datetime $updated_at
*
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime", nullable=true)
*/
private $updated_at;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set proceso
*
* @param string $proceso
* @return Historial
*/
public function setProceso($proceso)
{
$this->proceso = $proceso;
return $this;
}
/**
* Get proceso
*
* @return string
*/
public function getProceso()
{
return $this->proceso;
}
/**
* Set created_at
*
* @param \DateTime $createdAt
* @return Historial
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* @param \DateTime $updatedAt
* @return Historial
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Set usuario
*
* @param \Administracion\ModeloBundle\Entity\Usuario $usuario
* @return Historial
*/
public function setUsuario(\Administracion\ModeloBundle\Entity\Usuario $usuario)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* @return \Administracion\ModeloBundle\Entity\Usuario
*/
public function getUsuario()
{
return $this->usuario;
}
} | mit |
barbushin/php-console | src/PhpConsole/Connector.php | 18378 | <?php
namespace PhpConsole;
/**
* PHP Console client connector that encapsulates client-server protocol implementation
*
* You will need to install Google Chrome extension "PHP Console"
* https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef
*
* @package PhpConsole
* @version 3.1
* @link http://consle.com
* @author Sergey Barbushin http://linkedin.com/in/barbushin
* @copyright © Sergey Barbushin, 2011-2013. All rights reserved.
* @license http://www.opensource.org/licenses/BSD-3-Clause "The BSD 3-Clause License"
* @codeCoverageIgnore
*/
class Connector {
const SERVER_PROTOCOL = 5;
const SERVER_COOKIE = 'php-console-server';
const CLIENT_INFO_COOKIE = 'php-console-client';
const CLIENT_ENCODING = 'UTF-8';
const HEADER_NAME = 'PHP-Console';
const POSTPONE_HEADER_NAME = 'PHP-Console-Postpone';
const POST_VAR_NAME = '__PHP_Console';
const POSTPONE_REQUESTS_LIMIT = 10;
const PHP_HEADERS_SIZE = 1000; // maximum PHP response headers size
const CLIENT_HEADERS_LIMIT = 200000;
/** @var Connector */
protected static $instance;
/** @var Storage|null */
private static $postponeStorage;
/** @var Dumper|null */
protected $dumper;
/** @var Dispatcher\Debug|null */
protected $debugDispatcher;
/** @var Dispatcher\Errors|null */
protected $errorsDispatcher;
/** @var Dispatcher\Evaluate|null */
protected $evalDispatcher;
/** @var string */
protected $serverEncoding = self::CLIENT_ENCODING;
protected $sourcesBasePath;
protected $headersLimit;
/** @var Client|null */
private $client;
/** @var Auth|null */
private $auth;
/** @var Message[] */
private $messages = array();
private $postponeResponseId;
private $isSslOnlyMode = false;
private $isActiveClient = false;
private $isAuthorized = false;
private $isEvalListenerStarted = false;
private $registeredShutDowns = 0;
/**
* @return static
*/
public static function getInstance() {
if(!self::$instance) {
self::$instance = new static();
}
return self::$instance;
}
/**
* Set storage for postponed response data. Storage\Session is used by default, but if you have problems with overridden session handler you should use another one.
* IMPORTANT: This method cannot be called after Connector::getInstance()
* @param Storage $storage
* @throws \Exception
*/
public static function setPostponeStorage(Storage $storage) {
if(self::$instance) {
throw new \Exception(__METHOD__ . ' can be called only before ' . __CLASS__ . '::getInstance()');
}
self::$postponeStorage = $storage;
}
/**
* @return Storage
*/
private function getPostponeStorage() {
if(!self::$postponeStorage) {
self::$postponeStorage = new Storage\Session();
}
return self::$postponeStorage;
}
protected function __construct() {
$this->initConnection();
$this->setServerEncoding(ini_get('mbstring.internal_encoding') ? : self::CLIENT_ENCODING);
}
private final function __clone() {
}
/**
* Detect script is running in command-line mode
* @return int
*/
protected function isCliMode() {
return PHP_SAPI == 'cli';
}
/**
* Notify clients that there is active PHP Console on server & check if there is request from client with active PHP Console
* @throws \Exception
*/
private function initConnection() {
if($this->isCliMode()) {
return;
}
$this->initServerCookie();
$this->client = $this->initClient();
if($this->client) {
ob_start();
$this->isActiveClient = true;
$this->registerFlushOnShutDown();
$this->setHeadersLimit(isset($_SERVER['SERVER_SOFTWARE']) && stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false
? 4096 // default headers limit for Nginx
: 8192 // default headers limit for all other web-servers
);
$this->listenGetPostponedResponse();
$this->postponeResponseId = $this->setPostponeHeader();
}
}
/**
* Get connected client data(
* @return Client|null
* @throws \Exception
*/
private function initClient() {
if(isset($_COOKIE[self::CLIENT_INFO_COOKIE])) {
$clientData = @json_decode(base64_decode($_COOKIE[self::CLIENT_INFO_COOKIE], true), true);
if(!$clientData) {
throw new \Exception('Wrong format of response cookie data: ' . $_COOKIE[self::CLIENT_INFO_COOKIE]);
}
$client = new Client($clientData);
if(isset($clientData['auth'])) {
$client->auth = new ClientAuth($clientData['auth']);
}
return $client;
}
}
/**
* Notify clients that there is active PHP Console on server
* @throws \Exception
*/
private function initServerCookie() {
if(!isset($_COOKIE[self::SERVER_COOKIE]) || $_COOKIE[self::SERVER_COOKIE] != self::SERVER_PROTOCOL) {
$isSuccess = setcookie(self::SERVER_COOKIE, self::SERVER_PROTOCOL, null, '/');
if(!$isSuccess) {
throw new \Exception('Unable to set PHP Console server cookie');
}
}
}
/**
* Check if there is client is installed PHP Console extension
* @return bool
*/
public function isActiveClient() {
return $this->isActiveClient;
}
/**
* Set client connection as not active
*/
public function disable() {
$this->isActiveClient = false;
}
/**
* Check if client with valid auth credentials is connected
* @return bool
*/
public function isAuthorized() {
return $this->isAuthorized;
}
/**
* Set IP masks of clients that will be allowed to connect to PHP Console
* @param array $ipMasks Use *(star character) for "any numbers" placeholder array('192.168.*.*', '10.2.12*.*', '127.0.0.1', '2001:0:5ef5:79fb:*:*:*:*')
*/
public function setAllowedIpMasks(array $ipMasks) {
if($this->isActiveClient()) {
if(isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
foreach($ipMasks as $ipMask) {
if(preg_match('~^' . str_replace(array('.', '*'), array('\.', '\w+'), $ipMask) . '$~i', $ip)) {
return;
}
}
}
$this->disable();
}
}
/**
* @return Dumper
*/
public function getDumper() {
if(!$this->dumper) {
$this->dumper = new Dumper();
}
return $this->dumper;
}
/**
* Override default errors dispatcher
* @param Dispatcher\Errors $dispatcher
*/
public function setErrorsDispatcher(Dispatcher\Errors $dispatcher) {
$this->errorsDispatcher = $dispatcher;
}
/**
* Get dispatcher responsible for sending errors/exceptions messages
* @return Dispatcher\Errors
*/
public function getErrorsDispatcher() {
if(!$this->errorsDispatcher) {
$this->errorsDispatcher = new Dispatcher\Errors($this, $this->getDumper());
}
return $this->errorsDispatcher;
}
/**
* Override default debug dispatcher
* @param Dispatcher\Debug $dispatcher
*/
public function setDebugDispatcher(Dispatcher\Debug $dispatcher) {
$this->debugDispatcher = $dispatcher;
}
/**
* Get dispatcher responsible for sending debug messages
* @return Dispatcher\Debug
*/
public function getDebugDispatcher() {
if(!$this->debugDispatcher) {
$this->debugDispatcher = new Dispatcher\Debug($this, $this->getDumper());
}
return $this->debugDispatcher;
}
/**
* Override default eval requests dispatcher
* @param Dispatcher\Evaluate $dispatcher
*/
public function setEvalDispatcher(Dispatcher\Evaluate $dispatcher) {
$this->evalDispatcher = $dispatcher;
}
/**
* Get dispatcher responsible for handling eval requests
* @return Dispatcher\Evaluate
*/
public function getEvalDispatcher() {
if(!$this->evalDispatcher) {
$this->evalDispatcher = new Dispatcher\Evaluate($this, new EvalProvider(), $this->getDumper());
}
return $this->evalDispatcher;
}
/**
* Enable eval request to be handled by eval dispatcher. Must be called after all Connector configurations.
* Connector::getInstance()->setPassword() is required to be called before this method
* Use Connector::getInstance()->setAllowedIpMasks() for additional access protection
* Check Connector::getInstance()->getEvalDispatcher()->getEvalProvider() to customize eval accessibility & security options
* @param bool $exitOnEval
* @param bool $flushDebugMessages Clear debug messages handled before this method is called
* @throws \Exception
*/
public function startEvalRequestsListener($exitOnEval = true, $flushDebugMessages = true) {
if(!$this->auth) {
throw new \Exception('Eval dispatcher is allowed only in password protected mode. See PhpConsole\Connector::getInstance()->setPassword(...)');
}
if($this->isEvalListenerStarted) {
throw new \Exception('Eval requests listener already started');
}
$this->isEvalListenerStarted = true;
if($this->isActiveClient() && $this->isAuthorized() && isset($_POST[Connector::POST_VAR_NAME]['eval'])) {
$request = $_POST[Connector::POST_VAR_NAME]['eval'];
if(!isset($request['data']) || !isset($request['signature'])) {
throw new \Exception('Wrong PHP Console eval request');
}
if($this->auth->getSignature($request['data']) !== $request['signature']) {
throw new \Exception('Wrong PHP Console eval request signature');
}
if($flushDebugMessages) {
foreach($this->messages as $i => $message) {
if($message instanceof DebugMessage) {
unset($this->messages[$i]);
}
}
}
$this->convertEncoding($request['data'], $this->serverEncoding, self::CLIENT_ENCODING);
$this->getEvalDispatcher()->dispatchCode($request['data']);
if($exitOnEval) {
exit;
}
}
}
/**
* Set bath to base dir of project source code(so it will be stripped in paths displaying on client)
* @param $sourcesBasePath
* @throws \Exception
*/
public function setSourcesBasePath($sourcesBasePath) {
$sourcesBasePath = realpath($sourcesBasePath);
if(!$sourcesBasePath) {
throw new \Exception('Path "' . $sourcesBasePath . '" not found');
}
$this->sourcesBasePath = $sourcesBasePath;
}
/**
* Protect PHP Console connection by password
*
* Use Connector::getInstance()->setAllowedIpMasks() for additional secure
* @param string $password
* @param bool $publicKeyByIp Set authorization token depending on client IP
* @throws \Exception
*/
public function setPassword($password, $publicKeyByIp = true) {
if($this->auth) {
throw new \Exception('Password already defined');
}
$this->convertEncoding($password, self::CLIENT_ENCODING, $this->serverEncoding);
$this->auth = new Auth($password, $publicKeyByIp);
if($this->client) {
$this->isAuthorized = $this->client->auth && $this->auth->isValidAuth($this->client->auth);
}
}
/**
* Encode var to JSON with errors & encoding handling
* @param $var
* @return string
* @throws \Exception
*/
protected function jsonEncode($var) {
return json_encode($var, defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : null);
}
/**
* Recursive var data encoding conversion
* @param $data
* @param $fromEncoding
* @param $toEncoding
*/
protected function convertArrayEncoding(&$data, $toEncoding, $fromEncoding) {
array_walk_recursive($data, array($this, 'convertWalkRecursiveItemEncoding'), array($toEncoding, $fromEncoding));
}
/**
* Encoding conversion callback for array_walk_recursive()
* @param string $string
* @param null $key
* @param array $args
*/
protected function convertWalkRecursiveItemEncoding(&$string, $key = null, array $args) {
$this->convertEncoding($string, $args[0], $args[1]);
}
/**
* Convert string encoding
* @param string $string
* @param string $toEncoding
* @param string|null $fromEncoding
* @throws \Exception
*/
protected function convertEncoding(&$string, $toEncoding, $fromEncoding) {
if($string && is_string($string) && $toEncoding != $fromEncoding) {
static $isMbString;
if($isMbString === null) {
$isMbString = extension_loaded('mbstring');
}
if($isMbString) {
$string = @mb_convert_encoding($string, $toEncoding, $fromEncoding) ? : $string;
}
else {
$string = @iconv($fromEncoding, $toEncoding . '//IGNORE', $string) ? : $string;
}
if(!$string && $toEncoding == 'UTF-8') {
$string = utf8_encode($string);
}
}
}
/**
* Set headers size limit for your web-server. You can auto-detect headers size limit by /examples/utils/detect_headers_limit.php
* @param $bytes
* @throws \Exception
*/
public function setHeadersLimit($bytes) {
if($bytes < static::PHP_HEADERS_SIZE) {
throw new \Exception('Headers limit cannot be less then ' . __CLASS__ . '::PHP_HEADERS_SIZE');
}
$bytes -= static::PHP_HEADERS_SIZE;
$this->headersLimit = $bytes < static::CLIENT_HEADERS_LIMIT ? $bytes : static::CLIENT_HEADERS_LIMIT;
}
/**
* Set your server PHP internal encoding, if it's different from "mbstring.internal_encoding" or UTF-8
* @param $encoding
*/
public function setServerEncoding($encoding) {
if($encoding == 'utf8' || $encoding == 'utf-8') {
$encoding = 'UTF-8'; // otherwise mb_convert_encoding() sometime fails with error(thanks to @alexborisov)
}
$this->serverEncoding = $encoding;
}
/**
* Send data message to PHP Console client(if it's connected)
* @param Message $message
*/
public function sendMessage(Message $message) {
if($this->isActiveClient()) {
$this->messages[] = $message;
}
}
/**
* Register shut down callback handler. Must be called after all errors handlers register_shutdown_function()
*/
public function registerFlushOnShutDown() {
$this->registeredShutDowns++;
register_shutdown_function(array($this, 'onShutDown'));
}
/**
* This method must be called only by register_shutdown_function(). Never call it manually!
*/
public function onShutDown() {
$this->registeredShutDowns--;
if(!$this->registeredShutDowns) {
$this->proceedResponsePackage();
}
}
/**
* Force connection by SSL for clients with PHP Console installed
*/
public function enableSslOnlyMode() {
$this->isSslOnlyMode = true;
}
/**
* Check if client is connected by SSL
* @return bool
*/
protected function isSsl() {
return (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') || (isset($_SERVER['SERVER_PORT']) && ($_SERVER['SERVER_PORT']) == 443);
}
/**
* Send response data to client
* @throws \Exception
*/
private function proceedResponsePackage() {
if($this->isActiveClient()) {
$response = new Response();
$response->isSslOnlyMode = $this->isSslOnlyMode;
if(isset($_POST[self::POST_VAR_NAME]['getBackData'])) {
$response->getBackData = $_POST[self::POST_VAR_NAME]['getBackData'];
}
if(!$this->isSslOnlyMode || $this->isSsl()) {
if($this->auth) {
$response->auth = $this->auth->getServerAuthStatus($this->client->auth);
}
if(!$this->auth || $this->isAuthorized()) {
$response->isLocal = isset($_SERVER['REMOTE_ADDR']) && ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '::1');
$response->docRoot = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : null;
$response->sourcesBasePath = $this->sourcesBasePath;
$response->isEvalEnabled = $this->isEvalListenerStarted;
$response->messages = $this->messages;
}
}
$responseData = $this->serializeResponse($response);
if(strlen($responseData) > $this->headersLimit || !$this->setHeaderData($responseData, self::HEADER_NAME, false)) {
$this->getPostponeStorage()->push($this->postponeResponseId, $responseData);
}
}
}
private function setPostponeHeader() {
$postponeResponseId = mt_rand() . mt_rand() . mt_rand();
$this->setHeaderData($this->serializeResponse(
new PostponedResponse(array(
'id' => $postponeResponseId
))
), self::POSTPONE_HEADER_NAME, true);
return $postponeResponseId;
}
private function setHeaderData($responseData, $headerName, $throwException = true) {
if(headers_sent($file, $line)) {
if($throwException) {
throw new \Exception('Unable to process response data, headers already sent in ' . $file . ':' . $line . '. Try to use ob_start() and don\'t use flush().');
}
return false;
}
header($headerName . ': ' . $responseData);
return true;
}
protected function objectToArray(&$var) {
if(is_object($var)) {
$var = get_object_vars($var);
array_walk_recursive($var, array($this, 'objectToArray'));
}
}
protected function serializeResponse(DataObject $response) {
if($this->serverEncoding != self::CLIENT_ENCODING) {
$this->objectToArray($response);
$this->convertArrayEncoding($response, self::CLIENT_ENCODING, $this->serverEncoding);
}
return $this->jsonEncode($response);
}
/**
* Check if there is postponed response request and dispatch it
*/
private function listenGetPostponedResponse() {
if(isset($_POST[self::POST_VAR_NAME]['getPostponedResponse'])) {
header('Content-Type: application/json; charset=' . self::CLIENT_ENCODING);
echo $this->getPostponeStorage()->pop($_POST[self::POST_VAR_NAME]['getPostponedResponse']);
$this->disable();
exit;
}
}
}
abstract class DataObject {
public function __construct(array $properties = array()) {
foreach($properties as $property => $value) {
$this->$property = $value;
}
}
}
final class Client extends DataObject {
public $protocol;
/** @var ClientAuth|null */
public $auth;
}
final class ClientAuth extends DataObject {
public $publicKey;
public $token;
}
final class ServerAuthStatus extends DataObject {
public $publicKey;
public $isSuccess;
}
final class Response extends DataObject {
public $protocol = Connector::SERVER_PROTOCOL;
/** @var ServerAuthStatus */
public $auth;
public $docRoot;
public $sourcesBasePath;
public $getBackData;
public $isLocal;
public $isSslOnlyMode;
public $isEvalEnabled;
public $messages = array();
}
final class PostponedResponse extends DataObject {
public $protocol = Connector::SERVER_PROTOCOL;
public $isPostponed = true;
public $id;
}
abstract class Message extends DataObject {
public $type;
}
abstract class EventMessage extends Message {
public $data;
public $file;
public $line;
/** @var null|TraceCall[] */
public $trace;
}
final class TraceCall extends DataObject {
public $file;
public $line;
public $call;
}
final class DebugMessage extends EventMessage {
public $type = 'debug';
public $tags;
}
final class ErrorMessage extends EventMessage {
public $type = 'error';
public $code;
public $class;
}
final class EvalResultMessage extends Message {
public $type = 'eval_result';
public $return;
public $output;
public $time;
}
| mit |
howardhenry/geoip-lookup | tests/validate-app-environment.spec.js | 1309 | const { expect } = require('chai');
const validateAppEnvironment = require('../src/validate-app-environment');
describe('#validateAppEnvironment', () => {
let fn;
beforeEach(() => {
process.env.NODE_ENV = 'development';
process.env.DEBUG = 'false';
process.env.PORT = '9000';
});
it('should not throw an error if valid environment variables are present', () => {
fn = () => { validateAppEnvironment(); };
expect(fn).to.not.throw(Error);
});
it('should throw an error if env `NODE_ENV` is not `development`, `production` or `test`', () => {
process.env.NODE_ENV = 'foo';
fn = () => { validateAppEnvironment(); };
expect(fn).to.throw(Error);
});
it('should throw an error if env `DEBUG` is defined and not `true` or `false`', () => {
process.env.DEBUG = 'foo';
fn = () => { validateAppEnvironment(); };
expect(fn).to.throw(Error);
});
it('should throw an error if env `PORT` is not between `1` and `65535` inclusive', () => {
process.env.PORT = -10;
fn = () => { validateAppEnvironment(); };
expect(fn).to.throw(Error);
process.env.PORT = 65540;
fn = () => { validateAppEnvironment(); };
expect(fn).to.throw(Error);
});
});
| mit |
ReactiveServices/ReactiveServices.Application | ReactiveServices/Application/DispatcherLauncher.cs | 6398 | using NLog;
using ReactiveServices.ComputationalUnit.Dispatching;
using ReactiveServices.ComputationalUnit.Settings;
using ReactiveServices.MessageBus;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using ReactiveServices.ComputationalUnit;
using ReactiveServices.Extensions;
namespace ReactiveServices.Application
{
public class DispatcherLauncher : IDisposable
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private DispatcherLauncherId DispatcherLauncherId { get; set; }
private SubscriptionId LaunchConfirmationSubscriptionId { get; set; }
private ISubscriptionBus SubscriptionBus { get; set; }
private List<LaunchRecord> LaunchRecords { get; set; }
public const string LaunchConfirmationSubscriptionIdPrefix = "LaunchConfirmationSubscriptionFor_";
public DispatcherLauncher(ISubscriptionBus subscriptionBus)
{
DispatcherLauncherId = DispatcherLauncherId.New();
SubscriptionBus = subscriptionBus;
LaunchRecords = new List<LaunchRecord>();
LaunchConfirmationSubscriptionId = SubscriptionId.FromString(
LaunchConfirmationSubscriptionIdPrefix + DispatcherLauncherId
);
SubscribeToLaunchConfirmations();
}
public void Launch(DispatcherSettings settings)
{
RegisterLaunchRequestFor(settings.DispatcherId);
LaunchComputationalUnit(settings);
}
private string _computationalUnitExeName;
private string ComputationalUnitExeName
{
get
{
if (_computationalUnitExeName == null)
_computationalUnitExeName = Assembly.GetAssembly(typeof(Program)).GetName().Name + ".exe";
return _computationalUnitExeName;
}
}
protected virtual void LaunchComputationalUnit(DispatcherSettings settings)
{
var dispatcherSettingsFileName = Path.GetTempFileName();
using (var stream = new FileStream(dispatcherSettingsFileName, FileMode.Create, FileAccess.Write))
{
settings.SaveTo(stream);
}
var showConsoleWindow = Configuration.ConfigurationFiles.Settings.ReactiveServices.ShowConsoleWindow;
new Process().Start(
ComputationalUnitExeName,
ComputationalUnitArgumentsFor(dispatcherSettingsFileName),
showConsoleWindow,
settings.RequireAdministratorPriviledges
);
}
private static string ComputationalUnitArgumentsFor(string dispatcherSettingsFileName)
{
return String.Format("\"{0}\"", dispatcherSettingsFileName);
}
private void SubscribeToLaunchConfirmations()
{
SubscriptionBus.SubscribeTo<LaunchConfirmation>(
LaunchConfirmationSubscriptionId,
m =>
{
var dispatcherId = ((LaunchConfirmation)m).DispatcherId;
RegisterLaunchConfirmationFor(dispatcherId);
},
SubscriptionMode.Exclusive
);
}
private void RegisterLaunchRequestFor(DispatcherId dispatcherId)
{
lock (LaunchRecords)
{
LaunchRecords.Add(new LaunchRecord
{
DispatcherId = dispatcherId,
RequestTime = DateTime.Now
});
}
}
private void RegisterLaunchConfirmationFor(DispatcherId dispatcherId)
{
LaunchRecord[] launchRecords;
lock (LaunchRecords)
{
launchRecords = LaunchRecords.ToArray();
}
var launchRecord = launchRecords.FirstOrDefault(r => r.DispatcherId == dispatcherId && !r.IsConfirmed);
if (launchRecord != null)
launchRecord.ConfirmationTime = DateTime.Now;
}
public void WaitForLaunchConfirmations(TimeSpan launchTimeout)
{
try
{
var sw = new Stopwatch();
sw.Start();
while (!HasReceivedLaunchConfirmationFromAllDispatchers())
{
if (sw.Elapsed >= launchTimeout)
throw new TimeoutException();
Thread.Sleep(10);
}
sw.Stop();
}
catch (TimeoutException)
{
throw new TimeoutException(String.Format("Could not launch all configured work dispatchers within {0} milliseconds!", launchTimeout.TotalMilliseconds));
}
}
public bool HasReceivedLaunchConfirmationFromAllDispatchers()
{
LaunchRecord[] launchRecords;
lock (LaunchRecords)
{
launchRecords = LaunchRecords.ToArray();
}
return launchRecords.All(launchRecord => launchRecord.IsConfirmed);
}
public bool HasReceivedLaunchConfirmationFrom(DispatcherId dispatcherId)
{
LaunchRecord[] launchRecords;
lock (LaunchRecords)
{
launchRecords = LaunchRecords.ToArray();
}
var launchRecord = launchRecords.SingleOrDefault(r => r.DispatcherId == dispatcherId);
return launchRecord != null && launchRecord.IsConfirmed;
}
public void Dispose()
{
SubscriptionBus.Dispose();
}
}
public class InProcessDispatcherLauncher : DispatcherLauncher
{
public InProcessDispatcherLauncher(ISubscriptionBus subscriptionBus)
: base(subscriptionBus)
{
}
protected override void LaunchComputationalUnit(DispatcherSettings settings)
{
var dispatcher = new Dispatcher();
dispatcher.Initialize(settings);
/*
* Atention:
* These dispatcher continue to live after the InProcessDispatcherLauncher is disposed
* They will be disposed only after they receive a poison pill
*/
}
}
}
| mit |
mdowds/python-mock-firestore | tests/test_timestamp.py | 407 | import unittest
from datetime import datetime as dt
from mockfirestore import Timestamp
class TestTimestamp(unittest.TestCase):
def test_timestamp(self):
dt_timestamp = dt.now().timestamp()
timestamp = Timestamp(dt_timestamp)
seconds, nanos = str(dt_timestamp).split('.')
self.assertEqual(seconds, timestamp.seconds)
self.assertEqual(nanos, timestamp.nanos)
| mit |
catzaizai/MegneticLucene | Test/ML.Test/SearchTool.cs | 1456 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Inf.SearchTool;
using NUnit.Framework;
namespace ML.Test
{
[TestFixture]
public class SearchTool
{
[Test]
public void CreateIndex()
{
SearchHelper.CreateIndex(new SearchModel
{
Key = Guid.NewGuid().ToString(),
Value = "测试jalksdjfx2",
Content = "asdf测试,C#",
Hot = 2
});
SearchHelper.CreateIndex(new SearchModel
{
Key = Guid.NewGuid().ToString(),
Value = "测试jalksdjfx1",
Content = "asdf测试,C#",
Hot = 1
});
SearchHelper.CreateIndex(new SearchModel
{
Key = Guid.NewGuid().ToString(),
Value = "测试jalksdjfx3",
Content = "asdf测试,C#",
Hot = 3
});
}
[Test]
public void Search()
{
var result = SearchHelper.Search("mp4");
foreach (var searchModel in result)
{
Console.WriteLine(searchModel.Value + " : " + searchModel.Content);
}
}
[OneTimeTearDown]
public void DeleteAllIndex()
{
//SearchHelper.DeleteAllIndex();
}
}
}
| mit |
ahui2016/Mima | play/secretbox_play.rb | 165 | require 'base64'
require_relative '../rbnacl'
a = RbNaCl::Random.random_bytes
p a
b = Base64.urlsafe_encode64(a)
p b
c = Base64.urlsafe_decode64(b)
p c
puts a == c
| mit |
schlabberdog/pipes | src/com/github/users/dmoagx/pipes/ui/BoardView.java | 7786 | package com.github.users.dmoagx.pipes.ui;
import com.github.users.dmoagx.pipes.model.Board;
import com.github.users.dmoagx.pipes.model.FieldRef;
import com.github.users.dmoagx.pipes.model.FieldType;
import com.github.users.dmoagx.util.Matrix;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class BoardView extends JComponent implements MouseListener {
private Board board;
private Matrix<JLabel> labels = null;
public BoardView(Board board) {
setBoard(board);
addMouseListener(this);
}
protected void paintComponent(Graphics g) {
g.setColor(Color.white);
g.fillRect(0,0,getWidth(),getHeight());
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Stroke stroke2 = new BasicStroke(2.0f);
Stroke stroke1 = new BasicStroke(1.0f);
g2.setColor(Color.black);
//grid zeichnen
double boxWidth = (getWidth()-7) / board.getWidth();
double boxHeight = (getHeight()-7) / board.getHeight();
//wir brauchen eine copy sonst könnte sich die grid verändern während wir sie zeichnen
Board drawBoard = board.copy();
double xOffset = 3;
double yOffset = 3;
for (int y = 0; y < drawBoard.getHeight(); y++) {
for (int x = 0; x < drawBoard.getWidth(); x++) {
g2.setStroke(stroke2);
g2.drawRect((int)xOffset,(int)yOffset,(int)boxWidth,(int)boxHeight);
FieldType ft = drawBoard.getItemAt(x, y);
if(ft == FieldType.FORBIDDEN) {
g2.setStroke(stroke2);
g2.setColor(Color.red);
g2.drawLine((int)(xOffset+10),(int)(yOffset+10),(int)(xOffset+boxWidth-10),(int)(yOffset+boxHeight-10));
g2.drawLine((int)(xOffset+10),(int)(yOffset+boxHeight-10),(int)(xOffset+boxWidth-10),(int)(yOffset+10));
g2.setColor(Color.black);
}
else if(ft == FieldType.MUST) {
g2.fillOval((int)(xOffset+10),(int)(yOffset+10),(int)(boxWidth-20),(int)(boxHeight-20));
}
else if(ft.isReal()) {
//rohrverbindungen zeichnen
FieldRef fr = drawBoard.fieldRef(x,y);
g2.setStroke(stroke1);
if(!fr.isOnTopBorder() && fr.top().isReal()) {
//pipe nach oben
g2.setColor(Color.yellow);
g2.fillRect((int)(xOffset+20),(int)(yOffset-20),(int)(boxWidth-40),(int)(40));
g2.setColor(Color.black);
g2.drawRect((int)(xOffset+20),(int)(yOffset-20),(int)(boxWidth-40),(int)(40));
}
if(!fr.isOnLeftBorder() && fr.left().isReal()) {
//pipe nach oben
g2.setColor(Color.yellow);
g2.fillRect((int)(xOffset-20),(int)(yOffset+20),(int)(40),(int)(boxHeight-40));
g2.setColor(Color.black);
g2.drawRect((int)(xOffset-20),(int)(yOffset+20),(int)(40),(int)(boxHeight-40));
}
g2.setStroke(stroke2);
}
xOffset += boxWidth;
}
yOffset += boxHeight;
xOffset = 3;
}
xOffset = 3;
yOffset = 3;
for (int y = 0; y < drawBoard.getHeight(); y++) {
for (int x = 0; x < drawBoard.getWidth(); x++) {
FieldType ft = drawBoard.getItemAt(x, y);
FieldRef fr = drawBoard.fieldRef(x,y);
//labels neu anordnen
JLabel label = labels.get(x,y);
label.setLocation((int)(xOffset+15),(int)(yOffset+15));
label.setSize((int)(boxWidth-30),(int)(boxHeight-30));
String letter = "";
if(fr.isReal()){
g2.setStroke(stroke2);
g2.setColor(Color.gray);
if(fr.numNeighbours() > fr.intVal() || fr.hasNeighbourOfKind(ft))
g2.setColor(Color.red);
else if(fr.isStatisfied())
g2.setColor(Color.green);
g2.fillRect((int)(xOffset+10),(int)(yOffset+10),(int)(boxWidth-20),(int)(boxHeight-20));
g2.setColor(Color.black);
g2.drawRect((int) (xOffset + 10), (int) (yOffset + 10), (int) (boxWidth - 20), (int) (boxHeight - 20));
switch (ft) {
case PIPE_1:
letter = "1";
break;
case PIPE_2:
letter = "2";
break;
case PIPE_3:
letter = "3";
break;
case PIPE_4:
letter = "4";
break;
}
}
label.setText(letter);
xOffset += boxWidth;
}
yOffset += boxHeight;
xOffset = 3;
}
}
@Override
public void mouseClicked(MouseEvent e) {
float blockWidth = getWidth() / board.getWidth();
float blockHeight = getHeight() / board.getHeight();
//feld bestimmen wo geklickt wurde
int x = (int)Math.floor(e.getX()/blockWidth);
int y = (int)Math.floor(e.getY()/blockHeight);
//System.out.println("Clicked on X="+x+",Y="+y);
//aktuellen wert holen
FieldType cur = board.getItemAt(x,y);
//und weiterzählen
switch (cur) {
case EMPTY:
cur = FieldType.PIPE_1;
break;
case PIPE_1:
cur = FieldType.PIPE_2;
break;
case PIPE_2:
cur = FieldType.PIPE_3;
break;
case PIPE_3:
cur = FieldType.PIPE_4;
break;
case PIPE_4:
cur = FieldType.MUST;
break;
case MUST:
cur = FieldType.FORBIDDEN;
break;
case FORBIDDEN:
cur = FieldType.EMPTY;
break;
}
//zurückschreiben
board.setItemAt(x,y,cur);
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
//ignore
}
@Override
public void mouseReleased(MouseEvent e) {
//ignore
}
@Override
public void mouseEntered(MouseEvent e) {
//ignore
}
@Override
public void mouseExited(MouseEvent e) {
//ignore
}
public void setBoard(Board b) {
this.board = b;
if(labels != null) {
for (int x = 0; x < labels.getWidth(); x++) {
for (int y = 0; y < labels.getHeight(); y++) {
remove(labels.get(x,y));
labels.set(x,y,null);
}
}
}
labels = new Matrix<JLabel>(board.getWidth(),board.getHeight());
for (int x = 0; x < board.getWidth(); x++) {
for (int y = 0; y < board.getHeight(); y++) {
JLabel lbl = new JLabel("");
lbl.setHorizontalAlignment(SwingConstants.CENTER);
lbl.setVerticalAlignment(SwingConstants.CENTER);
add(lbl);
labels.set(x,y,lbl);
}
}
repaint();
}
}
| mit |
alanaberdeen/coupled-minimum-cost-flow-track | cmcft/tools/params/c_cost.py | 2405 | # c_cost.py
# Cost vector for edges in coupled matrix
import numpy as np
__all__ = ["c_cost"]
def c_cost(g, a_coup, a_vertices):
# TODO: think this function is slow. Check for performance increases.
# c_cost
# creates vector of costs for edges
#
# Inputs: g - graph structure
# a_coup - coupled incidence matrix
# a_vertices - order of rows in coupled matrix
#
# Outputs: c - list of costs for each edge in incidence matrix
#
# Initialise cost vector
c = []
# For all edges in coupled matrix (iterating over transpose)
for e in a_coup.T:
# Get vertices connected by edge
vertex_indices = np.nonzero(e)
v = [a_vertices[i] for i in vertex_indices[1]]
# Get weights
cost = 0
# For simple edges
if len(v) == 2:
try:
cost = g[v[0]][v[1]]['weight']
except KeyError:
cost = g[v[1]][v[0]]['weight']
# For coupled edges
elif len(v) == 4:
# Find merge/split event label
ms_node = ms_event(v, g)
for n in v:
try:
cost = cost + g.edge[n][ms_node]['weight']
except KeyError:
cost = cost + g.edge[ms_node][n]['weight']
# Append to cost vector
c.append(cost)
return c
def ms_event(vertices, graph):
# ms_event
# given 4 nodes find the split or merge vertex that they are connected to
#
# Inputs: vertices - list of 4 node labels
# graph - graph structure
# Outputs: event_label - label of split/merge node
#
# initialise_out set
num = []
event = None
# split nodes
if 'D' in vertices:
event = 'M'
for n in vertices:
if 'L' in n:
num.append(''.join(i for i in n if i.isdigit()))
# merge nodes
elif 'A' in vertices:
event = 'S'
for n in vertices:
if 'R' in n:
num.append(''.join(i for i in n if i.isdigit()))
# Combine to give event label
event_label = (event + '(' + num[0] + ',' + num[1] + ')')
# Check if correct way around
if not graph.has_node(event_label):
event_label = (event + '(' + num[1] + ',' + num[0] + ')')
return event_label
| mit |
laurynas/activemerchant_banklink | lib/active_merchant/billing/integrations/dnb_nord_ltu/common.rb | 220 | module ActiveMerchant #:nodoc:
module Billing #:nodoc:
module Integrations #:nodoc:
module DnbNordLtu #:nodoc:
module Common
include Banklink::Common
end
end
end
end
end
| mit |
SRoddis/Mongo.Migration | Mongo.Migration/Services/IDatabaseVersionService.cs | 467 | using Mongo.Migration.Documents;
using Mongo.Migration.Migrations.Database;
using MongoDB.Driver;
namespace Mongo.Migration.Services
{
public interface IDatabaseVersionService
{
DocumentVersion GetCurrentOrLatestMigrationVersion();
DocumentVersion GetLatestDatabaseVersion(IMongoDatabase db);
void Save(IMongoDatabase db, IDatabaseMigration migration);
void Remove(IMongoDatabase db, IDatabaseMigration migration);
}
} | mit |
sarjun/AlgorithmVisualization | polymer/ShadowDOM/test/js/MutationObserver.js | 7211 | /*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is goverened by a BSD-style
* license that can be found in the LICENSE file.
*/
suite('MutationObserver', function() {
var wrap = ShadowDOMPolyfill.wrap;
var addedNodes = [], removedNodes = [];
var div;
function newValue() {
return Date.now();
}
setup(function() {
addedNodes = [];
removedNodes = [];
});
teardown(function() {
addedNodes = undefined;
removedNodes = undefined;
if (div) {
if (div.parentNode)
div.parentNode.removeChild(div);
div = undefined;
}
});
function mergeRecords(records) {
records.forEach(function(record) {
if (record.addedNodes)
addedNodes.push.apply(addedNodes, record.addedNodes);
if (record.removedNodes)
removedNodes.push.apply(removedNodes, record.removedNodes);
});
}
test('target', function(done) {
if (!window.MutationObserver) {
done();
return;
}
var div = document.createElement('div');
var mo = new MutationObserver(function(records, observer) {
assert.equal(this, mo);
assert.equal(observer, mo);
assert.equal(records[0].type, 'attributes');
assert.equal(records[0].target, div);
mo.disconnect();
done();
});
mo.observe(div, {
attributes: true
});
div.setAttribute('a', newValue());
});
test('addedNodes', function(done) {
if (!window.MutationObserver) {
done();
return;
}
div = document.body.appendChild(document.createElement('div'));
var mo = new MutationObserver(function(records, observer) {
mergeRecords(records);
assert.equal(records[0].type, 'childList');
assert.equal(records[0].target, div);
assert.equal(addedNodes.length, 2);
assert.equal(addedNodes[0], a);
assert.equal(addedNodes[1], b);
mo.disconnect();
done();
});
mo.observe(div, {
childList: true
});
div.innerHTML = '<a></a><b></b>';
var a = div.firstChild;
var b = div.lastChild;
});
test('addedNodes siblings', function(done) {
if (!window.MutationObserver) {
done();
return;
}
div = document.body.appendChild(document.createElement('div'));
var mo = new MutationObserver(function(records, observer) {
mergeRecords(records);
assert.equal(records.length, 1);
assert.equal(records[0].type, 'childList');
assert.equal(records[0].target, div);
assert.equal(addedNodes.length, 1);
assert.equal(addedNodes[0], c);
assert.equal(records[0].previousSibling, a);
assert.equal(records[0].nextSibling, b);
mo.disconnect();
done();
});
div.innerHTML = '<a></a><b></b>';
var a = div.firstChild;
var b = div.lastChild;
mo.observe(div, {
childList: true
});
var c = document.createElement('c');
div.insertBefore(c, b);
});
test('removedNodes', function(done) {
if (!window.MutationObserver) {
done();
return;
}
div = document.body.appendChild(document.createElement('div'));
var mo = new MutationObserver(function(records, observer) {
mergeRecords(records);
assert.equal(records[0].type, 'childList');
assert.equal(records[0].target, div);
assert.equal(addedNodes.length, 2);
assert.equal(addedNodes[0], c);
assert.equal(addedNodes[1], d);
assert.equal(removedNodes.length, 2);
// The ordering of the removed nodes is different in IE11.
if (removedNodes[0] === a) {
assert.equal(removedNodes[1], b);
} else {
assert.equal(removedNodes[0], b);
assert.equal(removedNodes[1], a);
}
mo.disconnect();
done();
});
div.innerHTML = '<a></a><b></b>';
var a = div.firstChild;
var b = div.lastChild;
mo.observe(div, {
childList: true
});
div.innerHTML = '<c></c><d></d>';
var c = div.firstChild;
var d = div.lastChild;
});
test('removedNodes siblings', function(done) {
if (!window.MutationObserver) {
done();
return;
}
div = document.body.appendChild(document.createElement('div'));
var mo = new MutationObserver(function(records, observer) {
mergeRecords(records);
assert.equal(records.length, 1);
assert.equal(records[0].type, 'childList');
assert.equal(removedNodes.length, 1);
assert.equal(records[0].previousSibling, a);
assert.equal(records[0].nextSibling, c);
mo.disconnect();
done();
});
div.innerHTML = '<a></a><b></b><c></c>';
var a = div.firstChild;
var b = a.nextSibling;
var c = div.lastChild;
mo.observe(div, {
childList: true
});
div.removeChild(b);
});
test('observe document', function(done) {
if (!window.MutationObserver) {
done();
return;
}
var mo = new MutationObserver(function(records, observer) {
assert.equal(this, mo);
assert.equal(observer, mo);
assert.equal(records[0].type, 'attributes');
assert.equal(records[0].target, wrap(document).body);
mo.disconnect();
done();
});
mo.observe(document, {
attributes: true,
subtree: true
});
wrap(document).body.setAttribute('a', newValue());
});
test('observe document.body', function(done) {
if (!window.MutationObserver) {
done();
return;
}
var mo = new MutationObserver(function(records, observer) {
assert.equal(this, mo);
assert.equal(observer, mo);
assert.equal(records[0].type, 'attributes');
assert.equal(records[0].target, wrap(document).body);
mo.disconnect();
done();
});
mo.observe(document.body, {
attributes: true
});
wrap(document.body).setAttribute('a', newValue());
});
test('observe document.head', function(done) {
if (!window.MutationObserver) {
done();
return;
}
var mo = new MutationObserver(function(records, observer) {
assert.equal(this, mo);
assert.equal(observer, mo);
assert.equal(records[0].type, 'attributes');
assert.equal(records[0].target, wrap(document).head);
mo.disconnect();
done();
});
mo.observe(document.head, {
attributes: true
});
wrap(document.head).setAttribute('a', newValue());
});
test('observe text node', function(done) {
if (!window.MutationObserver) {
done();
return;
}
div = document.body.appendChild(document.createElement('div'));
var a = document.createTextNode('');
div.appendChild(a);
var mo = new MutationObserver(function(records, observer) {
mergeRecords(records);
assert.equal(this, mo);
assert.equal(observer, mo);
assert.equal(records[0].type, 'childList');
assert.equal(records[0].target, div);
// IE11 is broken and reports the text node being removed twice.
if (!/Trident/.test(navigator.userAgent))
assert.equal(removedNodes.length, 1);
assert.equal(removedNodes[0], a);
done();
});
mo.observe(div, {childList: true});
div.removeChild(a);
});
});
| mit |
sboulema/CodeNav | CodeNav.Shared/Mappers/MethodMapper.cs | 7772 | using CodeNav.Helpers;
using CodeNav.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.VisualStudio.Imaging;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using VisualBasicSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax;
namespace CodeNav.Mappers
{
public static class MethodMapper
{
public static CodeItem MapMethod(MethodDeclarationSyntax member, ICodeViewUserControl control, SemanticModel semanticModel)
{
return MapMethod(member, member.Identifier, member.Modifiers, member.Body, member.ReturnType as ITypeSymbol, member.ParameterList,
CodeItemKindEnum.Method, control, semanticModel);
}
public static CodeItem MapMethod(LocalFunctionStatementSyntax member, ICodeViewUserControl control, SemanticModel semanticModel)
{
return MapMethod(member, member.Identifier, member.Modifiers, member.Body, member.ReturnType as ITypeSymbol, member.ParameterList,
CodeItemKindEnum.LocalFunction, control, semanticModel);
}
private static CodeItem MapMethod(SyntaxNode node, SyntaxToken identifier,
SyntaxTokenList modifiers, BlockSyntax body, ITypeSymbol returnType,
ParameterListSyntax parameterList, CodeItemKindEnum kind,
ICodeViewUserControl control, SemanticModel semanticModel)
{
if (node == null)
{
return null;
}
CodeItem item;
var statementsCodeItems = StatementMapper.MapStatement(body, control, semanticModel);
VisibilityHelper.SetCodeItemVisibility(statementsCodeItems);
if (statementsCodeItems.Any(statement => statement.IsVisible == Visibility.Visible))
{
// Map method as item containing statements
item = BaseMapper.MapBase<CodeClassItem>(node, identifier,modifiers, control, semanticModel);
((CodeClassItem)item).Members.AddRange(statementsCodeItems);
((CodeClassItem)item).BorderColor = Colors.DarkGray;
}
else
{
// Map method as single item
item = BaseMapper.MapBase<CodeFunctionItem>(node, identifier, modifiers, control, semanticModel);
((CodeFunctionItem)item).Type = TypeMapper.Map(returnType);
((CodeFunctionItem)item).Parameters = ParameterMapper.MapParameters(parameterList);
item.Tooltip = TooltipMapper.Map(item.Access, ((CodeFunctionItem)item).Type, item.Name, parameterList);
}
item.Id = IdMapper.MapId(item.FullName, parameterList);
item.Kind = kind;
item.Moniker = IconMapper.MapMoniker(item.Kind, item.Access);
if (TriviaSummaryMapper.HasSummary(node) && SettingsHelper.UseXMLComments)
{
item.Tooltip = TriviaSummaryMapper.Map(node);
}
return item;
}
public static CodeItem MapMethod(VisualBasicSyntax.MethodStatementSyntax member, ICodeViewUserControl control, SemanticModel semanticModel)
{
if (member == null) return null;
var item = BaseMapper.MapBase<CodeFunctionItem>(member, member.Identifier, member.Modifiers, control, semanticModel);
item.Id = IdMapper.MapId(item.FullName, member.ParameterList, semanticModel);
item.Kind = CodeItemKindEnum.Method;
item.Moniker = IconMapper.MapMoniker(item.Kind, item.Access);
if (TriviaSummaryMapper.HasSummary(member) && SettingsHelper.UseXMLComments)
{
item.Tooltip = TriviaSummaryMapper.Map(member);
}
return item;
}
public static CodeItem MapMethod(VisualBasicSyntax.MethodBlockSyntax member, ICodeViewUserControl control, SemanticModel semanticModel)
{
if (member == null) return null;
CodeItem item;
var statementsCodeItems = StatementMapper.MapStatement(member.Statements, control, semanticModel);
VisibilityHelper.SetCodeItemVisibility(statementsCodeItems);
if (statementsCodeItems.Any(statement => statement.IsVisible == Visibility.Visible))
{
// Map method as item containing statements
item = BaseMapper.MapBase<CodeClassItem>(member, member.SubOrFunctionStatement.Identifier,
member.SubOrFunctionStatement.Modifiers, control, semanticModel);
((CodeClassItem)item).Members.AddRange(statementsCodeItems);
((CodeClassItem)item).BorderColor = Colors.DarkGray;
}
else
{
// Map method as single item
item = BaseMapper.MapBase<CodeFunctionItem>(member, member.SubOrFunctionStatement.Identifier,
member.SubOrFunctionStatement.Modifiers, control, semanticModel);
var symbol = SymbolHelper.GetSymbol<IMethodSymbol>(semanticModel, member);
((CodeFunctionItem)item).Type = TypeMapper.Map(symbol?.ReturnType);
((CodeFunctionItem)item).Parameters = ParameterMapper.MapParameters(member.SubOrFunctionStatement.ParameterList, semanticModel);
item.Tooltip = TooltipMapper.Map(item.Access, ((CodeFunctionItem)item).Type, item.Name,
member.SubOrFunctionStatement.ParameterList, semanticModel);
}
item.Id = IdMapper.MapId(item.FullName, member.SubOrFunctionStatement.ParameterList, semanticModel);
item.Kind = CodeItemKindEnum.Method;
item.Moniker = IconMapper.MapMoniker(item.Kind, item.Access);
if (TriviaSummaryMapper.HasSummary(member) && SettingsHelper.UseXMLComments)
{
item.Tooltip = TriviaSummaryMapper.Map(member);
}
return item;
}
public static CodeItem MapConstructor(VisualBasicSyntax.ConstructorBlockSyntax member, ICodeViewUserControl control, SemanticModel semanticModel)
{
if (member == null) return null;
var item = BaseMapper.MapBase<CodeFunctionItem>(member, member.SubNewStatement.NewKeyword, member.SubNewStatement.Modifiers, control, semanticModel);
item.Parameters = ParameterMapper.MapParameters(member.SubNewStatement.ParameterList, semanticModel);
item.Tooltip = TooltipMapper.Map(item.Access, item.Type, item.Name, member.SubNewStatement.ParameterList, semanticModel);
item.Id = IdMapper.MapId(member.SubNewStatement.NewKeyword, member.SubNewStatement.ParameterList, semanticModel);
item.Kind = CodeItemKindEnum.Constructor;
item.Moniker = IconMapper.MapMoniker(item.Kind, item.Access);
item.OverlayMoniker = KnownMonikers.Add;
return item;
}
public static CodeItem MapConstructor(ConstructorDeclarationSyntax member, ICodeViewUserControl control, SemanticModel semanticModel)
{
if (member == null) return null;
var item = BaseMapper.MapBase<CodeFunctionItem>(member, member.Identifier, member.Modifiers, control, semanticModel);
item.Parameters = ParameterMapper.MapParameters(member.ParameterList);
item.Tooltip = TooltipMapper.Map(item.Access, item.Type, item.Name, member.ParameterList);
item.Id = IdMapper.MapId(member.Identifier, member.ParameterList);
item.Kind = CodeItemKindEnum.Constructor;
item.Moniker = IconMapper.MapMoniker(item.Kind, item.Access);
item.OverlayMoniker = KnownMonikers.Add;
return item;
}
}
}
| mit |
sabarjp/VictusLudus | victusludus/src/com/teamderpy/victusludus/gui/eventhandler/TooltipHandler.java | 3801 | package com.teamderpy.victusludus.gui.eventhandler;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.EventListener;
import java.util.EventObject;
import com.badlogic.gdx.Gdx;
import com.teamderpy.victusludus.VictusLudusGame;
import com.teamderpy.victusludus.gui.eventhandler.event.TooltipEvent;
/**
* The Class TooltipHandler.
*/
public class TooltipHandler extends AbstractHandler{
/** The name. */
private static String name ="TOOLTIP_HANDLER";
/** The listener queue. */
private Deque<TooltipListener> listenerQueue;
/** The register queue. */
private Deque<TooltipListener> registerQueue;
/** The unregister queue. */
private Deque<TooltipListener> unregisterQueue;
/**
* Instantiates a new tooltip handler.
*/
public TooltipHandler(){
this.eventCounter = 0L;
this.listenerCount = 0L;
this.listenerQueue = new ArrayDeque<TooltipListener>();
this.registerQueue = new ArrayDeque<TooltipListener>();
this.unregisterQueue = new ArrayDeque<TooltipListener>();
}
/* signal all listeners with an event */
/* (non-Javadoc)
* @see com.teamderpy.victusludus.gui.eventhandler.AbstractHandler#signalAllNow(java.util.EventObject)
*/
@Override
public void signalAllNow(final EventObject e){
TooltipEvent evt = (TooltipEvent) e;
for(TooltipListener l: this.listenerQueue){
if(VictusLudusGame.engine.IS_DEBUGGING){
Gdx.app.log("info", "SIGNAL " + TooltipHandler.name + ": " + evt + " -> " + l);
}
if(l.onChangeTooltip(evt)) break;
}
}
/* registers listeners at the next opportunity */
/* (non-Javadoc)
* @see com.teamderpy.victusludus.gui.eventhandler.AbstractHandler#registerPlease(java.util.EventListener)
*/
@Override
public void registerPlease(final EventListener l){
this.registerQueue.add((TooltipListener) l);
}
/* unregisters listeners at the next opportunity */
/* (non-Javadoc)
* @see com.teamderpy.victusludus.gui.eventhandler.AbstractHandler#unregisterPlease(java.util.EventListener)
*/
@Override
public void unregisterPlease(final EventListener l){
this.unregisterQueue.add((TooltipListener) l);
}
/* (non-Javadoc)
* @see com.teamderpy.victusludus.gui.eventhandler.AbstractHandler#registerAllNow()
*/
@Override
public void registerAllNow() {
/* register new objects */
while(!this.registerQueue.isEmpty()){
TooltipListener l = this.registerQueue.removeFirst();
if(!this.listenerQueue.contains(l)){
if(this.listenerQueue.add(l)) {
this.listenerCount++;
}
if(VictusLudusGame.engine.IS_DEBUGGING) {
Gdx.app.log("info", "REGISTER " + TooltipHandler.name + ": " + l);
}
}
}
}
/* (non-Javadoc)
* @see com.teamderpy.victusludus.gui.eventhandler.AbstractHandler#unregisterAllNow()
*/
@Override
public void unregisterAllNow() {
/* unregister old objects */
while(!this.unregisterQueue.isEmpty()){
TooltipListener l = this.unregisterQueue.removeFirst();
if(this.listenerQueue.contains(l)){
if(this.listenerQueue.remove(l)) {
this.listenerCount--;
}
if(VictusLudusGame.engine.IS_DEBUGGING) {
Gdx.app.log("info", "UNREGISTER " + TooltipHandler.name + ": " + l);
}
}
}
}
/* (non-Javadoc)
* @see com.teamderpy.victusludus.gui.eventhandler.AbstractHandler#getEventCounter()
*/
@Override
public long getEventCounter() {
return this.eventCounter;
}
/* (non-Javadoc)
* @see com.teamderpy.victusludus.gui.eventhandler.AbstractHandler#getListenerCount()
*/
@Override
public long getListenerCount() {
return this.listenerCount;
}
@Override
public String getListenerList() {
StringBuilder buf = new StringBuilder();
for(EventListener l:this.listenerQueue){
buf.append(this.getClass() + " " + l.getClass() + ":" + l + "\n");
}
return buf.toString();
}
}
| mit |
shageman/rails_container_and_engines | config/application.rb | 2732 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module RailsContainerAndEngines
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
| mit |
kalibao/kalibao-framework | kalibao/common/models/cmsPage/CmsPageI18n.php | 3097 | <?php
/**
* @copyright Copyright (c) 2015 Kévin Walter <[email protected]> - Kalibao
* @license https://github.com/kalibao/kalibao-framework/blob/master/LICENSE
*/
namespace kalibao\common\models\cmsPage;
use Yii;
use kalibao\common\models\language\Language;
/**
* This is the model class for table "cms_page_i18n".
*
* @property integer $cms_page_id
* @property string $i18n_id
* @property string $title
* @property string $slug
* @property string $html_title
* @property string $html_description
* @property string $html_keywords
*
* @property CmsPage $cmsPage
* @property Language $i18n
*
* @package kalibao\common\models\cmsPage
* @version 1.0
* @author Kevin Walter <[email protected]>
*/
class CmsPageI18n extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'cms_page_i18n';
}
/**
* @inheritdoc
*/
public function scenarios()
{
return [
'insert' => [
'title', 'slug', 'html_title', 'html_description', 'html_keywords'
],
'update' => [
'title', 'slug', 'html_title', 'html_description', 'html_keywords'
],
'translate' => [
'title', 'slug', 'html_title', 'html_description', 'html_keywords'
],
'beforeInsert' => [
'title', 'slug', 'html_title', 'html_description', 'html_keywords'
]
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['cms_page_id', 'i18n_id'], 'required', 'on' => ['insert', 'update', 'translate']],
[['cms_page_id'], 'integer'],
[['title', 'slug'], 'required'],
[['html_description', 'html_keywords'], 'string'],
[['i18n_id'], 'string', 'max' => 16],
[['title', 'slug', 'html_title'], 'string', 'max' => 255],
[['i18n_id', 'slug'], 'unique', 'targetAttribute' => ['i18n_id', 'slug'], 'message' => Yii::t('kalibao', 'The combination of I18n ID and Slug has already been taken.')]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'cms_page_id' => Yii::t('kalibao.backend','Cms Page ID'),
'i18n_id' => Yii::t('kalibao.backend','I18n ID'),
'title' => Yii::t('kalibao','model:title'),
'slug' => Yii::t('kalibao','cms_page_i18n:slug'),
'html_title' => Yii::t('kalibao','cms_page_i18n:html_title'),
'html_description' => Yii::t('kalibao','cms_page_i18n:html_description'),
'html_keywords' => Yii::t('kalibao','cms_page_i18n:html_keywords'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsPage()
{
return $this->hasOne(CmsPage::className(), ['id' => 'cms_page_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getI18n()
{
return $this->hasOne(Language::className(), ['id' => 'i18n_id']);
}
}
| mit |
Verasoft/EF.Tracking | src/Verasoft.EF.Tracking/Properties/AssemblyInfo.cs | 1502 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Verasoft.EF")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Verasoft.Tools")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5d0557fc-d3f3-4d7e-a102-4f55f24c130a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("Verasoft.EF.Tracking.Identity")]
| mit |
gfoidl/Yeppp.net | source/Yeppp.net/CoreExtensions/Min.cs | 18163 | namespace System
{
public static class CoreExtensions_Min
{
#region int
/// <summary>Computes the minimum of signed 32-bit integer array elements.</summary>
/// <exception cref="System.NullReferenceException">If vArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If vArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative or length is zero.</exception>
/// <exception cref="System.IndexOutOfRangeException">If vOffset is negative, vOffset + length exceeds the length of vArray, or length is negative.</exception>
public static int Min(this int[] xArray)
{
return Yeppp.Core.Min_V32s_S32s(xArray, 0, xArray.Length);
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of corresponding elements in two signed 32-bit integer arrays.</summary>
/// <exception cref="System.NullReferenceException">If xArray, yArray or minimumArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray, yArray or minimumArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, yOffset is negative, yOffset + length exceeds the length of yArray, minimumOffset is negative, minimumOffset + length exceeds the length of minimumArray, or length is negative.</exception>
public static int[] MinPairwise(this int[] xArray, int[] yArray)
{
int[] minimumArray = new int[xArray.Length];
Yeppp.Core.Min_V32sV32s_V32s(xArray, 0, yArray, 0, minimumArray, 0, minimumArray.Length);
return minimumArray;
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of signed 32-bit integer array elements and a constant.</summary>
/// <exception cref="System.NullReferenceException">If xArray or minimumArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray or minimumArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, minimumOffset is negative, minimumOffset + length exceeds the length of minimumArray, or length is negative.</exception>
public static int[] MinPairwise(this int[] xArray, int c)
{
int[] minimumArray = new int[xArray.Length];
Yeppp.Core.Min_V32sS32s_V32s(xArray, 0, c, minimumArray, 0, minimumArray.Length);
return minimumArray;
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of corresponding elements in two signed 32-bit integer arrays and writes the result to the first array.</summary>
/// <exception cref="System.NullReferenceException">If xArray or yArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray or yArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, yOffset is negative, yOffset + length exceeds the length of yArray, or length is negative.</exception>
public static void MinAndReplace(this int[] xArray, int[] yArray)
{
Yeppp.Core.Min_IV32sV32s_IV32s(xArray, 0, yArray, 0, xArray.Length);
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of signed 32-bit integer array elements and a constant and writes the result to the same array.</summary>
/// <exception cref="System.NullReferenceException">If xArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, or length is negative.</exception>
public static void MinPairwiseAndReplace(this int[] xArray, int c)
{
Yeppp.Core.Min_IV32sS32s_IV32s(xArray, 0, c, xArray.Length);
}
#endregion
//---------------------------------------------------------------------
#region long
/// <summary>Computes the minimum of signed 64-bit integer array elements.</summary>
/// <exception cref="System.NullReferenceException">If vArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If vArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative or length is zero.</exception>
/// <exception cref="System.IndexOutOfRangeException">If vOffset is negative, vOffset + length exceeds the length of vArray, or length is negative.</exception>
public static long Min(this long[] xArray)
{
return Yeppp.Core.Min_V64s_S64s(xArray, 0, xArray.Length);
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of corresponding elements in two signed 64-bit integer arrays.</summary>
/// <exception cref="System.NullReferenceException">If xArray, yArray or minimumArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray, yArray or minimumArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, yOffset is negative, yOffset + length exceeds the length of yArray, minimumOffset is negative, minimumOffset + length exceeds the length of minimumArray, or length is negative.</exception>
public static long[] MinPairwise(this long[] xArray, int[] yArray)
{
long[] minimumArray = new long[xArray.Length];
Yeppp.Core.Min_V64sV32s_V64s(xArray, 0, yArray, 0, minimumArray, 0, minimumArray.Length);
return minimumArray;
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of signed 64-bit integer array elements and a constant.</summary>
/// <exception cref="System.NullReferenceException">If xArray or minimumArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray or minimumArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, minimumOffset is negative, minimumOffset + length exceeds the length of minimumArray, or length is negative.</exception>
public static long[] MinPairwise(this long[] xArray, int c)
{
long[] minimumArray = new long[xArray.Length];
Yeppp.Core.Min_V64sS32s_V64s(xArray, 0, c, minimumArray, 0, minimumArray.Length);
return minimumArray;
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of corresponding elements in two signed 64-bit integer arrays and writes the result to the first array.</summary>
/// <exception cref="System.NullReferenceException">If xArray or yArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray or yArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, yOffset is negative, yOffset + length exceeds the length of yArray, or length is negative.</exception>
public static void MinAndReplace(this long[] xArray, int[] yArray)
{
Yeppp.Core.Min_IV64sV32s_IV64s(xArray, 0, yArray, 0, xArray.Length);
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of signed 64-bit integer array elements and a constant and writes the result to the same array.</summary>
/// <exception cref="System.NullReferenceException">If xArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, or length is negative.</exception>
public static void MinPairwiseAndReplace(this long[] xArray, int c)
{
Yeppp.Core.Min_IV64sS32s_IV64s(xArray, 0, c, xArray.Length);
}
#endregion
//---------------------------------------------------------------------
#region float
/// <summary>Computes the minimum of single precision (32-bit) floating-point array elements.</summary>
/// <exception cref="System.NullReferenceException">If vArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If vArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative or length is zero.</exception>
/// <exception cref="System.IndexOutOfRangeException">If vOffset is negative, vOffset + length exceeds the length of vArray, or length is negative.</exception>
public static float Min(this float[] xArray)
{
return Yeppp.Core.Min_V32f_S32f(xArray, 0, xArray.Length);
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of corresponding elements in two single precision (32-bit) floating-point arrays.</summary>
/// <exception cref="System.NullReferenceException">If xArray, yArray or minimumArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray, yArray or minimumArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, yOffset is negative, yOffset + length exceeds the length of yArray, minimumOffset is negative, minimumOffset + length exceeds the length of minimumArray, or length is negative.</exception>
public static float[] MinPairwise(this float[] xArray, float[] yArray)
{
float[] minimumArray = new float[xArray.Length];
Yeppp.Core.Min_V32fV32f_V32f(xArray, 0, yArray, 0, minimumArray, 0, minimumArray.Length);
return minimumArray;
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of single precision (32-bit) floating-point array elements and a constant.</summary>
/// <exception cref="System.NullReferenceException">If xArray or minimumArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray or minimumArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, minimumOffset is negative, minimumOffset + length exceeds the length of minimumArray, or length is negative.</exception>
public static float[] MinPairwise(this float[] xArray, float c)
{
float[] minimumArray = new float[xArray.Length];
Yeppp.Core.Min_V32fS32f_V32f(xArray, 0, c, minimumArray, 0, minimumArray.Length);
return minimumArray;
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of corresponding elements in two single precision (32-bit) floating-point arrays and writes the result to the first array.</summary>
/// <exception cref="System.NullReferenceException">If xArray or yArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray or yArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, yOffset is negative, yOffset + length exceeds the length of yArray, or length is negative.</exception>
public static void MinAndReplace(this float[] xArray, float[] yArray)
{
Yeppp.Core.Min_IV32fV32f_IV32f(xArray, 0, yArray, 0, xArray.Length);
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of single precision (32-bit) floating-point array elements and a constant and writes the result to the same array.</summary>
/// <exception cref="System.NullReferenceException">If xArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, or length is negative.</exception>
public static void MinPairwiseAndReplace(this float[] xArray, float c)
{
Yeppp.Core.Min_IV32fS32f_IV32f(xArray, 0, c, xArray.Length);
}
#endregion
//---------------------------------------------------------------------
#region double
/// <summary>Computes the minimum of double precision (64-bit) floating-point array elements.</summary>
/// <exception cref="System.NullReferenceException">If vArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If vArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative or length is zero.</exception>
/// <exception cref="System.IndexOutOfRangeException">If vOffset is negative, vOffset + length exceeds the length of vArray, or length is negative.</exception>
public static double Min(this double[] xArray)
{
return Yeppp.Core.Min_V64f_S64f(xArray, 0, xArray.Length);
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of corresponding elements in two double precision (64-bit) floating-point arrays.</summary>
/// <exception cref="System.NullReferenceException">If xArray, yArray or minimumArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray, yArray or minimumArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, yOffset is negative, yOffset + length exceeds the length of yArray, minimumOffset is negative, minimumOffset + length exceeds the length of minimumArray, or length is negative.</exception>
public static double[] MinPairwise(this double[] xArray, double[] yArray)
{
double[] minimumArray = new double[xArray.Length];
Yeppp.Core.Min_V64fV64f_V64f(xArray, 0, yArray, 0, minimumArray, 0, minimumArray.Length);
return minimumArray;
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of double precision (64-bit) floating-point array elements and a constant.</summary>
/// <exception cref="System.NullReferenceException">If xArray or minimumArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray or minimumArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, minimumOffset is negative, minimumOffset + length exceeds the length of minimumArray, or length is negative.</exception>
public static double[] MinPairwise(this double[] xArray, double c)
{
double[] minimumArray = new double[xArray.Length];
Yeppp.Core.Min_V64fS64f_V64f(xArray, 0, c, minimumArray, 0, minimumArray.Length);
return minimumArray;
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of corresponding elements in two double precision (64-bit) floating-point arrays and writes the result to the first array.</summary>
/// <exception cref="System.NullReferenceException">If xArray or yArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray or yArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, yOffset is negative, yOffset + length exceeds the length of yArray, or length is negative.</exception>
public static void MinAndReplace(this double[] xArray, double[] yArray)
{
Yeppp.Core.Min_IV64fV64f_IV64f(xArray, 0, yArray, 0, xArray.Length);
}
//---------------------------------------------------------------------
/// <summary>Computes pairwise minima of single precision (32-bit) floating-point array elements and a constant and writes the result to the same array.</summary>
/// <exception cref="System.NullReferenceException">If xArray is null.</exception>
/// <exception cref="System.DataMisalignedException">If xArray is not naturally aligned.</exception>
/// <exception cref="System.ArgumentException">If length is negative.</exception>
/// <exception cref="System.IndexOutOfRangeException">If xOffset is negative, xOffset + length exceeds the length of xArray, or length is negative.</exception>
public static void MinPairwiseAndReplace(this double[] xArray, double c)
{
Yeppp.Core.Min_IV64fS64f_IV64f(xArray, 0, c, xArray.Length);
}
#endregion
}
} | mit |
matthieudelaro/easycrypt | cryptage.cpp | 10943 | #include "cryptage.h"
#include <cmath>
#include <iostream>
bool Cryptage::crypter(Image &image, std::string const& texte, unsigned int methode)
{
//Définition de l'emplacement de lecture de l'image
unsigned int x = 0, y = 0, couleur = ROUGE;
//on écrit l'en-tête
//1 on marque l'image comme étant cryptée : on écrit de façon brute les bytes correspondants à "secret", dans l'ordre suivant :
// de gauche à droite, de bas en haut, rouge puis vert puis bleu
std::vector<bool> bytesSecret = stringToBits("secret");
unsigned int bitsEcrits = 0;
while(bitsEcrits < bytesSecret.size())
{
// image[y][x][couleur] = bytesSecret[bitsEcrits];
// std::cerr << "Modif bit poids faible ("<< bytesSecret[bitsEcrits] << ") : " << (int)image[y][x][couleur] << " => ";
setBitPoidsFaible(image[y][x][couleur], bytesSecret[bitsEcrits]);
// std::cerr << (unsigned int)image[y][x][couleur] << std::endl;
avancerPixel(image, x, y, couleur, ROUGE);
bitsEcrits++;
}
//2 on marque la méthode de cryptage
std::vector<bool> bytesMethode = uintToBits(methode);
bitsEcrits = 0;
while(bitsEcrits < bytesMethode.size())
{
// image[y][x][couleur] = bytesMethode[bitsEcrits];
setBitPoidsFaible(image[y][x][couleur], bytesMethode[bitsEcrits]);
avancerPixel(image, x, y, couleur, ROUGE);
bitsEcrits++;
}
//3 on marque le nombre de bits à lire pour obtenir le texte
// std::cerr << "Cryptage : texte = " << texte << std::endl;
std::vector<bool> bytesTexte = stringToBits(texte);
std::vector<bool> bytesTailleTexte = uintToBits(bytesTexte.size());
bitsEcrits = 0;
// std::cerr << "La taille du texte contient " << bytesTailleTexte.size() << "bits.\n";
while(bitsEcrits < bytesTailleTexte.size())
{
// image[y][x][couleur] = bytesTailleTexte[bitsEcrits];
setBitPoidsFaible(image[y][x][couleur], bytesTailleTexte[bitsEcrits]);
avancerPixel(image, x, y, couleur, ROUGE);
bitsEcrits++;
}
//on écrit le texte
switch(methode)
{
case BOOLEEN_BITS_FAIBLES_VERTS :
bitsEcrits = 0;
couleur = VERT;
// std::cerr << "Le texte contient " << bytesTexte.size() << "bits.\n";
/*for(int bitsAecrire = bytesTexte.size()-1; bitsAecrire >= 0; bitsAecrire--)
{
setBitPoidsFaible(image[y][x][couleur], bytesTexte[bitsAecrire]);
avancerPixel(image, x, y, couleur, VERT);
}
bitsEcrits = 0;*/
// std::cerr << "Le texte contient " << bytesTexte.size() << "bits.\n";
while(bitsEcrits < bytesTexte.size())
{
// image[y][x][couleur] = bytesTexte[bitsEcrits];
couleur = VERT;
setBitPoidsFaible(image[y][x][couleur], bytesTexte[bitsEcrits]);
avancerPixel(image, x, y, couleur, VERT);
bitsEcrits++;
}
break;
default :
return false;
break;
}
return true;
}
bool Cryptage::decrypter(Image const& image, std::string &texte)
{
//Définition de l'emplacement de lecture de l'image
unsigned int x = 0, y = 0, couleur = ROUGE;
//On lit l'en-tête
//1 on vérifie que l'image est cryptée
//on lit 48 bits sur les bits de poids faibles rouges des 48 premiers pixels,
//en espérant trouver le texte "secret" (8bits * 6lettres = 48)
std::vector<bool> bitsSecret;
for(unsigned int bitsLus = 0; bitsLus < 48; bitsLus++)
{
bitsSecret.push_back(image[y][x][couleur]%2);
avancerPixel(image, x, y, couleur, ROUGE);
}
std::string texteSecret;
bitsToString(bitsSecret, texteSecret);
// std::cerr << "texteSecret = " << texteSecret << std::endl;
if((texteSecret == "secret")==false)//si l'image n'est pas cryptée, alors on arrête
return false;
//2 on lit la méthode de cryptage
std::vector<bool> bitsMethode;
for(unsigned int bitsLus = 0; bitsLus < 32/*sizeof(unsigned int)*/; bitsLus++)
{
bitsMethode.push_back(image[y][x][couleur]%2);
avancerPixel(image, x, y, couleur, ROUGE);
}
unsigned int methode = bitsToUint(bitsMethode);
//3 on lit le nombre de pixels à lire pour obtenir le texte
std::vector<bool> bitsTailleTexte;
for(unsigned int bitsLus = 0; bitsLus < 32/*sizeof(unsigned int)*/; bitsLus++)
{
bitsTailleTexte.push_back(image[y][x][couleur]%2);
avancerPixel(image, x, y, couleur, ROUGE);
}
unsigned int tailleTexte = bitsToUint(bitsTailleTexte);
// std::cerr << "il y a " << tailleTexte << "bits à lire.\n";
//on lit le texte
std::vector<bool> bitsTexte;
switch(methode)
{
case BOOLEEN_BITS_FAIBLES_VERTS :
couleur = VERT;
for(unsigned int bitsLus = 0; bitsLus < tailleTexte; bitsLus++)
{
bitsTexte.push_back(image[y][x][couleur]%2);
avancerPixel(image, x, y, couleur, VERT);
}
bitsToString(bitsTexte, texte);
// std::cerr << "texte = " << texte << std::endl;
break;
default :
return false;
break;
}
return true;
}
unsigned int Cryptage::bitsToUint(std::vector<bool> const& bits)
{
unsigned int out = 0;
unsigned int puissanceDe2 = 1;
for(unsigned int i = 0; i < bits.size(); i++)
{
out += bits[i]*puissanceDe2;
puissanceDe2 *= 2;
}
return out;
}
void Cryptage::setBitPoidsFaible(unsigned char &variable, bool valeur)
{
if(variable%2 == 0)
{
//variable += valeur;
if(valeur)
{
variable++;
}
}
else if(!valeur)//on sait que le bit de poids faible vaut 1. Donc si on voulait 0, alors
{
variable--;
}
}
std::vector<bool> Cryptage::uintToBits(unsigned int number)
{
std::vector<bool> out;
// std::cerr << "Nouvelle lettre : " << lettre << ", soit " << int(lettre) << "\n";
for(unsigned int j = 0; j < 8*sizeof(number); j++)
{
//int power = 7-j;
// int valeurBit = lettre%int(pow(2, j)+1);
int valeurBit = number%2;
// std::cerr << "lettre%2 = " << number%2 << " et lettre = " << number << "\n";
// std::cerr << "On ajoute un bit : " << valeurBit << " grâce à " << pow(2, j) << "\n";
// lettre -= valeurBit;
// lettre >> 1;
number = number >> 1;
out.push_back((bool) valeurBit);
}
// for(unsigned int i = 0; i < out.size(); i++)
// {
// std::cerr << out[i];
// }
return out;
}
std::vector<bool> Cryptage::stringToBits(std::string const& string)
{
std::vector<bool> out;
//on va placer, dans out, les bits représentant les lettres.
//on met les lettres une par une
//et pour chaque lettre, on met les bits un par un
//en commençant par le bit de poids faible
for(unsigned int i = 0; i < string.size(); i++)
{
char lettre = string[i];
// std::cerr << "Nouvelle lettre : " << lettre << ", soit " << int(lettre) << "\n";
for(unsigned int j = 0; j < taillecaractere; j++)
{
//int power = 7-j;
// int valeurBit = lettre%int(pow(2, j)+1);
int valeurBit = lettre%2;
// std::cerr << "lettre%2 = " << lettre%2 << " et lettre = " << lettre << "\n";
// std::cerr << "On ajoute un bit : " << valeurBit << " grâce à " << pow(2, j) << "\n";
// lettre -= valeurBit;
// lettre >> 1;
lettre = lettre >> 1;
out.push_back((bool) valeurBit);
}
}
// std::cerr << "Resultat : ";
// for(unsigned int i = 0; i < out.size(); i++)
// {
// std::cerr << out[i];
// }
// std::cerr << "\n";
return out;
}
bool Cryptage::bitsToString(std::vector<bool> const& bytes, std::string &out, unsigned int nombreDeBitsAignorer)
{
if((bytes.size() - nombreDeBitsAignorer)%taillecaractere != 0)
return false;//le nombre de bytes ne correspond pas à des lettres
unsigned int i = nombreDeBitsAignorer;
// std::cerr << "Décryptage\n";
while(i < bytes.size())
{
char lettre = 0;
/*std::cerr << "Nouvelle lettre : ";
for(unsigned int j = 0; j < taillecaractere; j++)
{
std::cerr << bytes[i+j];
}
std::cerr << "\n"*/;
for(unsigned int j = 0; j < taillecaractere; j++)
{
//int power = 7-j;
lettre += bytes[i]*pow(2, j);
// std::cerr << "On ajoute un bit : " << bytes[i]*pow(2, j) << " grâce à " << pow(2, j) << "\n";
i++;
}
// std::cerr << "Lettre = " << lettre << " (" << int(lettre) << ")\n";
out += lettre;
}
return true;
}
bool Cryptage::avancerCouleur(Image const& bytes, unsigned int &x, unsigned int &y, unsigned int &couleur)
{
unsigned int nextX = x, nextY = y, nextCouleur = couleur;
if(couleur == BLEU)
{
nextCouleur = ROUGE;
if(x+1 < bytes[y].size())
{
nextX = x+1;
}
else
{
if(y+1 < bytes.size())
{
nextY = y+1;
nextX = 0;
}
else
{
return false;
}
}
}
else
{
nextCouleur = couleur+1;
}
if(nextY < bytes.size() && nextX < bytes[nextY].size())
{
y = nextY;
x = nextX;
couleur = nextCouleur;
return true;
}
else
{
return false;
}
}
bool Cryptage::avancerPixel(const Image &bytes, unsigned int &x, unsigned int &y, unsigned int &couleur, bool nextCouleur)
{
unsigned int nextX = x, nextY = y;
if(x+1 < bytes[y].size())
{
nextX = x+1;
}
else
{
if(y+1 < bytes.size())
{
nextY = y+1;
nextX = 0;
}
else
{
return false;
}
}
if(nextY < bytes.size() && nextX < bytes[nextY].size())
{
y = nextY;
x = nextX;
couleur = nextCouleur;
return true;
}
else
{
return false;
}
}
| mit |
cedced19/flydocument-encrypted | policies/auth.js | 236 | module.exports = function(req, res, next) {
var config = require('../configuration.json');
if (config.users.length == 0) {
next();
} else if (!req.isAuthenticated()) {
res.redirect('/login');
} else {
next();
}
};
| mit |
definitionstudio/linktv_platform | app/controllers/admin/external_contents_controller.rb | 1035 | class Admin::ExternalContentsController < Admin::AdminController
helper :images, :videos, :video_segments, :external_contents
def new
@external_content = ExternalContent.new params[:external_content]
render :json => {
:status => 'success',
:html => render_to_string(:layout => false)
}
end
def create
@external_content = ExternalContent.new params[:external_content]
provisional = params[:provisional] || nil
if (provisional)
valid = @external_content.valid?
else
valid = @external_content.save
end
unless valid
render :action => :new, :layout => false
return
end
flash[:notice] = "External content created." unless provisional
html = nil
if (params[:render_for] || nil) == 'external-content-table'
html = render_to_string :partial => 'admin/video_segments/content_row_table', :locals => {
:content => @external_content}
end
render :json => {
:status => 'success',
:html => html
}
end
end
| mit |
DragonSpark/Framework | DragonSpark/Compose/Model/Commands/CommandInstanceSelector.cs | 410 | using DragonSpark.Compose.Model.Selection;
using DragonSpark.Model.Commands;
using DragonSpark.Model.Selection;
namespace DragonSpark.Compose.Model.Commands;
public class CommandInstanceSelector<TIn, T> : Selector<TIn, ICommand<T>>
{
public CommandInstanceSelector(ISelect<TIn, ICommand<T>> subject) : base(subject) {}
public IAssign<TIn, T> ToAssignment() => new SelectedInstance<TIn, T>(Get().Get);
} | mit |
zeroonegit/Go | src/github.com/zeroonegit/basic-types/basic-types.go | 283 | package main
import (
"fmt"
"math/cmplx"
)
var (
ToBe bool = false
MaxInt uint64 = 1<<64 - 1
z complex128 = cmplx.Sqrt(-5 + 12i)
)
func main() {
const f = "%T(%v)\n"
fmt.Printf(f, ToBe, ToBe)
fmt.Printf(f, MaxInt, MaxInt)
fmt.Printf(f, z, z)
}
| mit |
NamelessCoder/numerolog | src/NotFoundException.php | 133 | <?php
namespace NamelessCoder\Numerolog;
/**
* Class NotFoundException
*/
class NotFoundException extends NumerologException {
}
| mit |
imammlubis/sipp_ci | application/views/perusahaan/bayartagihan.php | 22669 |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Pembayaran Tagihan
<!--small>dashboard & statistics</small-->
</h1>
</div>
<!-- END PAGE TITLE -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<a href="#">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Transaksi</span>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Pembayaran Tagihan</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<!--Modal 1-->
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Form Perusahaan</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal"
enctype="multipart/form-data" method="post">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Jumlah Piutang (IDR) </label>
<div class="col-md-9">
<input name="jumlah" id="jumlah" placeholder="Jumlah Piutang"
class="form-control" type="text" disabled="disabled">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Jumlah Piutang (USD) </label>
<div class="col-md-9">
<input name="jumlahusd" id="jumlahusd" placeholder="Jumlah Piutang"
class="form-control" type="text" disabled="disabled">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nominal Pembayaran (IDR)</label>
<div class="col-md-9">
<input name="nominal" id="nominal"
placeholder="Nominal Pembayaran (IDR)" class="form-control" type="number">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nominal Pembayaran (USD)</label>
<div class="col-md-9">
<input name="nominaldollar" id="nominaldollar"
placeholder="Nominal Pembayaran (USD)" class="form-control" type="number">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Foto / Scan Bukti Pembayaran</label>
<div class="col-md-9">
<input name="image" id="image" placeholder="Foto / Scan"
class="form-control" type="file">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Keterangan apabila keberatan atas tagihan</label>
<div class="col-md-9">
<textarea name="keterangan" id="keterangan"
placeholder="Keterangan apabila keberatan atas tagihan"
class="form-control" rows="5">
</textarea>
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->
<!--End Modal1-->
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<div class="mt-content-body">
<div class="row">
<div class="col-md-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-cogs font-green-sharp"></i>
<span class="caption-subject font-green-sharp bold uppercase">Form Pembayaran Tagihan</span>
</div>
<div class="tools">
<a href="javascript:;" class="collapse" data-original-title="" title="">
</a>
</div>
</div>
<div class="portlet-body">
<div id="sample_1_wrapper" class="dataTables_wrapper no-footer">
<div class="modal-body form">
<form action="<?php echo base_url('perusahaan/BayarTagihan/do_upload');?>"
id="form" class="form-horizontal" enctype="multipart/form-data" method="post">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Jumlah Piutang (IDR) </label>
<div class="col-md-9">
<input name="jumlah" id="jumlah" placeholder="Jumlah Piutang IDR"
value = "<?php echo $piutangidr?>"
class="form-control" type="text" disabled="disabled">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Jumlah Piutang (USD) </label>
<div class="col-md-9">
<input name="jumlahusd" id="jumlahusd" placeholder="Jumlah Piutang USD"
value = "<?php echo $piutangusd?>"
class="form-control" type="text" disabled="disabled">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nominal Pembayaran (IDR)</label>
<div class="col-md-9">
<input name="nominal" id="nominal"
placeholder="Nominal Pembayaran (IDR)"
value="0" class="form-control" type="number">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nominal Pembayaran (USD)</label>
<div class="col-md-9">
<input name="nominaldollar" id="nominaldollar"
placeholder="Nominal Pembayaran (USD)"
value="0"
class="form-control" type="number">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Foto / Scan Bukti Pembayaran</label>
<div class="col-md-9">
<input name="userfile" id="userfile" placeholder="Foto / Scan"
class="form-control" type="file">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Keterangan apabila keberatan atas tagihan</label>
<div class="col-md-9">
<textarea name="keterangan" id="keterangan"
placeholder="Keterangan apabila keberatan atas tagihan"
class="form-control" rows="5" data-value="">
</textarea>
<span class="help-block"></span>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" value="upload" class="btn btn-primary">Submit</button>
<!-- <input type="submit" value="upload" />-->
<!-- <button type="button" id="btnSave" class="btn btn-primary">Save</button>-->
<!-- <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>-->
</div>
</form>
</div>
<div class="row">
<div class="col-md-7 col-sm-12">
</div>
</div>
</div>
</div>
</div>
<!-- END EXAMPLE TABLE PORTLET-->
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
</div>
<script type="text/javascript">
$('#itemName').select2({
placeholder: '--Pilih Perusahaan--',
ajax: {
url: 'tagihanawal/search',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
// function of datatables
var table;
$(document).ready(function() {
//datatables
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('perusahaan/RiwayatTransaksi/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 0 ], //first column / numbering column
"orderable": true //set not orderable
},
],
});
});
function view_email(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('perusahaan/RiwayatTransaksi/ajax_view_email/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="company_id"]').val(data.company_id);
$('[name="email"]').val(data.email);
$('#modal_form2').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Email'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function edit_company(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('perusahaan/RiwayatTransaksi/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
$('[name="nama"]').val(data.company_name);
$('[name="tipetagihan"]').val(data.legal_type);
$('[name="provinsi"]').val(data.province);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Perusahaan'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
//var formData = new FormData($(this)[0]);
// var formData = new FormData( $("#modal_form")[0] );
if(save_method == 'add') {
url = "<?php echo site_url('perusahaan/RiwayatTransaksi/ajax_add')?>";
} else {
url = "<?php echo site_url('perusahaan/RiwayatTransaksi/ajax_update')?>";
}
$.each($('image'[0]).files, function(i, file){
data.append('image', file);
});
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
//data: formData,
data: $('#form').serialize(),
dataType: "JSON",
// contentType : false,
// processData : false,
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
function delete_company(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('perusahaan/RiwayatTransaksi/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
function add_person()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Bayar Tagihan'); // Set Title to Bootstrap modal title
$('#nominal').val(0);
$('#nominaldollar').val(0);
$('#keterangan').val('');
$.ajax({
url : "<?php echo site_url('perusahaan/RiwayatTransaksi/get_piutang/')?>",
type: "GET",
dataType: "JSON",
success: function(data)
{
$('#jumlah').val(data)
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
$.ajax({
url : "<?php echo site_url('perusahaan/RiwayatTransaksi/get_piutang_dollar/')?>",
type: "GET",
dataType: "JSON",
success: function(data2)
{
$('#jumlahusd').val(data2)
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax '.errorThrown);
}
});
}
</script> | mit |
splosch/cursorMe | assets/javascript/app.js | 6356 | /* globals $, Dropzone, ga */
$(function( Dropzone ) {
"use strict";
window._gaq = window._gaq || [];
var app = {},
SEL_PAGE = "#page",
SEL_CONTAINER = "#container",
SEL_POINTER = "input[type='radio'][name='cursortype']",
SEL_POINTER_IMG = "input[type='radio'][name='cursortype']:checked + label img",
SEL_IMG_THUMBS = "ul#coursored_imgs",
EVT_CLICK = "click touchend keyup",
SEL_TOGGLE_GA = "input[type='radio'][name='track']",
ACTION_EL = {
save: "#save_the_image",
reset: "#reset_background",
upload: "#upload_image"
};
app = {
dropzone: {},
fallbackPointerUrl: "assets/images/icons/hand1.png",
init: function () {
var dropzoneOptions = {
previewsContainer : false,
url : "/#",
clickable : [SEL_CONTAINER, ACTION_EL.upload]
};
this.page = $(SEL_PAGE);
this.canvas = $.cursorMe($(SEL_CONTAINER));
this.dropzone = new Dropzone(SEL_CONTAINER, dropzoneOptions);
this.updatePointer();
this.addEventHandlers();
},
addEventHandlers: function () {
// set background image if dropzone detects that a image was added to the canvas
this.dropzone.on("imagefullsize", function(file, image) {
this.canvas.setBackground(image);
}.bind(this));
// handle changing the current cursor
this.page.on("change", SEL_POINTER, function(event){
this.updatePointer();
}.bind(this));
// ask the cursorMe canvas to return the created image and handle it
this.page.on(EVT_CLICK, ACTION_EL.save, function(event){
this.canvas.getImage(this.handleCreatedImage);
}.bind(this));
// remove current image from the stage
this.page.on(EVT_CLICK, ACTION_EL.reset, function(event){
this.canvas.setBackground();
this.updatePointer();
}.bind(this));
this.page.on(EVT_CLICK, "[data-track-interaction]", function(event){
this.trackInteraction(event);
}.bind(this));
$("#toggle_ga_tracking").on("change", SEL_TOGGLE_GA, function(event){
this.toggleGoogleAnalyticsTracking($(event.currentTarget).is("[value=1]"));
}.bind(this));
},
/* Takes the currently selected pointer image and hands it over
* to the cursorMe Stage to update the cursor
*/
updatePointer: function () {
var pointerImgUrl = $(SEL_POINTER_IMG).attr("src") || this.fallbackPointerUrl,
pointerImg = new Image();
pointerImg.src = pointerImgUrl;
$(pointerImg).on("load", this.canvas.setPointer(pointerImg));
},
/* Once a new image has been created,
* handleCreatedImage(image) takes care of presenting the outcome to the user
* Creation of a thumbnail & allowing to save or delete the created images
*/
handleCreatedImage: function ( image ) {
var download_action = $("<a />"),
delete_action = $("<a />"),
newThumbnail = $("<li>").append($(image).attr({width: "150"}))
.addClass("fadeInDown animated");
download_action.attr({
class: "glyphicon glyphicon-save",
text: "Click to download as PNG Image to your computer",
download: "cursored_screen.png",
href: "#save_this_image",
target: "_blank",
"data-track-interaction" : '{"category":"image","action":"save","label":"save_to_file"}'
}).on("click keyup", function(){
// take the imgs data uri and put it in the links destination href to allow download
$(this).attr("href", $(this).parent().find("img").attr("src"));
});
delete_action.attr({
class: "glyphicon glyphicon-trash",
text: "Click to Delete this Image - you got plenty left anyways right?!",
href: "#remove_this_image",
"data-track-interaction" : '{"category":"thumb","action":"delete","label":"delete_thumb"}'
}).on(EVT_CLICK, function(event){
// remove the image from the savend images
$(this).parents("li").remove();
event.preventDefault();
});
newThumbnail.append(download_action)
.append(delete_action);
$(SEL_IMG_THUMBS).append(newThumbnail);
},
/* interaction tracking interface for google analytics
* is fired from interaction with `[data-track-interaction]` data-attribute flagged items
* the attributes value contains data required for genearating a tracking event
* see https://developers.google.com/analytics/devguides/ for API details
*/
trackInteraction: function (event) {
var tracking_options = { hitType : "event" },
ordered_trackables = ["category", "action", "label", "value"],
ga_option_map = {
"category" : "eventCategory", // Required.
"action" : "eventAction", // Required.
"label" : "eventLabel",
"value" : "eventValue"
},
is_valid_event,
data = JSON.parse($(event.target).closest("[data-track-interaction]").attr("data-track-interaction")),
current_entry;
/* as long as one `current_entry` is left,
* use the extracted data, and go through object keys order defined by ordered_trackables
* if any required data is missing - skip the rest since they depend on each other
*/
while(current_entry = ordered_trackables.shift()) {
if(data.hasOwnProperty(current_entry) && data[current_entry]) {
tracking_options[ga_option_map[current_entry]] = data[current_entry];
if (current_entry === "action") {
is_valid_event = true;
}
} else {
break;
}
}
if (is_valid_event && typeof ga === "function") {
ga("send", tracking_options);
}
return is_valid_event;
},
toggleGoogleAnalyticsTracking: function ( do_track ) {
if (do_track) {
window.my_ga.revert_optout();
} else {
window.my_ga.optout();
}
}
};
app.init();
}( Dropzone));
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.