code
stringlengths
2
1.05M
(function() { // Inheritence Key: // InteractiveMeter.js > Path.js > Base.js var InteractiveMeter = function (source, min, max) { // Path manager deals with JSON JHVH.Path.call(this, source); this.off_color = source.off_color; this.min = min || 0; this.max = max || 1000; // flag for blocking inputs this.animating = true; startAnimation.call(this); } function startAnimation () { this.current = 1; var tem = {t: 1}; var tl = new TimelineMax(); tl.to(tem, 0.8, { t:this.max, onUpdate:function(){ this.current = tem.t; }.bind(this) }); tl.to(tem, 0.8, { t:this.min, onUpdate:function(){ this.current = tem.t; }.bind(this), onComplete:function(){ this.animating = false; }.bind(this) }); } // inherits Path.js InteractiveMeter.prototype = Object.create(JHVH.Path.prototype); // over-writes the way paths get drawn, as opposed to Base.drawToContext, which just does on/off states InteractiveMeter.prototype.drawToContext = function (ctx) { this.convertPaths.apply(this, [this.parts]); // segments to on state for (var i = 0, l = this.parts.length; i < l; i++) { if (i < this.tempIndex) { ctx.fillStyle = this.parts[i].color; } else { ctx.fillStyle = this.off_color; } // reuse the converted paths ctx.fill(this.parts[i].p2D); } } /* ** To display the correct number of meter bars we need to get the ratio ** between current and max temps, and apply it to the meter parts array. */ InteractiveMeter.prototype.update = function (ctx, amount) { if (this.animating) { this.current = this.current / this.max; } else if (amount) { this.current = amount; } else { this.current = this.min / this.max; } var index = Math.round(this.parts.length * this.current); this.tempIndex = index; this.drawToContext(ctx); } if (!window.JHVH) window.JHVH = {}; window.JHVH.InteractiveMeter = InteractiveMeter; })();
angular.module('firebaseService', [ 'firebase' ]) // a simple utility to create references to Firebase paths .factory('firebaseRef', function(Firebase, FBURL) { function pathRef(args) { for(var i=0; i < args.length; i++) { if( typeof(args[i]) === 'object' ) { args[i] = pathRef(args[i]); } } return args.join('/'); } /** * @function * @name firebaseRef * @param {String|Array...} path * @return a Firebase instance */ // console.log( pathRef([FBURL].concat(Array.prototype.slice.call(arguments))) ); return function() { return new Firebase( pathRef([FBURL].concat(Array.prototype.slice.call(arguments))) ); }; }) // a simple utility to create $firebase objects from angularFire .service('syncData', function($firebase, firebaseRef) { /** * @function * @name syncData * @param {String|Array...} path * @param {int} [limit] * @return a Firebase instance */ return function(path, limit) { var ref = firebaseRef(path); if(limit) { ref = ref.limit(limit); } return $firebase(ref); }; });
'use strict'; var xhrRequest = function (url, type, key, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function () { callback(this.status, this.responseText); }; xhr.open(type, url); xhr.setRequestHeader('WEB-API-Key', key); xhr.send(); } // http://gis.stackexchange.com/questions/29239/calculate-bearing-between-two-decimal-gps-coordinates function radians(n) { return n * (Math.PI / 180); } function degrees(n) { return n * (180 / Math.PI); } function computeBearing(source, destination) { var startLat = radians(source.latitude), startLong = radians(source.longitude), endLat = radians(destination.latitude), endLong = radians(destination.longitude), dLong = endLong - startLong, dPhi = Math.log(Math.tan(endLat/2.0+Math.PI/4.0)/Math.tan(startLat/2.0+Math.PI/4.0)); if (Math.abs(dLong) > Math.PI){ if (dLong > 0.0) dLong = -(2.0 * Math.PI - dLong); else dLong = (2.0 * Math.PI + dLong); } return Math.round((degrees(Math.atan2(dLong, dPhi)) + 360.0) % 360.0); } function getNearestATMs() { navigator.geolocation.getCurrentPosition( function (position) { console.log(JSON.stringify(position)); xhrRequest('https://api.csas.cz/sandbox/webapi/api/v2/places?radius=500&country=CZ&types=ATM&limit=1&lat=' + position.coords.latitude + '&lng=' + position.coords.longitude, 'GET', '7f29f5d5-c9d4-4266-8e6b-3733064da146', function (status, data) { console.log(status); console.log(data); var response = {}; if (status != 200) { response['KEY_NOT_FOUND'] = true; } else { var json = JSON.parse(data).items[0]; response = { 'KEY_DISTANCE': json.distance, 'KEY_DIRECTION': computeBearing(position.coords, { latitude: json.location.lat, longitude: json.location.lng }), 'KEY_ADDRESS': json.address + '\n' + json.city, 'KEY_ACCESS_TYPE': json.accessType }; } console.log("sending: " + JSON.stringify(response)); Pebble.sendAppMessage(response); }); }, function (error) { console.log('geolocation API error: ' + JSON.stringify(error)); }, {timeout: 2000, maximumAge: 60000, enableHighAccuracy: false} ); } Pebble.addEventListener('ready', function (e) { getNearestATMs(); }); Pebble.addEventListener('appmessage', function (e) { getNearestATMs(); });
/*global Codes, parseInt, Math, List, module*/ /* This object contains javascript global functions used in this project */ var Utils = { parseInt: function (string) { "use strict"; return (parseInt(string, Codes.DECIMAL_SYSTEM)); }, random: function () { "use strict"; return Math.random(); }, floor: function (number) { "use strict"; return Math.floor(number); }, stringify: function (object) { "use strict"; return JSON.stringify(object); }, parse: function (string) { "use strict"; return JSON.parse(string); }, genPieceDictionaryKey: function (piece) { "use strict"; return Codes.PIECE_KEY + "_" + piece.side1 + "_" + piece.side2; } }; try { module.exports = Utils; } catch (ignore) {}
'use strict'; /** * Das Modul fuer den Mensa-Zugriff. */ var canteen = angular.module('Canteen', []); /** * Kapselung des Zugriffs in Form eines Dienstes. * Noch einfacher klappt der Zugriff auf eine REST-Schnittstelle * in vielen Faellen mit dem Modul ngResource. */ canteen.factory('CanteenService', [ '$http', function($http) { var server = {}; /** * Abholen der Essen. * @param date Datum des Essens. * @returns Alle Essen, sortiert in Gruppen von Mahlzeiten. */ server.getMeals = function(url, date) { return $http.get(url + server.formatDate(date)); }; /** * Hilfsfunktion, um das Datum fuer die Anfrage aufzubereiten. * @param date Zu formatierendes Datum. * @returns {string} Datum als String im Format "yyyy-MM-dd". */ server.formatDate = function(date) { return(date.toISOString().split('T'))[ 0 ]; }; /** * Die eigentliche Funktion des Dienstes. * @param date Datum des Essens. * @returns Alle Essen, sortiert in Gruppen von Mahlzeiten. */ return { getMeals: function(url, date) { return server.getMeals(url, date); } } }]); /** * Controller fuer Ausgabe der Mahlzeiten. */ canteen.controller('CanteenController', ['$scope', 'CanteenService', function($scope, CanteenService) { // Vorinitialisiert mit aktuellem Datum, Zeit wird auf 00:00:00 gesetzt. var today = new Date(); $scope.canteenDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1); /** * Essen mit eingestelltem Datum erneut abholen. */ $scope.refresh = function() { CanteenService.getMeals($scope.url, $scope.canteenDate).then(function(response) { $scope.meals = response.data; }, function(error) { console.log('No meals:' + error); }); }; /** * Datum um einen tag erhoehen, Essen erneut abholen. */ $scope.incrementDate = function() { $scope.canteenDate = new Date($scope.canteenDate.getFullYear(), $scope.canteenDate.getMonth(), $scope.canteenDate.getDate() + 1); $scope.refresh(); }; /** * Empfang von Nachrichten eines Vater-Controllers. */ $scope.$on('refreshCanteen', function(event) {$scope.refresh();}); $scope.$on('incrementDate', function(event) {$scope.incrementDate();}); /** * Initial: Essen abholen. */ $scope.refresh(); }]); canteen.directive('canteenView', function() { return { scope: { url: '@url' }, templateUrl: 'canteen/canteenTemplate.html', restrict: 'E', link: function(scope, element, attrs) { } }; });
import React, { Component } from 'react'; export default class ResetButton extends Component { render () { return ( <button onClick={this.props.onClick}>Reset</button> ); } }
class microsoft_mediacenter_glidhost_glidloaderwrapper_1 { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = microsoft_mediacenter_glidhost_glidloaderwrapper_1;
const window = global; global.window = window; window.navigator = {};
var keyWords = [ "Collection","Debug","Print","Input","Error","Lock","Unlock","Line Input","Call","Erase","Put","Get","Empty","Step","Wend","While","Until","Let","Null","Each","To","True","False","Like","Is","Mod","Imp","Eqv","On Error","Set","Nothing","Declare","Lib","ByVal","ByRef","Dim","ReDim","Preserve","Const","Static","If","Then","End If","ElseIf","Else","GoTo","Open","Close","Output","Binary","Random","Access","Read","Write","ReadWrite","And","Or","Xor","Not","Private","Public","Sub","Function","Property","Case","Do","For","End","With","Select","Exit Function","Exit Sub","Exit Do","Exit For","Exit Property","End Sub","End Function","End Property","End Type","End With","End Select","Type","Enum","Option Explicit","Option Base","As","String","Integer","Long","Double","Single","Date","Boolean","Byte","Currency","Variant","New","Object","OLE_CANCELBOOL","OLE_COLOR","OLE_HANDLE","OLE_OPTEXCLUSIVE","OLE_TRISTATE","Next" ]; var colours = (function () { var cols = {}; var keyword = function () { return cols.keyWord || "darkblue"; } var comment = function () { return cols.comment || "green"; } var fn = function () { return cols.functionSub || "darkcyan"; } var init = function() { chrome.storage.sync.get("colours", function (c) { if (!chrome.runtime.error) { if (c.colours !== undefined) { cols = c.colours; } } }); } init(); return { keyWord: keyword, comment: comment, functionSub: fn } })(); (function() { if(typeof(SyntaxHighlighter)!="undefined") { chrome.storage.sync.get("highlighting", function(h) { if(!chrome.runtime.error) { if(h.highlighting === undefined || h.highlighting.on) { Array.prototype.slice.call(document.querySelectorAll("pre"),0).forEach(function(pre){ if(pre.id != "preview") { pre.innerHTML = pre.innerText; pre.className = "brush: vb;"; } else { pre.className = "" } }); SyntaxHighlighter.highlight(); } } }); } })() var colourTag = { open: function(colour) { return "[color=" + colour + "]"; }, close: "[/color]" }; var map = []; // Or you could call it "key" var app = app || {}; document.onkeydown = onkeyup = function(e){ e = e || event; // to deal with IE map[e.keyCode] = e.type == 'keydown'; if(map[65] && map[18]) { replaceSelectedText(document.querySelector(".cke_source.cke_enable_context_menu"), addCodeTags(getSelectedText())); map = []; } } function addCodeTags(text) { var intext = text; //Replace KeyWords for(var i=0;i<keyWords.length;i++){ var keyWord = keyWords[i]; intext = replaceKeyWords(intext, keyWord, colourTag.open(colours.keyWord()) + keyWord + colourTag.close); } //Add comments var comments = intext.match(/'+.*$/mg) ||[]; var remComments = intext.match(/Rem+.*$/mg) ||[]; comments = comments.concat(remComments); var uniqueComments = comments.filter(onlyUnique); for(var i=0;i<uniqueComments.length;i++){ intext = replaceAll(intext, uniqueComments[i],colourTag.open(colours.comment()) + uniqueComments[i] + colourTag.close); } //Highlight function/sub calls var functions = intext.match(/[A-z0-9$]+(?=\()/mg)||[]; var uniqueFunctions = functions.filter(onlyUnique); for(var i=0;i<uniqueFunctions.length;i++){ intext = replaceKeyWords(intext, uniqueFunctions[i],colourTag.open(colours.functionSub()) + uniqueFunctions[i] + colourTag.close); } //Parse strings var strings = intext.match(/"[^"]*"/mg) || []; var uniqueStrings = strings.filter(onlyUnique); for(var i=0;i<uniqueStrings.length;i++) { intext = replaceAll(intext, uniqueStrings[i], colourTag.open(colours.comment()) + uniqueStrings[i] + colourTag.close); } return "[code]" + intext + "[/code]"; } //Helper functions: function replaceKeyWords(string, find, replace) { var search = find.replace("$",""); var findR = reverseString(search); return reverseString(reverseString(string).replace(new RegExp( '"[^"]*"|((?:\\b|\\$)' + escapeRegExp(findR) + "\\b(?!.*'))", "mg"), function(m, group1) { if(group1==reverseString(find)) return reverseString(replace); else return m; }) ); } function escapeRegExp(string) { return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); } function reverseString(string) { return string.split("").reverse().join(""); } function getSelectedText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; } function onlyUnique(value, index, self) { if ( value === "'" ) { return false; } else { return self.indexOf(value) === index; } } function replaceAll(string, find, replace) { return string.replace(new RegExp(escapeRegExp(find), 'g'), replace); } function getInputSelection(el) { var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange; if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { start = el.selectionStart; end = el.selectionEnd; } else { range = document.selection.createRange(); if (range && range.parentElement() == el) { len = el.value.length; normalizedValue = el.value.replace(/\r\n/g, "\n"); // Create a working TextRange that lives only in the input textInputRange = el.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); // Check if the start and end of the selection are at the very end // of the input, since moveStart/moveEnd doesn't return what we want // in those cases endRange = el.createTextRange(); endRange.collapse(false); if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { start = end = len; } else { start = -textInputRange.moveStart("character", -len); start += normalizedValue.slice(0, start).split("\n").length - 1; if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) { end = len; } else { end = -textInputRange.moveEnd("character", -len); end += normalizedValue.slice(0, end).split("\n").length - 1; } } } } return { start: start, end: end }; } function replaceSelectedText(el, text) { var sel = getInputSelection(el), val = el.value; el.value = val.slice(0, sel.start) + text + val.slice(sel.end); }
'use strict'; // Google Analytics Collection APIs Reference: // https://developers.google.com/analytics/devguides/collection/analyticsjs/ angular.module('app.controllers',[]) // Path: / .controller('HomeController', ['$scope', '$location', '$window', function ($scope, $location, $window) { $scope.$root.title = 'MiniTrello Web'; $scope.goToRegister = function () { $location.path('/register'); }; $scope.goToLogin = function () { $location.path('/login'); }; $scope.$on('$viewContentLoaded', function () { $window.ga('send', 'pageview', { 'page': $location.path(), 'title': $scope.$root.title }); }); }]);
import { defaultSlackArchivePath } from '../util/globalPaths'; import { makePath } from '../util/paths'; import { getMessagesFromDailyArchive } from '../util/loadArchives'; import { setMessages } from '../actions/index'; export const loadMessagesForGroup = (store, messageGroupName) => { if (messageGroupName === '') { store.dispatch(setMessages(messageGroupName, [''])); } else { const channelPath = makePath( defaultSlackArchivePath, store.getState().channels.activeChannelName); const currentDailyArchivePath = makePath(channelPath, messageGroupName); const messages = getMessagesFromDailyArchive(currentDailyArchivePath); store.dispatch(setMessages(messageGroupName, messages)); } }; export default (store, messageGroupNames) => { // console.log('Load messages for:', messageGroupNames); for (const messageGroupName of messageGroupNames) { loadMessagesForGroup(store, messageGroupName); } };
import React from 'react' import { request } from 'utils' import { apiPrefix } from 'utils/config' import { Row, Col, Select, Form, Input, Button, List, Tag, Checkbox } from 'antd' import classnames from 'classnames' import { CloseOutlined } from '@ant-design/icons' import { Trans } from "@lingui/macro" import api from '@/services/api' import { Page } from 'components' import styles from './index.less' const { Option } = Select const InputGroup = Input.Group const methods = ['POST', 'GET', 'PUT', 'PATCH', 'DELETE'] const methodTagColor = { GET: 'green', POST: 'orange', DELETE: 'red', PUT: 'geekblue', } const requests = Object.values(api).map(item => { let url = apiPrefix + item let method = 'GET' const paramsArray = item.split(' ') if (paramsArray.length === 2) { method = paramsArray[0] url = apiPrefix + paramsArray[1] } return { method, url, } }) let uuid = 2 class RequestPage extends React.Component { formRef = React.createRef() constructor(props) { super(props) this.state = { method: 'GET', url: '/api/v1/routes', keys: [1], result: null, visible: true, } } handleRequest = () => { const { method, url } = this.state this.formRef.current.validateFields() .then(values => { // values: { check[1]: true, key[1]: 'username', value[1]: 'admin' } const params = {} for (let i in values) { if (i.startsWith('check')) { const index = i.match(/check\[(\d+)\]/)[1] const key = values[`key[${index}]`] params[key] = values[`value[${index}]`] } } request({ method, url, data: params }).then(data => { this.setState({ result: JSON.stringify(data), }) }) }) .catch(errorInfo => { console.log(errorInfo) /* errorInfo: { values: { username: 'username', password: 'password', }, errorFields: [ { password: ['username'], errors: ['Please input your Password!'] }, ], outOfDate: false, } */ }) } handleClickListItem = ({ method, url }) => { this.setState({ method, url, keys: [uuid++], result: null, }) } handleInputChange = e => { this.setState({ url: e.target.value, }) } handleSelectChange = method => { this.setState({ method, }) } handleAddField = () => { const { keys } = this.state const nextKeys = keys.concat(uuid) uuid++ this.setState({ keys: nextKeys, }) } handleRemoveField = key => { const { keys } = this.state this.setState({ keys: keys.filter(item => item !== key), }) } handleVisible = () => { this.setState({ visible: !this.state.visible, }) } render() { const { result, url, method, keys, visible } = this.state return ( <Page inner> <Row> <Col lg={8} md={24}> <List className={styles.requestList} dataSource={requests} renderItem={item => ( <List.Item className={classnames(styles.listItem, { [styles.lstItemActive]: item.method === method && item.url === url, })} onClick={this.handleClickListItem.bind(this, item)} > <span style={{ width: 72 }}> <Tag style={{ marginRight: 8 }} color={methodTagColor[item.method]} > {item.method} </Tag> </span> {item.url} </List.Item> )} /> </Col> <Col lg={16} md={24}> <Row type="flex" justify="space-between"> <InputGroup compact size="large" style={{ flex: 1 }}> <Select size="large" value={method} style={{ width: 100 }} onChange={this.handleSelectChange} > {methods.map(item => ( <Option value={item} key={item}> {item} </Option> ))} </Select> <Input value={url} onChange={this.handleInputChange} style={{ width: 'calc(100% - 200px)' }} /> <Button ghost={visible} type={visible ? 'primary' : ''} onClick={this.handleVisible} size="large" > <Trans>Params</Trans> </Button> </InputGroup> <Button size="large" type="primary" style={{ width: 100 }} onClick={this.handleRequest} > <Trans>Send</Trans> </Button> </Row> <Form ref={this.formRef} name="control-ref" > <div className={classnames(styles.paramsBlock, { [styles.hideParams]: !visible, })} > {keys.map((key, index) => ( <Row gutter={8} type="flex" justify="start" align="middle" key={key} > <Col style={{ marginTop: 8 }}> <Form.Item name={`check[${key}]`} valuePropName="checked"> <Checkbox defaultChecked /> </Form.Item> </Col> <Col style={{ marginTop: 8 }}> <Form.Item name={`key[${key}]`}> <Input placeholder="Key" /> </Form.Item> </Col> <Col style={{ marginTop: 8 }}> <Form.Item name={`value[${key}]`}> <Input placeholder="Value" /> </Form.Item> </Col> <Col style={{ marginTop: 8 }}> <CloseOutlined onClick={this.handleRemoveField.bind(this, key)} style={{ cursor: 'pointer' }} /> </Col> </Row> ))} <Row style={{ marginTop: 8 }}> <Button onClick={this.handleAddField}> <Trans>Add Param</Trans> </Button> </Row> </div> </Form> <div className={styles.result}>{result}</div> </Col> </Row> </Page> ) } } export default RequestPage
$(document).ready( function () { $('#table_cust').DataTable({ "paging": true, "lengthChange": true, "searching": true, "ordering": true, "info": false, "responsive": true, "autoWidth": false, "pageLength": 10, "ajax": { "url": "supplier/data.php", "type": "POST" }, "columns": [ { "data": "urutan" }, { "data": "nama_pemilik" }, { "data": "alamat" }, { "data": "no_telp_supplier" }, { "data": "tanggal_gabung" }, { "data": "button" }, ] }); }); $(document).on("click","#btnadd",function(){ $("#modalcust").modal("show"); $("#txtname").focus(); $("#txtname").val(""); $("#txtcountry").val(""); $("#cbogender").val(""); $("#txtphone").val(""); $("#crudmethod").val("N"); $("#txtid").val("0"); }); $(document).on( "click",".btnhapus", function() { var id_cust = $(this).attr("id_supplier"); var name = $(this).attr("nama_pemilik"); swal({ title: "Delete Cust?", text: "Delete Cust : "+name+" ?", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Delete", closeOnConfirm: true }, function(){ var value = { id_cust: id_cust }; $.ajax( { url : "supplier/delete.php", type: "POST", data : value, success: function(data, textStatus, jqXHR) { var data = jQuery.parseJSON(data); if(data.result ==1){ $.notify('Successfull delete customer'); $.notf var table = $('#table_cust').DataTable(); table.ajax.reload( null, false ); }else{ swal("Error","Can't delete customer data, error : "+data.error,"error"); } }, error: function(jqXHR, textStatus, errorThrown) { swal("Error!", textStatus, "error"); } }); }); }); $(document).on("click","#btnsave",function(){ var id_cust = $("#txtid").val(); var name = $("#txtname").val(); var gender = $("#cbogender").val(); var country = $("#txtcountry").val(); var phone = $("#txtphone").val(); var crud=$("#crudmethod").val(); if(name == '' || name == null ){ swal("Warning","Please fill nama pemilik","warning"); $("#txtname").focus(); return; } var value = { id_cust: id_cust, name: name, gender:gender, country:country, phone:phone, crud:crud }; $.ajax( { url : "supplier/save.php", type: "POST", data : value, success: function(data, textStatus, jqXHR) { var data = jQuery.parseJSON(data); if(data.crud == 'N'){ if(data.result == 1){ $.notify('Successfull save data'); var table = $('#table_cust').DataTable(); table.ajax.reload( null, false ); $("#txtname").focus(); $("#txtname").val(""); $("#txtcountry").val(""); $("#txtphone").val(""); $("#cbogender").val(""); $("#crudmethod").val("N"); $("#txtid").val("0"); // $("#txtnama").focus(); }else{ swal("Error","Can't save customer data, error : "+data.error,"error"); } }else if(data.crud == 'E'){ if(data.result == 1){ $.notify('Successfull update data'); var table = $('#table_cust').DataTable(); table.ajax.reload( null, false ); $("#txtname").focus(); }else{ swal("Error","Can't update customer data, error : "+data.error,"error"); } }else{ swal("Error","invalid order","error"); } }, error: function(jqXHR, textStatus, errorThrown) { swal("Error!", textStatus, "error"); } }); }); $(document).on("click","#btnedit",function(){ var id_supplier=$(this).attr("id_supplier"); var value = { id_supplier: id_supplier }; $.ajax( { url : "supplier/get_cust.php", type: "POST", data : value, success: function(data, textStatus, jqXHR) { var data = jQuery.parseJSON(data); $("#crudmethod").val("E"); $("#txtid").val(data.id_supplier); $("#txtname").val(data.nama_pemilik); $("#cbogender").val(data.alamat); $("#txtcountry").val(data.no_telp_supplier); $("#txtphone").val(data.tanggal_gabung); $("#modalcust").modal('show'); $("#txtname").focus(); }, error: function(jqXHR, textStatus, errorThrown) { swal("Error!", textStatus, "error"); } }); }); $.notifyDefaults({ type: 'success', delay: 500 });
$(function () { /** * PARTICIPATION: Participation details */ var paymentManagementModal = $('#dialogPriceConfiguration'), toPayTableEl = $('#dialogPriceConfiguration #payment tbody'), toPayFooterTableEl = $('#dialogPriceConfiguration #payment tfoot'), priceTagTableEl = $('#dialogPriceConfiguration #price tbody'), priceTagFooterTableEl = $('#dialogPriceConfiguration #price tfoot'), priceHistoryTableEl = $('#dialogPriceConfiguration #priceHistory tbody'), invoiceTableEl = $('#dialogPriceConfiguration #invoiceList tbody'), formatCurrencyNumber = function (value) { if (value === null) { return ''; } return jQuery.number(value, 2, ',', '.') + '&nbsp;€ '; }, handlePaymentControllerResponse = function (result, aids) { var multiple = (aids.toString().split(';').length > 1); if (result.payment_history) { displayPriceHistory(result.payment_history); } if (result.to_pay_list) { displayToPayInfo(result.to_pay_list); } if (result.to_pay_sum) { displayPaymentFullValue(result.to_pay_sum, multiple); } if (result.price_tag_list) { displayPriceTag(result.price_tag_list, multiple, result.price_tag_sum); } if (result.invoice_list) { displayInvoiceList(result.invoice_list); } }, displayToPayInfo = function (data) { var rawRow, rawRows = '', createInfoRow = function (toPayValue, participantPriceHtml, participantAid, participantName) { var cellValue; if (toPayValue === null) { cellValue = '<i title="Kein Preis festgelegt">keiner</i>'; } else { cellValue = formatCurrencyNumber(toPayValue); } $('#participant-price-' + participantAid.toString()).html(participantPriceHtml); return '<tr>' + ' <td class="value text-right">' + cellValue + '</td>' + ' <td class="participant">' + participantName + '</td>' + '</tr>'; }; jQuery.each(data, function (key, rowData) { rawRow = createInfoRow( rowData.to_pay_value, rowData.price_html, parseInt(rowData.participant_aid), eHtml(rowData.participant_name) ); rawRows += rawRow; }); toPayTableEl.html(rawRows); }, displayInvoiceList = function (data) { var rowsHtml = '', rowHtml; if (data && data.length) { jQuery.each(data, function (key, rowData) { var creatorHtml, downloadBtnHtml = ''; if (rowData.created_by && rowData.created_by.id) { creatorHtml = '<a class="creator" href="/admin/user/' + rowData.created_by.id + '">' + rowData.created_by.fullname + '</a>'; } else { creatorHtml = rowData.created_by.fullname; } if (rowData.download_url_pdf) { downloadBtnHtml = '<a href="' + rowData.download_url_pdf + '" target="_blank" class="btn btn-default btn-xs btn-download"><span class="glyphicon glyphicon-download-alt" aria-hidden="true"></span> Download PDF</a>'; downloadBtnHtml = '<div class="btn-group">\n' + ' <a href="' + rowData.download_url + '" title="Rechnugn als Word-Datei herunterladen" role="button" class="btn btn-default btn-xs btn-download"><span class="glyphicon glyphicon-download-alt" aria-hidden="true"></span> Download</a>\n' + ' <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">\n' + ' <span class="caret"></span>\n' + ' <span class="sr-only">Download Varianten</span>\n' + ' </button>\n' + ' <ul class="dropdown-menu">\n' + ' <li><a href="' + rowData.download_url + '"><span class="glyphicon glyphicon-book" aria-hidden="true"></span> Rechnung als Word-Dokument herunterladen</a></li>\n' + ' <li><a href="' + rowData.download_url_pdf + '"><span class="glyphicon glyphicon-print" aria-hidden="true"></span> Rechnung als PDF-Dokument herunterladen</a></li>\n' + ' </ul>\n' + '</div>'; } else if (rowData.download_url) { downloadBtnHtml = '<a href="' + rowData.download_url + '" target="_blank" class="btn btn-default btn-xs btn-download"><span class="glyphicon glyphicon-download-alt" aria-hidden="true"></span> Download</a>'; } rowHtml = '<tr>' + ' <td class="symbol" title="Rechnung">' + ' <span class="glyphicon glyphicon-page" aria-hidden="true"></span>' + ' </td>' + ' <td class="value">' + formatCurrencyNumber((rowData.sum / 100)) + '</td>' + ' <td>' + rowData.invoice_number + '</td>' + ' <td class="small"><span class="created">' + rowData.created_at + '</span>, ' + creatorHtml + '</td>' + ' <td class="text-right">' + downloadBtnHtml + '</td>' + '</tr>'; rowsHtml += rowHtml; }); } else { rowsHtml = '<td colspan="5" class="text-center">(Keine Rechnungen vorhanden)</td>'; } invoiceTableEl.html(rowsHtml); attachDownloadBtnListener(); }, displayPriceHistory = function (data) { var createPriceRow = function (type, value, description, date, creatorId, creatorName, participant) { var glyph, symbolTitle, creatorHtml; switch (type) { case 'price_payment': glyph = 'log-in'; symbolTitle = 'Zahlung erfasst'; break; case 'price_set': glyph = 'pencil'; symbolTitle = 'Grundpreis festgelegt'; break; } if (creatorId) { creatorHtml = '<a class="creator" href="/admin/user/' + creatorId + '">' + creatorName + '</a>'; } else { creatorHtml = creatorName; } return '<tr class="' + type + '">' + ' <td class="symbol" title="' + symbolTitle + '">' + ' <span class="glyphicon glyphicon-' + glyph + '" aria-hidden="true"></span>' + ' </td>' + ' <td class="participant">' + participant + '</td>' + ' <td class="value">' + formatCurrencyNumber(value) + '</td>' + ' <td class="description">' + description + '</td>' + ' <td class="small"><span class="created">' + date + '</span>, ' + creatorHtml + '</td>' + '</tr>'; }; var rawRows = ''; if (data && data.length) { var rawRow; jQuery.each(data, function (key, rowData) { rawRow = createPriceRow( rowData.type, rowData.value, eHtml(rowData.description), rowData.created_at, rowData.created_by_uid, eHtml(rowData.created_by_name), eHtml(rowData.participant_name) ); rawRows += rawRow; }); } else { rawRows = '<td colspan="5" class="text-center">(Kein Vorgang erfasst)</td>'; } priceHistoryTableEl.html(rawRows); }, displayPaymentFullValue = function (value, multiple) { var btn = $('.btn-payment-full'), valueText; if (value === null) { valueText = '<i title="Kein Preis festgelegt">keiner</i>'; btn.css('visibility', 'hidden'); } else { valueText = formatCurrencyNumber(value); btn.data('value', value); btn.html('<b>' + valueText + '</b> Komplett'); btn.css('visibility', 'visible'); } toPayFooterTableEl.html( '<tr class="total">' + ' <td class="value text-right"><b>' + valueText + '</b></td>' + ' <td class="participant">' + ' <b>Summe</b>' + (multiple ? ' (für alle Teilnehmer:innen)' : '') + ' </td>' + '</tr>' ); }, displayPriceTag = function (rows, multiple, price_tag_sum) { if (rows.length) { var htmlRows = []; jQuery.each(rows, function (key, rowData) { var description = '', symbolTitle = '?', glyphParticipant, glyphParticipantTitle, glyph = 'check'; switch (rowData.type) { case 'AppBundle\\Manager\\Payment\\PriceSummand\\BasePriceSummand': glyph = 'tag'; symbolTitle = 'Grundpreis'; description = 'Grundpreis'; break; case 'AppBundle\\Manager\\Payment\\PriceSummand\\FilloutSummand': glyph = 'edit'; symbolTitle = 'Formel mit Eingabewert'; description = 'Feld <i>' + eHtml(rowData.attribute_name) + '</i>'; break; } if (rowData.is_participation_summand) { glyphParticipant = 'file'; glyphParticipantTitle = 'Summand durch Anmeldung'; } else { glyphParticipant = 'user'; glyphParticipantTitle = 'Summand durch Teilnehmer:innen'; } htmlRows.push( '<tr>' + ' <td class="symbol" title="' + symbolTitle + '">' + ' <span class="glyphicon glyphicon-' + glyph + '" aria-hidden="true"></span>' + ' </td>' + ' <td class="participant">' + rowData.participant_name + '</td>' + ' <td class="value">' + formatCurrencyNumber(rowData.value) + '</td>' + ' <td>' + '<span class="glyphicon glyphicon-' + glyphParticipant + '" aria-hidden="true" title="' + glyphParticipantTitle + '"></span> ' + '</td>', ' <td class="description">' + description + '</td>' + '</tr>' ); }); priceTagTableEl.html(htmlRows.join('')); priceTagFooterTableEl.html( '<tr class="total">' + ' <td class="symbol" title="Gesamtpreis">' + ' </td>' + ' <td class="participant"></td>' + ' <td class="value">' + formatCurrencyNumber(price_tag_sum) + '</td>' + ' <td></td>' + ' <td class="description">' + ' <b>Summe</b>' + (multiple ? ' (für alle Teilnehmer:innen)' : '') + '</td>' + '</tr>' ); } else { priceTagTableEl.html( '<tr>' + '<td colspan="5" class="text-center">(Keine Preisinformationen erfasst)</td>' + '</tr>' ); } }; $('#dialogPriceConfiguration').on('show.bs.modal', function (event) { var button = $(event.relatedTarget), aids = button.data('aids'), modal = $(this), inputEls = modal.find('input'); paymentManagementModal.toggleClass('loading', true); toPayFooterTableEl.html(''); modal.find('.modal-title span').text(button.data('title')); modal.data('aids', aids); $.each(inputEls, function (i, el) { $(el).val(''); }); $.ajax({ url: '/admin/event/participant/price/history', data: { aids: aids }, success: function (result) { handlePaymentControllerResponse(result, aids); }, error: function () { $(document).trigger('add-alerts', { message: 'Preishistorie konnte nicht geladen werden', priority: 'error' }); }, complete: function () { paymentManagementModal.toggleClass('loading', false); } }); }); $('#dialogPriceConfiguration #payment .btn-predefined').on('click', function (e) { e.preventDefault(); var button = $(this); if (button.data('value')) { $('#paymentValue').val(button.data('value')); } if (button.data('description')) { $('#paymentDescription').val(button.data('description')); } }); $('#dialogPriceConfiguration #price .btn-predefined').on('click', function (e) { e.preventDefault(); var button = $(this); if (button.data('value')) { $('#newPriceValue').val(button.data('value')); } if (button.data('description')) { $('#newPriceDescription').val(button.data('description')); } }); $('#dialogPriceConfiguration .btn-primary').on('click', function (e) { e.preventDefault(); var button = $(this), modal = $('#dialogPriceConfiguration'), action = button.data('action'), aids = modal.data('aids'), value, description; button.toggleClass('disabled', true); paymentManagementModal.toggleClass('loading', true); switch (action) { case 'paymentReceived': value = modal.find('#paymentValue').val(); description = modal.find('#paymentDescription').val(); break; case 'newPrice': value = modal.find('#newPriceValue').val(); description = modal.find('#newPriceDescription').val(); break; } $.ajax({ url: '/admin/event/participant/price', data: { _token: modal.data('token'), action: action, aids: aids, value: value, description: description }, success: function (result) { if (result) { handlePaymentControllerResponse(result, aids); $('#priceHistoryLink').tab('show'); } }, error: function () { var message; switch (action) { case 'newPrice': message = 'Der Preis konnte nicht festgelegt werden'; break; default: message = 'Der Bezahlvorgang konnte nicht verarbeitet werden'; break; } $(document).trigger('add-alerts', { message: message, priority: 'error' }); }, complete: function () { paymentManagementModal.toggleClass('loading', false); button.toggleClass('disabled', false); } }); }); $('#createInvoiceBtn').on('click', function (e) { e.preventDefault(); var button = $(this); button.toggleClass('disabled', true); $.ajax({ url: '/admin/event/participation/invoice/create', data: { _token: button.data('token'), pid: button.data('pid') }, success: function (result) { if (result && result.invoice_list) { displayInvoiceList(result.invoice_list); } }, error: function () { $(document).trigger('add-alerts', { message: 'Die Rechnung konnte nicht erstellt werden', priority: 'error' }); }, complete: function () { button.toggleClass('disabled', false); } }); }); var modalEl = $('#modalPrefillAdmin') findParticipantEl = $('#prefillFindParticipant'), findParticipationEl = $('#prefillFindParticipation'); $('#prefillFindParticipation button').on('click', function (e) { findParticipationEl.hide(); findParticipantEl.show(); modalEl.find('.modal-title span').html('1'); }); const prefillActionFn = function (e) { e.preventDefault(); const buttonEl = $('#prefillFindParticipant .btn-primary'), inputEl = $('#prefillFindParticipant input'); if (buttonEl.hasClass('disabled')) { return; } buttonEl.toggleClass('disabled', true); inputEl.toggleClass('disabled', true); inputEl.attr('disabled', 'true'); $.ajax({ url: buttonEl.data('link-participants'), data: { _token: modalEl.data('token'), term: inputEl.val() }, success: function (result) { var participantResultEl = findParticipantEl.find('.list-group'); participantResultEl.html(''); if (result.list && result.list.length) { var html = ''; $.each(result.list, function (key, row) { html += '<div class="list-group-item" data-pids="' + row.pids.join(';') + '">'; html += ' <div class="list-group-item-text">'; html += ' <div class="row">'; html += ' <div class="col-xs-12 col-sm-5">'; html += ' <h4 class="list-group-item-heading">'; html += eHtml(row.name_last) + ', ' + eHtml(row.name_first); html += '</h4>'; html += ' <p>' + row.birthday + '</p>'; html += ' </div>'; html += ' <div class="col-xs-12 col-sm-7">'; html += ' <ul>'; $.each(row.items, function (key, item) { html += ' <li>'; html += '<a href="' + item.link + '" target="_blank">'; html += eHtml(item.event_title); html += '</a> (' + item.event_date + ')'; html += ' </li>'; }); html += ' </ul>'; html += ' </div>'; html += ' </div>'; html += ' </div>'; html += '</div>'; }); participantResultEl.html(html); } else { participantResultEl.html('<i>Keine passenden Einträge gefunden.</i>'); } $('#prefillFindParticipant .list-group-item').on('click', function (e) { if (e.target.nodeName === 'A') { return; //link clicked } findParticipantEl.hide(); findParticipationEl.show(); modalEl.find('.modal-title span').html('2'); var participationResultEl = findParticipationEl.find('.list-group'); participationResultEl.html('<i class="loading-text">(Anmeldungen werden herausgesucht...)</i>'); $.ajax({ url: buttonEl.data('link-participations'), data: { _token: modalEl.data('token'), pids: $(this).data('pids') }, success: function (result) { participationResultEl.html(''); if (result.list && result.list.length) { var html = ''; $.each(result.list, function (key, participation) { html += '<a class="list-group-item" data-pid="' + participation.pid + '" href="' + participation.link + '">'; html += ' <div class="list-group-item-text">'; html += ' <h4 class="list-group-item-heading">'; html += eHtml(participation.event_title); html += '</h4>'; html += ' <div class="row">'; html += ' <div class="col-xs-12 col-sm-5">'; html += ' <h5>Anmeldung</h5>'; html += ' <p>'; html += eHtml(participation.name_last) + ', ' + eHtml(participation.name_first); html += '<br>'; html += eHtml(participation.address_street) + '<br>'; html += eHtml(participation.address_zip) + ' ' + eHtml(participation.address_city) + '<br>'; html += '</p>'; html += ' </div>'; html += ' <div class="col-xs-12 col-sm-7">'; html += ' <h5>Teilnehmer:innen</h5>'; html += ' <ul>'; $.each(participation.participants, function (key, participant) { html += ' <li>'; html += eHtml(participant.name_last) + ', ' + eHtml(participant.name_first); html += ' </li>'; }); html += ' </ul>'; html += ' </div>'; html += ' </div>'; html += ' </div>'; html += '</a>'; }); participationResultEl.html(html); } else { participationResultEl.html('<i>Keine passenden Einträge gefunden.</i>'); } }, error: function (response) { participationResultEl.html('<i>Die Anmeldungen konnten nicht geladen werden.</i>'); } }); }); }, complete: function () { buttonEl.toggleClass('disabled', false); inputEl.toggleClass('disabled', false); inputEl.removeAttr('disabled'); } }); }; $('#prefillFindParticipant .btn-primary').on('click', prefillActionFn); $('#prefillFindParticipant form').on('submit', prefillActionFn); });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S12.10_A3.6_T2; * @section: 12.10; * @assertion: No matter how control leaves the embedded 'Statement', * the scope chain is always restored to its former state; * @description: Using "with" statement within another "with" statement, leading to completion by exception; */ this.p1 = 1; var result = "result"; var myObj = { p1: 'a', value: 'myObj_value', valueOf : function(){return 'obj_valueOf';} } var theirObj = { p1: true, value: 'theirObj_value', valueOf : function(){return 'thr_valueOf';} } try { with(myObj){ with(theirObj){ p1 = 'x1'; throw value; } } } catch(e){ result = p1; } ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if(p1 !== 1){ $ERROR('#1: p1 === 1. Actual: p1 ==='+ p1 ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if(myObj.p1 !== "a"){ $ERROR('#2: myObj.p1 === "a". Actual: myObj.p1 ==='+ myObj.p1 ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#3 if(theirObj.p1 !== "x1"){ $ERROR('#3: theirObj.p1 === "x1". Actual: theirObj.p1 ==='+ theirObj.p1 ); } // //////////////////////////////////////////////////////////////////////////////
let mongoose = require('mongoose'); let Schema = mongoose.Schema; let datumSchema = new Schema({ tableId : Number, rawVal : Number, delta : Number, timestamp : Number }, {collection : 'pong'}); module.exports = mongoose.model('Datum', datumSchema);
KISSY.add('mux.bcharts/charts/js/pub/views/infos/other',function(S,Base,node,Global,SVGElement,SVGGraphics,Light){ function Other(){ var self = this Other.superclass.constructor.apply(self,arguments); } Other.ATTRS = { element:{ value:null }, os:{ value:[] } } S.extend(Other,Base,{ init:function(){ var self = this Other.superclass.constructor.apply(self,arguments); self.set('element', new SVGElement('g')), self.get('element').set('class','other') self.get('parent').appendChild(self.get('element').element) self._widget() }, _widget:function(){ var self = this for(var a = 0, al = self.get('os').length; a < al; a++){ var $o = self.get('os')[a] if($o){ var light = new Light() var o = { parent : self.get('element'), fill : $o.fill_over } light.init(o) var x = $o.x, y = $o.y light.get('element').transformXY(x,y) } } } }); return Other; }, { requires:['base','node','../../utils/global','../../utils/svgelement','../svggraphics','./light'] } );
(function() { 'use strict'; var CONFIG = {}; var LAST_COUNTS; function buildConfig() { return new Promise((resolve, reject) => { var defaultConfig = { whmcsUrl: '', monitorOrders: true, monitorTickets: true, showNotifications: true }; // Populate the initial config object. chrome.storage.sync.get(defaultConfig, items => { Object.assign(CONFIG, items); resolve(CONFIG); }); // Listen for future config changes, updating the config object and // polling WHMCS again with the fresh settings. chrome.storage.onChanged.addListener(changes => { var updated = false; Object.keys(changes).forEach(key => { if (typeof defaultConfig[key] !== 'undefined') { updated = true; CONFIG[key] = changes[key].newValue; } }); if (updated) { pollWHMCS(); } }); }); } function buildLastCounts() { return new Promise((resolve, reject) => { chrome.storage.local.get('lastCounts', items => { LAST_COUNTS = items.lastCounts || {orders: 0, tickets: 0}; resolve(LAST_COUNTS); }); }); } function handleFreshCounts(counts) { if (counts == null || (!CONFIG.monitorOrders && !CONFIG.monitorTickets)) { setBrowserActionStatus(null); updateNotification('orders', 0); updateNotification('tickets', 0); counts = {orders: 0, tickets: 0}; } else { var total = 0; if (CONFIG.monitorOrders && counts.orders) { total += counts.orders; } if (CONFIG.monitorTickets && counts.tickets) { total += counts.tickets; } setBrowserActionStatus(total); updateNotification('orders', counts.orders); updateNotification('tickets', counts.tickets); } LAST_COUNTS = counts; chrome.storage.local.set({lastCounts: LAST_COUNTS}); } function updateNotification(type, count) { var id = 'monitor-' + type; var previousCount = LAST_COUNTS[type]; if (!count) { chrome.notifications.clear(id); } else if (count > previousCount && CONFIG.showNotifications) { var details = {}; details.type = 'basic'; details.iconUrl = 'icons/notification.png'; details.title = 'Pending ' + type[0].toUpperCase() + type.substr(1); details.message = 'You have ' + count + ' pending ' + (count == 1 ? type.substr(0, type.length - 1) : type) + '.'; details.contextMessage = 'WHMCS Notifier'; details.isClickable = true; chrome.notifications.create(id, details); } } function setBrowserActionStatus(count) { if (count === null) { chrome.browserAction.setBadgeText({text: '?'}); chrome.browserAction.setBadgeBackgroundColor({color: '#AAAAAA'}); chrome.browserAction.setIcon({path: { '19': 'icons/browser_disabled@1x.png', '38': 'icons/browser_disabled@2x.png' }}); } else { chrome.browserAction.setBadgeText({text: '' + (count || '')}); chrome.browserAction.setBadgeBackgroundColor({color: '#FF0000'}); chrome.browserAction.setIcon({path: { '19': 'icons/browser_standard@1x.png', '38': 'icons/browser_standard@2x.png' }}); } } function pollWHMCS() { if (!CONFIG.whmcsUrl) { console.debug('Polling aborted, no WHMCS URL configured.'); handleFreshCounts(null); return; } else if (!CONFIG.monitorOrders && !CONFIG.monitorTickets) { console.debug('Polling aborted, no monitors enabled.'); handleFreshCounts(null); return; } fetch(CONFIG.whmcsUrl, { credentials: 'include' }).then(response => { if (response.status !== 200) { throw new Error('The response code must be 200.'); } return response.text(); }).then(html => { var parser = new DOMParser(); var doc = parser.parseFromString(html, 'text/html'); var statsEl = doc.querySelector('div.header div.stats'); if (!statsEl) { throw new Error('Failed to parse the stats element.'); } var statEls = statsEl.querySelectorAll('span.stat'); var data = {}; data.orders = parseInt(statEls[0].innerText, 10); data.tickets = parseInt(statEls[2].innerText, 10); handleFreshCounts(data); }).catch(error => { handleFreshCounts(null); console.warn('Polling failed.', error); }); } function handleTabReload(tabId, changeInfo, tab) { if (changeInfo.status == 'complete' && tab.url && CONFIG.whmcsUrl && tab.url.indexOf(CONFIG.whmcsUrl) === 0) { var page = tab.url.substr(CONFIG.whmcsUrl.length); var excludedPages = ['whmcsconnect.php']; if (excludedPages.indexOf(page) == -1) { chrome.tabs.executeScript(tab.id, { file: 'content.js' }); } } } function highlightWHMCSTab() { if (!CONFIG.whmcsUrl) { return; } chrome.tabs.query({ url: CONFIG.whmcsUrl + '*' }, tabs => { if (tabs.length) { chrome.tabs.highlight({ tabs: tabs.map(tab => tab.index) }); } else { chrome.tabs.create({ url: CONFIG.whmcsUrl }); } }); } function handleNotificationClick(notificationId) { switch (notificationId) { case 'monitor-orders': var pageUrl = 'orders.php?status=Pending'; break; case 'monitor-tickets': var pageUrl = 'supporttickets.php'; break; default: return; } chrome.tabs.create({url:CONFIG.whmcsUrl + pageUrl}); chrome.notifications.clear(notificationId); } buildConfig().then(buildLastCounts).then(() => { chrome.alarms.create('poll', {periodInMinutes: 1}); chrome.alarms.onAlarm.addListener(pollWHMCS); chrome.tabs.onUpdated.addListener(handleTabReload); chrome.browserAction.onClicked.addListener(highlightWHMCSTab); chrome.notifications.onClicked.addListener(handleNotificationClick); chrome.runtime.onMessage.addListener(message => { if (message.type == 'counts') { handleFreshCounts(message.data); } }); pollWHMCS(); }); })();
'use strict'; var run = function() { // Replace '../bitcore' with 'bitcore' if you use this code elsewhere. var bitcore = require('../bitcore'); var RpcClient = bitcore.RpcClient; var hash = '0000000000b6288775bbd326bedf324ca8717a15191da58391535408205aada4'; var config = { protocol: 'http', user: 'user', pass: 'pass', host: '127.0.0.1', port: '17332', }; var rpc = new RpcClient(config); rpc.getBlock(hash, function(err, ret) { if (err) { console.error('An error occured fetching block', hash); console.error(err); return; } console.log(ret); }); }; module.exports.run = run; if (require.main === module) { run(); }
'use strict'; const util = require('util'); function sendResponse(ctx, statusCode, response, next, async) { if (async) { return true; } ctx.headers = { 'Content-Type': 'application/json' }; ctx.statusCode = statusCode; return next(null, response); } function errorHandler(ctx, error, next, async) { const response = { message: error.message, stack: error.stack, code: 'error' }; sendResponse(ctx, 500, response, next, async); } function returnFullObject(object) { return util.inspect(object, false, null); } function isRadioOrLineIn(uri) { return uri.startsWith('x-sonosapi-stream:') || uri.startsWith('x-sonosapi-radio:') || uri.startsWith('pndrradio:') || uri.startsWith('x-sonosapi-hls:') || uri.startsWith('x-rincon-stream:') || uri.startsWith('x-sonos-htastream:') || uri.startsWith('x-sonosprog-http:') || uri.startsWith('x-rincon-mp3radio:'); } const types = { array: '[object Array]', boolean: '[object Boolean]', get: (prop) => { return Object.prototype.toString.call(prop); }, number: '[object Number]', object: '[object Object]', string: '[object String]' }; module.exports = { sendResponse, errorHandler, isRadioOrLineIn, returnFullObject, types };
(function(root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.Freccia = (root.Freccia || {}); root.Freccia.Vector = factory(); } }(this, function() { 'use strict'; function Vector(x,y) { this.x = x; this.y = y; } Vector.prototype = { magnitude: function() { return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); }, toUnit: function() { var mag = this.magnitude(); return new Vector(this.x / mag, this.y / mag); }, add: function(v2) { return new Vector(this.x + v2.x, this.y + v2.y); }, sub: function(v2) { return new Vector(this.x - v2.x, this.y - v2.y); }, scale: function(scalar) { return new Vector(this.x * scalar, this.y * scalar); } }; return Vector; } )); (function(root, factory) { if (typeof define === 'function' && define.amd) { define(['freccia/vector'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('./vector.js')); } else { root.Freccia = (root.Freccia || {}); root.Freccia.TouchPoint = factory(Freccia.Vector); } }(this, function(Vector) { 'use strict'; function TouchPoint(touch) { this.moment = new Date(); this.location = new Vector(touch.pageX, touch.pageY); this.delta = null; this.dt = null; } TouchPoint.prototype = { setPrevPoint: function(prevPoint) { this.delta = this.location.sub(prevPoint.location); this.dt = this.moment - prevPoint.moment; return this; } }; return TouchPoint; } )); (function(root, factory) { if (typeof define === 'function' && define.amd) { define(['freccia/vector'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('./vector.js')); } else { root.Freccia = (root.Freccia || {}); root.Freccia.TouchPath = factory(); } }(this, function() { 'use strict'; function TouchPath(id, touches) { this.id = id; this.moment = new Date(); this.points = (touches || []); } TouchPath.prototype = { start: function() { return this.points[0]; }, end: function() { return this.points[this.points.length - 1]; }, net: function() { return this.end().location.sub(this.start().location); }, time: function() { var start = this.start(), end = this.end(); return (end.moment - start.moment) / 1000; }, netDistance: function() { return this.net().magnitude(); }, netSpeed: function() { return this.netDistance() / this.time(); }, velocity: function() { var speed = this.netSpeed(); return this.net().toUnit().scale(speed); }, addPoint: function(touchPoint) { touchPoint.setPrevPoint(this.end()); return this.points.push(touchPoint); } }; return TouchPath; } )); (function(root, factory) { if (typeof define === 'function' && define.amd) { define(['freccia/touch_path', 'freccia/touch_point'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('./touch_path.js'), require('./touch_point.js')); } else { root.Freccia = (root.Freccia || {}); root.Freccia.Manager = factory(Freccia.TouchPath, Freccia.TouchPoint); } }(this, function(TouchPath, TouchPoint) { 'use strict'; function Manager(element) { if (typeof element === 'string') { element = document.querySelectorAll(element)[0]; } this.element = element; this.activeTouchPaths = []; this.beginCallbacks = []; this.endCallbacks = []; this.moveCallbacks = []; this.listensForEvents = []; } function traceStart(event, manager) { event.preventDefault(); var touches = event.changedTouches; for(var i=0; i < touches.length; i++) { var point = new TouchPoint(touches[i]), path = new TouchPath(touches[i].identifier, [point]); manager.activeTouchPaths.push(path); manager.beginCallbacks.forEach(function(callback) { callback.call(manager, path, point); }); } } function traceMove(event, manager) { event.preventDefault(); var touches = event.changedTouches; for(var i=0; i < touches.length; i++) { var point = new TouchPoint(touches[i]), path = manager.findActiveTouchPath(touches[i].identifier); if (path) { path.addPoint(point); manager.moveCallbacks.forEach(function(callback) { callback.call(manager, path, point); }); } } } function traceEnd(event, manager) { event.preventDefault(); var touches = event.changedTouches; for(var i=0; i < touches.length; i++) { var point = new TouchPoint(touches[i]), path = manager.findActiveTouchPath(touches[i].identifier); if (path) { path.addPoint(point); manager.removeActiveTouchPath(path.id); manager.endCallbacks.forEach(function(callback) { callback.call(manager, path, point); }); } } } Manager.prototype = { listenAll: function() { this.listenFor('touchstart', traceStart); this.listenFor('touchend', traceEnd); this.listenFor('touchcancel', traceEnd); this.listenFor('touchmove', touchMove); }, listenFor: function(eventName, handler) { var self = this; self.listensForEvents.push(eventName); this.element.addEventListener(eventName, function(event) { handler(event, self); }, false); }, listensFor: function(eventName) { return this.listensForEvents.indexOf(eventName) > -1; }, _findActiveTouchPathPos: function(id) { for (var i=0; i < this.activeTouchPaths.length; i++) { if (this.activeTouchPaths[i].id === id) { return i; } } }, findActiveTouchPath: function(id) { return this.activeTouchPaths[this._findActiveTouchPathPos(id)]; }, removeActiveTouchPath: function(id) { return this.activeTouchPaths.splice(this._findActiveTouchPathPos(id), 1); }, on: function(event, callback) { switch(event) { case 'start': if (! this.listensFor('touchstart')) { this.listenFor('touchstart', traceStart); } this.beginCallbacks.push(callback); break; case 'end': if (! this.listensFor('touchend')) { this.listenFor('touchend', traceEnd); this.listenFor('touchcancel', traceEnd); } this.endCallbacks.push(callback); break; case 'move': if (! this.listensFor('touchmove')) { this.listenFor('touchmove', traceMove); } this.moveCallbacks.push(callback); } return this; } }; return Manager; } ));
define("ghost/routes/editor/new", ["ghost/routes/authenticated","ghost/mixins/style-body","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var AuthenticatedRoute = __dependency1__["default"]; var styleBody = __dependency2__["default"]; var EditorNewRoute = AuthenticatedRoute.extend(styleBody, { classNames: ['editor'], model: function () { return this.store.createRecord('post'); }, setupController: function (controller, model) { this._super(controller, model); controller.set('scratch', ''); // used to check if anything has changed in the editor controller.set('previousTagNames', Ember.A()); }, actions: { willTransition: function (transition) { var controller = this.get('controller'), isDirty = controller.get('isDirty'), model = controller.get('model'), isNew = model.get('isNew'), isSaving = model.get('isSaving'), isDeleted = model.get('isDeleted'); // when `isDeleted && isSaving`, model is in-flight, being saved // to the server. in that case we can probably just transition // now and have the server return the record, thereby updating it if (!(isDeleted && isSaving) && isDirty) { transition.abort(); this.send('openModal', 'leave-editor', [controller, transition]); return; } if (isNew) { model.deleteRecord(); } // since the transition is now certain to complete.. window.onbeforeunload = null; } } }); __exports__["default"] = EditorNewRoute; });
describe('ngNuxeoUI module', function () { 'use strict'; var nuxeo, $compile, $scope, $templateCache; beforeEach( module( 'ngNuxeoUI', 'data/entry-picture.json', 'data/entry-audio.json', 'expected/nuxeo-picture.html', 'expected/nuxeo-audio.html', 'data/user.json' ) ); beforeEach(inject(function ($httpBackend, _nuxeo_, _$compile_, _$rootScope_, _nuxeoUser_, _$templateCache_) { nuxeo = _nuxeo_; $compile = _$compile_; $scope = _$rootScope_.$new(); $templateCache = _$templateCache_; _nuxeoUser_.id =_nuxeoUser_.pathId = 'Administrator'; })); describe('nuxeoDocument directive', function () { it('should display an image when entry is a Picture', function () { inject(function (_dataEntryPicture_) { $scope.entry = new nuxeo.Document(_dataEntryPicture_); }); var expectedPicture = $templateCache.get('expected/nuxeo-picture.html'); // Compile a piece of HTML containing the directive var element = $compile('<nuxeo-document entry="entry" publish-to="{{publishPath}}" on-success="onSuccess()" on-error="onError()"></nuxeo-document>')($scope); // fire all the watches $scope.$digest(); expect(element.html().ignoreUnsignificantChars()).toEqual(expectedPicture.ignoreUnsignificantChars()); }); it('should display audio when entry is a Audio', function () { inject(function (_dataEntryAudio_) { $scope.entry = new nuxeo.Document(_dataEntryAudio_); }); var expectedAudio = $templateCache.get('expected/nuxeo-audio.html'); // Compile a piece of HTML containing the directive var element = $compile('<nuxeo-document entry="entry" publish-to="{{publishPath}}" on-success="onSuccess()" on-error="onError()"></nuxeo-document>')($scope); // fire all the watches $scope.$digest(); expect(element.html().ignoreUnsignificantChars()).toEqual(expectedAudio.ignoreUnsignificantChars()); }); }); });
module.exports.basename = require('./basename'); module.exports.dirname = require('./dirname'); module.exports.fclose = require('./fclose'); module.exports.feof = require('./feof'); module.exports.fgetc = require('./fgetc'); module.exports.fgetcsv = require('./fgetcsv'); module.exports.fgets = require('./fgets'); module.exports.fgetss = require('./fgetss'); module.exports.file = require('./file'); module.exports.file_exists = require('./file_exists'); module.exports.file_get_contents = require('./file_get_contents'); module.exports.filemtime = require('./filemtime'); module.exports.filesize = require('./filesize'); module.exports.fopen = require('./fopen'); module.exports.fpassthru = require('./fpassthru'); module.exports.fread = require('./fread'); module.exports.fscanf = require('./fscanf'); module.exports.fseek = require('./fseek'); module.exports.ftell = require('./ftell'); module.exports.pathinfo = require('./pathinfo'); module.exports.pclose = require('./pclose'); module.exports.popen = require('./popen'); module.exports.readfile = require('./readfile'); module.exports.realpath = require('./realpath'); module.exports.rewind = require('./rewind');
var $hxClasses = $hxClasses || {},$estr = function() { return js.Boot.__string_rec(this,''); }; function $extend(from, fields) { function inherit() {}; inherit.prototype = from; var proto = new inherit(); for (var name in fields) proto[name] = fields[name]; return proto; } var CADelegate = $hxClasses["CADelegate"] = function() { this.startPointPassed = false; this.kenBurnsPointInPassed = false; this.kenBurnsPointOutPassed = false; }; CADelegate.__name__ = ["CADelegate"]; CADelegate.prototype = { kbOut: function() { this.kenBurnsPointOutPassed = true; if(Reflect.isFunction(this.kenBurnsBeginsFadingOut)) try { this.kenBurnsBeginsFadingOut.apply(null,this.arguments); } catch( e ) { haxe.Log.trace(e,{ fileName : "CADelegate.hx", lineNumber : 74, className : "CADelegate", methodName : "kbOut"}); } } ,kbIn: function() { this.kenBurnsPointInPassed = true; if(Reflect.isFunction(this.kenBurnsDidFadedIn)) try { this.kenBurnsDidFadedIn.apply(null,this.arguments); } catch( e ) { haxe.Log.trace(e,{ fileName : "CADelegate.hx", lineNumber : 67, className : "CADelegate", methodName : "kbIn"}); } } ,repeat: function() { if(Reflect.isFunction(this.animationDidReversed)) try { this.animationDidReversed.apply(null,this.arguments); } catch( e ) { haxe.Log.trace(e,{ fileName : "CADelegate.hx", lineNumber : 60, className : "CADelegate", methodName : "repeat"}); } } ,stop: function() { if(Reflect.isFunction(this.animationDidStop)) try { this.animationDidStop.apply(null,this.arguments); } catch( e ) { haxe.Log.trace(e,{ fileName : "CADelegate.hx", lineNumber : 50, className : "CADelegate", methodName : "stop"}); haxe.Log.trace(this.pos.className + " -> " + this.pos.methodName + " -> " + this.pos.lineNumber,{ fileName : "CADelegate.hx", lineNumber : 51, className : "CADelegate", methodName : "stop"}); var stack = haxe.Stack.exceptionStack(); haxe.Log.trace(haxe.Stack.toString(stack),{ fileName : "CADelegate.hx", lineNumber : 53, className : "CADelegate", methodName : "stop"}); } } ,start: function() { this.startPointPassed = true; if(Reflect.isFunction(this.animationDidStart)) try { this.animationDidStart.apply(null,this.arguments); } catch( e ) { haxe.Log.trace(e,{ fileName : "CADelegate.hx", lineNumber : 38, className : "CADelegate", methodName : "start"}); } } ,pos: null ,kenBurnsPointOut: null ,kenBurnsPointIn: null ,kenBurnsPointOutPassed: null ,kenBurnsPointInPassed: null ,startPointPassed: null ,kenBurnsArgs: null ,kenBurnsBeginsFadingOut: null ,kenBurnsDidFadedIn: null ,arguments: null ,animationDidReversed: null ,animationDidStop: null ,animationDidStart: null ,__class__: CADelegate } var CAObject = $hxClasses["CAObject"] = function(target,properties,duration,delay,Eq,pos) { this.target = target; this.properties = properties; this.repeatCount = 0; this.autoreverses = false; this.fromTime = new Date().getTime(); this.duration = duration == null?CoreAnimation.defaultDuration:duration <= 0?0.001:duration; this.delay = delay == null || delay < 0?0:delay; if(Eq == null) this.timingFunction = CoreAnimation.defaultTimingFunction; else this.timingFunction = Eq; this.delegate = new CADelegate(); this.delegate.pos = pos; this.fromValues = { }; this.toValues = { }; }; CAObject.__name__ = ["CAObject"]; CAObject.prototype = { toString: function() { return "[CAObject: target=" + Std.string(this.target) + ", duration=" + this.duration + ", delay=" + this.delay + ", fromTime=" + this.fromTime + ", properties=" + Std.string(this.properties) + ", repeatCount=" + this.repeatCount + "]"; } ,calculate: function(time_diff,prop) { return this.timingFunction(time_diff,Reflect.field(this.fromValues,prop),Reflect.field(this.toValues,prop) - Reflect.field(this.fromValues,prop),this.duration,null); } ,repeat: function() { this.fromTime = new Date().getTime(); this.delay = 0; if(this.autoreverses) { var v = this.fromValues; this.fromValues = this.toValues; this.toValues = v; } this.repeatCount--; } ,initTime: function() { this.fromTime = new Date().getTime(); this.duration = this.duration * 1000; this.delay = this.delay * 1000; } ,animate: function(time_diff) { throw "CAObject should be extended, use a CATransition (" + Std.string(this.delegate.pos) + ")"; } ,init: function() { throw "CAObject should be extended, use a CATransition (" + Std.string(this.delegate.pos) + ")"; } ,delegate: null ,constraintBounds: null ,timingFunction: null ,autoreverses: null ,repeatCount: null ,duration: null ,delay: null ,fromTime: null ,toValues: null ,fromValues: null ,properties: null ,next: null ,prev: null ,target: null ,__class__: CAObject } var CASequence = $hxClasses["CASequence"] = function(objs) { this.objs = objs; }; CASequence.__name__ = ["CASequence"]; CASequence.prototype = { animationDidStopHandler: function(func) { if(func != null) { if(Reflect.isFunction(func)) func.apply(null,[]); } if(this.objs.length > 0) this.start(); } ,start: function() { var obj = this.objs.shift(); if(this.objs.length > 0) { var arguments = obj.delegate.animationDidStop; obj.delegate.animationDidStop = $bind(this,this.animationDidStopHandler); obj.delegate.arguments = [arguments]; } CoreAnimation.add(obj); } ,objs: null ,__class__: CASequence } var CATransitionInterface = $hxClasses["CATransitionInterface"] = function() { } CATransitionInterface.__name__ = ["CATransitionInterface"]; CATransitionInterface.prototype = { animate: null ,init: null ,__class__: CATransitionInterface } var CATCallFunc = $hxClasses["CATCallFunc"] = function(target,properties,duration,delay,Eq,pos) { CAObject.call(this,target,properties,duration,delay,Eq,pos); }; CATCallFunc.__name__ = ["CATCallFunc"]; CATCallFunc.__interfaces__ = [CATransitionInterface]; CATCallFunc.__super__ = CAObject; CATCallFunc.prototype = $extend(CAObject.prototype,{ animate: function(time_diff) { var _g = 0, _g1 = Reflect.fields(this.toValues); while(_g < _g1.length) { var prop = _g1[_g]; ++_g; try { this.target(this.timingFunction(time_diff,Reflect.field(this.fromValues,prop),Reflect.field(this.toValues,prop) - Reflect.field(this.fromValues,prop),this.duration,null)); } catch( e ) { haxe.Log.trace(e,{ fileName : "CATCallFunc.hx", lineNumber : 41, className : "CATCallFunc", methodName : "animate"}); } } } ,init: function() { if(!Reflect.isFunction(this.target)) throw "Function must be of type: Float->Void"; var _g = 0, _g1 = Reflect.fields(this.properties); while(_g < _g1.length) { var p = _g1[_g]; ++_g; if(js.Boot.__instanceof(Reflect.field(this.properties,p),Int) || js.Boot.__instanceof(Reflect.field(this.properties,p),Float)) { this.fromValues[p] = 0; this.toValues[p] = Reflect.field(this.properties,p); } else try { this.fromValues[p] = Reflect.field(Reflect.field(this.properties,p),"fromValue"); try { this.target(Reflect.field(this.fromValues,p)); } catch( e ) { haxe.Log.trace(e,{ fileName : "CATCallFunc.hx", lineNumber : 28, className : "CATCallFunc", methodName : "init"}); } this.toValues[p] = Reflect.field(Reflect.field(this.properties,p),"toValue"); } catch( e ) { haxe.Log.trace(e,{ fileName : "CATCallFunc.hx", lineNumber : 31, className : "CATCallFunc", methodName : "init"}); } } } ,__class__: CATCallFunc }); var CATween = $hxClasses["CATween"] = function(target,properties,duration,delay,Eq,pos) { CAObject.call(this,target,properties,duration,delay,Eq,pos); }; CATween.__name__ = ["CATween"]; CATween.__interfaces__ = [CATransitionInterface]; CATween.__super__ = CAObject; CATween.prototype = $extend(CAObject.prototype,{ animate: function(time_diff) { var _g = 0, _g1 = Reflect.fields(this.toValues); while(_g < _g1.length) { var prop = _g1[_g]; ++_g; try { var setter = "set" + HxOverrides.substr(prop,0,1).toUpperCase() + HxOverrides.substr(prop,1,null); if(setter != null) Reflect.field(this.target,setter).apply(this.target,[this.timingFunction(time_diff,Reflect.field(this.fromValues,prop),Reflect.field(this.toValues,prop) - Reflect.field(this.fromValues,prop),this.duration,null)]); } catch( e ) { haxe.Log.trace(e,{ fileName : "CATween.hx", lineNumber : 51, className : "CATween", methodName : "animate"}); } } } ,init: function() { var _g = 0, _g1 = Reflect.fields(this.properties); while(_g < _g1.length) { var p = _g1[_g]; ++_g; if(js.Boot.__instanceof(Reflect.field(this.properties,p),Int) || js.Boot.__instanceof(Reflect.field(this.properties,p),Float)) { var getter = "get" + HxOverrides.substr(p,0,1).toUpperCase() + HxOverrides.substr(p,1,null); if(getter == null) this.fromValues[p] = Reflect.field(this.target,p); else this.fromValues[p] = Reflect.field(this.target,getter).apply(this.target,[]); this.toValues[p] = Reflect.field(this.properties,p); } else try { this.fromValues[p] = Reflect.field(Reflect.field(this.properties,p),"fromValue"); this.target[p] = Reflect.field(this.fromValues,p); this.toValues[p] = Reflect.field(Reflect.field(this.properties,p),"toValue"); } catch( e ) { haxe.Log.trace(e,{ fileName : "CATween.hx", lineNumber : 32, className : "CATween", methodName : "init"}); } } } ,__class__: CATween }); var caequations = caequations || {} caequations.Linear = $hxClasses["caequations.Linear"] = function() { } caequations.Linear.__name__ = ["caequations","Linear"]; caequations.Linear.NONE = function(t,b,c,d,p_params) { return c * t / d + b; } var CoreAnimation = $hxClasses["CoreAnimation"] = function() { } CoreAnimation.__name__ = ["CoreAnimation"]; CoreAnimation.latest = null; CoreAnimation.ticker = null; CoreAnimation.add = function(obj) { if(obj == null) return; if(obj.target == null) return; var a = CoreAnimation.latest; var prev = CoreAnimation.latest; if(prev != null) prev.next = obj; obj.prev = prev; CoreAnimation.latest = obj; obj.init(); obj.initTime(); if(CoreAnimation.ticker == null) { CoreAnimation.ticker = new EVLoop({ fileName : "CoreAnimation.hx", lineNumber : 50, className : "CoreAnimation", methodName : "add"}); CoreAnimation.ticker.setFuncToCall(CoreAnimation.updateAnimations); } } CoreAnimation.remove = function(obj) { if(obj == null) return; var a = CoreAnimation.latest; while(a != null) { if(a.target == obj) CoreAnimation.removeCAObject(a); a = a.prev; } } CoreAnimation.removeCAObject = function(a) { if(a.prev != null) a.prev.next = a.next; if(a.next != null) a.next.prev = a.prev; if(CoreAnimation.latest == a) CoreAnimation.latest = a.prev != null?a.prev:null; CoreAnimation.removeTimer(); a = null; } CoreAnimation.removeTimer = function() { if(CoreAnimation.latest == null && CoreAnimation.ticker != null) { CoreAnimation.ticker.destroy(); CoreAnimation.ticker = null; } } CoreAnimation.destroy = function() { CoreAnimation.latest = null; CoreAnimation.removeTimer(); } CoreAnimation.updateAnimations = function() { var current_time = new Date().getTime(); var time_diff = 0.0; var a = CoreAnimation.latest; while(a != null) { if(a.target == null) { a = a.prev; CoreAnimation.removeCAObject(a); break; } time_diff = current_time - a.fromTime - a.delay; if(time_diff >= a.duration) time_diff = a.duration; if(time_diff > 0) { a.animate(time_diff); if(time_diff > 0 && !a.delegate.startPointPassed) a.delegate.start(); if(time_diff >= a.duration) { if(a.repeatCount > 0) { a.repeat(); a.delegate.repeat(); } else { CoreAnimation.removeCAObject(a); a.delegate.stop(); } } if(a.delegate.kenBurnsPointIn != null) { if(time_diff > a.delegate.kenBurnsPointIn && !a.delegate.kenBurnsPointInPassed) a.delegate.kbIn(); if(time_diff > a.delegate.kenBurnsPointOut && !a.delegate.kenBurnsPointOutPassed) a.delegate.kbOut(); } } a = a.prev; } } CoreAnimation.timestamp = function() { return new Date().getTime(); } var RCSignal = $hxClasses["RCSignal"] = function() { this.enabled = true; this.removeAll(); }; RCSignal.__name__ = ["RCSignal"]; RCSignal.prototype = { destroy: function(pos) { this.listeners = null; this.exposableListener = null; } ,exists: function(listener) { var $it0 = this.listeners.iterator(); while( $it0.hasNext() ) { var l = $it0.next(); if(l == listener) return true; } return false; } ,callMethod: function(listener,args,pos) { try { listener.apply(null,args); } catch( e ) { haxe.Log.trace("[RCSignal error: " + Std.string(e) + ", called from: " + Std.string(pos) + "]",{ fileName : "RCSignal.hx", lineNumber : 75, className : "RCSignal", methodName : "callMethod"}); Fugu.stack(); } } ,dispatch: function(p1,p2,p3,p4,pos) { if(!this.enabled) return; var args = new Array(); var _g = 0, _g1 = [p1,p2,p3,p4]; while(_g < _g1.length) { var p = _g1[_g]; ++_g; if(p != null) args.push(p); else break; } var $it0 = this.listeners.iterator(); while( $it0.hasNext() ) { var listener = $it0.next(); this.callMethod(listener,args,pos); } if(this.exposableListener != null) { this.callMethod(this.exposableListener,args,pos); this.exposableListener = null; } } ,removeAll: function() { this.listeners = new List(); this.exposableListener = null; } ,remove: function(listener) { var $it0 = this.listeners.iterator(); while( $it0.hasNext() ) { var l = $it0.next(); if(Reflect.compareMethods(l,listener)) { this.listeners.remove(l); break; } } if(Reflect.compareMethods(this.exposableListener,listener)) this.exposableListener = null; } ,addFirst: function(listener,pos) { this.listeners.push(listener); } ,addOnce: function(listener,pos) { if(this.exists(listener)) haxe.Log.trace("This listener is already added, it will not be called only once as you expect. " + Std.string(pos),{ fileName : "RCSignal.hx", lineNumber : 23, className : "RCSignal", methodName : "addOnce"}); this.exposableListener = listener; } ,add: function(listener) { this.listeners.add(listener); } ,enabled: null ,exposableListener: null ,listeners: null ,__class__: RCSignal } var EVFullScreen = $hxClasses["EVFullScreen"] = function() { RCSignal.call(this); }; EVFullScreen.__name__ = ["EVFullScreen"]; EVFullScreen.__super__ = RCSignal; EVFullScreen.prototype = $extend(RCSignal.prototype,{ __class__: EVFullScreen }); var EVLoop = $hxClasses["EVLoop"] = function(pos) { }; EVLoop.__name__ = ["EVLoop"]; EVLoop.prototype = { destroy: function() { this.stop({ fileName : "EVLoop.hx", lineNumber : 47, className : "EVLoop", methodName : "destroy"}); } ,stop: function(pos) { if(this.ticker == null) return; this.ticker.stop(); this.ticker = null; } ,loop: function() { if(this.run != null) this.run(); } ,setFuncToCall: function(func) { this.stop({ fileName : "EVLoop.hx", lineNumber : 18, className : "EVLoop", methodName : "setFuncToCall"}); this.run = func; this.ticker = new haxe.Timer(Math.round(1 / EVLoop.FPS * 1000)); this.ticker.run = $bind(this,this.loop); return func; } ,run: null ,ticker: null ,__class__: EVLoop ,__properties__: {set_run:"setFuncToCall"} } var EVMouse = $hxClasses["EVMouse"] = function(type,target,pos) { if(target == null) throw "Can't use a null target. " + Std.string(pos); RCSignal.call(this); this.type = type; this.target = target; this.delta = 0; this.targets = new List(); if(js.Boot.__instanceof(target,JSView)) this.layer = (js.Boot.__cast(target , JSView)).layer; if(this.layer == null) this.layer = target; this.addEventListener(pos); }; EVMouse.__name__ = ["EVMouse"]; EVMouse.__super__ = RCSignal; EVMouse.prototype = $extend(RCSignal.prototype,{ destroy: function(pos) { this.removeEventListener(); RCSignal.prototype.destroy.call(this,{ fileName : "EVMouse.hx", lineNumber : 208, className : "EVMouse", methodName : "destroy"}); } ,MouseScroll: function(e) { if(Reflect.field(e,"wheelDelta") != null) this.delta = e.wheelDelta; else if(Reflect.field(e,"detail") != null) this.delta = -Math.round(e.detail * 5); this.e = e; this.dispatch(this,null,null,null,{ fileName : "EVMouse.hx", lineNumber : 200, className : "EVMouse", methodName : "MouseScroll"}); } ,mouseScrollHandler: null ,removeWheelListener: function() { if(this.layer.removeEventListener) { this.layer.removeEventListener("mousewheel",this.mouseScrollHandler,false); this.layer.removeEventListener("DOMMouseScroll",this.mouseScrollHandler,false); } else if(this.layer.detachEvent) this.layer.detachEvent("onmousewheel",this.mouseScrollHandler); } ,addWheelListener: function() { this.mouseScrollHandler = $bind(this,this.MouseScroll); if(this.layer.addEventListener) { this.layer.addEventListener("mousewheel",this.mouseScrollHandler,false); this.layer.addEventListener("DOMMouseScroll",this.mouseScrollHandler,false); } else if(this.layer.attachEvent) this.layer.attachEvent("onmousewheel",this.mouseScrollHandler); } ,updateAfterEvent: function() { } ,mouseHandler: function(e) { if(e == null) e = js.Lib.window.event; this.e = e; this.dispatch(this,null,null,null,{ fileName : "EVMouse.hx", lineNumber : 143, className : "EVMouse", methodName : "mouseHandler"}); } ,removeEventListener: function() { switch(this.type) { case "mouseup": this.layer.onmouseup = null; break; case "mousedown": this.layer.onmousedown = null; break; case "mouseover": this.layer.onmouseover = null; break; case "mouseout": this.layer.onmouseout = null; break; case "mousemove": this.layer.onmousemove = null; break; case "mouseclick": this.layer.onclick = null; break; case "mousedoubleclick": this.layer.ondblclick = null; break; case "mousewheel": this.removeWheelListener(); break; } } ,addEventListener: function(pos) { var $it0 = this.targets.iterator(); while( $it0.hasNext() ) { var t = $it0.next(); if(t.target == this.target && t.type == this.type) { haxe.Log.trace("Target already in use by this event type. Called from " + Std.string(pos),{ fileName : "EVMouse.hx", lineNumber : 86, className : "EVMouse", methodName : "addEventListener"}); return; } } switch(this.type) { case "mouseup": this.layer.onmouseup = $bind(this,this.mouseHandler); break; case "mousedown": this.layer.onmousedown = $bind(this,this.mouseHandler); break; case "mouseover": this.layer.onmouseover = $bind(this,this.mouseHandler); break; case "mouseout": this.layer.onmouseout = $bind(this,this.mouseHandler); break; case "mousemove": this.layer.onmousemove = $bind(this,this.mouseHandler); break; case "mouseclick": this.layer.onclick = $bind(this,this.mouseHandler); break; case "mousedoubleclick": this.layer.ondblclick = $bind(this,this.mouseHandler); break; case "mousewheel": this.addWheelListener(); break; default: haxe.Log.trace("The mouse event you're trying to add does not exist. " + Std.string(pos),{ fileName : "EVMouse.hx", lineNumber : 101, className : "EVMouse", methodName : "addEventListener"}); } } ,targets: null ,layer: null ,delta: null ,e: null ,type: null ,target: null ,__class__: EVMouse }); var EVResize = $hxClasses["EVResize"] = function() { RCSignal.call(this); js.Lib.window.onresize = $bind(this,this.resizeHandler); }; EVResize.__name__ = ["EVResize"]; EVResize.__super__ = RCSignal; EVResize.prototype = $extend(RCSignal.prototype,{ resizeHandler: function(e) { var w = js.Lib.window.innerWidth; var h = js.Lib.window.innerHeight; this.dispatch(w,h,null,null,{ fileName : "EVResize.hx", lineNumber : 34, className : "EVResize", methodName : "resizeHandler"}); } ,__class__: EVResize }); var Fugu = $hxClasses["Fugu"] = function() { } Fugu.__name__ = ["Fugu"]; Fugu.safeDestroy = function(obj,destroy,pos) { if(destroy == null) destroy = true; if(obj == null) return false; var objs = js.Boot.__instanceof(obj,Array)?obj:[obj]; var _g = 0; while(_g < objs.length) { var o = objs[_g]; ++_g; if(o == null) continue; if(destroy) try { o.destroy(); } catch( e ) { haxe.Log.trace("[Error when destroying object: " + Std.string(o) + ", called from " + Std.string(pos) + "]",{ fileName : "Fugu.hx", lineNumber : 28, className : "Fugu", methodName : "safeDestroy"}); haxe.Log.trace(Fugu.stack(),{ fileName : "Fugu.hx", lineNumber : 29, className : "Fugu", methodName : "safeDestroy"}); } if(js.Boot.__instanceof(o,JSView)) (js.Boot.__cast(o , JSView)).removeFromSuperview(); else { var parent = null; try { parent = o.parent; } catch( e ) { null; } if(parent != null) { if(parent.contains(o)) parent.removeChild(o); } } } return true; } Fugu.safeRemove = function(obj) { return Fugu.safeDestroy(obj,false,{ fileName : "Fugu.hx", lineNumber : 46, className : "Fugu", methodName : "safeRemove"}); } Fugu.safeAdd = function(target,obj) { if(target == null || obj == null) return false; var objs = js.Boot.__instanceof(obj,Array)?obj:[obj]; var _g = 0; while(_g < objs.length) { var o = objs[_g]; ++_g; if(o != null) target.addChild(o); } return true; } Fugu.glow = function(target,color,alpha,blur,strength) { if(strength == null) strength = 0.6; } Fugu.color = function(target,color) { } Fugu.resetColor = function(target) { } Fugu.brightness = function(target,brightness) { } Fugu.align = function(obj,alignment,constraint_w,constraint_h,obj_w,obj_h,margin_x,margin_y) { if(margin_y == null) margin_y = 0; if(margin_x == null) margin_x = 0; if(obj == null) return; var arr = alignment.toLowerCase().split(","); if(obj_w == null) obj_w = obj.getWidth(); if(obj_h == null) obj_h = obj.getHeight(); obj.setX((function($this) { var $r; switch(arr[0]) { case "l": $r = margin_x; break; case "m": $r = Math.round((constraint_w - obj_w) / 2); break; case "r": $r = Math.round(constraint_w - obj_w - margin_x); break; default: $r = Std.parseInt(arr[0]); } return $r; }(this))); obj.setY((function($this) { var $r; switch(arr[1]) { case "t": $r = margin_y; break; case "m": $r = Math.round((constraint_h - obj_h) / 2); break; case "b": $r = Math.round(constraint_h - obj_h - margin_y); break; default: $r = Std.parseInt(arr[1]); } return $r; }(this))); } Fugu.stack = function() { var stack = haxe.Stack.exceptionStack(); haxe.Log.trace(haxe.Stack.toString(stack),{ fileName : "Fugu.hx", lineNumber : 161, className : "Fugu", methodName : "stack"}); } var JSExternalInterface = $hxClasses["JSExternalInterface"] = function() { } JSExternalInterface.__name__ = ["JSExternalInterface"]; JSExternalInterface.addCallback = function(functionName,closure) { switch(functionName) { case "setSWFAddressValue": SWFAddress.addEventListener("change",function(e) { closure(e.value); }); break; } } JSExternalInterface.call = function(functionName,p1,p2,p3,p4,p5) { switch(functionName) { case "SWFAddress.back": SWFAddress.back(); break; case "SWFAddress.forward": SWFAddress.forward(); break; case "SWFAddress.go": SWFAddress.go(p1); break; case "SWFAddress.href": SWFAddress.href(p1,p2); break; case "SWFAddress.popup": SWFAddress.popup(p1,p2,p3,p4); break; case "SWFAddress.getBaseURL": return SWFAddress.getBaseURL(); case "SWFAddress.getStrict": return SWFAddress.getStrict(); case "SWFAddress.setStrict": SWFAddress.setStrict(p1); break; case "SWFAddress.getHistory": return SWFAddress.getHistory(); case "SWFAddress.setHistory": SWFAddress.setHistory(p1); break; case "SWFAddress.getTracker": return SWFAddress.getTracker(); case "SWFAddress.setTracker": SWFAddress.setTracker(p1); break; case "SWFAddress.getTitle": return SWFAddress.getTitle(); case "SWFAddress.setTitle": SWFAddress.setTitle(p1); break; case "SWFAddress.getStatus": return SWFAddress.getStatus(); case "SWFAddress.setStatus": SWFAddress.setStatus(p1); break; case "SWFAddress.resetStatus": SWFAddress.resetStatus(); break; case "SWFAddress.getValue": return SWFAddress.getValue(); case "SWFAddress.setValue": SWFAddress.setValue(p1); break; case "SWFAddress.getIds": return SWFAddress.getIds(); case "function() { return (typeof SWFAddress != \"undefined\"); }": return function() { return (typeof SWFAddress != "undefined"); }(); default: throw "You are trying to call an inexisting extern method"; } return null; } var HXAddressSignal = $hxClasses["HXAddressSignal"] = function() { this.removeAll(); }; HXAddressSignal.__name__ = ["HXAddressSignal"]; HXAddressSignal.prototype = { dispatch: function(args) { var $it0 = this.listeners.iterator(); while( $it0.hasNext() ) { var listener = $it0.next(); try { listener.apply(null,[args.slice()]); } catch( e ) { haxe.Log.trace("[HXAddressEvent error calling: " + Std.string(listener) + "]",{ fileName : "HXAddress.hx", lineNumber : 524, className : "HXAddressSignal", methodName : "dispatch"}); } } } ,removeAll: function() { this.listeners = new List(); } ,remove: function(listener) { var $it0 = this.listeners.iterator(); while( $it0.hasNext() ) { var l = $it0.next(); if(Reflect.compareMethods(l,listener)) { this.listeners.remove(listener); return; } } } ,add: function(listener) { this.listeners.add(listener); } ,listeners: null ,__class__: HXAddressSignal } var haxe = haxe || {} haxe.Timer = $hxClasses["haxe.Timer"] = function(time_ms) { var me = this; this.id = window.setInterval(function() { me.run(); },time_ms); }; haxe.Timer.__name__ = ["haxe","Timer"]; haxe.Timer.delay = function(f,time_ms) { var t = new haxe.Timer(time_ms); t.run = function() { t.stop(); f(); }; return t; } haxe.Timer.measure = function(f,pos) { var t0 = haxe.Timer.stamp(); var r = f(); haxe.Log.trace(haxe.Timer.stamp() - t0 + "s",pos); return r; } haxe.Timer.stamp = function() { return new Date().getTime() / 1000; } haxe.Timer.prototype = { run: function() { } ,stop: function() { if(this.id == null) return; window.clearInterval(this.id); this.id = null; } ,id: null ,__class__: haxe.Timer } var HXAddress = $hxClasses["HXAddress"] = function() { throw "HXAddress should not be instantiated."; }; HXAddress.__name__ = ["HXAddress"]; HXAddress._queueTimer = null; HXAddress._initTimer = null; HXAddress.init = null; HXAddress.change = null; HXAddress.externalChange = null; HXAddress.internalChange = null; HXAddress._initialize = function() { if(HXAddress._availability) try { HXAddress._availability = JSExternalInterface.call("function() { return (typeof SWFAddress != \"undefined\"); }"); JSExternalInterface.addCallback("getSWFAddressValue",function() { return HXAddress._value; }); JSExternalInterface.addCallback("setSWFAddressValue",HXAddress._setValue); } catch( e ) { HXAddress._availability = false; } HXAddress.init = new HXAddressSignal(); HXAddress.change = new HXAddressSignal(); HXAddress.externalChange = new HXAddressSignal(); HXAddress.internalChange = new HXAddressSignal(); HXAddress._initTimer = new haxe.Timer(10); HXAddress._initTimer.run = HXAddress._check; return true; } HXAddress._check = function() { if(HXAddress.init.listeners.length > 0 && !HXAddress._init) { HXAddress._setValueInit(HXAddress._getValue()); HXAddress._init = true; } if(HXAddress.change.listeners.length > 0) { if(HXAddress._initTimer != null) HXAddress._initTimer.stop(); HXAddress._initTimer = null; HXAddress._init = true; HXAddress._setValueInit(HXAddress._getValue()); } } HXAddress._strictCheck = function(value,force) { if(HXAddress.getStrict()) { if(force) { if(HxOverrides.substr(value,0,1) != "/") value = "/" + value; } else if(value == "") value = "/"; } return value; } HXAddress._getValue = function() { var value = null, ids = null; if(HXAddress._availability) { value = Std.string(JSExternalInterface.call("SWFAddress.getValue")); var arr = JSExternalInterface.call("SWFAddress.getIds"); if(arr != null) ids = arr.toString(); } if(HXAddress.isNull(ids) || !HXAddress._availability || HXAddress._initChanged) value = HXAddress._value; else if(HXAddress.isNull(value)) value = ""; return HXAddress._strictCheck(value,false); } HXAddress._setValueInit = function(value) { HXAddress._value = value; var pathNames = HXAddress.getPathNames(); if(!HXAddress._init) HXAddress.init.dispatch(pathNames); else { HXAddress.change.dispatch(pathNames); HXAddress.externalChange.dispatch(pathNames); } HXAddress._initChange = true; } HXAddress._setValue = function(value) { if(HXAddress.isNull(value)) value = ""; if(HXAddress._value == value && HXAddress._init) return; if(!HXAddress._initChange) return; HXAddress._value = value; var pathNames = HXAddress.getPathNames(); if(!HXAddress._init) { HXAddress._init = true; HXAddress.init.dispatch(pathNames); } HXAddress.change.dispatch(pathNames); HXAddress.externalChange.dispatch(pathNames); } HXAddress._callQueue = function() { haxe.Log.trace("If you see this trace means something went wrong, _callQueue is used in flash on Mac only",{ fileName : "HXAddress.hx", lineNumber : 142, className : "HXAddress", methodName : "_callQueue"}); if(HXAddress._queue.length != 0) { var script = ""; var _g = 0, _g1 = HXAddress._queue; while(_g < _g1.length) { var q = _g1[_g]; ++_g; if(js.Boot.__instanceof(q.param,String)) q.param = "\"" + Std.string(q.param) + "\""; script += q.fn + "(" + Std.string(q.param) + ");"; } HXAddress._queue = []; } else if(HXAddress._queueTimer != null) { HXAddress._queueTimer.stop(); HXAddress._queueTimer = null; } } HXAddress._call = function(fn,param) { if(param == null) param = ""; if(HXAddress._availability) { JSExternalInterface.call(fn,param); return; if(HXAddress.isMac()) { if(HXAddress._queue.length == 0) { if(HXAddress._queueTimer != null) HXAddress._queueTimer.stop(); HXAddress._queueTimer = new haxe.Timer(10); HXAddress._queueTimer.run = HXAddress._callQueue; } var q = { fn : fn, param : param}; HXAddress._queue.push(q); } else JSExternalInterface.call(fn,param); } } HXAddress.back = function() { HXAddress._call("SWFAddress.back"); } HXAddress.forward = function() { HXAddress._call("SWFAddress.forward"); } HXAddress.up = function() { var path = HXAddress.getPath(); HXAddress.setValue(HxOverrides.substr(path,0,path.lastIndexOf("/",path.length - 2) + (HxOverrides.substr(path,path.length - 1,null) == "/"?1:0))); } HXAddress.go = function(delta) { HXAddress._call("SWFAddress.go",delta); } HXAddress.href = function(url,target) { if(target == null) target = "_self"; if(HXAddress._availability && (HXAddress.isActiveX() || HXAddress.isJS())) { JSExternalInterface.call("SWFAddress.href",url,target); return; } } HXAddress.popup = function(url,name,options,handler) { if(handler == null) handler = ""; if(options == null) options = "\"\""; if(name == null) name = "popup"; if(HXAddress._availability && (HXAddress.isActiveX() || HXAddress.isJS() || JSExternalInterface.call("asual.util.Browser.isSafari"))) { haxe.Log.trace("good to go",{ fileName : "HXAddress.hx", lineNumber : 243, className : "HXAddress", methodName : "popup"}); JSExternalInterface.call("SWFAddress.popup",url,name,options,handler); return; } } HXAddress.getBaseURL = function() { var url = null; if(HXAddress._availability) url = Std.string(JSExternalInterface.call("SWFAddress.getBaseURL")); return HXAddress.isNull(url) || !HXAddress._availability?"":url; } HXAddress.getStrict = function() { var strict = null; if(HXAddress._availability) strict = Std.string(JSExternalInterface.call("SWFAddress.getStrict")); return HXAddress.isNull(strict)?HXAddress._strict:strict == "true"; } HXAddress.setStrict = function(strict) { HXAddress._call("SWFAddress.setStrict",strict); HXAddress._strict = strict; } HXAddress.getHistory = function() { if(HXAddress._availability) { var hasHistory = JSExternalInterface.call("SWFAddress.getHistory"); return hasHistory == "true" || hasHistory == true; } return false; } HXAddress.setHistory = function(history) { HXAddress._call("SWFAddress.setHistory",history); } HXAddress.getTracker = function() { return HXAddress._availability?Std.string(JSExternalInterface.call("SWFAddress.getTracker")):""; } HXAddress.setTracker = function(tracker) { HXAddress._call("SWFAddress.setTracker",tracker); } HXAddress.getTitle = function() { var title = HXAddress._availability?Std.string(JSExternalInterface.call("SWFAddress.getTitle")):""; if(HXAddress.isNull(title)) title = ""; return StringTools.htmlUnescape(title); } HXAddress.setTitle = function(title) { HXAddress._call("SWFAddress.setTitle",StringTools.htmlEscape(StringTools.htmlUnescape(title))); } HXAddress.getStatus = function() { var status = HXAddress._availability?Std.string(JSExternalInterface.call("SWFAddress.getStatus")):""; if(HXAddress.isNull(status)) status = ""; return StringTools.htmlUnescape(status); } HXAddress.setStatus = function(status) { HXAddress._call("SWFAddress.setStatus",StringTools.htmlEscape(StringTools.htmlUnescape(status))); } HXAddress.resetStatus = function() { HXAddress._call("SWFAddress.resetStatus"); } HXAddress.getValue = function() { return StringTools.htmlUnescape(HXAddress._strictCheck(HXAddress._value,false)); } HXAddress.setValue = function(value) { if(HXAddress.isNull(value)) value = ""; value = StringTools.htmlEscape(StringTools.htmlUnescape(HXAddress._strictCheck(value,true))); if(HXAddress._value == value) return; HXAddress._value = value; HXAddress._call("SWFAddress.setValue",value); if(HXAddress._init) { var pathNames = HXAddress.getPathNames(); HXAddress.change.dispatch(pathNames); HXAddress.internalChange.dispatch(pathNames); } else HXAddress._initChanged = true; } HXAddress.getPath = function() { var value = HXAddress.getValue(); if(value.indexOf("?") != -1) return value.split("?")[0]; else if(value.indexOf("#") != -1) return value.split("#")[0]; else return value; } HXAddress.getPathNames = function() { var path = HXAddress.getPath(); var names = path.split("/"); if(HxOverrides.substr(path,0,1) == "/" || path.length == 0) names.splice(0,1); if(HxOverrides.substr(path,path.length - 1,1) == "/") names.splice(names.length - 1,1); return names; } HXAddress.getQueryString = function() { var value = HXAddress.getValue(); var index = value.indexOf("?"); if(index != -1 && index < value.length) return HxOverrides.substr(value,index + 1,null); return null; } HXAddress.getParameter = function(param) { var value = HXAddress.getValue(); var index = value.indexOf("?"); if(index != -1) { value = HxOverrides.substr(value,index + 1,null); var params = value.split("&"); var i = params.length; while(i-- >= 0) { var p = params[i].split("="); if(p[0] == param) return p[1]; } } return null; } HXAddress.getParameterNames = function() { var value = HXAddress.getValue(); var index = value.indexOf("?"); var names = new Array(); if(index != -1) { value = HxOverrides.substr(value,index + 1,null); if(value != "" && value.indexOf("=") != -1) { var params = value.split("&"); var i = 0; while(i < params.length) { names.push(params[i].split("=")[0]); i++; } } } return names; } HXAddress.isNull = function(value) { return value == "undefined" || value == "null" || value == null; } HXAddress.isMac = function() { return true; } HXAddress.isActiveX = function() { return true; } HXAddress.isJS = function() { return true; } HXAddress.prototype = { __class__: HXAddress } var Hash = $hxClasses["Hash"] = function() { this.h = { }; }; Hash.__name__ = ["Hash"]; Hash.prototype = { toString: function() { var s = new StringBuf(); s.b += Std.string("{"); var it = this.keys(); while( it.hasNext() ) { var i = it.next(); s.b += Std.string(i); s.b += Std.string(" => "); s.b += Std.string(Std.string(this.get(i))); if(it.hasNext()) s.b += Std.string(", "); } s.b += Std.string("}"); return s.b; } ,iterator: function() { return { ref : this.h, it : this.keys(), hasNext : function() { return this.it.hasNext(); }, next : function() { var i = this.it.next(); return this.ref["$" + i]; }}; } ,keys: function() { var a = []; for( var key in this.h ) { if(this.h.hasOwnProperty(key)) a.push(key.substr(1)); } return HxOverrides.iter(a); } ,remove: function(key) { key = "$" + key; if(!this.h.hasOwnProperty(key)) return false; delete(this.h[key]); return true; } ,exists: function(key) { return this.h.hasOwnProperty("$" + key); } ,get: function(key) { return this.h["$" + key]; } ,set: function(key,value) { this.h["$" + key] = value; } ,h: null ,__class__: Hash } var HashArray = $hxClasses["HashArray"] = function() { Hash.call(this); this.array = new Array(); }; HashArray.__name__ = ["HashArray"]; HashArray.__super__ = Hash; HashArray.prototype = $extend(Hash.prototype,{ indexForKey: function(key) { var _g1 = 0, _g = this.array.length; while(_g1 < _g) { var i = _g1++; if(this.array[i] == key) return i; } return -1; } ,insert: function(pos,key,value) { if(Hash.prototype.exists.call(this,key)) return; this.array.splice(pos,0,key); Hash.prototype.set.call(this,key,value); } ,remove: function(key) { HxOverrides.remove(this.array,key); return Hash.prototype.remove.call(this,key); } ,set: function(key,value) { if(!Hash.prototype.exists.call(this,key)) this.array.push(key); Hash.prototype.set.call(this,key,value); } ,array: null ,__class__: HashArray }); var HxOverrides = $hxClasses["HxOverrides"] = function() { } HxOverrides.__name__ = ["HxOverrides"]; HxOverrides.dateStr = function(date) { var m = date.getMonth() + 1; var d = date.getDate(); var h = date.getHours(); var mi = date.getMinutes(); var s = date.getSeconds(); return date.getFullYear() + "-" + (m < 10?"0" + m:"" + m) + "-" + (d < 10?"0" + d:"" + d) + " " + (h < 10?"0" + h:"" + h) + ":" + (mi < 10?"0" + mi:"" + mi) + ":" + (s < 10?"0" + s:"" + s); } HxOverrides.strDate = function(s) { switch(s.length) { case 8: var k = s.split(":"); var d = new Date(); d.setTime(0); d.setUTCHours(k[0]); d.setUTCMinutes(k[1]); d.setUTCSeconds(k[2]); return d; case 10: var k = s.split("-"); return new Date(k[0],k[1] - 1,k[2],0,0,0); case 19: var k = s.split(" "); var y = k[0].split("-"); var t = k[1].split(":"); return new Date(y[0],y[1] - 1,y[2],t[0],t[1],t[2]); default: throw "Invalid date format : " + s; } } HxOverrides.cca = function(s,index) { var x = s.charCodeAt(index); if(x != x) return undefined; return x; } HxOverrides.substr = function(s,pos,len) { if(pos != null && pos != 0 && len != null && len < 0) return ""; if(len == null) len = s.length; if(pos < 0) { pos = s.length + pos; if(pos < 0) pos = 0; } else if(len < 0) len = s.length + len - pos; return s.substr(pos,len); } HxOverrides.remove = function(a,obj) { var i = 0; var l = a.length; while(i < l) { if(a[i] == obj) { a.splice(i,1); return true; } i++; } return false; } HxOverrides.iter = function(a) { return { cur : 0, arr : a, hasNext : function() { return this.cur < this.arr.length; }, next : function() { return this.arr[this.cur++]; }}; } var IntIter = $hxClasses["IntIter"] = function(min,max) { this.min = min; this.max = max; }; IntIter.__name__ = ["IntIter"]; IntIter.prototype = { next: function() { return this.min++; } ,hasNext: function() { return this.min < this.max; } ,max: null ,min: null ,__class__: IntIter } var JSCanvas = $hxClasses["JSCanvas"] = function() { } JSCanvas.__name__ = ["JSCanvas"]; var RCDisplayObject = $hxClasses["RCDisplayObject"] = function() { this.viewWillAppear = new RCSignal(); this.viewWillDisappear = new RCSignal(); this.viewDidAppear = new RCSignal(); this.viewDidDisappear = new RCSignal(); }; RCDisplayObject.__name__ = ["RCDisplayObject"]; RCDisplayObject.prototype = { toString: function() { return "[RCView bounds:" + this.getBounds().origin.x + "x" + this.getBounds().origin.y + "," + this.getBounds().size.width + "x" + this.getBounds().size.height + "]"; } ,destroy: function() { CoreAnimation.remove(this.caobj); this.size = null; } ,addAnimation: function(obj) { CoreAnimation.add(this.caobj = obj); } ,hitTest: function(otherObject) { return false; } ,removeChild: function(child) { } ,addChildAt: function(child,index) { } ,addChild: function(child) { } ,getMouseY: function() { return 0; } ,getMouseX: function() { return 0; } ,resetScale: function() { this.setWidth(this.originalSize.width); this.setHeight(this.originalSize.height); } ,scale: function(sx,sy) { } ,scaleToFill: function(w,h) { if(w / this.originalSize.width > h / this.originalSize.height) { this.setWidth(w); this.setHeight(w * this.originalSize.height / this.originalSize.width); } else { this.setHeight(h); this.setWidth(h * this.originalSize.width / this.originalSize.height); } } ,scaleToFit: function(w,h) { if(this.size.width / w > this.size.height / h && this.size.width > w) { this.setWidth(w); this.setHeight(w * this.originalSize.height / this.originalSize.width); } else if(this.size.height > h) { this.setHeight(h); this.setWidth(h * this.originalSize.width / this.originalSize.height); } else if(this.size.width > this.originalSize.width && this.size.height > this.originalSize.height) { this.setWidth(this.size.width); this.setHeight(this.size.height); } else this.resetScale(); } ,setCenter: function(pos) { this.center = pos; this.setX(pos.x - this.size.width / 2 | 0); this.setY(pos.y - this.size.height / 2 | 0); return this.center; } ,setBackgroundColor: function(color) { return color; } ,setClipsToBounds: function(clip) { return clip; } ,setScaleY: function(sy) { this.scaleY_ = sy; this.scale(this.scaleX_,this.scaleY_); return this.scaleY_; } ,getScaleY: function() { return this.scaleY_; } ,setScaleX: function(sx) { this.scaleX_ = sx; this.scale(this.scaleX_,this.scaleY_); return this.scaleX_; } ,getScaleX: function() { return this.scaleX_; } ,setBounds: function(b) { this.setX(b.origin.x); this.setY(b.origin.y); this.setWidth(b.size.width); this.setHeight(b.size.height); return b; } ,getBounds: function() { return new RCRect(this.x_,this.y_,this.size.width,this.size.height); } ,getRotation: function() { return this.rotation; } ,setRotation: function(r) { return this.rotation = r; } ,setContentSize: function(s) { return this.contentSize = s; } ,getContentSize: function() { return this.size; } ,setHeight: function(h) { return this.size.height = h; } ,getHeight: function() { return this.size.height; } ,setWidth: function(w) { return this.size.width = w; } ,getWidth: function() { return this.size.width; } ,setY: function(y) { return this.y_ = y; } ,getY: function() { return this.y_; } ,setX: function(x) { return this.x_ = x; } ,getX: function() { return this.x_; } ,setAlpha: function(a) { return this.alpha = a; } ,getAlpha: function() { return this.alpha; } ,setVisible: function(v) { return this.visible = v; } ,init: function() { } ,caobj: null ,originalSize: null ,contentSize_: null ,scaleY_: null ,scaleX_: null ,y_: null ,x_: null ,parent: null ,mouseY: null ,mouseX: null ,visible: null ,rotation: null ,alpha: null ,scaleY: null ,scaleX: null ,height: null ,width: null ,y: null ,x: null ,backgroundColor: null ,clipsToBounds: null ,center: null ,contentSize: null ,size: null ,bounds: null ,viewDidDisappear: null ,viewDidAppear: null ,viewWillDisappear: null ,viewWillAppear: null ,__class__: RCDisplayObject ,__properties__: {set_bounds:"setBounds",get_bounds:"getBounds",set_contentSize:"setContentSize",get_contentSize:"getContentSize",set_center:"setCenter",set_clipsToBounds:"setClipsToBounds",set_backgroundColor:"setBackgroundColor",set_x:"setX",get_x:"getX",set_y:"setY",get_y:"getY",set_width:"setWidth",get_width:"getWidth",set_height:"setHeight",get_height:"getHeight",set_scaleX:"setScaleX",get_scaleX:"getScaleX",set_scaleY:"setScaleY",get_scaleY:"getScaleY",set_alpha:"setAlpha",get_alpha:"getAlpha",set_rotation:"setRotation",get_rotation:"getRotation",set_visible:"setVisible",get_mouseX:"getMouseX",get_mouseY:"getMouseY"} } var JSView = $hxClasses["JSView"] = function(x,y,w,h) { RCDisplayObject.call(this); this.size = new RCSize(w,h); this.contentSize_ = this.size.copy(); this.scaleX_ = 1; this.scaleY_ = 1; this.alpha_ = 1; this.layer = js.Lib.document.createElement("div"); this.layer.style.position = "absolute"; this.layer.style.margin = "0px 0px 0px 0px"; this.layer.style.width = "auto"; this.layer.style.height = "auto"; this.setX(x); this.setY(y); }; JSView.__name__ = ["JSView"]; JSView.__super__ = RCDisplayObject; JSView.prototype = $extend(RCDisplayObject.prototype,{ getMouseY: function() { if(this.parent == null) return this.mouseY; return this.parent.getMouseY() - this.getY(); } ,getMouseX: function() { return this.layer.clientX; if(this.parent == null) return this.mouseX; return this.parent.getMouseX() - this.getX(); } ,stopDrag: function() { } ,startDrag: function(lockCenter,rect) { } ,setRotation: function(r) { this.layer.style[this.getTransformProperty()] = "rotate(" + r + "deg)"; return RCDisplayObject.prototype.setRotation.call(this,r); } ,getTransformProperty: function() { if(this.transformProperty != null) return this.transformProperty; var _g = 0, _g1 = ["transform","WebkitTransform","msTransform","MozTransform","OTransform"]; while(_g < _g1.length) { var p = _g1[_g]; ++_g; if(this.layer.style[p] != null) { this.transformProperty = p; return p; } } return "transform"; } ,scale: function(sx,sy) { this.layer.style[this.getTransformProperty() + "Origin"] = "top left"; this.layer.style[this.getTransformProperty()] = "scale(" + sx + "," + sy + ")"; } ,transformProperty: null ,getContentSize: function() { this.contentSize_.width = this.layer.scrollWidth; this.contentSize_.height = this.layer.scrollHeight; return this.contentSize_; } ,setHeight: function(h) { this.layer.style.height = h + "px"; return RCDisplayObject.prototype.setHeight.call(this,h); } ,setWidth: function(w) { this.layer.style.width = w + "px"; return RCDisplayObject.prototype.setWidth.call(this,w); } ,setY: function(y) { this.layer.style.top = Std.string(y * RCDevice.currentDevice().dpiScale) + "px"; return RCDisplayObject.prototype.setY.call(this,y); } ,setX: function(x) { this.layer.style.left = Std.string(x * RCDevice.currentDevice().dpiScale) + "px"; return RCDisplayObject.prototype.setX.call(this,x); } ,setAlpha: function(a) { if(RCDevice.currentDevice().userAgent == RCUserAgent.MSIE) { this.layer.style.msFilter = "progid:DXImageTransform.Microsoft.Alpha(Opacity=" + Std.string(a * 100) + ")"; this.layer.style.filter = "alpha(opacity=" + Std.string(a * 100) + ")"; } else this.layer.style.opacity = Std.string(a); return RCDisplayObject.prototype.setAlpha.call(this,a); } ,setVisible: function(v) { this.layer.style.visibility = v?"visible":"hidden"; return RCDisplayObject.prototype.setVisible.call(this,v); } ,setClipsToBounds: function(clip) { if(clip) { this.layer.style.overflow = "hidden"; this.layerScrollable = js.Lib.document.createElement("div"); this.layerScrollable.style.width = this.size.width + "px"; this.layerScrollable.style.height = this.size.height + "px"; while(this.layer.hasChildNodes()) this.layerScrollable.appendChild(this.layer.removeChild(this.layer.firstChild)); this.layer.appendChild(this.layerScrollable); } else { while(this.layerScrollable.hasChildNodes()) this.layer.appendChild(this.layerScrollable.removeChild(this.layerScrollable.firstChild)); this.layer.style.overflow = null; this.layer.removeChild(this.layerScrollable); this.layerScrollable = null; } return clip; } ,setBackgroundColor: function(color) { if(color == null) { this.layer.style.background = null; return color; } var red = (color & 16711680) >> 16; var green = (color & 65280) >> 8; var blue = color & 255; this.layer.style.backgroundColor = "rgb(" + red + "," + green + "," + blue + ")"; return color; } ,removeFromSuperview: function() { if(this.parent != null) this.parent.removeChild(this); } ,removeChild: function(child) { if(child == null) return; child.viewWillDisappear.dispatch(null,null,null,null,{ fileName : "JSView.hx", lineNumber : 75, className : "JSView", methodName : "removeChild"}); child.parent = null; this.layer.removeChild(child.layer); child.viewDidDisappear.dispatch(null,null,null,null,{ fileName : "JSView.hx", lineNumber : 78, className : "JSView", methodName : "removeChild"}); } ,addChildAt: function(child,index) { if(this.layer.childNodes[index] != null) this.layer.insertBefore(child.layer,this.layer.childNodes[index]); else this.layer.appendChild(child.layer); } ,addChild: function(child) { if(child == null) return; child.viewWillAppear.dispatch(null,null,null,null,{ fileName : "JSView.hx", lineNumber : 58, className : "JSView", methodName : "addChild"}); child.parent = this; this.layer.appendChild(child.layer); child.viewDidAppear.dispatch(null,null,null,null,{ fileName : "JSView.hx", lineNumber : 61, className : "JSView", methodName : "addChild"}); } ,alpha_: null ,graphics: null ,layerScrollable: null ,layer: null ,__class__: JSView }); var List = $hxClasses["List"] = function() { this.length = 0; }; List.__name__ = ["List"]; List.prototype = { map: function(f) { var b = new List(); var l = this.h; while(l != null) { var v = l[0]; l = l[1]; b.add(f(v)); } return b; } ,filter: function(f) { var l2 = new List(); var l = this.h; while(l != null) { var v = l[0]; l = l[1]; if(f(v)) l2.add(v); } return l2; } ,join: function(sep) { var s = new StringBuf(); var first = true; var l = this.h; while(l != null) { if(first) first = false; else s.b += Std.string(sep); s.b += Std.string(l[0]); l = l[1]; } return s.b; } ,toString: function() { var s = new StringBuf(); var first = true; var l = this.h; s.b += Std.string("{"); while(l != null) { if(first) first = false; else s.b += Std.string(", "); s.b += Std.string(Std.string(l[0])); l = l[1]; } s.b += Std.string("}"); return s.b; } ,iterator: function() { return { h : this.h, hasNext : function() { return this.h != null; }, next : function() { if(this.h == null) return null; var x = this.h[0]; this.h = this.h[1]; return x; }}; } ,remove: function(v) { var prev = null; var l = this.h; while(l != null) { if(l[0] == v) { if(prev == null) this.h = l[1]; else prev[1] = l[1]; if(this.q == l) this.q = prev; this.length--; return true; } prev = l; l = l[1]; } return false; } ,clear: function() { this.h = null; this.q = null; this.length = 0; } ,isEmpty: function() { return this.h == null; } ,pop: function() { if(this.h == null) return null; var x = this.h[0]; this.h = this.h[1]; if(this.h == null) this.q = null; this.length--; return x; } ,last: function() { return this.q == null?null:this.q[0]; } ,first: function() { return this.h == null?null:this.h[0]; } ,push: function(item) { var x = [item,this.h]; this.h = x; if(this.q == null) this.q = x; this.length++; } ,add: function(item) { var x = [item]; if(this.h == null) this.h = x; else this.q[1] = x; this.q = x; this.length++; } ,length: null ,q: null ,h: null ,__class__: List } var Main = $hxClasses["Main"] = function() { } Main.__name__ = ["Main"]; Main.lin = null; Main.ph = null; Main.circ = null; Main.req = null; Main.win = null; Main.main = function() { haxe.Firebug.redirectTraces(); var mousew = new EVMouse("mousewheel",RCWindow.sharedWindow().target,{ fileName : "Main.hx", lineNumber : 24, className : "Main", methodName : "main"}); try { haxe.Log.trace("step1 - RCFont, RCTextView",{ fileName : "Main.hx", lineNumber : 33, className : "Main", methodName : "main"}); var f = new RCFont(); f.color = 16777215; f.font = "Arial"; f.size = 30; f.embedFonts = false; var t = new RCTextView(50,30,null,null,"HTML5",f); RCWindow.sharedWindow().addChild(t); haxe.Log.trace("t.width " + t.getWidth(),{ fileName : "Main.hx", lineNumber : 41, className : "Main", methodName : "main"}); haxe.Log.trace("step1 - backgroundColor",{ fileName : "Main.hx", lineNumber : 43, className : "Main", methodName : "main"}); Main.win = RCWindow.sharedWindow(); Main.win.setBackgroundColor(15724527); haxe.Log.trace("step2 - RCFontManager",{ fileName : "Main.hx", lineNumber : 60, className : "Main", methodName : "main"}); RCFontManager.init(); haxe.Log.trace("step2 - RCAssets",{ fileName : "Main.hx", lineNumber : 62, className : "Main", methodName : "main"}); RCAssets.loadFileWithKey("photo","../assets/900x600.jpg"); RCAssets.loadFileWithKey("some_text","../assets/data.txt"); RCAssets.loadFileWithKey("Urban","../assets/FFF Urban.ttf"); RCAssets.loadFontWithKey("Futu","../assets/FUTUNEBI.TTF"); RCAssets.onComplete = Main.testJsFont; haxe.Log.trace("step2 - RCRectangle",{ fileName : "Main.hx", lineNumber : 70, className : "Main", methodName : "main"}); var rect = new RCRectangle(0,0,300,150,RCColor.redColor()); RCWindow.sharedWindow().addChild(rect); rect.setClipsToBounds(true); rect.setCenter(new RCPoint(RCWindow.sharedWindow().getWidth() / 2,RCWindow.sharedWindow().getHeight() / 2)); haxe.Log.trace("step2 - RCImage",{ fileName : "Main.hx", lineNumber : 77, className : "Main", methodName : "main"}); Main.ph = new RCImage(1,1,"../assets/900x600.jpg"); Main.ph.onComplete = Main.resizePhoto; rect.addChild(Main.ph); haxe.Log.trace("step3 - ellipse",{ fileName : "Main.hx", lineNumber : 82, className : "Main", methodName : "main"}); Main.circ = new RCEllipse(0,0,100,100,RCColor.darkGrayColor()); RCWindow.sharedWindow().addChild(Main.circ); var size = RCWindow.sharedWindow().size; haxe.Log.trace(size,{ fileName : "Main.hx", lineNumber : 97, className : "Main", methodName : "main"}); var a1 = new CATween(Main.circ,{ x : size.width - 100, y : 0},2,0,caequations.Cubic.IN_OUT,{ fileName : "Main.hx", lineNumber : 98, className : "Main", methodName : "main"}); var a2 = new CATween(Main.circ,{ x : size.width - 100, y : size.height - 100},2,0,caequations.Cubic.IN_OUT,{ fileName : "Main.hx", lineNumber : 99, className : "Main", methodName : "main"}); var a3 = new CATween(Main.circ,{ x : 0, y : size.height - 100},2,0,caequations.Cubic.IN_OUT,{ fileName : "Main.hx", lineNumber : 100, className : "Main", methodName : "main"}); var a4 = new CATween(Main.circ,{ x : 0, y : 0},2,0,caequations.Cubic.IN_OUT,{ fileName : "Main.hx", lineNumber : 101, className : "Main", methodName : "main"}); var seq = new CASequence([a1,a2,a3,a4]); seq.start(); haxe.Log.trace("step5 - line",{ fileName : "Main.hx", lineNumber : 105, className : "Main", methodName : "main"}); Main.lin = new RCLine(30,300,400,600,16724736); RCWindow.sharedWindow().addChild(Main.lin); haxe.Log.trace("step6 - Keys",{ fileName : "Main.hx", lineNumber : 110, className : "Main", methodName : "main"}); var k = new RCKeyboardController(); k.onLeft = Main.moveLeft; k.onRight = Main.moveRight; haxe.Log.trace("step7 - Mouse",{ fileName : "Main.hx", lineNumber : 115, className : "Main", methodName : "main"}); var m = new EVMouse("mouseover",rect.layer,{ fileName : "Main.hx", lineNumber : 116, className : "Main", methodName : "main"}); m.add(function(_) { haxe.Log.trace("onOver",{ fileName : "Main.hx", lineNumber : 117, className : "Main", methodName : "main"}); }); haxe.Log.trace("step8 - text",{ fileName : "Main.hx", lineNumber : 119, className : "Main", methodName : "main"}); Main.testTexts(); haxe.Log.trace("step8 - signals",{ fileName : "Main.hx", lineNumber : 121, className : "Main", methodName : "main"}); Main.testSignals(); haxe.Log.trace("step8 - buttons",{ fileName : "Main.hx", lineNumber : 123, className : "Main", methodName : "main"}); Main.testButtons(); haxe.Log.trace("step9 - SKSlider",{ fileName : "Main.hx", lineNumber : 133, className : "Main", methodName : "main"}); var s = new haxe.SKSlider(); haxe.Log.trace("step9 - RCSlider",{ fileName : "Main.hx", lineNumber : 135, className : "Main", methodName : "main"}); var sl = new RCSlider(50,250,160,10,s); RCWindow.sharedWindow().addChild(sl); sl.setMaxValue(500); sl.setValue(30); haxe.Log.trace("step10 - Http",{ fileName : "Main.hx", lineNumber : 144, className : "Main", methodName : "main"}); Main.req = new RCHttp(); Main.req.onComplete = function() { haxe.Log.trace("http result " + Main.req.result,{ fileName : "Main.hx", lineNumber : 146, className : "Main", methodName : "main"}); }; Main.req.onError = function() { haxe.Log.trace("http error " + Main.req.result,{ fileName : "Main.hx", lineNumber : 147, className : "Main", methodName : "main"}); }; Main.req.onStatus = function() { haxe.Log.trace("http status " + Main.req.status,{ fileName : "Main.hx", lineNumber : 148, className : "Main", methodName : "main"}); }; Main.req.readFile("../assets/data.txt"); haxe.Log.trace("step11 - CATCallFunc",{ fileName : "Main.hx", lineNumber : 151, className : "Main", methodName : "main"}); var anim = new CATCallFunc(Main.setAlpha_,{ alpha : { fromValue : 0, toValue : 1}},2.8,0,caequations.Cubic.IN_OUT,{ fileName : "Main.hx", lineNumber : 152, className : "Main", methodName : "main"}); CoreAnimation.add(anim); } catch( e ) { Fugu.stack(); haxe.Log.trace(e,{ fileName : "Main.hx", lineNumber : 156, className : "Main", methodName : "main"}); } } Main.setAlpha_ = function(a) { Main.lin.setAlpha(a); } Main.testJsFont = function() { var f = new RCFont(); f.color = 0; f.font = "Futu"; f.size = 34; f.embedFonts = false; var t = new RCTextView(50,120,null,null,"blah blah blah",f); RCWindow.sharedWindow().addChild(t); haxe.Log.trace("t.width " + t.getWidth(),{ fileName : "Main.hx", lineNumber : 168, className : "Main", methodName : "testJsFont"}); } Main.resizePhoto = function() { haxe.Log.trace("startResizing",{ fileName : "Main.hx", lineNumber : 181, className : "Main", methodName : "resizePhoto"}); var ph2 = Main.ph.copy(); RCWindow.sharedWindow().addChild(ph2); haxe.Log.trace(Main.ph.getContentSize(),{ fileName : "Main.hx", lineNumber : 196, className : "Main", methodName : "resizePhoto"}); var scrollview = new RCScrollView(780,10,300,300); RCWindow.sharedWindow().addChild(scrollview); scrollview.setContentView(ph2); var anim = new CATween(Main.ph,{ x : { fromValue : -Main.ph.getWidth(), toValue : Main.ph.getWidth()}},2,0,caequations.Cubic.IN_OUT,{ fileName : "Main.hx", lineNumber : 203, className : "Main", methodName : "resizePhoto"}); anim.repeatCount = 5; anim.autoreverses = true; CoreAnimation.add(anim); } Main.moveLeft = function() { var _g = Main.circ; _g.setX(_g.getX() - 10); } Main.moveRight = function() { var _g = Main.circ; _g.setX(_g.getX() + 10); } Main.signal = null; Main.testSignals = function() { Main.signal = new RCSignal(); Main.signal.add(Main.printNr); Main.signal.addOnce(Main.printNr2,{ fileName : "Main.hx", lineNumber : 222, className : "Main", methodName : "testSignals"}); Main.signal.remove(Main.printNr); Main.signal.removeAll(); var _g = 0; while(_g < 5) { var i = _g++; Main.signal.dispatch(Math.random(),null,null,null,{ fileName : "Main.hx", lineNumber : 226, className : "Main", methodName : "testSignals"}); } } Main.printNr = function(nr) { } Main.printNr2 = function(nr) { } Main.testButtons = function() { try { var s = new haxe.SKButton("Switch"); var b = new RCButton(50,200,s); RCWindow.sharedWindow().addChild(b); b.onRelease = function() { HXAddress.href("flash.html"); }; b.onOver = function() { haxe.Log.trace("over",{ fileName : "Main.hx", lineNumber : 246, className : "Main", methodName : "testButtons"}); }; b.onOut = function() { haxe.Log.trace("out",{ fileName : "Main.hx", lineNumber : 247, className : "Main", methodName : "testButtons"}); }; b.onPress = function() { haxe.Log.trace("press",{ fileName : "Main.hx", lineNumber : 248, className : "Main", methodName : "testButtons"}); }; var s1 = new haxe.SKButtonRadio(); var b1 = new RCButtonRadio(50,230,s1); RCWindow.sharedWindow().addChild(b1); var group = new RCGroup(50,200,0,null,Main.createRadioButton); RCWindow.sharedWindow().addChild(group); group.add([1,2,3,4,5,5]); var seg = new RCSegmentedControl(100,400,640,50,ios.SKSegment); RCWindow.sharedWindow().addChild(seg); seg.initWithLabels(["Masculin","Feminin","123","Label 12345"],false); seg.click.add(Main.segClick); } catch( e ) { Fugu.stack(); } } Main.createRadioButton = function(indexPath) { var s = new haxe.SKButtonRadio(); var b = new RCButtonRadio(0,0,s); return b; } Main.segClick = function(s) { haxe.Log.trace(s.getSelectedIndex(),{ fileName : "Main.hx", lineNumber : 273, className : "Main", methodName : "segClick"}); } Main.testTexts = function() { try { var f = new RCFont(); f.color = 16777215; f.font = "Arial"; f.size = 30; f.embedFonts = false; var t = new RCTextView(50,30,null,null,"HTML5",f); RCWindow.sharedWindow().addChild(t); haxe.Log.trace("t.width " + t.getWidth(),{ fileName : "Main.hx", lineNumber : 285, className : "Main", methodName : "testTexts"}); var f2 = f.copy(); f2.color = 16777215; f2.size = 16; var r = new RCTextRoll(50,60,200,null,"What's this fuss about true randomness?",f2); RCWindow.sharedWindow().addChild(r); r.start(); r.setBackgroundColor(16724736); } catch( e ) { Fugu.stack(); } } Main.prototype = { x__: function() { } ,__class__: Main } var RCAssets = $hxClasses["RCAssets"] = function() { this.imagesList = new Hash(); this.swfList = new Hash(); this.dataList = new Hash(); this.nr = 0; this.max = 0; }; RCAssets.__name__ = ["RCAssets"]; RCAssets.INSTANCE = null; RCAssets.errorMessage = null; RCAssets.currentPercentLoaded = null; RCAssets.percentLoaded = null; RCAssets.useCache = null; RCAssets.onComplete = function() { } RCAssets.onProgress = function() { } RCAssets.onError = function() { } RCAssets.init = function() { if(RCAssets.INSTANCE != null) return; RCAssets.INSTANCE = new RCAssets(); RCAssets.currentPercentLoaded = new Hash(); RCAssets.useCache = false; } RCAssets.sharedAssets = function() { RCAssets.init(); return RCAssets.INSTANCE; } RCAssets.loadFileWithKey = function(key,URL) { return RCAssets.sharedAssets().set(key,URL); } RCAssets.loadFontWithKey = function(key,URL) { return RCAssets.sharedAssets().set(key,URL,false); } RCAssets.getFileWithKey = function(key,returnAsBitmap) { if(returnAsBitmap == null) returnAsBitmap = true; return RCAssets.sharedAssets().get(key,returnAsBitmap); } RCAssets.prototype = { get: function(key,returnAsBitmap) { if(returnAsBitmap == null) returnAsBitmap = true; RCAssets.init(); if(this.imagesList.exists(key)) return this.imagesList.get(key).copy(); else if(this.dataList.exists(key)) return this.dataList.get(key); else if(this.swfList.exists(key)) return this.swfList.get(key); haxe.Log.trace("Asset with key '" + key + "' was not found.",{ fileName : "RCAssets.hx", lineNumber : 262, className : "RCAssets", methodName : "get"}); return null; } ,totalProgress: function() { var totalPercent = 0; var i = 0; var $it0 = RCAssets.currentPercentLoaded.keys(); while( $it0.hasNext() ) { var key = $it0.next(); i++; totalPercent += RCAssets.currentPercentLoaded.get(key); } RCAssets.percentLoaded = Math.round(totalPercent / i); RCAssets.onProgress(); } ,onCompleteHandler: function() { this.nr++; if(this.nr >= this.max) RCAssets.onComplete(); } ,completeHandler: function(key,obj) { var class_name = Type.getClassName(Type.getClass(obj)); switch(class_name) { case "RCImage": this.imagesList.set(key,obj); break; case "RCHttp": this.dataList.set(key,obj.result); break; case "RCSwf": this.swfList.set(key,obj); break; default: haxe.Log.trace("Asset not supported: key=" + key + ", class_name=" + class_name,{ fileName : "RCAssets.hx", lineNumber : 192, className : "RCAssets", methodName : "completeHandler"}); } this.onCompleteHandler(); } ,progressHandler: function(key,obj) { RCAssets.currentPercentLoaded.set(key,obj.percentLoaded); this.totalProgress(); } ,errorHandler: function(key,obj) { haxe.Log.trace("Error loading URL for key: '" + key + "' with object: " + Std.string(obj),{ fileName : "RCAssets.hx", lineNumber : 173, className : "RCAssets", methodName : "errorHandler"}); this.max--; RCAssets.onError(); if(this.nr >= this.max) RCAssets.onComplete(); } ,loadFont: function(key,URL) { var fontType = ""; var st = js.Lib.document.createElement("style"); st.innerHTML = "@font-face{font-family:" + key + "; src: url('" + URL + "')" + fontType + ";}"; js.Lib.document.getElementsByTagName("head")[0].appendChild(st); haxe.Timer.delay($bind(this,this.onCompleteHandler),16); } ,loadText: function(key,URL) { var _g = this; var data = new RCHttp(); if(data.result == null) { data.onProgress = (function(f,a1,a2) { return function() { return f(a1,a2); }; })($bind(this,this.progressHandler),key,data); data.onComplete = (function(f,a1,a2) { return function() { return f(a1,a2); }; })($bind(this,this.completeHandler),key,data); data.onError = (function(f,a1,a2) { return function() { return f(a1,a2); }; })($bind(this,this.errorHandler),key,data); data.readFile(URL); } else haxe.Timer.delay(function() { _g.completeHandler(key,data); },10); } ,loadSwf: function(key,URL,newDomain) { if(newDomain == null) newDomain = true; var swf = new RCSwf(0,0,URL,newDomain); swf.onProgress = (function(f,a1,a2) { return function() { return f(a1,a2); }; })($bind(this,this.progressHandler),key,swf); swf.onComplete = (function(f,a1,a2) { return function() { return f(a1,a2); }; })($bind(this,this.completeHandler),key,swf); swf.onError = (function(f,a1,a2) { return function() { return f(a1,a2); }; })($bind(this,this.errorHandler),key,swf); } ,loadPhoto: function(key,URL) { var photo = new RCImage(0,0,URL); photo.onProgress = (function(f,a1,a2) { return function() { return f(a1,a2); }; })($bind(this,this.progressHandler),key,photo); photo.onComplete = (function(f,a1,a2) { return function() { return f(a1,a2); }; })($bind(this,this.completeHandler),key,photo); photo.onError = (function(f,a1,a2) { return function() { return f(a1,a2); }; })($bind(this,this.errorHandler),key,photo); } ,set: function(key,URL,newDomain) { if(newDomain == null) newDomain = true; this.max++; if(key == null) key = Std.string(Math.random()); if(URL.toLowerCase().indexOf(".swf") != -1) this.loadSwf(key,URL,newDomain); else if(URL.toLowerCase().indexOf(".xml") != -1 || URL.toLowerCase().indexOf(".plist") != -1 || URL.toLowerCase().indexOf(".txt") != -1 || URL.toLowerCase().indexOf(".css") != -1) this.loadText(key,URL); else if(URL.toLowerCase().indexOf(".ttf") != -1 || URL.toLowerCase().indexOf(".otf") != -1) this.loadFont(key,URL); else { if(RCDevice.currentDevice().dpiScale == 2) { var u = URL.split("."); var ext = u.pop(); URL = u.join(".") + "@2x." + ext; } this.loadPhoto(key,URL); } return true; } ,max: null ,nr: null ,dataList: null ,swfList: null ,imagesList: null ,__class__: RCAssets } var RCControl = $hxClasses["RCControl"] = function(x,y,w,h) { JSView.call(this,x,y,w,h); this.configureDispatchers(); this.setEnabled(true); }; RCControl.__name__ = ["RCControl"]; RCControl.__super__ = JSView; RCControl.prototype = $extend(JSView.prototype,{ destroy: function() { this.click.destroy({ fileName : "RCControl.hx", lineNumber : 171, className : "RCControl", methodName : "destroy"}); this.press.destroy({ fileName : "RCControl.hx", lineNumber : 172, className : "RCControl", methodName : "destroy"}); this.release.destroy({ fileName : "RCControl.hx", lineNumber : 173, className : "RCControl", methodName : "destroy"}); this.over.destroy({ fileName : "RCControl.hx", lineNumber : 174, className : "RCControl", methodName : "destroy"}); this.out.destroy({ fileName : "RCControl.hx", lineNumber : 175, className : "RCControl", methodName : "destroy"}); JSView.prototype.destroy.call(this); } ,getHighlighted: function() { return this.state_ == RCControlState.HIGHLIGHTED; } ,setEnabled: function(c) { this.enabled_ = c; this.click.enabled = this.enabled_; this.press.enabled = this.enabled_; this.release.enabled = this.enabled_; this.over.enabled = this.enabled_; this.out.enabled = this.enabled_; return this.enabled_; } ,getEnabled: function() { return this.enabled_; } ,getSelected: function() { return this.state_ == RCControlState.SELECTED; } ,setState: function(state) { this.state_ = state; switch( (this.state_)[1] ) { case 0: js.Lib.document.body.style.cursor = "auto"; break; case 1: js.Lib.document.body.style.cursor = "pointer"; break; case 2: js.Lib.document.body.style.cursor = "auto"; break; case 3: js.Lib.document.body.style.cursor = "auto"; break; } } ,clickHandler: function(e) { this.setState(RCControlState.SELECTED); this.onClick(); } ,rollOutHandler: function(e) { this.setState(RCControlState.NORMAL); this.onOut(); } ,rollOverHandler: function(e) { this.setState(RCControlState.HIGHLIGHTED); this.onOver(); } ,mouseUpHandler: function(e) { this.setState(RCControlState.HIGHLIGHTED); this.onRelease(); } ,mouseDownHandler: function(e) { this.setState(RCControlState.SELECTED); this.onPress(); } ,configureDispatchers: function() { this.click = new EVMouse("mouseclick",this,{ fileName : "RCControl.hx", lineNumber : 80, className : "RCControl", methodName : "configureDispatchers"}); this.press = new EVMouse("mousedown",this,{ fileName : "RCControl.hx", lineNumber : 82, className : "RCControl", methodName : "configureDispatchers"}); this.release = new EVMouse("mouseup",this,{ fileName : "RCControl.hx", lineNumber : 83, className : "RCControl", methodName : "configureDispatchers"}); this.over = new EVMouse("mouseover",this,{ fileName : "RCControl.hx", lineNumber : 84, className : "RCControl", methodName : "configureDispatchers"}); this.out = new EVMouse("mouseout",this,{ fileName : "RCControl.hx", lineNumber : 85, className : "RCControl", methodName : "configureDispatchers"}); this.click.addFirst($bind(this,this.clickHandler),{ fileName : "RCControl.hx", lineNumber : 87, className : "RCControl", methodName : "configureDispatchers"}); this.press.addFirst($bind(this,this.mouseDownHandler),{ fileName : "RCControl.hx", lineNumber : 88, className : "RCControl", methodName : "configureDispatchers"}); this.release.addFirst($bind(this,this.mouseUpHandler),{ fileName : "RCControl.hx", lineNumber : 89, className : "RCControl", methodName : "configureDispatchers"}); this.over.addFirst($bind(this,this.rollOverHandler),{ fileName : "RCControl.hx", lineNumber : 90, className : "RCControl", methodName : "configureDispatchers"}); this.out.addFirst($bind(this,this.rollOutHandler),{ fileName : "RCControl.hx", lineNumber : 91, className : "RCControl", methodName : "configureDispatchers"}); } ,init: function() { if(this.state_ == null) this.setState(RCControlState.NORMAL); } ,onOut: function() { } ,onOver: function() { } ,onRelease: function() { } ,onPress: function() { } ,onClick: function() { } ,state_: null ,enabled_: null ,selected: null ,highlighted: null ,enabled: null ,editingDidEndOnExit: null ,editingDidEnd: null ,editingChanged: null ,editingDidBegin: null ,out: null ,over: null ,release: null ,press: null ,click: null ,__class__: RCControl ,__properties__: $extend(JSView.prototype.__properties__,{set_enabled:"setEnabled",get_enabled:"getEnabled",get_highlighted:"getHighlighted",get_selected:"getSelected"}) }); var RCButton = $hxClasses["RCButton"] = function(x,y,skin) { this.setup(skin); RCControl.call(this,x,y,this.currentBackground.getWidth(),this.currentBackground.getHeight()); }; RCButton.__name__ = ["RCButton"]; RCButton.__super__ = RCControl; RCButton.prototype = $extend(RCControl.prototype,{ toString: function() { return "[RCButton bounds:" + this.getBounds().origin.x + "x" + this.getBounds().origin.y + "," + this.getBounds().size.width + "x" + this.getBounds().size.height + "]"; } ,setBackgroundImage: function(image,state) { } ,setTitleColor: function(color,state) { } ,setTitle: function(title,state) { } ,setState: function(state) { if(this.state_ == state) return; try { Fugu.safeRemove([this.currentBackground,this.currentImage]); switch( (state)[1] ) { case 0: this.currentBackground = this.skin.normal.background; this.currentImage = this.skin.normal.label; break; case 1: this.currentBackground = this.skin.highlighted.background; this.currentImage = this.skin.highlighted.label; break; case 2: this.currentBackground = this.skin.disabled.background; this.currentImage = this.skin.disabled.label; break; case 3: this.currentBackground = this.skin.selected.background; this.currentImage = this.skin.selected.label; break; } if(this.currentBackground != null) this.addChild(this.currentBackground); if(this.currentImage != null) this.addChild(this.currentImage); if(this.skin.hit != null) this.addChild(this.skin.hit); this.size.width = this.currentBackground != null?this.currentBackground.getWidth():this.currentImage.getWidth(); this.size.height = this.currentBackground != null?this.currentBackground.getHeight():this.currentImage.getHeight(); RCControl.prototype.setState.call(this,state); } catch( e ) { haxe.Log.trace(e,{ fileName : "RCButton.hx", lineNumber : 103, className : "RCButton", methodName : "setState"}); } } ,setup: function(skin) { this.skin = skin; if(skin.hit != null) skin.hit.setAlpha(0); if(skin.normal.label == null) skin.normal.label = skin.normal.image; if(skin.normal.label == null) skin.normal.label = skin.normal.otherView; var _g = 0, _g1 = Reflect.fields(skin.normal); while(_g < _g1.length) { var key = _g1[_g]; ++_g; if(key == "colors") continue; if(Reflect.field(skin.highlighted,key) == null) skin.highlighted[key] = Reflect.field(skin.normal,key); if(Reflect.field(skin.selected,key) == null) skin.selected[key] = Reflect.field(skin.highlighted,key); if(Reflect.field(skin.disabled,key) == null) skin.disabled[key] = Reflect.field(skin.normal,key); } this.currentBackground = skin.normal.background; this.currentImage = skin.normal.label; } ,currentBackground: null ,currentImage: null ,currentTitleColor: null ,currentTitle: null ,skin: null ,__class__: RCButton }); var RCButtonRadio = $hxClasses["RCButtonRadio"] = function(x,y,skin) { RCButton.call(this,x,y,skin); this.toggable_ = true; }; RCButtonRadio.__name__ = ["RCButtonRadio"]; RCButtonRadio.__super__ = RCButton; RCButtonRadio.prototype = $extend(RCButton.prototype,{ untoggle: function() { if(this.toggable_) this.setState(RCControlState.NORMAL); } ,toggle: function() { if(this.toggable_) this.setState(RCControlState.SELECTED); } ,setToggable: function(v) { if(!v) this.setState(RCControlState.NORMAL); return this.toggable_ = v; } ,getToggable: function() { return this.toggable_; } ,rollOutHandler: function(e) { if(!this.getSelected()) this.setState(RCControlState.NORMAL); this.onOut(); } ,rollOverHandler: function(e) { if(!this.getSelected()) this.setState(RCControlState.HIGHLIGHTED); this.onOver(); } ,clickHandler: function(e) { this.setState(this.getSelected()?RCControlState.NORMAL:RCControlState.SELECTED); this.onClick(); } ,mouseUpHandler: function(e) { this.onRelease(); } ,mouseDownHandler: function(e) { this.onPress(); } ,toggable: null ,toggable_: null ,__class__: RCButtonRadio ,__properties__: $extend(RCButton.prototype.__properties__,{set_toggable:"setToggable",get_toggable:"getToggable"}) }); var RCColor = $hxClasses["RCColor"] = function(fillColor,strokeColor,a) { this.fillColor = fillColor; this.strokeColor = strokeColor; this.alpha = a == null?1.0:a; this.redComponent = (fillColor >> 16 & 255) / 255; this.greenComponent = (fillColor >> 8 & 255) / 255; this.blueComponent = (fillColor & 255) / 255; this.fillColorStyle = RCColor.HEXtoString(fillColor); this.strokeColorStyle = RCColor.HEXtoString(strokeColor); }; RCColor.__name__ = ["RCColor"]; RCColor.blackColor = function() { return RCColor.colorWithWhite(0); } RCColor.darkGrayColor = function() { return RCColor.colorWithWhite(0.333); } RCColor.lightGrayColor = function() { return RCColor.colorWithWhite(0.667); } RCColor.whiteColor = function() { return RCColor.colorWithWhite(1); } RCColor.grayColor = function() { return RCColor.colorWithWhite(0.5); } RCColor.redColor = function() { return RCColor.colorWithRGBA(1,0,0); } RCColor.greenColor = function() { return RCColor.colorWithRGBA(0,1,0); } RCColor.blueColor = function() { return RCColor.colorWithRGBA(0,0,1); } RCColor.cyanColor = function() { return RCColor.colorWithRGBA(0,1,1); } RCColor.yellowColor = function() { return RCColor.colorWithRGBA(1,1,0); } RCColor.magentaColor = function() { return RCColor.colorWithRGBA(1,0,1); } RCColor.orangeColor = function() { return RCColor.colorWithRGBA(1,0.5,0); } RCColor.purpleColor = function() { return RCColor.colorWithRGBA(0.5,0,0.5); } RCColor.brownColor = function() { return RCColor.colorWithRGBA(0.6,0.4,0.2); } RCColor.clearColor = function() { return RCColor.colorWithWhite(0,0); } RCColor.colorWithWhite = function(white,alpha) { if(alpha == null) alpha = 1.0; return new RCColor(RCColor.RGBtoHEX(white,white,white),null,alpha); } RCColor.colorWithRGBA = function(red,green,blue,alpha) { if(alpha == null) alpha = 1.0; return new RCColor(RCColor.RGBtoHEX(red,green,blue),null,alpha); } RCColor.colorWithHSBA = function(hue,saturation,brightness,alpha) { if(alpha == null) alpha = 1.0; return new RCColor(RCColor.RGBtoHEX(hue,saturation,brightness),null,alpha); } RCColor.colorWithFillAndStroke = function(fillColor,strokeColor) { return new RCColor(fillColor,strokeColor); } RCColor.HEXtoString = function(color) { if(color == null) return null; return "#" + StringTools.lpad(StringTools.hex(color),"0",6); } RCColor.RGBtoHEX = function(r,g,b) { return Math.round(r * 255) << 16 | Math.round(g * 255) << 8 | Math.round(b * 255); } RCColor.prototype = { alpha: null ,blueComponent: null ,greenComponent: null ,redComponent: null ,strokeColorStyle: null ,fillColorStyle: null ,strokeColor: null ,fillColor: null ,__class__: RCColor } var RCControlState = $hxClasses["RCControlState"] = { __ename__ : ["RCControlState"], __constructs__ : ["NORMAL","HIGHLIGHTED","DISABLED","SELECTED"] } RCControlState.NORMAL = ["NORMAL",0]; RCControlState.NORMAL.toString = $estr; RCControlState.NORMAL.__enum__ = RCControlState; RCControlState.HIGHLIGHTED = ["HIGHLIGHTED",1]; RCControlState.HIGHLIGHTED.toString = $estr; RCControlState.HIGHLIGHTED.__enum__ = RCControlState; RCControlState.DISABLED = ["DISABLED",2]; RCControlState.DISABLED.toString = $estr; RCControlState.DISABLED.__enum__ = RCControlState; RCControlState.SELECTED = ["SELECTED",3]; RCControlState.SELECTED.toString = $estr; RCControlState.SELECTED.__enum__ = RCControlState; var RCDeviceOrientation = $hxClasses["RCDeviceOrientation"] = { __ename__ : ["RCDeviceOrientation"], __constructs__ : ["UIDeviceOrientationUnknown","UIDeviceOrientationPortrait","UIDeviceOrientationPortraitUpsideDown","UIDeviceOrientationLandscapeLeft","UIDeviceOrientationLandscapeRight","UIDeviceOrientationFaceUp","UIDeviceOrientationFaceDown"] } RCDeviceOrientation.UIDeviceOrientationUnknown = ["UIDeviceOrientationUnknown",0]; RCDeviceOrientation.UIDeviceOrientationUnknown.toString = $estr; RCDeviceOrientation.UIDeviceOrientationUnknown.__enum__ = RCDeviceOrientation; RCDeviceOrientation.UIDeviceOrientationPortrait = ["UIDeviceOrientationPortrait",1]; RCDeviceOrientation.UIDeviceOrientationPortrait.toString = $estr; RCDeviceOrientation.UIDeviceOrientationPortrait.__enum__ = RCDeviceOrientation; RCDeviceOrientation.UIDeviceOrientationPortraitUpsideDown = ["UIDeviceOrientationPortraitUpsideDown",2]; RCDeviceOrientation.UIDeviceOrientationPortraitUpsideDown.toString = $estr; RCDeviceOrientation.UIDeviceOrientationPortraitUpsideDown.__enum__ = RCDeviceOrientation; RCDeviceOrientation.UIDeviceOrientationLandscapeLeft = ["UIDeviceOrientationLandscapeLeft",3]; RCDeviceOrientation.UIDeviceOrientationLandscapeLeft.toString = $estr; RCDeviceOrientation.UIDeviceOrientationLandscapeLeft.__enum__ = RCDeviceOrientation; RCDeviceOrientation.UIDeviceOrientationLandscapeRight = ["UIDeviceOrientationLandscapeRight",4]; RCDeviceOrientation.UIDeviceOrientationLandscapeRight.toString = $estr; RCDeviceOrientation.UIDeviceOrientationLandscapeRight.__enum__ = RCDeviceOrientation; RCDeviceOrientation.UIDeviceOrientationFaceUp = ["UIDeviceOrientationFaceUp",5]; RCDeviceOrientation.UIDeviceOrientationFaceUp.toString = $estr; RCDeviceOrientation.UIDeviceOrientationFaceUp.__enum__ = RCDeviceOrientation; RCDeviceOrientation.UIDeviceOrientationFaceDown = ["UIDeviceOrientationFaceDown",6]; RCDeviceOrientation.UIDeviceOrientationFaceDown.toString = $estr; RCDeviceOrientation.UIDeviceOrientationFaceDown.__enum__ = RCDeviceOrientation; var RCDeviceType = $hxClasses["RCDeviceType"] = { __ename__ : ["RCDeviceType"], __constructs__ : ["IPhone","IPad","IPod","Android","WebOS","Mac","Flash","Playstation","Other"] } RCDeviceType.IPhone = ["IPhone",0]; RCDeviceType.IPhone.toString = $estr; RCDeviceType.IPhone.__enum__ = RCDeviceType; RCDeviceType.IPad = ["IPad",1]; RCDeviceType.IPad.toString = $estr; RCDeviceType.IPad.__enum__ = RCDeviceType; RCDeviceType.IPod = ["IPod",2]; RCDeviceType.IPod.toString = $estr; RCDeviceType.IPod.__enum__ = RCDeviceType; RCDeviceType.Android = ["Android",3]; RCDeviceType.Android.toString = $estr; RCDeviceType.Android.__enum__ = RCDeviceType; RCDeviceType.WebOS = ["WebOS",4]; RCDeviceType.WebOS.toString = $estr; RCDeviceType.WebOS.__enum__ = RCDeviceType; RCDeviceType.Mac = ["Mac",5]; RCDeviceType.Mac.toString = $estr; RCDeviceType.Mac.__enum__ = RCDeviceType; RCDeviceType.Flash = ["Flash",6]; RCDeviceType.Flash.toString = $estr; RCDeviceType.Flash.__enum__ = RCDeviceType; RCDeviceType.Playstation = ["Playstation",7]; RCDeviceType.Playstation.toString = $estr; RCDeviceType.Playstation.__enum__ = RCDeviceType; RCDeviceType.Other = ["Other",8]; RCDeviceType.Other.toString = $estr; RCDeviceType.Other.__enum__ = RCDeviceType; var RCUserAgent = $hxClasses["RCUserAgent"] = { __ename__ : ["RCUserAgent"], __constructs__ : ["MSIE","MSIE9","GECKO","WEBKIT","OTHER"] } RCUserAgent.MSIE = ["MSIE",0]; RCUserAgent.MSIE.toString = $estr; RCUserAgent.MSIE.__enum__ = RCUserAgent; RCUserAgent.MSIE9 = ["MSIE9",1]; RCUserAgent.MSIE9.toString = $estr; RCUserAgent.MSIE9.__enum__ = RCUserAgent; RCUserAgent.GECKO = ["GECKO",2]; RCUserAgent.GECKO.toString = $estr; RCUserAgent.GECKO.__enum__ = RCUserAgent; RCUserAgent.WEBKIT = ["WEBKIT",3]; RCUserAgent.WEBKIT.toString = $estr; RCUserAgent.WEBKIT.__enum__ = RCUserAgent; RCUserAgent.OTHER = ["OTHER",4]; RCUserAgent.OTHER.toString = $estr; RCUserAgent.OTHER.__enum__ = RCUserAgent; var RCDevice = $hxClasses["RCDevice"] = function() { this.dpiScale = 1; this.userAgent = this.detectUserAgent(); this.userInterfaceIdiom = this.detectUserInterfaceIdiom(); }; RCDevice.__name__ = ["RCDevice"]; RCDevice._currentDevice = null; RCDevice.currentDevice = function() { if(RCDevice._currentDevice == null) RCDevice._currentDevice = new RCDevice(); return RCDevice._currentDevice; } RCDevice.prototype = { detectUserInterfaceIdiom: function() { var agent = js.Lib.window.navigator.userAgent.toLowerCase(); if(agent.indexOf("iphone") > -1) return RCDeviceType.IPhone; if(agent.indexOf("ipad") > -1) return RCDeviceType.IPad; if(agent.indexOf("ipod") > -1) return RCDeviceType.IPod; if(agent.indexOf("playstation") > -1) return RCDeviceType.Playstation; return RCDeviceType.Other; } ,detectUserAgent: function() { var agent = js.Lib.window.navigator.userAgent.toLowerCase(); if(agent.indexOf("msie") > -1) return RCUserAgent.MSIE; if(agent.indexOf("msie 9.") > -1) return RCUserAgent.MSIE9; if(agent.indexOf("webkit") > -1) return RCUserAgent.WEBKIT; if(agent.indexOf("gecko") > -1) return RCUserAgent.GECKO; return RCUserAgent.OTHER; } ,userAgent: null ,dpiScale: null ,uniqueIdentifier: null ,userInterfaceIdiom: null ,orientation: null ,systemVersion: null ,systemName: null ,model: null ,name: null ,__class__: RCDevice } var _RCDraw = _RCDraw || {} _RCDraw.LineScaleMode = $hxClasses["_RCDraw.LineScaleMode"] = function() { } _RCDraw.LineScaleMode.__name__ = ["_RCDraw","LineScaleMode"]; var RCDraw = $hxClasses["RCDraw"] = function(x,y,w,h,color,alpha) { if(alpha == null) alpha = 1.0; JSView.call(this,x,y,w,h); this.setAlpha(alpha); this.borderThickness = 1; try { this.graphics = this.layer; } catch( e ) { haxe.Log.trace(e,{ fileName : "RCDraw.hx", lineNumber : 37, className : "RCDraw", methodName : "new"}); } if(js.Boot.__instanceof(color,RCColor) || js.Boot.__instanceof(color,RCGradient)) this.color = color; else if(js.Boot.__instanceof(color,Int) || js.Boot.__instanceof(color,Int)) this.color = new RCColor(color); else if(js.Boot.__instanceof(color,Array)) this.color = new RCColor(color[0],color[1]); else this.color = new RCColor(0); }; RCDraw.__name__ = ["RCDraw"]; RCDraw.__super__ = JSView; RCDraw.prototype = $extend(JSView.prototype,{ frame: function() { return new RCRect(this.getX(),this.getY(),this.size.width,this.size.height); } ,configure: function() { if(js.Boot.__instanceof(this.color,RCColor)) { if(this.color.fillColor != null) this.graphics.beginFill(this.color.fillColor,this.color.alpha); if(this.color.strokeColor != null) { var pixelHinting = true; var scaleMode = _RCDraw.LineScaleMode.NONE; var caps = null; var joints = null; var miterLimit = 3; this.graphics.lineStyle(this.borderThickness,this.color.strokeColor,this.color.alpha,pixelHinting,scaleMode,caps,joints,miterLimit); } } } ,borderThickness: null ,color: null ,__class__: RCDraw }); var RCDrawInterface = $hxClasses["RCDrawInterface"] = function() { } RCDrawInterface.__name__ = ["RCDrawInterface"]; RCDrawInterface.prototype = { redraw: null ,configure: null ,__class__: RCDrawInterface } var RCEllipse = $hxClasses["RCEllipse"] = function(x,y,w,h,color,alpha) { if(alpha == null) alpha = 1.0; RCDraw.call(this,x,y,w,h,color,alpha); this.redraw(); }; RCEllipse.__name__ = ["RCEllipse"]; RCEllipse.__interfaces__ = [RCDrawInterface]; RCEllipse.__super__ = RCDraw; RCEllipse.prototype = $extend(RCDraw.prototype,{ fillEllipse: function(xc,yc,width,height) { var iHtml = new Array(); var a = Math.round(width / 2); var b = Math.round(height / 2); var hexColor = (js.Boot.__cast(this.color , RCColor)).fillColorStyle; var x = 0; var y = b; var a2 = a * a; var b2 = b * b; var xp, yp; xp = 1; yp = y; while(b2 * x < a2 * y) { x++; if(b2 * x * x + a2 * (y - 0.5) * (y - 0.5) - a2 * b2 >= 0) y--; if(x == 1 && y != yp) { iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;width:1px;height:1px;left:" + xc + "px;top:" + (yc + yp - 1) + "px;background-color:" + hexColor + "\"></DIV>"; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;width:1px;height:1px;left:" + xc + "px;top:" + (yc - yp) + "px;background-color:" + hexColor + "\"></DIV>"; } if(y != yp) { iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;height:1px;left:" + (xc - x + 1) + "px;top:" + (yc - yp) + "px;width:" + (2 * x - 1) + "px;background-color:" + hexColor + "\"></DIV>"; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;height:1px;left:" + (xc - x + 1) + "px;top:" + (yc + yp) + "px;width:" + (2 * x - 1) + "px;background-color:" + hexColor + "\"></DIV>"; yp = y; xp = x; } if(b2 * x >= a2 * y) { iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;height:1px;left:" + (xc - x) + "px;top:" + (yc - yp) + "px;width:" + (2 * x + 1) + "px;background-color:" + hexColor + "\"></DIV>"; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;height:1px;left:" + (xc - x) + "px;top:" + (yc + yp) + "px;width:" + (2 * x + 1) + "px;background-color:" + hexColor + "\"></DIV>"; } } xp = x; yp = y; var divHeight = 1; while(y != 0) { y--; if(b2 * (x + 0.5) * (x + 0.5) + a2 * y * y - a2 * b2 <= 0) x++; if(x != xp) { divHeight = yp - y; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;left:" + (xc - xp) + "px;top:" + (yc - yp) + "px;width:" + (2 * xp + 1) + "px;height:" + divHeight + "px;background-color:" + hexColor + "\"></DIV>"; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;left:" + (xc - xp) + "px;top:" + (yc + y + 1) + "px;width:" + (2 * xp + 1) + "px;height:" + divHeight + "px;background-color:" + hexColor + "\"></DIV>"; xp = x; yp = y; } if(y == 0) { divHeight = yp - y + 1; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;left:" + (xc - xp) + "px;top:" + (yc - yp) + "px;width:" + (2 * x + 1) + "px;height:" + divHeight + "px;background-color:" + hexColor + "\"></DIV>"; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;left:" + (xc - xp) + "px;top:" + (yc + y) + "px;width:" + (2 * x + 1) + "px;height:" + divHeight + "px;background-color:" + hexColor + "\"></DIV>"; } } this.layer.innerHTML = iHtml.join(""); return this.layer; } ,redraw: function() { this.fillEllipse(Math.round(this.size.width / 2),Math.round(this.size.height / 2),this.size.width,this.size.height); } ,__class__: RCEllipse }); var RCFont = $hxClasses["RCFont"] = function() { this.font = "Arial"; this.html = true; this.embedFonts = true; this.autoSize = true; this.selectable = false; this.color = 14540253; this.size = 12; this.leading = 4; this.leftMargin = 0; this.rightMargin = 0; this.letterSpacing = 0; this.format = { }; this.style = { }; }; RCFont.__name__ = ["RCFont"]; RCFont.fontWithName = function(fontName,size) { var fnt = new RCFont(); fnt.font = fontName; fnt.size = size; return fnt; } RCFont.familyNames = function() { return []; } RCFont.systemFontOfSize = function(size) { var fnt = new RCFont(); fnt.size = size; fnt.embedFonts = false; return fnt; } RCFont.boldSystemFontOfSize = function(size) { var fnt = RCFont.systemFontOfSize(size); fnt.bold = true; return fnt; } RCFont.italicSystemFontOfSize = function(size) { var fnt = RCFont.systemFontOfSize(size); fnt.italic = true; return fnt; } RCFont.prototype = { getStyleSheet: function() { return this.style; } ,getFormat: function() { this.format.align = null; this.format.blockIndent = this.blockIndent; this.format.bold = this.bold; this.format.bullet = this.bullet; this.format.color = this.color; this.format.font = this.font; this.format.italic = this.italic; this.format.indent = this.indent; this.format.kerning = this.kerning; this.format.leading = this.leading * RCDevice.currentDevice().dpiScale; this.format.leftMargin = this.leftMargin * RCDevice.currentDevice().dpiScale; this.format.letterSpacing = this.letterSpacing; this.format.rightMargin = this.rightMargin * RCDevice.currentDevice().dpiScale; this.format.size = this.size * RCDevice.currentDevice().dpiScale; this.format.tabStops = this.tabStops; this.format.target = this.target; this.format.underline = this.underline; this.format.url = this.url; return this.format; } ,copy: function(exceptions) { var rcfont = new RCFont(); var fields = Type.getInstanceFields(RCFont); var _g = 0; while(_g < fields.length) { var field = fields[_g]; ++_g; if(field == "copy" || field == "getFormat" || field == "getStyleSheet" || field == "get_format" || field == "get_style") continue; rcfont[field] = Reflect.field(this,field); } if(exceptions != null) { var _g = 0, _g1 = Reflect.fields(exceptions); while(_g < _g1.length) { var excp = _g1[_g]; ++_g; if(Reflect.hasField(rcfont,excp)) rcfont[excp] = Reflect.field(exceptions,excp); } } return rcfont; } ,url: null ,underline: null ,target: null ,tabStops: null ,size: null ,rightMargin: null ,letterSpacing: null ,leftMargin: null ,leading: null ,kerning: null ,italic: null ,indent: null ,font: null ,display: null ,color: null ,bullet: null ,bold: null ,blockIndent: null ,align: null ,thickness: null ,sharpness: null ,selectable: null ,displayAsPassword: null ,autoSize: null ,antiAliasType: null ,type: null ,embedFonts: null ,style: null ,format: null ,html: null ,__class__: RCFont ,__properties__: {get_format:"getFormat",get_style:"getStyleSheet"} } var RCFontManager = $hxClasses["RCFontManager"] = function() { }; RCFontManager.__name__ = ["RCFontManager"]; RCFontManager.INSTANCE = null; RCFontManager.init = function() { if(RCFontManager.INSTANCE == null) { RCFontManager.INSTANCE = new RCFontManager(); RCFontManager.INSTANCE.initDefaults(); } } RCFontManager.instance = function() { if(RCFontManager.INSTANCE == null) RCFontManager.init(); return RCFontManager.INSTANCE; } RCFontManager.registerFont = function(key,data) { RCFontManager.instance().hash_rcfont.set(key,data); } RCFontManager.registerStyle = function(key,data) { RCFontManager.instance().hash_style.set(key,data); } RCFontManager.remove = function(key) { RCFontManager.instance().hash_style.remove(key); RCFontManager.instance().hash_rcfont.remove(key); } RCFontManager.getFont = function(key,exceptions) { if(key == null) key = "system"; return RCFontManager.instance().hash_rcfont.get(key).copy(exceptions); } RCFontManager.getStyleSheet = function(key,exception) { if(key == null) key = "default"; if(key == "css" && RCFontManager.instance().hash_style.exists("css")) return RCFontManager.instance().hash_style.get("css"); return RCFontManager.instance().createStyle(RCFontManager.INSTANCE.hash_style.get(key),exception); } RCFontManager.addSwf = function(swf) { RCFontManager.instance().push(swf); } RCFontManager.setCSS = function(css) { RCFontManager.instance().setCSSFile(css); } RCFontManager.registerSwfFont = function(str) { return false; } RCFontManager.prototype = { createStyle: function(properties,exceptions) { var style = null; return style; } ,setCSSFile: function(css) { } ,push: function(e) { this.fontsSwfList.push(e); } ,initDefaults: function() { this.hash_style = new Hash(); this.hash_rcfont = new Hash(); this.fontsSwfList = new Array(); this._defaultStyleSheetData = { a_link : { color : "#999999", textDecoration : "underline"}, a_hover : { color : "#33CCFF"}, h1 : { size : 16}}; RCFontManager.registerStyle("default",this._defaultStyleSheetData); } ,hash_rcfont: null ,hash_style: null ,_defaultStyleSheetData: null ,event: null ,fontsSwfList: null ,fontsDomain: null ,__class__: RCFontManager } var RCGradient = $hxClasses["RCGradient"] = function(colors,alphas,linear) { if(linear == null) linear = true; this.gradientColors = colors; this.gradientAlphas = alphas == null?[1.0,1.0]:alphas; this.gradientRatios = [0,255]; this.focalPointRatio = 0; this.tx = 0; this.ty = 0; this.matrixRotation = Math.PI * 0.5; }; RCGradient.__name__ = ["RCGradient"]; RCGradient.prototype = { matrixRotation: null ,ty: null ,tx: null ,focalPointRatio: null ,gradientType: null ,interpolationMethod: null ,spreadMethod: null ,gradientRatios: null ,gradientAlphas: null ,gradientColors: null ,strokeColor: null ,__class__: RCGradient } var RCGroup = $hxClasses["RCGroup"] = function(x,y,gapX,gapY,constructor_) { JSView.call(this,x,y); this.gapX = gapX; this.gapY = gapY; this.constructor_ = constructor_; this.items = new Array(); this.itemPush = new RCSignal(); this.itemRemove = new RCSignal(); this.update = new RCSignal(); }; RCGroup.__name__ = ["RCGroup"]; RCGroup.__super__ = JSView; RCGroup.prototype = $extend(JSView.prototype,{ destroy: function() { Fugu.safeDestroy(this.items,null,{ fileName : "RCGroup.hx", lineNumber : 130, className : "RCGroup", methodName : "destroy"}); this.items = null; JSView.prototype.destroy.call(this); } ,get: function(i) { return this.items[i]; } ,keepItemsArranged: function() { var _g1 = 0, _g = this.items.length; while(_g1 < _g) { var i = _g1++; var newX = 0.0, newY = 0.0; var new_s = this.items[i]; var old_s = this.items[i - 1]; if(i != 0) { if(this.gapX != null) newX = old_s.getX() + old_s.getWidth() + this.gapX; if(this.gapY != null) newY = old_s.getY() + old_s.getHeight() + this.gapY; } new_s.setX(newX); new_s.setY(newY); this.size.width = newX + new_s.size.width; this.size.height = newY + new_s.size.height; } this.update.dispatch(this,null,null,null,{ fileName : "RCGroup.hx", lineNumber : 101, className : "RCGroup", methodName : "keepItemsArranged"}); } ,remove: function(i) { Fugu.safeDestroy(this.items[i],null,{ fileName : "RCGroup.hx", lineNumber : 69, className : "RCGroup", methodName : "remove"}); this.keepItemsArranged(); this.itemRemove.dispatch(new RCIndexPath(0,i),null,null,null,{ fileName : "RCGroup.hx", lineNumber : 74, className : "RCGroup", methodName : "remove"}); } ,add: function(params,alternativeConstructor) { if(!Reflect.isFunction(this.constructor_) && !Reflect.isFunction(alternativeConstructor)) return; if(alternativeConstructor != null) this.constructor_ = alternativeConstructor; if(this.constructor_ == null) throw "RCGroup needs passed a constructor function."; var i = 0; var _g = 0; while(_g < params.length) { var param = params[_g]; ++_g; var s = this.constructor_(new RCIndexPath(0,i)); this.addChild(s); this.items.push(s); s.init(); this.itemPush.dispatch(new RCIndexPath(0,i),null,null,null,{ fileName : "RCGroup.hx", lineNumber : 59, className : "RCGroup", methodName : "add"}); i++; } this.keepItemsArranged(); } ,update: null ,itemRemove: null ,itemPush: null ,gapY: null ,gapX: null ,constructor_: null ,items: null ,__class__: RCGroup }); var RCRequest = $hxClasses["RCRequest"] = function() { }; RCRequest.__name__ = ["RCRequest"]; RCRequest.prototype = { destroy: function() { this.removeListeners(this.loader); this.loader = null; } ,createVariables: function(variables_list) { var variables = new _RCRequest.URLVariables(); if(variables_list != null) { var _g = 0, _g1 = Reflect.fields(variables_list); while(_g < _g1.length) { var f = _g1[_g]; ++_g; variables[f] = Reflect.field(variables_list,f); } } return variables; } ,createRequest: function(URL,variables,method) { var request = new haxe.Http(URL); haxe.Log.trace(request,{ fileName : "RCRequest.hx", lineNumber : 194, className : "RCRequest", methodName : "createRequest"}); haxe.Log.trace(request.url,{ fileName : "RCRequest.hx", lineNumber : 194, className : "RCRequest", methodName : "createRequest"}); return request; } ,ioErrorHandler: function(e) { this.result = e; this.onError(); } ,httpStatusHandler: function(e) { this.status = e; this.onStatus(); } ,securityErrorHandler: function(e) { this.result = e; this.onError(); } ,progressHandler: function(e) { } ,completeHandler: function(e) { this.result = e; if(this.result.indexOf("error::") != -1) { this.result = this.result.split("error::").pop(); this.onError(); } else this.onComplete(); } ,openHandler: function(e) { this.onOpen(); } ,removeListeners: function(dispatcher) { dispatcher.onData = null; dispatcher.onError = null; dispatcher.onStatus = null; } ,addListeners: function(dispatcher) { dispatcher.onData = $bind(this,this.completeHandler); dispatcher.onError = $bind(this,this.securityErrorHandler); dispatcher.onStatus = $bind(this,this.httpStatusHandler); } ,load: function(URL,variables,method) { if(method == null) method = "POST"; this.loader = new haxe.Http(URL); this.loader.async = true; var _g = 0, _g1 = Reflect.fields(variables); while(_g < _g1.length) { var key = _g1[_g]; ++_g; this.loader.setParameter(key,Reflect.field(variables,key)); } this.addListeners(this.loader); this.loader.request(method == "POST"?true:false); } ,onStatus: function() { } ,onProgress: function() { } ,onError: function() { } ,onComplete: function() { } ,onOpen: function() { } ,percentLoaded: null ,status: null ,result: null ,loader: null ,__class__: RCRequest } var RCHttp = $hxClasses["RCHttp"] = function(apiPath) { if(apiPath == null) apiPath = ""; this.apiPath = apiPath; if(apiPath != "" && !StringTools.endsWith(apiPath,"/")) this.apiPath += "/"; RCRequest.call(this); }; RCHttp.__name__ = ["RCHttp"]; RCHttp.__super__ = RCRequest; RCHttp.prototype = $extend(RCRequest.prototype,{ navigateToURL: function(URL,variables_list,method,target) { if(target == null) target = "_self"; if(method == null) method = "POST"; haxe.Log.trace(URL,{ fileName : "RCHttp.hx", lineNumber : 52, className : "RCHttp", methodName : "navigateToURL"}); haxe.Log.trace(variables_list,{ fileName : "RCHttp.hx", lineNumber : 52, className : "RCHttp", methodName : "navigateToURL"}); haxe.Log.trace(method,{ fileName : "RCHttp.hx", lineNumber : 52, className : "RCHttp", methodName : "navigateToURL"}); haxe.Log.trace(target,{ fileName : "RCHttp.hx", lineNumber : 52, className : "RCHttp", methodName : "navigateToURL"}); var variables = this.createVariables(variables_list); } ,call: function(script,variables_list,method) { if(method == null) method = "POST"; this.load(this.apiPath + script,this.createVariables(variables_list),method); } ,readDirectory: function(directoryName) { var variables = this.createVariables({ path : directoryName}); this.load(this.apiPath + "filesystem/readDirectory.php",variables); } ,readFile: function(file) { this.load(file); } ,apiPath: null ,__class__: RCHttp }); var RCImage = $hxClasses["RCImage"] = function(x,y,URL) { JSView.call(this,x,y); this.loader = js.Lib.document.createElement("img"); this.addListeners(); this.initWithContentsOfFile(URL); }; RCImage.__name__ = ["RCImage"]; RCImage.imageNamed = function(name) { return new RCImage(0,0,name); } RCImage.imageWithContentsOfFile = function(path) { return new RCImage(0,0,path); } RCImage.resizableImageWithCapInsets = function(path,capWidth) { return new RCImage(0,0,path); } RCImage.imageWithRegionOfImage = function(image,size,source_rect,draw_at) { return null; } RCImage.__super__ = JSView; RCImage.prototype = $extend(JSView.prototype,{ scaleToFill: function(w,h) { JSView.prototype.scaleToFill.call(this,w,h); this.loader.style.width = this.size.width + "px"; this.loader.style.height = this.size.height + "px"; } ,scaleToFit: function(w,h) { JSView.prototype.scaleToFit.call(this,w,h); this.loader.style.width = this.size.width + "px"; this.loader.style.height = this.size.height + "px"; } ,destroy: function() { this.removeListeners(); this.loader = null; JSView.prototype.destroy.call(this); } ,removeListeners: function() { this.loader.onload = null; this.loader.onerror = null; } ,addListeners: function() { this.loader.onload = $bind(this,this.completeHandler); this.loader.onerror = $bind(this,this.errorHandler); } ,copy: function() { return new RCImage(0,0,this.loader.src); } ,ioErrorHandler: function(e) { this.errorMessage = Std.string(e); this.onError(); } ,errorHandler: function(e) { this.errorMessage = Std.string(e); this.onError(); } ,completeHandler: function(e) { var _g = this; this.size.width = this.loader.width; this.size.height = this.loader.height; this.layer.appendChild(this.loader); this.originalSize = this.size.copy(); this.isLoaded = true; if(RCDevice.currentDevice().userAgent == RCUserAgent.MSIE) { haxe.Timer.delay(function() { _g.onComplete(); },1); return; } this.onComplete(); } ,initWithContentsOfFile: function(URL) { this.isLoaded = false; this.percentLoaded = 0; if(URL == null) return; this.loader.draggable = false; this.loader.src = URL; } ,onError: function() { } ,onProgress: function() { } ,onComplete: function() { } ,errorMessage: null ,percentLoaded: null ,isLoaded: null ,bitmapData: null ,loader: null ,__class__: RCImage }); var RCImageStretchable = $hxClasses["RCImageStretchable"] = function(x,y,imageLeft,imageMiddle,imageRight) { JSView.call(this,x,y); this.l = new RCImage(0,0,imageLeft); this.l.onComplete = $bind(this,this.onCompleteHandler); this.m = new RCImage(0,0,imageMiddle); this.m.onComplete = $bind(this,this.onCompleteHandler); this.r = new RCImage(0,0,imageRight); this.r.onComplete = $bind(this,this.onCompleteHandler); this.addChild(this.l); this.addChild(this.m); this.addChild(this.r); }; RCImageStretchable.__name__ = ["RCImageStretchable"]; RCImageStretchable.__super__ = JSView; RCImageStretchable.prototype = $extend(JSView.prototype,{ destroy: function() { this.l.destroy(); this.m.destroy(); this.r.destroy(); JSView.prototype.destroy.call(this); } ,setWidth: function(w) { this.size.width = w; if(!this.l.isLoaded || !this.m.isLoaded || !this.r.isLoaded) return w; this.l.setX(0); this.m.setX(Math.round(this.l.getWidth())); var mw = Math.round(w - this.l.getWidth() - this.r.getWidth()); if(mw < 0) mw = 0; this.m.setWidth(mw); var rx = Math.round(w - this.r.getWidth()); if(rx < this.m.getX() + mw) rx = Math.round(this.m.getX() + mw); this.r.setX(rx); return w; } ,onCompleteHandler: function() { if(this.l.isLoaded && this.m.isLoaded && this.r.isLoaded && this.size.width != 0) this.setWidth(this.size.width); this.onComplete(); } ,onComplete: function() { } ,r: null ,m: null ,l: null ,__class__: RCImageStretchable }); var RCIndexPath = $hxClasses["RCIndexPath"] = function(section,row) { this.section = section; this.row = row; }; RCIndexPath.__name__ = ["RCIndexPath"]; RCIndexPath.prototype = { toString: function() { return "[RCIndexPath section : " + this.section + ", row : " + this.row + "]"; } ,copy: function() { return new RCIndexPath(this.section,this.row); } ,next: function() { return this; } ,hasNext: function() { return true; } ,row: null ,section: null ,__class__: RCIndexPath } var RCKeyboardController = $hxClasses["RCKeyboardController"] = function() { this.resume(); }; RCKeyboardController.__name__ = ["RCKeyboardController"]; RCKeyboardController.prototype = { destroy: function() { this.hold(); } ,hold: function() { js.Lib.document.onkeydown = null; js.Lib.document.onkeyup = null; } ,resume: function() { js.Lib.document.onkeydown = $bind(this,this.keyDownHandler); js.Lib.document.onkeyup = $bind(this,this.keyUpHandler); } ,keyUpHandler: function(e) { this["char"] = ""; this.onKeyUp(); } ,keyDownHandler: function(e) { this.keyCode = e.keyCode; haxe.Log.trace(this.keyCode,{ fileName : "RCKeyboardController.hx", lineNumber : 43, className : "RCKeyboardController", methodName : "keyDownHandler"}); this["char"] = ""; this.onKeyDown(); switch(e.keyCode) { case 37: this.onLeft(); break; case 39: this.onRight(); break; case 38: this.onUp(); break; case 40: this.onDown(); break; case 13: this.onEnter(); break; case 32: this.onSpace(); break; case 27: this.onEsc(); break; } } ,keyCode: null ,'char': null ,onKeyDown: function() { } ,onKeyUp: function() { } ,onEsc: function() { } ,onSpace: function() { } ,onEnter: function() { } ,onDown: function() { } ,onUp: function() { } ,onRight: function() { } ,onLeft: function() { } ,__class__: RCKeyboardController } var Keyboard = $hxClasses["Keyboard"] = function() { } Keyboard.__name__ = ["Keyboard"]; var RCLine = $hxClasses["RCLine"] = function(x1,y1,x2,y2,color,alpha,lineWeight) { if(lineWeight == null) lineWeight = 1; if(alpha == null) alpha = 1.0; RCDraw.call(this,x1,y1,x2 - x1,y2 - y1,color,alpha); this.lineWeight = lineWeight; this.redraw(); }; RCLine.__name__ = ["RCLine"]; RCLine.__interfaces__ = [RCDrawInterface]; RCLine.__super__ = RCDraw; RCLine.prototype = $extend(RCDraw.prototype,{ drawLine: function(x0,y0,x1,y1) { var hexColor = (js.Boot.__cast(this.color , RCColor)).fillColorStyle; if(y0 == y1) { if(x0 <= x1) this.layer.innerHTML = "<DIV style=\"position:absolute;overflow:hidden;left:" + x0 + "px;top:" + y0 + "px;width:" + (x1 - x0 + 1) + "px;height:" + this.lineWeight + ";background-color:" + hexColor + "\"></DIV>"; else if(x0 > x1) this.layer.innerHTML = "<DIV style=\"position:absolute;overflow:hidden;left:" + x1 + "px;top:" + y0 + "px;width:" + (x0 - x1 + 1) + "px;height:" + this.lineWeight + ";background-color:" + hexColor + "\"></DIV>"; return this.layer; } if(x0 == x1) { if(y0 <= y1) this.layer.innerHTML = "<DIV style=\"position:absolute;overflow:hidden;left:" + x0 + "px;top:" + y0 + "px;width:" + this.lineWeight + ";height:" + (y1 - y0 + 1) + "px;background-color:" + hexColor + "\"></DIV>"; else if(y0 > y1) this.layer.innerHTML = "<DIV style=\"position:absolute;overflow:hidden;left:" + x0 + "px;top:" + y1 + "px;width:" + this.lineWeight + ";height:" + (y0 - y1 + 1) + "px;background-color:" + hexColor + "\"></DIV>"; return this.layer; } var iHtml = new Array(); var yArray = new Array(); var dx = Math.abs(x1 - x0); var dy = Math.abs(y1 - y0); var pixHeight = Math.round(Math.sqrt(this.lineWeight * this.lineWeight / (dy * dy / (dx * dx) + 1))); var pixWidth = Math.round(Math.sqrt(this.lineWeight * this.lineWeight - pixHeight * pixHeight)); if(pixWidth == 0) pixWidth = 1; if(pixHeight == 0) pixHeight = 1; var steep = Math.abs(y1 - y0) > Math.abs(x1 - x0); if(steep) { var tmp = x0; x0 = y0; y0 = tmp; tmp = x1; x1 = y1; y1 = tmp; } if(x0 > x1) { var tmp = x0; x0 = x1; x1 = tmp; tmp = y0; y0 = y1; y1 = tmp; } var deltax = x1 - x0; var deltay = Math.abs(y1 - y0); var error = deltax / 2; var ystep; var y = y0; ystep = y0 < y1?1:-1; var xp = 0; var yp = 0; var divWidth = 0; var divHeight = 0; if(steep) divWidth = pixWidth; else divHeight = pixHeight; var _g1 = x0, _g = x1 + 1; while(_g1 < _g) { var x = _g1++; if(steep) { if(x == x0) { xp = y; yp = x; } else if(y == xp) divHeight = divHeight + 1; else { divHeight = divHeight + pixHeight; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;left:" + xp + "px;top:" + yp + "px;width:" + divWidth + "px;height:" + divHeight + "px;background-color:" + hexColor + "\"></DIV>"; divHeight = 0; xp = y; yp = x; } if(x == x1) { if(divHeight != 0) { divHeight = divHeight + pixHeight; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;left:" + xp + "px;top:" + yp + "px;width:" + divWidth + "px;height:" + divHeight + "px;background-color:" + hexColor + "\"></DIV>"; } else { divHeight = pixHeight; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;left:" + y + "px;top:" + x + "px;width:" + divWidth + "px;height:" + divHeight + "px;background-color:" + hexColor + "\"></DIV>"; } } } else { if(x == x0) { xp = x; yp = y; } else if(y == yp) divWidth = divWidth + 1; else { divWidth = divWidth + pixWidth; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;left:" + xp + "px;top:" + yp + "px;width:" + divWidth + "px;height:" + divHeight + "px;background-color:" + hexColor + "\"></DIV>"; divWidth = 0; xp = x; yp = y; } if(x == x1) { if(divWidth != 0) { divWidth = divWidth + pixWidth; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;left:" + xp + "px;top:" + yp + "px;width:" + divWidth + "px;height:" + divHeight + "px;background-color:" + hexColor + "\"></DIV>"; } else { divWidth = pixWidth; iHtml[iHtml.length] = "<DIV style=\"position:absolute;overflow:hidden;left:" + x + "px;top:" + y + "px;width:" + divWidth + "px;height:" + divHeight + "px;background-color:" + hexColor + "\"></DIV>"; } } } error = error - deltay; if(error < 0) { y = y + ystep; error = error + deltax; } } this.layer.innerHTML = iHtml.join(""); return this.layer; } ,redraw: function() { this.layer.innerHTML = ""; this.drawLine(0,0,Math.round(this.size.width),Math.round(this.size.height)); } ,lineWeight: null ,__class__: RCLine }); var RCNotification = $hxClasses["RCNotification"] = function(name,functionToCall) { this.name = name; this.functionToCall = functionToCall; }; RCNotification.__name__ = ["RCNotification"]; RCNotification.prototype = { toString: function() { return "[RCNotification with name: '" + this.name + "', functionToCall: " + Std.string(this.functionToCall) + "]"; } ,functionToCall: null ,name: null ,__class__: RCNotification } var RCNotificationCenter = $hxClasses["RCNotificationCenter"] = function() { } RCNotificationCenter.__name__ = ["RCNotificationCenter"]; RCNotificationCenter.notificationsList = null; RCNotificationCenter.init = function() { if(RCNotificationCenter.notificationsList == null) { RCNotificationCenter.notificationsList = new List(); var fs = new EVFullScreen(); fs.add(RCNotificationCenter.fullScreenHandler); var rs = new EVResize(); rs.add(RCNotificationCenter.resizeHandler); } } RCNotificationCenter.resizeHandler = function(w,h) { RCNotificationCenter.postNotification("resize",[w,h],{ fileName : "RCNotificationCenter.hx", lineNumber : 27, className : "RCNotificationCenter", methodName : "resizeHandler"}); } RCNotificationCenter.fullScreenHandler = function(b) { RCNotificationCenter.postNotification("fullscreen",[b],{ fileName : "RCNotificationCenter.hx", lineNumber : 30, className : "RCNotificationCenter", methodName : "fullScreenHandler"}); } RCNotificationCenter.addObserver = function(name,func) { RCNotificationCenter.init(); RCNotificationCenter.notificationsList.add(new RCNotification(name,func)); } RCNotificationCenter.removeObserver = function(name,func) { RCNotificationCenter.init(); var $it0 = RCNotificationCenter.notificationsList.iterator(); while( $it0.hasNext() ) { var notification = $it0.next(); if(notification.name == name && Reflect.compareMethods(notification.functionToCall,func)) RCNotificationCenter.notificationsList.remove(notification); } } RCNotificationCenter.postNotification = function(name,args,pos) { RCNotificationCenter.init(); var notificationFound = false; var $it0 = RCNotificationCenter.notificationsList.iterator(); while( $it0.hasNext() ) { var notification = $it0.next(); if(notification.name == name) try { notificationFound = true; notification.functionToCall.apply(null,args); } catch( e ) { haxe.Log.trace("[RCNotificationCenter error calling function: " + Std.string(notification.functionToCall) + " from: " + Std.string(pos) + "]",{ fileName : "RCNotificationCenter.hx", lineNumber : 72, className : "RCNotificationCenter", methodName : "postNotification"}); } } return notificationFound; } RCNotificationCenter.list = function() { var $it0 = RCNotificationCenter.notificationsList.iterator(); while( $it0.hasNext() ) { var notification = $it0.next(); haxe.Log.trace(notification,{ fileName : "RCNotificationCenter.hx", lineNumber : 83, className : "RCNotificationCenter", methodName : "list"}); } } var RCPoint = $hxClasses["RCPoint"] = function(x,y) { this.x = x == null?0:x; this.y = y == null?0:y; }; RCPoint.__name__ = ["RCPoint"]; RCPoint.prototype = { toString: function() { return "[RCPoint x:" + this.x + ", y:" + this.y + "]"; } ,copy: function() { return new RCPoint(this.x,this.y); } ,y: null ,x: null ,__class__: RCPoint } var RCRect = $hxClasses["RCRect"] = function(x,y,w,h) { this.origin = new RCPoint(x,y); this.size = new RCSize(w,h); }; RCRect.__name__ = ["RCRect"]; RCRect.prototype = { toString: function() { return "[RCRect x:" + this.origin.x + ", y:" + this.origin.y + ", width:" + this.size.width + ", height:" + this.size.height + "]"; } ,copy: function() { return new RCRect(this.origin.x,this.origin.y,this.size.width,this.size.height); } ,size: null ,origin: null ,__class__: RCRect } var RCRectangle = $hxClasses["RCRectangle"] = function(x,y,w,h,color,alpha,r) { if(alpha == null) alpha = 1.0; RCDraw.call(this,x,y,w,h,color,alpha); this.roundness = r; this.redraw(); }; RCRectangle.__name__ = ["RCRectangle"]; RCRectangle.__interfaces__ = [RCDrawInterface]; RCRectangle.__super__ = RCDraw; RCRectangle.prototype = $extend(RCDraw.prototype,{ setHeight: function(h) { this.size.height = h; this.redraw(); return h; } ,setWidth: function(w) { this.size.width = w; this.redraw(); return w; } ,redraw: function() { var dpi = RCDevice.currentDevice().dpiScale; var fillColorStyle = this.color.fillColorStyle; var strokeColorStyle = this.color.strokeColorStyle; this.layer.style.margin = "0px 0px 0px 0px"; this.layer.style.width = this.size.width * dpi + "px"; this.layer.style.height = this.size.height * dpi + "px"; this.layer.style.backgroundColor = fillColorStyle; if(strokeColorStyle != null) { this.layer.style.borderStyle = "solid"; this.layer.style.borderWidth = this.borderThickness + "px"; this.layer.style.borderColor = strokeColorStyle; } if(this.roundness != null) { this.layer.style.MozBorderRadius = this.roundness * dpi / 2 + "px"; this.layer.style.borderRadius = this.roundness * dpi / 2 + "px"; } } ,roundness: null ,__class__: RCRectangle }); var _RCRequest = _RCRequest || {} _RCRequest.URLVariables = $hxClasses["_RCRequest.URLVariables"] = function() { }; _RCRequest.URLVariables.__name__ = ["_RCRequest","URLVariables"]; _RCRequest.URLVariables.prototype = { __class__: _RCRequest.URLVariables } var _RCScrollBar = _RCScrollBar || {} _RCScrollBar.Direction = $hxClasses["_RCScrollBar.Direction"] = { __ename__ : ["_RCScrollBar","Direction"], __constructs__ : ["HORIZONTAL","VERTICAL"] } _RCScrollBar.Direction.HORIZONTAL = ["HORIZONTAL",0]; _RCScrollBar.Direction.HORIZONTAL.toString = $estr; _RCScrollBar.Direction.HORIZONTAL.__enum__ = _RCScrollBar.Direction; _RCScrollBar.Direction.VERTICAL = ["VERTICAL",1]; _RCScrollBar.Direction.VERTICAL.toString = $estr; _RCScrollBar.Direction.VERTICAL.__enum__ = _RCScrollBar.Direction; var RCScrollBar = $hxClasses["RCScrollBar"] = function(x,y,w,h,indicatorSize,skin) { RCControl.call(this,x,y,w,h); this.moving = false; this.minValue_ = 0; this.maxValue_ = 100; this.value_ = 0.0; this.skin = skin; this.indicatorSize = indicatorSize; this.viewDidAppear.add($bind(this,this.init)); }; RCScrollBar.__name__ = ["RCScrollBar"]; RCScrollBar.__super__ = RCControl; RCScrollBar.prototype = $extend(RCControl.prototype,{ destroy: function() { this.valueChanged.destroy({ fileName : "RCScrollBar.hx", lineNumber : 163, className : "RCScrollBar", methodName : "destroy"}); this.mouseUpOverStage_.destroy({ fileName : "RCScrollBar.hx", lineNumber : 164, className : "RCScrollBar", methodName : "destroy"}); this.mouseMoveOverStage_.destroy({ fileName : "RCScrollBar.hx", lineNumber : 165, className : "RCScrollBar", methodName : "destroy"}); this.skin.destroy(); RCControl.prototype.destroy.call(this); } ,setValue: function(v) { var x1 = 0.0, x2 = 0.0; this.value_ = v; switch( (this.direction_)[1] ) { case 0: x2 = this.size.width - this.scrollbar.getWidth(); this.scrollbar.setX(Zeta.lineEquationInt(x1,x2,v,this.minValue_,this.maxValue_)); break; case 1: x2 = this.size.height - this.scrollbar.getHeight(); this.scrollbar.setY(Zeta.lineEquationInt(x1,x2,v,this.minValue_,this.maxValue_)); break; } this.valueChanged.dispatch(this,null,null,null,{ fileName : "RCScrollBar.hx", lineNumber : 154, className : "RCScrollBar", methodName : "setValue"}); return this.value_; } ,getValue: function() { return this.value_; } ,mouseMoveHandler: function(e) { var y0 = 0.0, y1 = 0.0, y2 = 0.0; switch( (this.direction_)[1] ) { case 0: y2 = this.size.width - this.scrollbar.getWidth(); y0 = Zeta.limitsInt(this.getMouseX() - this.scrollbar.getWidth() / 2,0,y2); break; case 1: y2 = this.size.height - this.scrollbar.getHeight(); y0 = Zeta.limitsInt(this.getMouseY() - this.scrollbar.getHeight() / 2,0,y2); break; } this.setValue(Zeta.lineEquation(this.minValue_,this.maxValue_,y0,y1,y2)); e.updateAfterEvent(); } ,clickHandler: function(e) { this.setState(RCControlState.SELECTED); this.onClick(); } ,rollOutHandler: function(e) { this.setState(RCControlState.NORMAL); this.scrollbar.setAlpha(0.4); this.onOut(); } ,rollOverHandler: function(e) { this.setState(RCControlState.HIGHLIGHTED); this.scrollbar.setAlpha(1); this.onOver(); } ,mouseUpHandler: function(e) { this.moving = false; this.mouseUpOverStage_.remove($bind(this,this.mouseUpHandler)); this.mouseMoveOverStage_.remove($bind(this,this.mouseMoveHandler)); this.setState(RCControlState.HIGHLIGHTED); this.onRelease(); } ,mouseDownHandler: function(e) { haxe.Log.trace("mouseDownHandler",{ fileName : "RCScrollBar.hx", lineNumber : 79, className : "RCScrollBar", methodName : "mouseDownHandler"}); this.moving = true; this.mouseUpOverStage_.add($bind(this,this.mouseUpHandler)); this.mouseMoveOverStage_.add($bind(this,this.mouseMoveHandler)); this.mouseMoveHandler(e); this.setState(RCControlState.SELECTED); this.onPress(); } ,configureDispatchers: function() { RCControl.prototype.configureDispatchers.call(this); this.valueChanged = new RCSignal(); this.mouseUpOverStage_ = new EVMouse("mouseup",RCWindow.sharedWindow().stage,{ fileName : "RCScrollBar.hx", lineNumber : 75, className : "RCScrollBar", methodName : "configureDispatchers"}); this.mouseMoveOverStage_ = new EVMouse("mousemove",RCWindow.sharedWindow().stage,{ fileName : "RCScrollBar.hx", lineNumber : 76, className : "RCScrollBar", methodName : "configureDispatchers"}); } ,init: function() { RCControl.prototype.init.call(this); this.direction_ = this.size.width > this.size.height?_RCScrollBar.Direction.HORIZONTAL:_RCScrollBar.Direction.VERTICAL; this.background = this.skin.normal.background; this.background.setWidth(this.size.width); this.background.setHeight(this.size.height); this.addChild(this.background); this.scrollbar = this.skin.normal.otherView; this.scrollbar.setWidth(this.direction_ == _RCScrollBar.Direction.HORIZONTAL?this.indicatorSize:this.size.width); this.scrollbar.setHeight(this.direction_ == _RCScrollBar.Direction.VERTICAL?this.indicatorSize:this.size.height); this.scrollbar.setAlpha(0.4); this.addChild(this.scrollbar); } ,valueChanged: null ,value: null ,mouseMoveOverStage_: null ,mouseUpOverStage_: null ,moving: null ,maxValue_: null ,minValue_: null ,value_: null ,direction_: null ,indicatorSize: null ,scrollbar: null ,background: null ,skin: null ,__class__: RCScrollBar ,__properties__: $extend(RCControl.prototype.__properties__,{set_value:"setValue",get_value:"getValue"}) }); var RCScrollView = $hxClasses["RCScrollView"] = function(x,y,w,h) { JSView.call(this,x,y,w,h); this.setClipsToBounds(true); this.setContentView(new JSView(0,0)); }; RCScrollView.__name__ = ["RCScrollView"]; RCScrollView.__super__ = JSView; RCScrollView.prototype = $extend(JSView.prototype,{ destroy: function() { Fugu.safeDestroy([this.vertScrollBarSync,this.horizScrollBarSync,this.vertScrollBar,this.horizScrollBar],null,{ fileName : "RCScrollView.hx", lineNumber : 139, className : "RCScrollView", methodName : "destroy"}); this.vertScrollBarSync = null; this.horizScrollBarSync = null; JSView.prototype.destroy.call(this); } ,hold: function() { if(this.vertScrollBarSync != null) this.vertScrollBarSync.hold(); if(this.horizScrollBarSync != null) this.horizScrollBarSync.hold(); } ,resume: function() { if(this.vertScrollBarSync != null) this.vertScrollBarSync.resume(); if(this.horizScrollBarSync != null) this.horizScrollBarSync.resume(); } ,setMarginsFade: function(b) { return b; } ,setBounce: function(b) { this.bounces = b; return b; } ,zoomToRect: function(rect,animated) { } ,scrollRectToVisible: function(rect,animated) { } ,scrollViewDidScrollHandler: function(s) { this.scrollViewDidScroll(); } ,setScrollEnabled: function(b) { haxe.Log.trace("setScrollEnabled " + Std.string(b),{ fileName : "RCScrollView.hx", lineNumber : 59, className : "RCScrollView", methodName : "setScrollEnabled"}); var colors = [null,null,14540253,16777215]; haxe.Log.trace("contentSize " + Std.string(this.contentView.getContentSize()),{ fileName : "RCScrollView.hx", lineNumber : 61, className : "RCScrollView", methodName : "setScrollEnabled"}); haxe.Log.trace(this.size,{ fileName : "RCScrollView.hx", lineNumber : 62, className : "RCScrollView", methodName : "setScrollEnabled"}); if(this.getContentSize().width > this.size.width && this.horizScrollBarSync == null && b && false) { haxe.Log.trace("add horiz",{ fileName : "RCScrollView.hx", lineNumber : 66, className : "RCScrollView", methodName : "setScrollEnabled"}); var scroller_w = Zeta.lineEquationInt(this.size.width / 2,this.size.width,this.getContentSize().width,this.size.width * 2,this.size.width); var skinH = new haxe.SKScrollBar(colors); this.horizScrollBar = new RCScrollBar(0,this.size.height - 10,this.size.width,8,scroller_w,skinH); this.horizScrollBarSync = new RCSliderSync(RCWindow.sharedWindow().target,this.contentView,this.horizScrollBar,this.size.width,"horizontal"); this.horizScrollBarSync.valueChanged.add($bind(this,this.scrollViewDidScrollHandler)); this.addChild(this.horizScrollBar); } else { Fugu.safeDestroy([this.horizScrollBar,this.horizScrollBarSync],null,{ fileName : "RCScrollView.hx", lineNumber : 75, className : "RCScrollView", methodName : "setScrollEnabled"}); this.horizScrollBar = null; this.horizScrollBarSync = null; } haxe.Log.trace("contentView.height " + this.contentView.getHeight(),{ fileName : "RCScrollView.hx", lineNumber : 79, className : "RCScrollView", methodName : "setScrollEnabled"}); if(this.contentView.getHeight() > this.size.height && this.vertScrollBarSync == null && b) { haxe.Log.trace("add vert",{ fileName : "RCScrollView.hx", lineNumber : 84, className : "RCScrollView", methodName : "setScrollEnabled"}); var scroller_h = Zeta.lineEquationInt(this.size.height / 2,this.size.height,this.getContentSize().height,this.size.height * 2,this.size.height); var skinV = new haxe.SKScrollBar(colors); this.vertScrollBar = new RCScrollBar(this.size.width - 10,0,8,this.size.height,scroller_h,skinV); this.vertScrollBarSync = new RCSliderSync(RCWindow.sharedWindow().target,this.contentView,this.vertScrollBar,this.size.height,"vertical"); this.vertScrollBarSync.valueChanged.add($bind(this,this.scrollViewDidScrollHandler)); this.addChild(this.vertScrollBar); } else { Fugu.safeDestroy([this.vertScrollBar,this.vertScrollBarSync],null,{ fileName : "RCScrollView.hx", lineNumber : 93, className : "RCScrollView", methodName : "setScrollEnabled"}); this.vertScrollBar = null; this.vertScrollBarSync = null; } return b; } ,setContentView: function(content) { Fugu.safeRemove(this.contentView); this.contentView = content; this.addChild(this.contentView); this.setContentSize(this.contentView.getContentSize()); this.setScrollEnabled(true); } ,scrollViewDidEndScrollingAnimation: function() { } ,scrollViewDidScrollToTop: function() { } ,scrollViewDidEndDragging: function() { } ,scrollViewWillBeginDragging: function() { } ,scrollViewDidScroll: function() { } ,scrollIndicatorInsets: null ,scrollEnabled: null ,pagingEnabled: null ,decelerationRate: null ,bounces: null ,enableMarginsFade: null ,autohideSliders: null ,dragging: null ,contentView: null ,horizScrollBarSync: null ,vertScrollBarSync: null ,horizScrollBar: null ,vertScrollBar: null ,__class__: RCScrollView ,__properties__: $extend(JSView.prototype.__properties__,{set_enableMarginsFade:"setMarginsFade",set_bounces:"setBounce",set_scrollEnabled:"setScrollEnabled"}) }); var RCSegmentedControl = $hxClasses["RCSegmentedControl"] = function(x,y,w,h,skin) { JSView.call(this,x,y,w,h); this.selectedIndex_ = -1; this.items = new HashArray(); this.click = new RCSignal(); this.itemAdded = new RCSignal(); this.itemRemoved = new RCSignal(); if(skin == null) skin = ios.SKSegment; this.skin = skin; }; RCSegmentedControl.__name__ = ["RCSegmentedControl"]; RCSegmentedControl.__super__ = JSView; RCSegmentedControl.prototype = $extend(JSView.prototype,{ destroy: function() { if(this.items != null) { var $it0 = this.items.keys(); while( $it0.hasNext() ) { var key = $it0.next(); Fugu.safeDestroy(this.items.get(key),null,{ fileName : "RCSegmentedControl.hx", lineNumber : 240, className : "RCSegmentedControl", methodName : "destroy"}); } } this.items = null; this.click.destroy({ fileName : "RCSegmentedControl.hx", lineNumber : 242, className : "RCSegmentedControl", methodName : "destroy"}); this.itemAdded.destroy({ fileName : "RCSegmentedControl.hx", lineNumber : 243, className : "RCSegmentedControl", methodName : "destroy"}); this.itemRemoved.destroy({ fileName : "RCSegmentedControl.hx", lineNumber : 244, className : "RCSegmentedControl", methodName : "destroy"}); JSView.prototype.destroy.call(this); } ,clickHandler: function(label) { this.setSelectedIndex(this.items.indexForKey(label)); this.click.dispatch(this,null,null,null,{ fileName : "RCSegmentedControl.hx", lineNumber : 234, className : "RCSegmentedControl", methodName : "clickHandler"}); } ,disable: function(label) { this.items.get(label).setEnabled(false); this.items.get(label).setAlpha(0.4); } ,enable: function(label) { this.items.get(label).setEnabled(true); this.items.get(label).setAlpha(1); } ,exists: function(label) { return this.items.exists(label); } ,get: function(label) { return this.items.get(label); } ,toggled: function(label) { return this.items.get(label).getSelected(); } ,unselect: function(label) { this.items.get(label).setEnabled(true); this.items.get(label).untoggle(); } ,select: function(label,can_unselect) { if(can_unselect == null) can_unselect = true; haxe.Log.trace("select " + label + ", " + Std.string(can_unselect),{ fileName : "RCSegmentedControl.hx", lineNumber : 173, className : "RCSegmentedControl", methodName : "select"}); if(this.items.exists(label)) { this.items.get(label).toggle(); if(can_unselect) this.items.get(label).setEnabled(false); else this.items.get(label).setEnabled(true); } if(can_unselect) { var $it0 = this.items.keys(); while( $it0.hasNext() ) { var key = $it0.next(); if(key != label) this.unselect(key); } } } ,keepButtonsArranged: function() { return; var _g1 = 0, _g = this.items.array.length; while(_g1 < _g) { var i = _g1++; var newX = 0.0, newY = 0.0; var new_b = this.items.get(this.items.array[i]); } } ,remove: function(label) { if(this.items.exists(label)) { Fugu.safeDestroy(this.items.get(label),null,{ fileName : "RCSegmentedControl.hx", lineNumber : 142, className : "RCSegmentedControl", methodName : "remove"}); this.items.remove(label); } this.keepButtonsArranged(); this.itemRemoved.dispatch(this,null,null,null,{ fileName : "RCSegmentedControl.hx", lineNumber : 150, className : "RCSegmentedControl", methodName : "remove"}); } ,setSelectedIndex: function(i) { haxe.Log.trace("setIndex " + this.selectedIndex_ + " > " + i,{ fileName : "RCSegmentedControl.hx", lineNumber : 127, className : "RCSegmentedControl", methodName : "setSelectedIndex"}); if(this.selectedIndex_ == i) return i; this.selectedIndex_ = i; this.select(this.labels[i]); return this.selectedIndex_; } ,getSelectedIndex: function() { return this.selectedIndex_; } ,constructButton: function(i) { var position = (function($this) { var $r; switch(i) { case 0: $r = "left"; break; case $this.labels.length - 1: $r = "right"; break; default: $r = "middle"; } return $r; }(this)); var segmentX = 0; var _g = 0; while(_g < i) { var j = _g++; segmentX += this.segmentsWidth[j]; } var s = Type.createInstance(this.skin,[this.labels[i],this.segmentsWidth[i],this.size.height,position,null]); var b = new RCButtonRadio(segmentX,0,s); return b; } ,initWithLabels: function(labels,equalSizes) { if(equalSizes == null) equalSizes = true; this.labels = labels; this.segmentsWidth = new Array(); if(equalSizes) { var segmentWidth = Math.round(this.size.width / labels.length); var _g = 0; while(_g < labels.length) { var l = labels[_g]; ++_g; this.segmentsWidth.push(segmentWidth); } } else { var labelLengths = new Array(); var totalLabelsLength = 0; var _g = 0; while(_g < labels.length) { var l = labels[_g]; ++_g; labelLengths.push(l.length); totalLabelsLength += l.length; } var _g = 0; while(_g < labelLengths.length) { var ll = labelLengths[_g]; ++_g; var p = ll * 100 / totalLabelsLength; this.segmentsWidth.push(Math.round(p * this.size.width / 100)); } } var i = 0; var _g = 0; while(_g < labels.length) { var label = labels[_g]; ++_g; if(this.items.exists(label)) continue; var b = this.constructButton(i); b.onClick = (function(f,a1) { return function() { return f(a1); }; })($bind(this,this.clickHandler),label); this.addChild(b); b.init(); this.items.set(label,b); this.itemAdded.dispatch(this,null,null,null,{ fileName : "RCSegmentedControl.hx", lineNumber : 92, className : "RCSegmentedControl", methodName : "initWithLabels"}); i++; } this.keepButtonsArranged(); } ,selectedIndex: null ,itemRemoved: null ,itemAdded: null ,click: null ,selectedIndex_: null ,segmentsWidth: null ,items: null ,labels: null ,skin: null ,__class__: RCSegmentedControl ,__properties__: $extend(JSView.prototype.__properties__,{set_selectedIndex:"setSelectedIndex",get_selectedIndex:"getSelectedIndex"}) }); var RCSize = $hxClasses["RCSize"] = function(w,h) { this.width = w == null?0:w; this.height = h == null?0:h; }; RCSize.__name__ = ["RCSize"]; RCSize.prototype = { toString: function() { return "[RCSize width:" + this.width + ", height:" + this.height + "]"; } ,copy: function() { return new RCSize(this.width,this.height); } ,height: null ,width: null ,__class__: RCSize } var RCSkin = $hxClasses["RCSkin"] = function(colors) { this.normal = { background : null, label : null, image : null, otherView : null, colors : { background : null, label : null, image : null, otherView : null}, scale : 1}; this.highlighted = { background : null, label : null, image : null, otherView : null, colors : { background : null, label : null, image : null, otherView : null}, scale : 1}; this.disabled = { background : null, label : null, image : null, otherView : null, colors : { background : null, label : null, image : null, otherView : null}, scale : 1}; this.selected = { background : null, label : null, image : null, otherView : null, colors : { background : null, label : null, image : null, otherView : null}, scale : 1}; if(colors != null) { this.normal.colors.background = colors[0]; this.normal.colors.label = colors[1]; this.highlighted.colors.background = colors[2]; this.highlighted.colors.label = colors[3]; this.disabled.colors.background = colors[2]; this.disabled.colors.label = colors[3]; } }; RCSkin.__name__ = ["RCSkin"]; RCSkin.prototype = { destroy: function() { } ,hit: null ,selected: null ,disabled: null ,highlighted: null ,normal: null ,__class__: RCSkin } var _RCSlider = _RCSlider || {} _RCSlider.Direction = $hxClasses["_RCSlider.Direction"] = { __ename__ : ["_RCSlider","Direction"], __constructs__ : ["HORIZONTAL","VERTICAL"] } _RCSlider.Direction.HORIZONTAL = ["HORIZONTAL",0]; _RCSlider.Direction.HORIZONTAL.toString = $estr; _RCSlider.Direction.HORIZONTAL.__enum__ = _RCSlider.Direction; _RCSlider.Direction.VERTICAL = ["VERTICAL",1]; _RCSlider.Direction.VERTICAL.toString = $estr; _RCSlider.Direction.VERTICAL.__enum__ = _RCSlider.Direction; var RCSlider = $hxClasses["RCSlider"] = function(x,y,w,h,skin) { this.init_ = false; this.moving_ = false; this.minValue_ = 0.0; this.maxValue_ = 100.0; this.value_ = 0.0; this.direction_ = w > h?_RCSlider.Direction.HORIZONTAL:_RCSlider.Direction.VERTICAL; if(skin == null) skin = new haxe.SKSlider(); this.skin = skin; RCControl.call(this,x,y,w,h); this.viewDidAppear.add($bind(this,this.viewDidAppear_)); }; RCSlider.__name__ = ["RCSlider"]; RCSlider.__super__ = RCControl; RCSlider.prototype = $extend(RCControl.prototype,{ destroy: function() { this.mouseUpOverStage_.destroy({ fileName : "RCSlider.hx", lineNumber : 217, className : "RCSlider", methodName : "destroy"}); this.mouseMoveOverStage_.destroy({ fileName : "RCSlider.hx", lineNumber : 218, className : "RCSlider", methodName : "destroy"}); this.valueChanged.destroy({ fileName : "RCSlider.hx", lineNumber : 219, className : "RCSlider", methodName : "destroy"}); this.skin.destroy(); RCControl.prototype.destroy.call(this); } ,setMaximumValueImage: function(v) { return v; } ,setMinimumValueImage: function(v) { return v; } ,setMaxValue: function(v) { this.maxValue_ = v; this.setValue(this.value_); return v; } ,setMinValue: function(v) { this.minValue_ = v; this.setValue(this.value_); return v; } ,setValue: function(v) { this.value_ = v; if(!this.init_) return v; var x1 = 0.0, x2 = 0.0; switch( (this.direction_)[1] ) { case 0: x2 = this.size.width - this.scrubber.getWidth(); this.scrubber.setX(Zeta.lineEquationInt(x1,x2,v,this.minValue_,this.maxValue_)); this.scrubber.setY(Math.round((this.size.height - this.scrubber.getHeight()) / 2)); this.sliderHighlighted.setWidth(this.scrubber.getX() + this.scrubber.getWidth() / 2); break; case 1: x2 = this.size.height - this.scrubber.getHeight(); this.scrubber.setY(Zeta.lineEquationInt(x1,x2,v,this.minValue_,this.maxValue_)); this.sliderHighlighted.setHeight(this.scrubber.getY() + this.scrubber.getHeight() / 2); break; } this.valueChanged.dispatch(this,null,null,null,{ fileName : "RCSlider.hx", lineNumber : 173, className : "RCSlider", methodName : "setValue"}); return this.value_; } ,getValue: function() { return this.value_; } ,mouseMoveHandler: function(e) { var y0 = 0.0, y1 = 0.0, y2 = 0.0; switch( (this.direction_)[1] ) { case 0: y2 = this.size.width - this.scrubber.getWidth(); y0 = Zeta.limitsInt(this.getMouseX() - this.scrubber.getWidth() / 2,0,y2); break; case 1: y2 = this.size.height - this.scrubber.getHeight(); y0 = Zeta.limitsInt(this.getMouseY() - this.scrubber.getHeight() / 2,0,y2); break; } this.setValue(Zeta.lineEquation(this.minValue_,this.maxValue_,y0,y1,y2)); } ,mouseUpHandler: function(e) { this.moving_ = false; this.mouseUpOverStage_.remove($bind(this,this.mouseUpHandler)); this.mouseMoveOverStage_.remove($bind(this,this.mouseMoveHandler)); } ,mouseDownHandler: function(e) { this.moving_ = true; this.mouseUpOverStage_.add($bind(this,this.mouseUpHandler)); this.mouseMoveOverStage_.add($bind(this,this.mouseMoveHandler)); this.mouseMoveHandler(e); } ,setEnabled: function(c) { return this.enabled_ = false; } ,configureDispatchers: function() { RCControl.prototype.configureDispatchers.call(this); this.valueChanged = new RCSignal(); this.mouseUpOverStage_ = new EVMouse("mouseup",RCWindow.sharedWindow().stage,{ fileName : "RCSlider.hx", lineNumber : 95, className : "RCSlider", methodName : "configureDispatchers"}); this.mouseMoveOverStage_ = new EVMouse("mousemove",RCWindow.sharedWindow().stage,{ fileName : "RCSlider.hx", lineNumber : 96, className : "RCSlider", methodName : "configureDispatchers"}); } ,viewDidAppear_: function() { this.sliderNormal = this.skin.normal.background; if(this.sliderNormal == null) this.sliderNormal = new JSView(0,0); this.sliderNormal.setWidth(this.size.width); this.sliderHighlighted = this.skin.highlighted.background; if(this.sliderHighlighted == null) this.sliderHighlighted = new JSView(0,0); this.sliderHighlighted.setWidth(this.size.width); this.scrubber = this.skin.normal.otherView; if(this.scrubber == null) this.scrubber = new JSView(0,0); this.scrubber.setY(Math.round((this.size.height - this.scrubber.getHeight()) / 2)); this.addChild(this.sliderNormal); this.addChild(this.sliderHighlighted); this.addChild(this.scrubber); this.press.add($bind(this,this.mouseDownHandler)); this.over.add($bind(this,this.rollOverHandler)); this.out.add($bind(this,this.rollOutHandler)); this.init_ = true; this.setValue(this.value_); } ,valueChanged: null ,maximumValueImage: null ,minimumValueImage: null ,value: null ,maxValue: null ,minValue: null ,scrubber: null ,sliderHighlighted: null ,sliderNormal: null ,skin: null ,mouseMoveOverStage_: null ,mouseUpOverStage_: null ,direction_: null ,moving_: null ,maxValue_: null ,minValue_: null ,value_: null ,init_: null ,__class__: RCSlider ,__properties__: $extend(RCControl.prototype.__properties__,{set_minValue:"setMinValue",set_maxValue:"setMaxValue",set_value:"setValue",get_value:"getValue",set_minimumValueImage:"setMinimumValueImage",set_maximumValueImage:"setMaximumValueImage"}) }); var _RCSliderSync = _RCSliderSync || {} _RCSliderSync.Direction = $hxClasses["_RCSliderSync.Direction"] = { __ename__ : ["_RCSliderSync","Direction"], __constructs__ : ["HORIZONTAL","VERTICAL"] } _RCSliderSync.Direction.HORIZONTAL = ["HORIZONTAL",0]; _RCSliderSync.Direction.HORIZONTAL.toString = $estr; _RCSliderSync.Direction.HORIZONTAL.__enum__ = _RCSliderSync.Direction; _RCSliderSync.Direction.VERTICAL = ["VERTICAL",1]; _RCSliderSync.Direction.VERTICAL.toString = $estr; _RCSliderSync.Direction.VERTICAL.__enum__ = _RCSliderSync.Direction; _RCSliderSync.DecelerationRate = $hxClasses["_RCSliderSync.DecelerationRate"] = { __ename__ : ["_RCSliderSync","DecelerationRate"], __constructs__ : ["RCScrollViewDecelerationRateNormal","RCScrollViewDecelerationRateFast"] } _RCSliderSync.DecelerationRate.RCScrollViewDecelerationRateNormal = ["RCScrollViewDecelerationRateNormal",0]; _RCSliderSync.DecelerationRate.RCScrollViewDecelerationRateNormal.toString = $estr; _RCSliderSync.DecelerationRate.RCScrollViewDecelerationRateNormal.__enum__ = _RCSliderSync.DecelerationRate; _RCSliderSync.DecelerationRate.RCScrollViewDecelerationRateFast = ["RCScrollViewDecelerationRateFast",1]; _RCSliderSync.DecelerationRate.RCScrollViewDecelerationRateFast.toString = $estr; _RCSliderSync.DecelerationRate.RCScrollViewDecelerationRateFast.__enum__ = _RCSliderSync.DecelerationRate; var RCSliderSync = $hxClasses["RCSliderSync"] = function(target,contentView,slider,valueMax,direction) { this.target = target; this.contentView = contentView; this.slider = slider; this.direction = direction == "horizontal"?_RCSliderSync.Direction.HORIZONTAL:_RCSliderSync.Direction.VERTICAL; this.setMaxValue(Math.round(valueMax)); this.setStartValue(Math.round(this.getContentPosition())); this.setFinalValue(this.valueStart); this.f = 1; this.valueChanged = new RCSignal(); this.ticker = new EVLoop({ fileName : "RCSliderSync.hx", lineNumber : 60, className : "RCSliderSync", methodName : "new"}); this.mouseWheel = new EVMouse("mousewheel",target,{ fileName : "RCSliderSync.hx", lineNumber : 61, className : "RCSliderSync", methodName : "new"}); this.resume(); }; RCSliderSync.__name__ = ["RCSliderSync"]; RCSliderSync.prototype = { destroy: function() { this.hold(); this.valueChanged.destroy({ fileName : "RCSliderSync.hx", lineNumber : 168, className : "RCSliderSync", methodName : "destroy"}); this.ticker.destroy(); this.mouseWheel.destroy({ fileName : "RCSliderSync.hx", lineNumber : 170, className : "RCSliderSync", methodName : "destroy"}); } ,setStartValue: function(value) { return this.valueStart = value; } ,setFinalValue: function(value) { return this.valueFinal = value; } ,setMaxValue: function(value) { return this.valueMax = value; } ,getContentSize: function() { return this.direction == _RCSliderSync.Direction.HORIZONTAL?this.contentView.getWidth():this.contentView.getHeight(); } ,getContentPosition: function() { return this.direction == _RCSliderSync.Direction.HORIZONTAL?this.contentView.getX():this.contentView.getY(); } ,moveContentTo: function(next_value) { if(this.direction == _RCSliderSync.Direction.HORIZONTAL) this.contentView.setX(Math.round(next_value)); else this.contentView.setY(Math.round(next_value)); } ,loop: function() { var next_value = (this.valueFinal - this.getContentPosition()) / 3; if(Math.abs(next_value) < 1) { this.ticker.setFuncToCall(null); this.moveContentTo(this.valueFinal); } else this.moveContentTo(this.getContentPosition() + next_value); this.valueChanged.dispatch(this,null,null,null,{ fileName : "RCSliderSync.hx", lineNumber : 132, className : "RCSliderSync", methodName : "loop"}); } ,startLoop: function() { if(this.valueFinal > this.valueStart) this.setFinalValue(this.valueStart); if(this.valueFinal < this.valueStart + this.valueMax - this.getContentSize()) this.setFinalValue(Math.round(this.valueStart + this.valueMax - this.getContentSize())); this.ticker.setFuncToCall($bind(this,this.loop)); } ,sliderChangedHandler: function(e) { this.setFinalValue(Zeta.lineEquationInt(this.valueStart,this.valueStart + this.valueMax - this.getContentSize(),e.getValue(),0,100)); this.startLoop(); } ,wheelHandler: function(e) { var _g = this; _g.setFinalValue(_g.valueFinal + e.delta); this.startLoop(); this.slider.setValue(Zeta.lineEquationInt(0,100,this.valueFinal,this.valueStart,this.valueStart + this.valueMax - this.getContentSize())); if(e.delta < 0) this.onScrollRight(); else this.onScrollLeft(); } ,resume: function() { this.mouseWheel.add($bind(this,this.wheelHandler)); this.slider.valueChanged.add($bind(this,this.sliderChangedHandler)); } ,hold: function() { this.mouseWheel.remove($bind(this,this.wheelHandler)); this.slider.valueChanged.remove($bind(this,this.sliderChangedHandler)); } ,onScrollRight: function() { } ,onScrollLeft: function() { } ,contentValueChanged: null ,valueChanged: null ,valueFinal: null ,valueStart: null ,valueMax: null ,mouseWheel: null ,ticker: null ,decelerationRate: null ,f: null ,direction: null ,slider: null ,contentView: null ,target: null ,__class__: RCSliderSync ,__properties__: {set_valueMax:"setMaxValue",set_valueStart:"setStartValue",set_valueFinal:"setFinalValue"} } var RCSwf = $hxClasses["RCSwf"] = function(x,y,URL,newDomain) { if(newDomain == null) newDomain = true; this.newDomain = newDomain; this.id_ = "swf_" + HxOverrides.dateStr(new Date()); RCImage.call(this,x,y,URL); }; RCSwf.__name__ = ["RCSwf"]; RCSwf.__super__ = RCImage; RCSwf.prototype = $extend(RCImage.prototype,{ destroy: function() { this.removeListeners(); try { this.loader.contentLoaderInfo.content.destroy(); } catch( e ) { haxe.Log.trace(e,{ fileName : "RCSwf.hx", lineNumber : 88, className : "RCSwf", methodName : "destroy"}); var stack = haxe.Stack.exceptionStack(); haxe.Log.trace(haxe.Stack.toString(stack),{ fileName : "RCSwf.hx", lineNumber : 90, className : "RCSwf", methodName : "destroy"}); } } ,callMethod: function(method,params) { return Reflect.field(this.target,method).apply(this.target,params); } ,completeHandler: function(e) { haxe.Log.trace(e,{ fileName : "RCSwf.hx", lineNumber : 59, className : "RCSwf", methodName : "completeHandler"}); this.isLoaded = true; this.onComplete(); } ,initWithContentsOfFile: function(URL) { this.isLoaded = false; this.percentLoaded = 0; this.layer.id = this.id_; this.layer.appendChild(this.layer); } ,id_: null ,newDomain: null ,event: null ,target: null ,__class__: RCSwf }); var RCTextRoll = $hxClasses["RCTextRoll"] = function(x,y,w,h,str,properties) { JSView.call(this,x,y,w,h); this.continuous = true; this.txt1 = new RCTextView(0,0,null,h,str,properties); this.addChild(this.txt1); this.viewDidAppear.add($bind(this,this.viewDidAppear_)); }; RCTextRoll.__name__ = ["RCTextRoll"]; RCTextRoll.__super__ = JSView; RCTextRoll.prototype = $extend(JSView.prototype,{ destroy: function() { this.stop(); JSView.prototype.destroy.call(this); } ,reset: function() { if(this.timer != null) { this.timer.stop(); this.timer = null; } this.txt1.setX(0); this.txt2.setX(Math.round(this.txt1.getWidth() + 20)); } ,loop: function() { var _g = this.txt1, _g1 = _g.getX(); _g.setX(_g1 - 1); _g1; var _g = this.txt2, _g1 = _g.getX(); _g.setX(_g1 - 1); _g1; if(!this.continuous && this.txt2.getX() <= 0) { this.stop(); this.timer = haxe.Timer.delay($bind(this,this.startRolling),3000); } if(this.txt1.getX() < -this.txt1.getContentSize().width) this.txt1.setX(Math.round(this.txt2.getX() + this.txt2.getContentSize().width + 20)); if(this.txt2.getX() < -this.txt2.getContentSize().width) this.txt2.setX(Math.round(this.txt1.getX() + this.txt1.getContentSize().width + 20)); } ,startRolling: function() { this.stopRolling({ fileName : "RCTextRoll.hx", lineNumber : 81, className : "RCTextRoll", methodName : "startRolling"}); this.timerLoop = new haxe.Timer(20); this.timerLoop.run = $bind(this,this.loop); } ,stopRolling: function(pos) { if(this.timerLoop != null) this.timerLoop.stop(); this.timerLoop = null; } ,stop: function() { if(this.txt2 == null) return; this.stopRolling({ fileName : "RCTextRoll.hx", lineNumber : 71, className : "RCTextRoll", methodName : "stop"}); this.reset(); } ,start: function() { if(this.txt2 == null) return; if(this.continuous) this.startRolling(); else this.timer = haxe.Timer.delay($bind(this,this.startRolling),3000); } ,setText: function(str) { return str; } ,getText: function() { return this.txt1.getText(); } ,viewDidAppear_: function() { this.size.height = this.txt1.getContentSize().height; if(this.txt1.getContentSize().width > this.size.width) { if(this.txt2 != null) return; this.txt2 = new RCTextView(Math.round(this.txt1.getContentSize().width + 20),0,null,null,this.getText(),this.txt1.rcfont); this.addChild(this.txt2); this.setClipsToBounds(true); } } ,text: null ,continuous: null ,timerLoop: null ,timer: null ,txt2: null ,txt1: null ,__class__: RCTextRoll ,__properties__: $extend(JSView.prototype.__properties__,{set_text:"setText",get_text:"getText"}) }); var RCTextView = $hxClasses["RCTextView"] = function(x,y,w,h,str,rcfont) { JSView.call(this,Math.round(x),Math.round(y),w,h); this.rcfont = rcfont.copy(); this.setWidth(this.size.width); this.setHeight(this.size.height); this.viewDidAppear.add($bind(this,this.viewDidAppear_)); this.init(); this.setText(str); }; RCTextView.__name__ = ["RCTextView"]; RCTextView.__super__ = JSView; RCTextView.prototype = $extend(JSView.prototype,{ destroy: function() { this.target = null; JSView.prototype.destroy.call(this); } ,setText: function(str) { if(this.rcfont.html) this.layer.innerHTML = str; else this.layer.innerHTML = str; this.size.width = this.getContentSize().width; return str; } ,getText: function() { return this.layer.innerHTML; } ,viewDidAppear_: function() { this.size.width = this.getContentSize().width; } ,redraw: function() { var wrap = this.size.width != 0; var multiline = this.size.height != 0; this.layer.style.whiteSpace = wrap?"normal":"nowrap"; this.layer.style.wordWrap = wrap?"break-word":"normal"; var style = this.rcfont.selectable?"text":"none"; this.layer.style.WebkitUserSelect = style; this.layer.style.MozUserSelect = style; this.layer.style.lineHeight = this.rcfont.leading + this.rcfont.size + "px"; this.layer.style.fontFamily = this.rcfont.font; this.layer.style.fontSize = this.rcfont.size + "px"; this.layer.style.fontWeight = this.rcfont.bold?"bold":"normal"; this.layer.style.fontStyle = this.rcfont.italic?"italic":"normal"; this.layer.style.letterSpacing = this.rcfont.letterSpacing + "px"; this.layer.style.textAlign = this.rcfont.align; this.layer.style.color = RCColor.HEXtoString(this.rcfont.color); this.layer.style.contentEditable = "true"; if(this.rcfont.autoSize) { this.layer.style.width = multiline?this.size.width + "px":"auto"; this.layer.style.height = "auto"; } else { this.layer.style.width = this.size.width + "px"; this.layer.style.height = this.size.height + "px"; } if(this.size.width != 0) this.setWidth(this.size.width); } ,init: function() { JSView.prototype.init.call(this); this.redraw(); } ,text: null ,rcfont: null ,target: null ,__class__: RCTextView ,__properties__: $extend(JSView.prototype.__properties__,{set_text:"setText",get_text:"getText"}) }); var RCWindow = $hxClasses["RCWindow"] = function(id) { if(RCWindow.sharedWindow_ != null) { var err = "RCWindow is a singletone, create and access it with RCWindow.sharedWindow(?id)"; haxe.Log.trace(err,{ fileName : "RCWindow.hx", lineNumber : 59, className : "RCWindow", methodName : "new"}); throw err; } JSView.call(this,0.0,0.0,0.0,0.0); this.stage = js.Lib.document; this.setTarget(id); this.SCREEN_W = js.Lib.window.screen.width; this.SCREEN_H = js.Lib.window.screen.height; RCNotificationCenter.addObserver("resize",$bind(this,this.resizeHandler)); }; RCWindow.__name__ = ["RCWindow"]; RCWindow.sharedWindow_ = null; RCWindow.sharedWindow = function(id) { if(RCWindow.sharedWindow_ == null) RCWindow.sharedWindow_ = new RCWindow(id); return RCWindow.sharedWindow_; } RCWindow.__super__ = JSView; RCWindow.prototype = $extend(JSView.prototype,{ toString: function() { return "[RCWindow target=" + Std.string(this.target) + "]"; } ,getCenterY: function(h) { return Math.round(this.getHeight() / 2 - h / RCDevice.currentDevice().dpiScale / 2); } ,getCenterX: function(w) { return Math.round(this.getWidth() / 2 - w / RCDevice.currentDevice().dpiScale / 2); } ,destroyModalViewController: function() { this.modalView.removeFromSuperview(); this.modalView.destroy(); this.modalView = null; } ,dismissModalViewController: function() { if(this.modalView == null) return; var anim = new CATween(this.modalView,{ y : this.getHeight()},0.3,0,caequations.Cubic.IN,{ fileName : "RCWindow.hx", lineNumber : 246, className : "RCWindow", methodName : "dismissModalViewController"}); anim.delegate.animationDidStop = $bind(this,this.destroyModalViewController); CoreAnimation.add(anim); } ,addModalViewController: function(view) { if(this.modalView != null) return; this.modalView = view; this.modalView.setX(0); CoreAnimation.add(new CATween(this.modalView,{ y : { fromValue : this.getHeight(), toValue : 0}},0.5,0,caequations.Cubic.IN_OUT,{ fileName : "RCWindow.hx", lineNumber : 237, className : "RCWindow", methodName : "addModalViewController"})); this.addChild(this.modalView); } ,supportsFullScreen: function() { if(Reflect.field(this.target,"cancelFullScreen") != null) return true; else { var _g = 0, _g1 = ["webkit","moz","o","ms","khtml"]; while(_g < _g1.length) { var prefix = _g1[_g]; ++_g; if(Reflect.field(js.Lib.document,prefix + "CancelFullScreen") != null) { this.fsprefix = prefix; return true; } } } return false; return false; } ,isFullScreen: function() { if(this.supportsFullScreen()) switch(this.fsprefix) { case "": return this.target.fullScreen; case "webkit": return this.target.webkitIsFullScreen; default: return Reflect.field(this.target,this.fsprefix + "FullScreen"); } return false; } ,normal: function() { if(this.supportsFullScreen()) { if(this.fsprefix == "") "cancelFullScreen".apply(this.target,[]); else Reflect.field(this.target,this.fsprefix + "CancelFullScreen").apply(this.target,[]); } } ,fullscreen: function() { if(this.supportsFullScreen()) { if(this.fsprefix == null) "requestFullScreen".apply(this.target,[]); else Reflect.field(this.target,this.fsprefix + "RequestFullScreen").apply(this.target,[]); } } ,fsprefix: null ,setBackgroundColor: function(color) { if(color == null) this.target.style.background = null; else { var red = (color & 16711680) >> 16; var green = (color & 65280) >> 8; var blue = color & 255; var alpha = 1; this.target.style.background = "rgba(" + red + "," + green + "," + blue + "," + alpha + ")"; } return color; } ,setTarget: function(id) { if(id != null) this.target = js.Lib.document.getElementById(id); else { this.target = js.Lib.document.body; this.target.style.margin = "0px 0px 0px 0px"; this.target.style.overflow = "hidden"; if(RCDevice.currentDevice().userAgent == RCUserAgent.MSIE) { this.target.style.width = js.Lib.document.documentElement.clientWidth + "px"; this.target.style.height = js.Lib.document.documentElement.clientHeight + "px"; } else { this.target.style.width = js.Lib.window.innerWidth + "px"; this.target.style.height = js.Lib.window.innerHeight + "px"; } } this.size.width = this.target.scrollWidth; this.size.height = this.target.scrollHeight; haxe.Log.trace(this.size,{ fileName : "RCWindow.hx", lineNumber : 124, className : "RCWindow", methodName : "setTarget"}); this.target.appendChild(this.layer); } ,resizeHandler: function(w,h) { this.size.width = w; this.size.height = h; } ,modalView: null ,SCREEN_H: null ,SCREEN_W: null ,stage: null ,target: null ,__class__: RCWindow }); var Reflect = $hxClasses["Reflect"] = function() { } Reflect.__name__ = ["Reflect"]; Reflect.hasField = function(o,field) { return Object.prototype.hasOwnProperty.call(o,field); } Reflect.field = function(o,field) { var v = null; try { v = o[field]; } catch( e ) { } return v; } Reflect.setField = function(o,field,value) { o[field] = value; } Reflect.getProperty = function(o,field) { var tmp; return o == null?null:o.__properties__ && (tmp = o.__properties__["get_" + field])?o[tmp]():o[field]; } Reflect.setProperty = function(o,field,value) { var tmp; if(o.__properties__ && (tmp = o.__properties__["set_" + field])) o[tmp](value); else o[field] = value; } Reflect.callMethod = function(o,func,args) { return func.apply(o,args); } Reflect.fields = function(o) { var a = []; if(o != null) { var hasOwnProperty = Object.prototype.hasOwnProperty; for( var f in o ) { if(hasOwnProperty.call(o,f)) a.push(f); } } return a; } Reflect.isFunction = function(f) { return typeof(f) == "function" && !(f.__name__ || f.__ename__); } Reflect.compare = function(a,b) { return a == b?0:a > b?1:-1; } Reflect.compareMethods = function(f1,f2) { if(f1 == f2) return true; if(!Reflect.isFunction(f1) || !Reflect.isFunction(f2)) return false; return f1.scope == f2.scope && f1.method == f2.method && f1.method != null; } Reflect.isObject = function(v) { if(v == null) return false; var t = typeof(v); return t == "string" || t == "object" && !v.__enum__ || t == "function" && (v.__name__ || v.__ename__); } Reflect.deleteField = function(o,f) { if(!Reflect.hasField(o,f)) return false; delete(o[f]); return true; } Reflect.copy = function(o) { var o2 = { }; var _g = 0, _g1 = Reflect.fields(o); while(_g < _g1.length) { var f = _g1[_g]; ++_g; o2[f] = Reflect.field(o,f); } return o2; } Reflect.makeVarArgs = function(f) { return function() { var a = Array.prototype.slice.call(arguments); return f(a); }; } var Std = $hxClasses["Std"] = function() { } Std.__name__ = ["Std"]; Std["is"] = function(v,t) { return js.Boot.__instanceof(v,t); } Std.string = function(s) { return js.Boot.__string_rec(s,""); } Std["int"] = function(x) { return x | 0; } Std.parseInt = function(x) { var v = parseInt(x,10); if(v == 0 && (HxOverrides.cca(x,1) == 120 || HxOverrides.cca(x,1) == 88)) v = parseInt(x); if(isNaN(v)) return null; return v; } Std.parseFloat = function(x) { return parseFloat(x); } Std.random = function(x) { return Math.floor(Math.random() * x); } var StringBuf = $hxClasses["StringBuf"] = function() { this.b = ""; }; StringBuf.__name__ = ["StringBuf"]; StringBuf.prototype = { toString: function() { return this.b; } ,addSub: function(s,pos,len) { this.b += HxOverrides.substr(s,pos,len); } ,addChar: function(c) { this.b += String.fromCharCode(c); } ,add: function(x) { this.b += Std.string(x); } ,b: null ,__class__: StringBuf } var StringTools = $hxClasses["StringTools"] = function() { } StringTools.__name__ = ["StringTools"]; StringTools.urlEncode = function(s) { return encodeURIComponent(s); } StringTools.urlDecode = function(s) { return decodeURIComponent(s.split("+").join(" ")); } StringTools.htmlEscape = function(s) { return s.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;"); } StringTools.htmlUnescape = function(s) { return s.split("&gt;").join(">").split("&lt;").join("<").split("&amp;").join("&"); } StringTools.startsWith = function(s,start) { return s.length >= start.length && HxOverrides.substr(s,0,start.length) == start; } StringTools.endsWith = function(s,end) { var elen = end.length; var slen = s.length; return slen >= elen && HxOverrides.substr(s,slen - elen,elen) == end; } StringTools.isSpace = function(s,pos) { var c = HxOverrides.cca(s,pos); return c >= 9 && c <= 13 || c == 32; } StringTools.ltrim = function(s) { var l = s.length; var r = 0; while(r < l && StringTools.isSpace(s,r)) r++; if(r > 0) return HxOverrides.substr(s,r,l - r); else return s; } StringTools.rtrim = function(s) { var l = s.length; var r = 0; while(r < l && StringTools.isSpace(s,l - r - 1)) r++; if(r > 0) return HxOverrides.substr(s,0,l - r); else return s; } StringTools.trim = function(s) { return StringTools.ltrim(StringTools.rtrim(s)); } StringTools.rpad = function(s,c,l) { var sl = s.length; var cl = c.length; while(sl < l) if(l - sl < cl) { s += HxOverrides.substr(c,0,l - sl); sl = l; } else { s += c; sl += cl; } return s; } StringTools.lpad = function(s,c,l) { var ns = ""; var sl = s.length; if(sl >= l) return s; var cl = c.length; while(sl < l) if(l - sl < cl) { ns += HxOverrides.substr(c,0,l - sl); sl = l; } else { ns += c; sl += cl; } return ns + s; } StringTools.replace = function(s,sub,by) { return s.split(sub).join(by); } StringTools.hex = function(n,digits) { var s = ""; var hexChars = "0123456789ABCDEF"; do { s = hexChars.charAt(n & 15) + s; n >>>= 4; } while(n > 0); if(digits != null) while(s.length < digits) s = "0" + s; return s; } StringTools.fastCodeAt = function(s,index) { return s.charCodeAt(index); } StringTools.isEOF = function(c) { return c != c; } var ValueType = $hxClasses["ValueType"] = { __ename__ : ["ValueType"], __constructs__ : ["TNull","TInt","TFloat","TBool","TObject","TFunction","TClass","TEnum","TUnknown"] } ValueType.TNull = ["TNull",0]; ValueType.TNull.toString = $estr; ValueType.TNull.__enum__ = ValueType; ValueType.TInt = ["TInt",1]; ValueType.TInt.toString = $estr; ValueType.TInt.__enum__ = ValueType; ValueType.TFloat = ["TFloat",2]; ValueType.TFloat.toString = $estr; ValueType.TFloat.__enum__ = ValueType; ValueType.TBool = ["TBool",3]; ValueType.TBool.toString = $estr; ValueType.TBool.__enum__ = ValueType; ValueType.TObject = ["TObject",4]; ValueType.TObject.toString = $estr; ValueType.TObject.__enum__ = ValueType; ValueType.TFunction = ["TFunction",5]; ValueType.TFunction.toString = $estr; ValueType.TFunction.__enum__ = ValueType; ValueType.TClass = function(c) { var $x = ["TClass",6,c]; $x.__enum__ = ValueType; $x.toString = $estr; return $x; } ValueType.TEnum = function(e) { var $x = ["TEnum",7,e]; $x.__enum__ = ValueType; $x.toString = $estr; return $x; } ValueType.TUnknown = ["TUnknown",8]; ValueType.TUnknown.toString = $estr; ValueType.TUnknown.__enum__ = ValueType; var Type = $hxClasses["Type"] = function() { } Type.__name__ = ["Type"]; Type.getClass = function(o) { if(o == null) return null; return o.__class__; } Type.getEnum = function(o) { if(o == null) return null; return o.__enum__; } Type.getSuperClass = function(c) { return c.__super__; } Type.getClassName = function(c) { var a = c.__name__; return a.join("."); } Type.getEnumName = function(e) { var a = e.__ename__; return a.join("."); } Type.resolveClass = function(name) { var cl = $hxClasses[name]; if(cl == null || !cl.__name__) return null; return cl; } Type.resolveEnum = function(name) { var e = $hxClasses[name]; if(e == null || !e.__ename__) return null; return e; } Type.createInstance = function(cl,args) { switch(args.length) { case 0: return new cl(); case 1: return new cl(args[0]); case 2: return new cl(args[0],args[1]); case 3: return new cl(args[0],args[1],args[2]); case 4: return new cl(args[0],args[1],args[2],args[3]); case 5: return new cl(args[0],args[1],args[2],args[3],args[4]); case 6: return new cl(args[0],args[1],args[2],args[3],args[4],args[5]); case 7: return new cl(args[0],args[1],args[2],args[3],args[4],args[5],args[6]); case 8: return new cl(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7]); default: throw "Too many arguments"; } return null; } Type.createEmptyInstance = function(cl) { function empty() {}; empty.prototype = cl.prototype; return new empty(); } Type.createEnum = function(e,constr,params) { var f = Reflect.field(e,constr); if(f == null) throw "No such constructor " + constr; if(Reflect.isFunction(f)) { if(params == null) throw "Constructor " + constr + " need parameters"; return f.apply(e,params); } if(params != null && params.length != 0) throw "Constructor " + constr + " does not need parameters"; return f; } Type.createEnumIndex = function(e,index,params) { var c = e.__constructs__[index]; if(c == null) throw index + " is not a valid enum constructor index"; return Type.createEnum(e,c,params); } Type.getInstanceFields = function(c) { var a = []; for(var i in c.prototype) a.push(i); HxOverrides.remove(a,"__class__"); HxOverrides.remove(a,"__properties__"); return a; } Type.getClassFields = function(c) { var a = Reflect.fields(c); HxOverrides.remove(a,"__name__"); HxOverrides.remove(a,"__interfaces__"); HxOverrides.remove(a,"__properties__"); HxOverrides.remove(a,"__super__"); HxOverrides.remove(a,"prototype"); return a; } Type.getEnumConstructs = function(e) { var a = e.__constructs__; return a.slice(); } Type["typeof"] = function(v) { switch(typeof(v)) { case "boolean": return ValueType.TBool; case "string": return ValueType.TClass(String); case "number": if(Math.ceil(v) == v % 2147483648.0) return ValueType.TInt; return ValueType.TFloat; case "object": if(v == null) return ValueType.TNull; var e = v.__enum__; if(e != null) return ValueType.TEnum(e); var c = v.__class__; if(c != null) return ValueType.TClass(c); return ValueType.TObject; case "function": if(v.__name__ || v.__ename__) return ValueType.TObject; return ValueType.TFunction; case "undefined": return ValueType.TNull; default: return ValueType.TUnknown; } } Type.enumEq = function(a,b) { if(a == b) return true; try { if(a[0] != b[0]) return false; var _g1 = 2, _g = a.length; while(_g1 < _g) { var i = _g1++; if(!Type.enumEq(a[i],b[i])) return false; } var e = a.__enum__; if(e != b.__enum__ || e == null) return false; } catch( e ) { return false; } return true; } Type.enumConstructor = function(e) { return e[0]; } Type.enumParameters = function(e) { return e.slice(2); } Type.enumIndex = function(e) { return e[1]; } Type.allEnums = function(e) { var all = []; var cst = e.__constructs__; var _g = 0; while(_g < cst.length) { var c = cst[_g]; ++_g; var v = Reflect.field(e,c); if(!Reflect.isFunction(v)) all.push(v); } return all; } var Zeta = $hxClasses["Zeta"] = function() { } Zeta.__name__ = ["Zeta"]; Zeta.isIn = function(search_this,in_this,pos) { if(pos == null) pos = "fit"; if(search_this == null || in_this == null) return false; var arr1 = js.Boot.__instanceof(search_this,Array)?search_this:[search_this]; var arr2 = js.Boot.__instanceof(in_this,Array)?in_this:[in_this]; var _g = 0; while(_g < arr1.length) { var a1 = arr1[_g]; ++_g; var _g1 = 0; while(_g1 < arr2.length) { var a2 = arr2[_g1]; ++_g1; switch(pos.toLowerCase()) { case "anywhere": if(a1.toLowerCase().indexOf(a2.toLowerCase()) != -1) return true; break; case "end": if(a1.toLowerCase().substr(a1.length - a2.length) == a2.toLowerCase()) return true; break; case "fit": if(a1 == a2) return true; break; case "lowercase": if(a1.toLowerCase() == a2.toLowerCase()) return true; break; default: haxe.Log.trace("Position in string not implemented",{ fileName : "Zeta.hx", lineNumber : 49, className : "Zeta", methodName : "isIn"}); return false; } } } return false; } Zeta.concatObjects = function(objs) { var finalObject = { }; var _g = 0; while(_g < objs.length) { var currentObject = objs[_g]; ++_g; var _g1 = 0, _g2 = Reflect.fields(currentObject); while(_g1 < _g2.length) { var prop = _g2[_g1]; ++_g1; if(Reflect.field(currentObject,prop) != null) finalObject[prop] = Reflect.field(currentObject,prop); } } return finalObject; } Zeta.sort = function(array,sort_type,sort_array) { if(sort_type.toLowerCase() == "lastmodifieddescending") return array; if(sort_type.toLowerCase() == "lastmodifiedascending") sort_type = "reverse"; if(sort_type.toLowerCase() == "customascending" && sort_array != null) sort_type = "custom"; if(sort_type.toLowerCase() == "customdescending" && sort_array != null) { sort_array.reverse(); sort_type = "custom"; } switch(sort_type.toLowerCase()) { case "reverse": array.reverse(); break; case "ascending": array.sort(Zeta.ascendingSort); break; case "descending": array.sort(Zeta.descendingSort); break; case "random": array.sort(Zeta.randomSort); break; case "custom": var arr = new Array(); var _g = 0; while(_g < sort_array.length) { var a = sort_array[_g]; ++_g; var _g1 = 0; while(_g1 < array.length) { var b = array[_g1]; ++_g1; if(a == b) { arr.push(a); HxOverrides.remove(array,a); break; } } } return arr.concat(array); default: array.sortOn(sort_type,Array.NUMERIC); } return array; } Zeta.randomSort = function(a,b) { return -1 + Std.random(3); } Zeta.ascendingSort = function(a,b) { return Std.string(a) > Std.string(b)?1:-1; } Zeta.descendingSort = function(a,b) { return Std.string(a) > Std.string(b)?-1:1; } Zeta.array = function(len,zeros) { if(zeros == null) zeros = false; var a = new Array(); var _g = 0; while(_g < len) { var i = _g++; a.push(zeros?0:i); } return a; } Zeta.duplicateArray = function(arr) { var newArr = new Array(); var _g = 0; while(_g < arr.length) { var a = arr[_g]; ++_g; newArr.push(a); } return newArr; } Zeta.lineEquation = function(x1,x2,y0,y1,y2) { return (x2 - x1) * (y0 - y1) / (y2 - y1) + x1; } Zeta.lineEquationInt = function(x1,x2,y0,y1,y2) { return Math.round((x2 - x1) * (y0 - y1) / (y2 - y1) + x1); } Zeta.limits = function(val,min,max) { return val < min?min:val > max?max:val; } Zeta.limitsInt = function(val,min,max) { return Math.round(val < min?min:val > max?max:val); } caequations.Cubic = $hxClasses["caequations.Cubic"] = function() { } caequations.Cubic.__name__ = ["caequations","Cubic"]; caequations.Cubic.IN = function(t,b,c,d,p_params) { return c * (t /= d) * t * t + b; } caequations.Cubic.OUT = function(t,b,c,d,p_params) { return c * ((t = t / d - 1) * t * t + 1) + b; } caequations.Cubic.IN_OUT = function(t,b,c,d,p_params) { if((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; } caequations.Cubic.OUT_IN = function(t,b,c,d,p_params) { if(t < d / 2) return caequations.Cubic.OUT(t * 2,b,c / 2,d,null); return caequations.Cubic.IN(t * 2 - d,b + c / 2,c / 2,d,null); } haxe.Firebug = $hxClasses["haxe.Firebug"] = function() { } haxe.Firebug.__name__ = ["haxe","Firebug"]; haxe.Firebug.detect = function() { try { return console != null && console.error != null; } catch( e ) { return false; } } haxe.Firebug.redirectTraces = function() { haxe.Log.trace = haxe.Firebug.trace; js.Lib.onerror = haxe.Firebug.onError; } haxe.Firebug.onError = function(err,stack) { var buf = err + "\n"; var _g = 0; while(_g < stack.length) { var s = stack[_g]; ++_g; buf += "Called from " + s + "\n"; } haxe.Firebug.trace(buf,null); return true; } haxe.Firebug.trace = function(v,inf) { var type = inf != null && inf.customParams != null?inf.customParams[0]:null; if(type != "warn" && type != "info" && type != "debug" && type != "error") type = inf == null?"error":"log"; console[type]((inf == null?"":inf.fileName + ":" + inf.lineNumber + " : ") + Std.string(v)); } haxe.Http = $hxClasses["haxe.Http"] = function(url) { this.url = url; this.headers = new Hash(); this.params = new Hash(); this.async = true; }; haxe.Http.__name__ = ["haxe","Http"]; haxe.Http.requestUrl = function(url) { var h = new haxe.Http(url); h.async = false; var r = null; h.onData = function(d) { r = d; }; h.onError = function(e) { throw e; }; h.request(false); return r; } haxe.Http.prototype = { onStatus: function(status) { } ,onError: function(msg) { } ,onData: function(data) { } ,request: function(post) { var me = this; var r = new js.XMLHttpRequest(); var onreadystatechange = function() { if(r.readyState != 4) return; var s = (function($this) { var $r; try { $r = r.status; } catch( e ) { $r = null; } return $r; }(this)); if(s == undefined) s = null; if(s != null) me.onStatus(s); if(s != null && s >= 200 && s < 400) me.onData(r.responseText); else switch(s) { case null: case undefined: me.onError("Failed to connect or resolve host"); break; case 12029: me.onError("Failed to connect to host"); break; case 12007: me.onError("Unknown host"); break; default: me.onError("Http Error #" + r.status); } }; if(this.async) r.onreadystatechange = onreadystatechange; var uri = this.postData; if(uri != null) post = true; else { var $it0 = this.params.keys(); while( $it0.hasNext() ) { var p = $it0.next(); if(uri == null) uri = ""; else uri += "&"; uri += StringTools.urlEncode(p) + "=" + StringTools.urlEncode(this.params.get(p)); } } try { if(post) r.open("POST",this.url,this.async); else if(uri != null) { var question = this.url.split("?").length <= 1; r.open("GET",this.url + (question?"?":"&") + uri,this.async); uri = null; } else r.open("GET",this.url,this.async); } catch( e ) { this.onError(e.toString()); return; } if(this.headers.get("Content-Type") == null && post && this.postData == null) r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); var $it1 = this.headers.keys(); while( $it1.hasNext() ) { var h = $it1.next(); r.setRequestHeader(h,this.headers.get(h)); } r.send(uri); if(!this.async) onreadystatechange(); } ,setPostData: function(data) { this.postData = data; } ,setParameter: function(param,value) { this.params.set(param,value); } ,setHeader: function(header,value) { this.headers.set(header,value); } ,params: null ,headers: null ,postData: null ,async: null ,url: null ,__class__: haxe.Http } haxe.Log = $hxClasses["haxe.Log"] = function() { } haxe.Log.__name__ = ["haxe","Log"]; haxe.Log.trace = function(v,infos) { js.Boot.__trace(v,infos); } haxe.Log.clear = function() { js.Boot.__clear_trace(); } haxe.SKButton = $hxClasses["haxe.SKButton"] = function(label_str,colors) { RCSkin.call(this,colors); var f = RCFont.boldSystemFontOfSize(11); f.color = 0; f.align = "center"; this.normal.label = new RCTextView(0,4,70,20,label_str,f); this.normal.label.setY(Math.round(4.5)); this.normal.background = new RCRectangle(0,0,70,20,10066329,1,8); this.normal.background.addChild(new RCRectangle(1,1,68,18,16711422,1,6)); this.highlighted.background = new RCRectangle(0,0,70,20,3355443,1,8); this.highlighted.background.addChild(new RCRectangle(1,1,68,18,16770816,1,6)); this.hit = new RCRectangle(0,0,70,20,16777215,0); }; haxe.SKButton.__name__ = ["haxe","SKButton"]; haxe.SKButton.__super__ = RCSkin; haxe.SKButton.prototype = $extend(RCSkin.prototype,{ __class__: haxe.SKButton }); haxe.SKButtonRadio = $hxClasses["haxe.SKButtonRadio"] = function(colors) { RCSkin.call(this,colors); var r = 14; this.normal.background = new RCEllipse(0,0,r,r,10066329); this.normal.background.addChild(new RCEllipse(1,1,r - 2,r - 2,16645629)); this.normal.label = new JSView(0,0); this.highlighted.background = new RCEllipse(0,0,r,r,3355443); this.highlighted.background.addChild(new RCEllipse(1,1,r - 2,r - 2,10066329)); this.highlighted.label = new RCEllipse(r / 2 - 2.,r / 2 - 2.,4,4,16777215); this.selected.background = new RCEllipse(0,0,r,r,3355443); this.selected.background.addChild(new RCEllipse(1,1,r - 2,r - 2,16770816)); this.selected.label = new RCEllipse(r / 2 - 2.,r / 2 - 2.,4,4,3355443); this.hit = new RCRectangle(0,0,r,r,16777215); }; haxe.SKButtonRadio.__name__ = ["haxe","SKButtonRadio"]; haxe.SKButtonRadio.__super__ = RCSkin; haxe.SKButtonRadio.prototype = $extend(RCSkin.prototype,{ __class__: haxe.SKButtonRadio }); haxe.SKScrollBar = $hxClasses["haxe.SKScrollBar"] = function(colors) { RCSkin.call(this,colors); var w = 8, h = 8; this.normal.background = new RCRectangle(0,0,w,h,10066329,0.6,8); this.normal.otherView = new RCRectangle(0,0,w,h,3355443,1,8); this.hit = new RCRectangle(0,0,w,h,6710886,0); }; haxe.SKScrollBar.__name__ = ["haxe","SKScrollBar"]; haxe.SKScrollBar.__super__ = RCSkin; haxe.SKScrollBar.prototype = $extend(RCSkin.prototype,{ __class__: haxe.SKScrollBar }); haxe.SKSlider = $hxClasses["haxe.SKSlider"] = function(colors) { RCSkin.call(this,colors); var w = 160; var h = 8; this.normal.background = new RCRectangle(0,0,w,h,7829367,1,8); this.normal.otherView = new RCEllipse(0,0,h * 2,h * 2,3355443); this.normal.otherView.addChild(new RCEllipse(1,1,h * 2 - 2,h * 2 - 2,16763904)); this.highlighted.background = new RCRectangle(0,0,w,h,0,1,8); this.hit = new JSView(0,0); }; haxe.SKSlider.__name__ = ["haxe","SKSlider"]; haxe.SKSlider.__super__ = RCSkin; haxe.SKSlider.prototype = $extend(RCSkin.prototype,{ __class__: haxe.SKSlider }); haxe.StackItem = $hxClasses["haxe.StackItem"] = { __ename__ : ["haxe","StackItem"], __constructs__ : ["CFunction","Module","FilePos","Method","Lambda"] } haxe.StackItem.CFunction = ["CFunction",0]; haxe.StackItem.CFunction.toString = $estr; haxe.StackItem.CFunction.__enum__ = haxe.StackItem; haxe.StackItem.Module = function(m) { var $x = ["Module",1,m]; $x.__enum__ = haxe.StackItem; $x.toString = $estr; return $x; } haxe.StackItem.FilePos = function(s,file,line) { var $x = ["FilePos",2,s,file,line]; $x.__enum__ = haxe.StackItem; $x.toString = $estr; return $x; } haxe.StackItem.Method = function(classname,method) { var $x = ["Method",3,classname,method]; $x.__enum__ = haxe.StackItem; $x.toString = $estr; return $x; } haxe.StackItem.Lambda = function(v) { var $x = ["Lambda",4,v]; $x.__enum__ = haxe.StackItem; $x.toString = $estr; return $x; } haxe.Stack = $hxClasses["haxe.Stack"] = function() { } haxe.Stack.__name__ = ["haxe","Stack"]; haxe.Stack.callStack = function() { var oldValue = Error.prepareStackTrace; Error.prepareStackTrace = function(error,callsites) { var stack = []; var _g = 0; while(_g < callsites.length) { var site = callsites[_g]; ++_g; var method = null; var fullName = site.getFunctionName(); if(fullName != null) { var idx = fullName.lastIndexOf("."); if(idx >= 0) { var className = HxOverrides.substr(fullName,0,idx); var methodName = HxOverrides.substr(fullName,idx + 1,null); method = haxe.StackItem.Method(className,methodName); } } stack.push(haxe.StackItem.FilePos(method,site.getFileName(),site.getLineNumber())); } return stack; }; var a = haxe.Stack.makeStack(new Error().stack); a.shift(); Error.prepareStackTrace = oldValue; return a; } haxe.Stack.exceptionStack = function() { return []; } haxe.Stack.toString = function(stack) { var b = new StringBuf(); var _g = 0; while(_g < stack.length) { var s = stack[_g]; ++_g; b.b += Std.string("\nCalled from "); haxe.Stack.itemToString(b,s); } return b.b; } haxe.Stack.itemToString = function(b,s) { var $e = (s); switch( $e[1] ) { case 0: b.b += Std.string("a C function"); break; case 1: var m = $e[2]; b.b += Std.string("module "); b.b += Std.string(m); break; case 2: var line = $e[4], file = $e[3], s1 = $e[2]; if(s1 != null) { haxe.Stack.itemToString(b,s1); b.b += Std.string(" ("); } b.b += Std.string(file); b.b += Std.string(" line "); b.b += Std.string(line); if(s1 != null) b.b += Std.string(")"); break; case 3: var meth = $e[3], cname = $e[2]; b.b += Std.string(cname); b.b += Std.string("."); b.b += Std.string(meth); break; case 4: var n = $e[2]; b.b += Std.string("local function #"); b.b += Std.string(n); break; } } haxe.Stack.makeStack = function(s) { if(typeof(s) == "string") { var stack = s.split("\n"); var m = []; var _g = 0; while(_g < stack.length) { var line = stack[_g]; ++_g; m.push(haxe.StackItem.Module(line)); } return m; } else return s; } var ios = ios || {} ios.SKSegment = $hxClasses["ios.SKSegment"] = function(label,w,h,buttonPosition,colors) { RCSkin.call(this,colors); var segmentLeft; var segmentMiddle; var segmentRight; var segmentLeftSelected; var segmentMiddleSelected; var segmentRightSelected; switch(buttonPosition) { case "left": segmentLeft = "LL"; segmentMiddle = "M"; segmentRight = "M"; segmentLeftSelected = "LL"; segmentMiddleSelected = "M"; segmentRightSelected = "LR"; break; case "right": segmentLeft = "M"; segmentMiddle = "M"; segmentRight = "RR"; segmentLeftSelected = "RL"; segmentMiddleSelected = "M"; segmentRightSelected = "RR"; break; default: segmentLeft = "M"; segmentMiddle = "M"; segmentRight = "M"; segmentLeftSelected = "RL"; segmentMiddleSelected = "M"; segmentRightSelected = "LR"; } var hd = RCDevice.currentDevice().dpiScale == 2?"@2x":""; var sl = "Resources/ios/RCSegmentedControl/" + segmentLeft + hd + ".png"; var sm = "Resources/ios/RCSegmentedControl/" + segmentMiddle + hd + ".png"; var sr = "Resources/ios/RCSegmentedControl/" + segmentRight + hd + ".png"; this.normal.background = new RCImageStretchable(0,0,sl,sm,sr); this.normal.background.setWidth(w); var slh = "Resources/ios/RCSegmentedControl/" + segmentLeftSelected + "Selected" + hd + ".png"; var smh = "Resources/ios/RCSegmentedControl/" + segmentMiddleSelected + "Selected" + hd + ".png"; var srh = "Resources/ios/RCSegmentedControl/" + segmentRightSelected + "Selected" + hd + ".png"; this.highlighted.background = new RCImageStretchable(0,0,slh,smh,srh); this.highlighted.background.setWidth(w); var font = RCFont.boldSystemFontOfSize(13); font.align = "center"; font.color = 3355443; this.normal.label = new RCTextView(0,0,w,null,label,font); this.normal.label.setY(Math.round((h - 20) / 2)); font.color = 16777215; this.highlighted.label = new RCTextView(0,0,w,null,label,font); this.highlighted.label.setY(Math.round((h - 20) / 2)); this.hit = new RCRectangle(0,0,w,h,0); }; ios.SKSegment.__name__ = ["ios","SKSegment"]; ios.SKSegment.__super__ = RCSkin; ios.SKSegment.prototype = $extend(RCSkin.prototype,{ __class__: ios.SKSegment }); var js = js || {} js.Boot = $hxClasses["js.Boot"] = function() { } js.Boot.__name__ = ["js","Boot"]; js.Boot.__unhtml = function(s) { return s.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;"); } js.Boot.__trace = function(v,i) { var msg = i != null?i.fileName + ":" + i.lineNumber + ": ":""; msg += js.Boot.__string_rec(v,""); var d; if(typeof(document) != "undefined" && (d = document.getElementById("haxe:trace")) != null) d.innerHTML += js.Boot.__unhtml(msg) + "<br/>"; else if(typeof(console) != "undefined" && console.log != null) console.log(msg); } js.Boot.__clear_trace = function() { var d = document.getElementById("haxe:trace"); if(d != null) d.innerHTML = ""; } js.Boot.isClass = function(o) { return o.__name__; } js.Boot.isEnum = function(e) { return e.__ename__; } js.Boot.getClass = function(o) { return o.__class__; } js.Boot.__string_rec = function(o,s) { if(o == null) return "null"; if(s.length >= 5) return "<...>"; var t = typeof(o); if(t == "function" && (o.__name__ || o.__ename__)) t = "object"; switch(t) { case "object": if(o instanceof Array) { if(o.__enum__) { if(o.length == 2) return o[0]; var str = o[0] + "("; s += "\t"; var _g1 = 2, _g = o.length; while(_g1 < _g) { var i = _g1++; if(i != 2) str += "," + js.Boot.__string_rec(o[i],s); else str += js.Boot.__string_rec(o[i],s); } return str + ")"; } var l = o.length; var i; var str = "["; s += "\t"; var _g = 0; while(_g < l) { var i1 = _g++; str += (i1 > 0?",":"") + js.Boot.__string_rec(o[i1],s); } str += "]"; return str; } var tostr; try { tostr = o.toString; } catch( e ) { return "???"; } if(tostr != null && tostr != Object.toString) { var s2 = o.toString(); if(s2 != "[object Object]") return s2; } var k = null; var str = "{\n"; s += "\t"; var hasp = o.hasOwnProperty != null; for( var k in o ) { ; if(hasp && !o.hasOwnProperty(k)) { continue; } if(k == "prototype" || k == "__class__" || k == "__super__" || k == "__interfaces__" || k == "__properties__") { continue; } if(str.length != 2) str += ", \n"; str += s + k + " : " + js.Boot.__string_rec(o[k],s); } s = s.substring(1); str += "\n" + s + "}"; return str; case "function": return "<function>"; case "string": return o; default: return String(o); } } js.Boot.__interfLoop = function(cc,cl) { if(cc == null) return false; if(cc == cl) return true; var intf = cc.__interfaces__; if(intf != null) { var _g1 = 0, _g = intf.length; while(_g1 < _g) { var i = _g1++; var i1 = intf[i]; if(i1 == cl || js.Boot.__interfLoop(i1,cl)) return true; } } return js.Boot.__interfLoop(cc.__super__,cl); } js.Boot.__instanceof = function(o,cl) { try { if(o instanceof cl) { if(cl == Array) return o.__enum__ == null; return true; } if(js.Boot.__interfLoop(o.__class__,cl)) return true; } catch( e ) { if(cl == null) return false; } switch(cl) { case Int: return Math.ceil(o%2147483648.0) === o; case Float: return typeof(o) == "number"; case Bool: return o === true || o === false; case String: return typeof(o) == "string"; case Dynamic: return true; default: if(o == null) return false; if(cl == Class && o.__name__ != null) return true; else null; if(cl == Enum && o.__ename__ != null) return true; else null; return o.__enum__ == cl; } } js.Boot.__cast = function(o,t) { if(js.Boot.__instanceof(o,t)) return o; else throw "Cannot cast " + Std.string(o) + " to " + Std.string(t); } js.Lib = $hxClasses["js.Lib"] = function() { } js.Lib.__name__ = ["js","Lib"]; js.Lib.document = null; js.Lib.window = null; js.Lib.debug = function() { debugger; } js.Lib.alert = function(v) { alert(js.Boot.__string_rec(v,"")); } js.Lib.eval = function(code) { return eval(code); } js.Lib.setErrorHandler = function(f) { js.Lib.onerror = f; } var $_; function $bind(o,m) { var f = function(){ return f.method.apply(f.scope, arguments); }; f.scope = o; f.method = m; return f; }; if(Array.prototype.indexOf) HxOverrides.remove = function(a,o) { var i = a.indexOf(o); if(i == -1) return false; a.splice(i,1); return true; }; else null; Math.__name__ = ["Math"]; Math.NaN = Number.NaN; Math.NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY; Math.POSITIVE_INFINITY = Number.POSITIVE_INFINITY; $hxClasses.Math = Math; Math.isFinite = function(i) { return isFinite(i); }; Math.isNaN = function(i) { return isNaN(i); }; String.prototype.__class__ = $hxClasses.String = String; String.__name__ = ["String"]; Array.prototype.__class__ = $hxClasses.Array = Array; Array.__name__ = ["Array"]; Date.prototype.__class__ = $hxClasses.Date = Date; Date.__name__ = ["Date"]; var Int = $hxClasses.Int = { __name__ : ["Int"]}; var Dynamic = $hxClasses.Dynamic = { __name__ : ["Dynamic"]}; var Float = $hxClasses.Float = Number; Float.__name__ = ["Float"]; var Bool = $hxClasses.Bool = Boolean; Bool.__ename__ = ["Bool"]; var Class = $hxClasses.Class = { __name__ : ["Class"]}; var Enum = { }; var Void = $hxClasses.Void = { __ename__ : ["Void"]}; if(typeof document != "undefined") js.Lib.document = document; if(typeof window != "undefined") { js.Lib.window = window; js.Lib.window.onerror = function(msg,url,line) { var f = js.Lib.onerror; if(f == null) return false; return f(msg,[url + ":" + line]); }; } js.XMLHttpRequest = window.XMLHttpRequest?XMLHttpRequest:window.ActiveXObject?function() { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch( e ) { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch( e1 ) { throw "Unable to create XMLHttpRequest object."; } } }:(function($this) { var $r; throw "Unable to create XMLHttpRequest object."; return $r; }(this)); CoreAnimation.defaultTimingFunction = caequations.Linear.NONE; CoreAnimation.defaultDuration = 0.8; EVLoop.FPS = 60; EVMouse.UP = "mouseup"; EVMouse.DOWN = "mousedown"; EVMouse.OVER = "mouseover"; EVMouse.OUT = "mouseout"; EVMouse.MOVE = "mousemove"; EVMouse.CLICK = "mouseclick"; EVMouse.DOUBLE_CLICK = "mousedoubleclick"; EVMouse.WHEEL = "mousewheel"; JSExternalInterface.available = true; HXAddress._init = false; HXAddress._initChange = false; HXAddress._initChanged = false; HXAddress._strict = true; HXAddress._value = ""; HXAddress._queue = new Array(); HXAddress._availability = JSExternalInterface.available; HXAddress._initializer = HXAddress._initialize(); RCColor.BLACK = 0; RCColor.WHITE = 16777215; RCColor.RED = 16711680; RCColor.GREEN = 65280; RCColor.BLUE = 255; RCColor.CYAN = 65535; RCColor.YELLOW = 16776960; _RCDraw.LineScaleMode.NONE = null; Keyboard.LEFT = 37; Keyboard.RIGHT = 39; Keyboard.UP = 38; Keyboard.DOWN = 40; Keyboard.ENTER = 13; Keyboard.SPACE = 32; Keyboard.ESCAPE = 27; RCTextRoll.GAP = 20; Zeta.FIT = "fit"; Zeta.END = "end"; Zeta.ANYWHERE = "anywhere"; Zeta.LOWERCASE = "lowercase"; js.Lib.onerror = null; Main.main();
import PropTypes from 'prop-types' import React from 'react' import {loadImage} from './loadImage' export default class ImageLoader extends React.PureComponent { static propTypes = { src: PropTypes.string.isRequired, children: PropTypes.func } state = { loadedImage: null, error: null } componentWillMount() { this.loadImage(this.props.src) } componentWillUnmount() { this.unsubscribe() } unsubscribe() { if (this.subscription) { this.subscription.unsubscribe() } } loadImage(src) { this.unsubscribe() this.subscription = loadImage(src).subscribe({ next: url => this.setState({loadedImage: url, error: null}), error: error => this.setState({loadImage: null, error: error}) }) } componentWillReceiveProps(nextProps) { if (nextProps.src !== this.props.src) { this.loadImage(nextProps.src) } } render() { const {children} = this.props const {error, loadedImage} = this.state return error || loadedImage ? children({image: loadedImage, error}) : null } }
var module = angular.module("selectDirective", ['ui.select', 'ngSanitize']); module.directive("paramSelector", function () { 'use strict' return { restrict: 'E', templateUrl: '/scripts/directives/select.html', controller: 'ParamSelectorController', scope: { matchPlaceholder: '@', paramTitle: '@', paramValue: '=', items: '=', funcEval: '&' }, link: function (scope) { scope.setSelectedItem = function (paramValue) { scope.paramValue = paramValue; }; scope.hasHighScore = function(item){ return (scope.funcEval()(item) === 3); } } } }); module.controller("ParamSelectorController", function ($scope) { $scope.scope = $scope; $scope.$watch('paramValue', function () { $scope.setSelectedItem($scope.paramValue); }); });
import React from 'react'; import PropTypes from 'prop-types'; import styles from '../styles/app.scss'; import Menu from '../containers/Menu.js'; // import { Link } from 'react-router'; class App extends React.Component { render() { console.log(this.props.path); return ( <section id={styles.app}> {!this.props.path.includes('/order/') && <header className={styles.section_header}> <div className={styles.logo_container}> <div id={styles.logo}></div> </div> <div className={styles.section_title}>ERP Lite</div> </header>} <div className={styles.site_wrap}> {this.props.path === '/' || this.props.path.includes('/order/') || <Menu />} { this.props.children } </div> </section> ); } } App.propTypes = { children: PropTypes.object, path: PropTypes.string }; export default App;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _simpleAssign = require('simple-assign'); var _simpleAssign2 = _interopRequireDefault(_simpleAssign); var _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var getStyles = function getStyles(_ref, _ref2) { var index = _ref.index; var stepper = _ref2.stepper; var orientation = stepper.orientation; var styles = { root: { flex: '0 0 auto' } }; if (index > 0) { if (orientation === 'horizontal') { styles.root.marginLeft = -6; } else if (orientation === 'vertical') { styles.root.marginTop = -14; } } return styles; }; var Step = function (_React$Component) { _inherits(Step, _React$Component); function Step() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, Step); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(Step)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.renderChild = function (child) { var _this$props = _this.props; var active = _this$props.active; var completed = _this$props.completed; var disabled = _this$props.disabled; var index = _this$props.index; var last = _this$props.last; var icon = index + 1; return _react2.default.cloneElement(child, (0, _simpleAssign2.default)({ active: active, completed: completed, disabled: disabled, icon: icon, last: last }, child.props)); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Step, [{ key: 'render', value: function render() { var _props = this.props; var children = _props.children; var style = _props.style; var other = _objectWithoutProperties(_props, ['children', 'style']); var prepareStyles = this.context.muiTheme.prepareStyles; var styles = getStyles(this.props, this.context); return _react2.default.createElement( 'div', _extends({ style: prepareStyles((0, _simpleAssign2.default)(styles.root, style)) }, other), _react2.default.Children.map(children, this.renderChild) ); } }]); return Step; }(_react2.default.Component); Step.propTypes = { /** * Sets the step as active. Is passed to child components. */ active: _react.PropTypes.bool, /** * Should be `Step` sub-components such as `StepLabel`. */ children: _react.PropTypes.node, /** * Mark the step as completed. Is passed to child components. */ completed: _react.PropTypes.bool, /** * Mark the step as disabled, will also disable the button if * `StepButton` is a child of `Step`. Is passed to child components. */ disabled: _react.PropTypes.bool, /** * @ignore * Used internally for numbering. */ index: _react.PropTypes.number, /** * @ignore */ last: _react.PropTypes.bool, /** * Override the inline-style of the root element. */ style: _react.PropTypes.object }; Step.contextTypes = { muiTheme: _react.PropTypes.object.isRequired, stepper: _react.PropTypes.object }; exports.default = Step;
import _ from 'underscore'; import moment from 'moment'; import Immutable from 'immutable'; export const Project = Immutable.Record({ id: null, name: null, url: null, desc: null, status: null, createdAt: null, updatedAt: null }, 'Project'); export default function(state, action) { if (_.isUndefined(state)) { return new Project(); } else { return state; } }
'use strict' const elasticsearch = require('elasticsearch') const config = require('../config') const client = new elasticsearch.Client({ host: config.ELASTIC_URL, log: 'error' }) module.exports.getFrontpage = (request, reply) => { const viewOptions = { query: '', total: 0, results: [] } reply.view('index', viewOptions) } module.exports.doSearch = (request, reply) => { const params = request.params const query = params ? request.params.query : request.query.query client.search({ q: query, size: request.query.size || 20, from: request.query.from || 0 }, (error, data) => { if (error) { reply(error) } else { const viewOptions = { query: query, total: data.hits.total, results: data.hits.hits || [] } reply.view('index', viewOptions) } }) }
// Generated on 2015-03-13 using generator-angular 0.11.1 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Configurable paths for the application var appConfig = { app: require('./bower.json').appPath || 'app', dist: 'dist' }; // Define the configuration for all the tasks grunt.initConfig({ // Project settings yeoman: appConfig, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['wiredep'] }, js: { files: ['<%= yeoman.app %>/scripts/{,*/}*.js'], tasks: ['newer:jshint:all'], options: { livereload: '<%= connect.options.livereload %>' } }, jsTest: { files: ['test/spec/{,*/}*.js'], tasks: ['newer:jshint:test', 'karma'] }, compass: { files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'], tasks: ['compass:server', 'autoprefixer'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= yeoman.app %>/{,*/}*.html', '.tmp/styles/{,*/}*.css', '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' ] } }, // The actual grunt server settings connect: { options: { port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729 }, livereload: { options: { open: true, middleware: function (connect) { return [ connect.static('.tmp'), connect().use( '/bower_components', connect.static('./bower_components') ), connect().use( '/app/styles', connect.static('./app/styles') ), connect.static(appConfig.app) ]; } } }, test: { options: { port: 9001, middleware: function (connect) { return [ connect.static('.tmp'), connect.static('test'), connect().use( '/bower_components', connect.static('./bower_components') ), connect.static(appConfig.app) ]; } } }, dist: { options: { open: true, base: '<%= yeoman.dist %>' } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: { src: [ 'Gruntfile.js', '<%= yeoman.app %>/scripts/{,*/}*.js' ] }, test: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/spec/{,*/}*.js'] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/{,*/}*', '!<%= yeoman.dist %>/.git{,*/}*' ] }] }, server: '.tmp' }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, server: { options: { map: true, }, files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the app wiredep: { app: { src: ['<%= yeoman.app %>/index.html'], ignorePath: /\.\.\// }, test: { devDependencies: true, src: '<%= karma.unit.configFile %>', ignorePath: /\.\.\//, fileTypes:{ js: { block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi, detect: { js: /'(.*\.js)'/gi }, replace: { js: '\'{{filePath}}\',' } } } }, sass: { src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'], ignorePath: /(\.\.\/){1,2}bower_components\// } }, // Compiles Sass to CSS and generates necessary files if requested compass: { options: { sassDir: '<%= yeoman.app %>/styles', cssDir: '.tmp/styles', generatedImagesDir: '.tmp/images/generated', imagesDir: '<%= yeoman.app %>/images', javascriptsDir: '<%= yeoman.app %>/scripts', fontsDir: '<%= yeoman.app %>/styles/fonts', importPath: './bower_components', httpImagesPath: '/images', httpGeneratedImagesPath: '/images/generated', httpFontsPath: '/styles/fonts', relativeAssets: false, assetCacheBuster: false, raw: 'Sass::Script::Number.precision = 10\n' }, dist: { options: { generatedImagesDir: '<%= yeoman.dist %>/images/generated' } }, server: { options: { sourcemap: true } } }, // Renames files for browser caching purposes filerev: { dist: { src: [ '<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/styles/{,*/}*.css', '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '<%= yeoman.dist %>/styles/fonts/*' ] } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: '<%= yeoman.app %>/index.html', options: { dest: '<%= yeoman.dist %>', flow: { html: { steps: { js: ['concat', 'uglifyjs'], css: ['cssmin'] }, post: {} } } } }, // Performs rewrites based on filerev and the useminPrepare configuration usemin: { html: ['<%= yeoman.dist %>/{,*/}*.html'], css: ['<%= yeoman.dist %>/styles/{,*/}*.css'], options: { assetsDirs: [ '<%= yeoman.dist %>', '<%= yeoman.dist %>/images', '<%= yeoman.dist %>/styles' ] } }, // The following *-min tasks will produce minified files in the dist folder // By default, your `index.html`'s <!-- Usemin block --> will take care of // minification. These next options are pre-configured if you do not wish // to use the Usemin blocks. // cssmin: { // dist: { // files: { // '<%= yeoman.dist %>/styles/main.css': [ // '.tmp/styles/{,*/}*.css' // ] // } // } // }, // uglify: { // dist: { // files: { // '<%= yeoman.dist %>/scripts/scripts.js': [ // '<%= yeoman.dist %>/scripts/scripts.js' // ] // } // } // }, // concat: { // dist: {} // }, imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.{png,jpg,jpeg,gif}', dest: '<%= yeoman.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.svg', dest: '<%= yeoman.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseWhitespace: true, conservativeCollapse: true, collapseBooleanAttributes: true, removeCommentsFromCDATA: true, removeOptionalTags: true }, files: [{ expand: true, cwd: '<%= yeoman.dist %>', src: ['*.html', 'views/{,*/}*.html'], dest: '<%= yeoman.dist %>' }] } }, // ng-annotate tries to make the code safe for minification automatically // by using the Angular long form for dependency injection. ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: '*.js', dest: '.tmp/concat/scripts' }] } }, // Replace Google CDN references cdnify: { dist: { html: ['<%= yeoman.dist %>/*.html'] } }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', '*.html', 'views/{,*/}*.html', 'images/{,*/}*.{webp}', 'styles/fonts/{,*/}*.*' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: ['generated/*'] }, { expand: true, cwd: '.', src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*', dest: '<%= yeoman.dist %>' }] }, styles: { expand: true, cwd: '<%= yeoman.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, // Run some tasks in parallel to speed up the build process concurrent: { server: [ 'compass:server' ], test: [ 'compass' ], dist: [ 'compass:dist', 'imagemin', 'svgmin' ] }, // Test settings karma: { unit: { configFile: 'test/karma.conf.js', singleRun: true } } }); grunt.registerTask('serve', 'Compile then start a connect web server', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'wiredep', 'concurrent:server', 'autoprefixer:server', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run(['serve:' + target]); }); grunt.registerTask('test', [ 'clean:server', 'wiredep', 'concurrent:test', 'autoprefixer', 'connect:test', 'karma' ]); grunt.registerTask('build', [ 'clean:dist', 'wiredep', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'concat', 'ngAnnotate', 'copy:dist', 'cdnify', 'cssmin', 'uglify', 'filerev', 'usemin', 'htmlmin' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); };
'use strict'; describe('Controller: BooksBookidCtrl', function () { // load the controller's module beforeEach(module('dashboardApp')); var BooksBookidCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); BooksBookidCtrl = $controller('BooksBookidCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
var gulp = require('gulp'), sass = require('gulp-sass'), nodemon = require('gulp-nodemon'), jshint = require('gulp-jshint'), livereload = require('gulp-livereload'), paths = { js: ['./src/js/**/*.js'], node: ['./*.js', './lib/**/*.js'], sass: ['./src/scss/*.scss'], css: './public/css' }; gulp.task('lint', function () { gulp.src(paths.js.concat(paths.node)) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('sass', function () { gulp.src(paths.sass) .pipe(sass({ outputStyle: 'expanded' })) .pipe(gulp.dest(paths.css)) .pipe(livereload()); }); gulp.task('develop', function () { nodemon({ script: 'app.js', ext: 'jade js scss' }) .on('change', ['lint', 'sass']); }); gulp.task('default', ['lint', 'sass', 'develop']);
'use strict'; const autoprefixer = require('autoprefixer'); const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); const StyleLintPlugin = require('stylelint-webpack-plugin'); const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); const eslintFormatter = require('react-dev-utils/eslintFormatter'); const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); const getClientEnvironment = require('./env'); const paths = require('./paths'); // Webpack uses `publicPath` to determine where the app is being served from. // In development, we always serve from the root. This makes config easier. const publicPath = '/'; // `publicUrl` is just like `publicPath`, but we will provide it to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz. const publicUrl = ''; // Get environment variables to inject into our app. const env = getClientEnvironment(publicUrl); // This is the development configuration. // It is focused on developer experience and fast rebuilds. // The production configuration is different and lives in a separate file. module.exports = { // You may want 'eval' instead if you prefer to see the compiled output in DevTools. // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343. devtool: 'cheap-module-source-map', // These are the "entry points" to our application. // This means they will be the "root" imports that are included in JS bundle. // The first two entry points enable "hot" CSS and auto-refreshes for JS. entry: [ // We ship a few polyfills by default: require.resolve('./polyfills'), // Include an alternative client for WebpackDevServer. A client's job is to // connect to WebpackDevServer by a socket and get notified about changes. // When you save a file, the client will either apply hot updates (in case // of CSS changes), or refresh the page (in case of JS changes). When you // make a syntax error, this client will display a syntax error overlay. // Note: instead of the default WebpackDevServer client, we use a custom one // to bring better experience for Create React App users. You can replace // the line below with these two lines if you prefer the stock client: // require.resolve('webpack-dev-server/client') + '?/', // require.resolve('webpack/hot/dev-server'), require.resolve('react-dev-utils/webpackHotDevClient'), // Finally, this is your app's code: paths.appIndexJs, // We include the app code last so that if there is a runtime error during // initialization, it doesn't blow up the WebpackDevServer client, and // changing JS code would still trigger a refresh. ], output: { // Add /* filename */ comments to generated require()s in the output. pathinfo: true, // This does not produce a real file. It's just the virtual path that is // served by WebpackDevServer in development. This is the JS bundle // containing code from all our entry points, and the Webpack runtime. filename: 'static/js/bundle.js', // There are also additional JS chunk files if you use code splitting. chunkFilename: 'static/js/[name].chunk.js', // This is the URL that app is served from. We use "/" in development. publicPath: publicPath, // Point sourcemap entries to original disk location (format as URL on Windows) devtoolModuleFilenameTemplate: info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'), }, resolve: { // This allows you to set a fallback for where Webpack should look for modules. // We placed these paths second because we want `node_modules` to "win" // if there are any conflicts. This matches Node resolution mechanism. // https://github.com/facebookincubator/create-react-app/issues/253 modules: ['node_modules', paths.appNodeModules].concat( // It is guaranteed to exist because we tweak it in `env.js` process.env.NODE_PATH.split(path.delimiter).filter(Boolean) ), // These are the reasonable defaults supported by the Node ecosystem. // We also include JSX as a common component filename extension to support // some tools, although we do not recommend using it, see: // https://github.com/facebookincubator/create-react-app/issues/290 // `web` extension prefixes have been added for better support // for React Native Web. extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'], alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 'react-native': 'react-native-web', }, plugins: [ // Prevents users from importing files from outside of src/ (or node_modules/). // This often causes confusion because we only process files within src/ with babel. // To fix this, we prevent you from importing files out of src/ -- if you'd like to, // please link the files into your node_modules/ and let module-resolution kick in. // Make sure your source files are compiled, as they will not be processed in any way. new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]), ], }, module: { strictExportPresence: true, rules: [ // TODO: Disable require.ensure as it's not a standard language feature. // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176. // { parser: { requireEnsure: false } }, // First, run the linter. // It's important to do this before Babel processes the JS. { test: /\.(js|jsx|mjs)$/, enforce: 'pre', use: [ { options: { formatter: eslintFormatter, eslintPath: require.resolve('eslint'), }, loader: require.resolve('eslint-loader'), }, ], include: paths.appSrc, }, { // "oneOf" will traverse all following loaders until one will // match the requirements. When no loader matches it will fall // back to the "file" loader at the end of the loader list. oneOf: [ // "url" loader works like "file" loader except that it embeds assets // smaller than specified limit in bytes as data URLs to avoid requests. // A missing `test` is equivalent to a match. { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], loader: require.resolve('url-loader'), options: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]', }, }, // Process JS with Babel. { test: /\.(js|jsx|mjs)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true, }, }, // "postcss" loader applies autoprefixer to our CSS. // "css" loader resolves paths in CSS and adds assets as dependencies. // "style" loader turns CSS into JS modules that inject <style> tags. // In production, we use a plugin to extract that CSS to a file, but // in development "style" loader enables hot editing of CSS. { test: /\.(css|less|sass|scss)$/, exclude: [paths.appNodeModules, path.resolve(paths.appSrc, 'assets')], use: require('./cssloader.config')(false), }, { test: /\.(css|less|sass|scss)$/, include: [paths.appNodeModules, path.resolve(paths.appSrc, 'assets')], use: require('./cssloader.config')(true), }, // "file" loader makes sure those assets get served by WebpackDevServer. // When you `import` an asset, you get its (virtual) filename. // In production, they would get copied to the `build` folder. // This loader doesn't use a "test" so it will catch all modules // that fall through the other loaders. { // Exclude `js` files to keep "css" loader working as it injects // it's runtime that would otherwise processed through "file" loader. // Also exclude `html` and `json` extensions so they get processed // by webpacks internal loaders. exclude: [/\.js$/, /\.html$/, /\.json$/], loader: require.resolve('file-loader'), options: { name: 'static/media/[name].[hash:8].[ext]', }, }, ], }, // ** STOP ** Are you adding a new loader? // Make sure to add the new loader(s) before the "file" loader. ], }, plugins: [ // Makes some environment variables available in index.html. // The public URL is available as %PUBLIC_URL% in index.html, e.g.: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In development, this will be an empty string. new InterpolateHtmlPlugin(env.raw), // Generates an `index.html` file with the <script> injected. new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, }), // Add module names to factory functions so they appear in browser profiler. new webpack.NamedModulesPlugin(), // Makes some environment variables available to the JS code, for example: // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`. new webpack.DefinePlugin(env.stringified), // This is necessary to emit hot updates (currently CSS only): new webpack.HotModuleReplacementPlugin(), // Watcher doesn't work well if you mistype casing in a path so we use // a plugin that prints an error when you attempt to do this. // See https://github.com/facebookincubator/create-react-app/issues/240 new CaseSensitivePathsPlugin(), // If you require a missing module and then `npm install` it, you still have // to restart the development server for Webpack to discover it. This plugin // makes the discovery automatic so you don't have to restart. // See https://github.com/facebookincubator/create-react-app/issues/186 new WatchMissingNodeModulesPlugin(paths.appNodeModules), // Moment.js is an extremely popular library that bundles large locale files // by default due to how Webpack interprets its code. This is a practical // solution that requires the user to opt into importing specific locales. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack // You can remove this if you don't use Moment.js: new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), // style lint check new StyleLintPlugin({ files: [ `${paths.appSrc}/**/*.css`, `${paths.appSrc}/**/*.less`, `${paths.appSrc}/**/*.scss`, `${paths.appSrc}/**/*.sass`, ], failOnError: false, }) ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty', }, // Turn off performance hints during development because we don't do any // splitting or minification in interest of speed. These warnings become // cumbersome. performance: { hints: false, }, };
class database { constructor(client, host, user, password, database){ this.knex = require('knex')({ client: client, connection: { host: host, user: user, password: password, database: database } }); } } module.exports = database;
#!/usr/bin/env node /** * Sample Express (mostly) static server. * * Serves up the root of the project. */ var express = require("express"), winston = require("winston"), winMid = require("../index"), app = express(), logOpts = { transports: [ new (winston.transports.Console)({ json: true }) ] }; // Uncaught exception handler. process.on("uncaughtException", winMid.uncaught(logOpts, { extra: "uncaught" })); // Middleware automatically adds request logging at finish of request. app.use(winMid.request(logOpts, { type: "per-request-log" })); app.use(winMid.error(logOpts, { type: "error-log" })); // In addition to the automatic request logging, can **manually** log within // requests (here a custom middleware, but you get the idea...) app.get("/custom-logging", function (req, res) { res.locals._log.info("This is the per-request logger object!", { extra: "metadata" }); res.send("Custom message logged..."); }); app.get("/add-meta", function (req, res) { res.locals._log .addMeta({ extra: "addMeta-meta" }) .info("This is the per-request logger object!"); res.send("Custom add-meta logged..."); }); app.get("/transform-meta", function (req, res) { var log = res.locals._log .transformMeta(function (meta) { return { oldReq: meta.req, totallyNew: "totally new stuff" }; }); log.info("This is the per-request logger object!"); log.warn("This is extra custom log with callback", function () { // Do a console log so we don't have our logger everywhere... console.log("CONSOLE: CALLED BACK"); }); res.send("Custom transform-meta logged..."); }); app.get("/error", function (req, res, next) { next(new Error("Error!")); }); app.get("/uncaught", function () { throw new Error("Uncaught exception!"); }); // Configure static server. app.use(express.static(__dirname + "/..")); // Add server root logger. app._log = new winMid.Log(logOpts, { type: "single-server-log" }); // Start server. app.listen(9876); app._log.info("Started Express server at: http://127.0.0.1:9876", { extra: "metadata" });
exports.config = { seleniumServerJar: './node_modules/gulp-protractor/node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar', seleniumAddress: 'http://localhost:4444/wd/hub', capabilities: { 'browserName': 'chrome', 'chromeOptions': { 'args': ['no-sandbox'] // workaround: https://code.google.com/p/chromedriver/issues/detail?id=539 } }, // Options to be passed to Jasmine-node. jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000 } };
import React from 'react'; import { shallow } from 'enzyme'; import UpdateBookDetails from '../../../../src/components/library/admin/UpdateBookDetails'; import { book } from '../../../__mocks__/mockData'; const props = { book }; const wrapper = shallow( <UpdateBookDetails {...props} /> ); describe('CategoryList Component', () => { it('should render without crashing', () => { expect(wrapper.exists()).toBe(true); }); it('should render update book details', () => { expect(wrapper.find('#update-book-details').exists()).toBe(true); expect(wrapper.find('#update-book-details h1').text()).toBe('White Teeth'); expect(wrapper.find('#update-book-details h5').text()).toBe('Zadie Smith'); }); });
import SpriteMagic from './SpriteMagic'; export default Object.assign((options = {}) => { const spriteMagic = new SpriteMagic(options); return (url, prev, done) => { spriteMagic.resolve({ url, prev }) .then(done) .catch(err => setImmediate(() => { throw err; })); }; }, { SpriteMagic });
/*exported CNPJBASE */ var CNPJBASE = function(value) { if(!value) { return value; } var cnpjBasePattern = new StringMask('00.000.000'); var formatedValue = cnpjBasePattern.apply(value); return formatedValue; };
'use strict'; const Vector3 = require('./vector3.js'); /** * @author mrdoob / http://mrdoob.com/ * @author supereggbert / http://www.paulbrunt.co.uk/ * @author philogb / http://blog.thejit.org/ * @author jordi_ros / http://plattsoft.com * @author D1plo1d / http://github.com/D1plo1d * @author alteredq / http://alteredqualia.com/ * @author mikael emtinger / http://gomo.se/ * @author timknip / http://www.floorplanner.com/ * @author bhouston / http://clara.io * @author WestLangley / http://github.com/WestLangley */ function Matrix4 () { this.elements = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; if (arguments.length > 0) { console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.'); } } Object.assign(Matrix4.prototype, { isMatrix4: true, set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { var te = this.elements; te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; return this; }, identity: function () { this.set( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); return this; }, clone: function () { return new Matrix4().fromArray(this.elements); }, copy: function (m) { var te = this.elements; var me = m.elements; te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; return this; }, copyPosition: function (m) { var te = this.elements; var me = m.elements; te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; return this; }, extractBasis: function (xAxis, yAxis, zAxis) { xAxis.setFromMatrixColumn(this, 0); yAxis.setFromMatrixColumn(this, 1); zAxis.setFromMatrixColumn(this, 2); return this; }, makeBasis: function (xAxis, yAxis, zAxis) { this.set( xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1 ); return this; }, extractRotation: (function () { var v1 = new Vector3(); return function extractRotation (m) { var te = this.elements; var me = m.elements; var scaleX = 1 / v1.setFromMatrixColumn(m, 0).length(); var scaleY = 1 / v1.setFromMatrixColumn(m, 1).length(); var scaleZ = 1 / v1.setFromMatrixColumn(m, 2).length(); te[ 0 ] = me[ 0 ] * scaleX; te[ 1 ] = me[ 1 ] * scaleX; te[ 2 ] = me[ 2 ] * scaleX; te[ 4 ] = me[ 4 ] * scaleY; te[ 5 ] = me[ 5 ] * scaleY; te[ 6 ] = me[ 6 ] * scaleY; te[ 8 ] = me[ 8 ] * scaleZ; te[ 9 ] = me[ 9 ] * scaleZ; te[ 10 ] = me[ 10 ] * scaleZ; return this; }; }()), makeRotationFromEuler: function (euler) { if ((euler && euler.isEuler) === false) { console.error('THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.'); } var te = this.elements; var x = euler.x; var y = euler.y; var z = euler.z; var a = Math.cos(x); var b = Math.sin(x); var c = Math.cos(y); var d = Math.sin(y); var e = Math.cos(z); var f = Math.sin(z); var ae = 0; var af = 0; var be = 0; var bf = 0; var ce = 0; var cf = 0; var de = 0; var df = 0; var ac = 0; var ad = 0; var bc = 0; var bd = 0; if (euler.order === 'XYZ') { ae = a * e; af = a * f; be = b * e; bf = b * f; te[ 0 ] = c * e; te[ 4 ] = -c * f; te[ 8 ] = d; te[ 1 ] = af + be * d; te[ 5 ] = ae - bf * d; te[ 9 ] = -b * c; te[ 2 ] = bf - ae * d; te[ 6 ] = be + af * d; te[ 10 ] = a * c; } else if (euler.order === 'YXZ') { ce = c * e; cf = c * f; de = d * e; df = d * f; te[ 0 ] = ce + df * b; te[ 4 ] = de * b - cf; te[ 8 ] = a * d; te[ 1 ] = a * f; te[ 5 ] = a * e; te[ 9 ] = -b; te[ 2 ] = cf * b - de; te[ 6 ] = df + ce * b; te[ 10 ] = a * c; } else if (euler.order === 'ZXY') { ce = c * e; cf = c * f; de = d * e; df = d * f; te[ 0 ] = ce - df * b; te[ 4 ] = -a * f; te[ 8 ] = de + cf * b; te[ 1 ] = cf + de * b; te[ 5 ] = a * e; te[ 9 ] = df - ce * b; te[ 2 ] = -a * d; te[ 6 ] = b; te[ 10 ] = a * c; } else if (euler.order === 'ZYX') { ae = a * e; af = a * f; be = b * e; bf = b * f; te[ 0 ] = c * e; te[ 4 ] = be * d - af; te[ 8 ] = ae * d + bf; te[ 1 ] = c * f; te[ 5 ] = bf * d + ae; te[ 9 ] = af * d - be; te[ 2 ] = -d; te[ 6 ] = b * c; te[ 10 ] = a * c; } else if (euler.order === 'YZX') { ac = a * c; ad = a * d; bc = b * c; bd = b * d; te[ 0 ] = c * e; te[ 4 ] = bd - ac * f; te[ 8 ] = bc * f + ad; te[ 1 ] = f; te[ 5 ] = a * e; te[ 9 ] = -b * e; te[ 2 ] = -d * e; te[ 6 ] = ad * f + bc; te[ 10 ] = ac - bd * f; } else if (euler.order === 'XZY') { ac = a * c; ad = a * d; bc = b * c; bd = b * d; te[ 0 ] = c * e; te[ 4 ] = -f; te[ 8 ] = d * e; te[ 1 ] = ac * f + bd; te[ 5 ] = a * e; te[ 9 ] = ad * f - bc; te[ 2 ] = bc * f - ad; te[ 6 ] = b * e; te[ 10 ] = bd * f + ac; } // last column te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; // bottom row te[ 12 ] = 0; te[ 13 ] = 0; te[ 14 ] = 0; te[ 15 ] = 1; return this; }, makeRotationFromQuaternion: function (q) { var te = this.elements; var x = q._x; var y = q._y; var z = q._z; var w = q._w; var x2 = x + x; var y2 = y + y; var z2 = z + z; var xx = x * x2; var xy = x * y2; var xz = x * z2; var yy = y * y2; var yz = y * z2; var zz = z * z2; var wx = w * x2; var wy = w * y2; var wz = w * z2; te[ 0 ] = 1.0 - (yy + zz); te[ 4 ] = xy - wz; te[ 8 ] = xz + wy; te[ 1 ] = xy + wz; te[ 5 ] = 1.0 - (xx + zz); te[ 9 ] = yz - wx; te[ 2 ] = xz - wy; te[ 6 ] = yz + wx; te[ 10 ] = 1.0 - (xx + yy); // last column te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; // bottom row te[ 12 ] = 0; te[ 13 ] = 0; te[ 14 ] = 0; te[ 15 ] = 1; return this; }, lookAt: (function () { var x = new Vector3(); var y = new Vector3(); var z = new Vector3(); return function lookAt (eye, target, up) { var te = this.elements; z.subVectors(eye, target); if (z.lengthSq() === 0) { // eye and target are in the same position z.z = 1; } z.normalize(); x.crossVectors(up, z); if (x.lengthSq() === 0) { // eye and target are in the same vertical z.z += 0.0001; x.crossVectors(up, z); } x.normalize(); y.crossVectors(z, x); te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x; te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y; te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z; return this; }; }()), multiply: function (m, n) { if (n !== undefined) { console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.'); return this.multiplyMatrices(m, n); } return this.multiplyMatrices(this, m); }, premultiply: function (m) { return this.multiplyMatrices(m, this); }, multiplyMatrices: function (a, b) { var ae = a.elements; var be = b.elements; var te = this.elements; var a11 = ae[ 0 ]; var a12 = ae[ 4 ]; var a13 = ae[ 8 ]; var a14 = ae[ 12 ]; var a21 = ae[ 1 ]; var a22 = ae[ 5 ]; var a23 = ae[ 9 ]; var a24 = ae[ 13 ]; var a31 = ae[ 2 ]; var a32 = ae[ 6 ]; var a33 = ae[ 10 ]; var a34 = ae[ 14 ]; var a41 = ae[ 3 ]; var a42 = ae[ 7 ]; var a43 = ae[ 11 ]; var a44 = ae[ 15 ]; var b11 = be[ 0 ]; var b12 = be[ 4 ]; var b13 = be[ 8 ]; var b14 = be[ 12 ]; var b21 = be[ 1 ]; var b22 = be[ 5 ]; var b23 = be[ 9 ]; var b24 = be[ 13 ]; var b31 = be[ 2 ]; var b32 = be[ 6 ]; var b33 = be[ 10 ]; var b34 = be[ 14 ]; var b41 = be[ 3 ]; var b42 = be[ 7 ]; var b43 = be[ 11 ]; var b44 = be[ 15 ]; te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; return this; }, multiplyScalar: function (s) { var te = this.elements; te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; return this; }, applyToBufferAttribute: (function () { var v1 = new Vector3(); return function applyToBufferAttribute (attribute) { for (var i = 0, l = attribute.count; i < l; i++) { v1.x = attribute.getX(i); v1.y = attribute.getY(i); v1.z = attribute.getZ(i); v1.applyMatrix4(this); attribute.setXYZ(i, v1.x, v1.y, v1.z); } return attribute; }; }()), determinant: function () { var te = this.elements; var n11 = te[ 0 ]; var n12 = te[ 4 ]; var n13 = te[ 8 ]; var n14 = te[ 12 ]; var n21 = te[ 1 ]; var n22 = te[ 5 ]; var n23 = te[ 9 ]; var n24 = te[ 13 ]; var n31 = te[ 2 ]; var n32 = te[ 6 ]; var n33 = te[ 10 ]; var n34 = te[ 14 ]; var n41 = te[ 3 ]; var n42 = te[ 7 ]; var n43 = te[ 11 ]; var n44 = te[ 15 ]; // TODO: make this more efficient // (based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm) return ( n41 * (n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34 ) + n42 * (n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31 ) + n43 * (n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31 ) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31 ) ); }, transpose: function () { var te = this.elements; var tmp; tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; return this; }, setPosition: function (v) { var te = this.elements; te[ 12 ] = v.x; te[ 13 ] = v.y; te[ 14 ] = v.z; return this; }, getInverse: function (m, throwOnDegenerate) { // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm var te = this.elements; var me = m.elements; var n11 = me[ 0 ]; var n21 = me[ 1 ]; var n31 = me[ 2 ]; var n41 = me[ 3 ]; var n12 = me[ 4 ]; var n22 = me[ 5 ]; var n32 = me[ 6 ]; var n42 = me[ 7 ]; var n13 = me[ 8 ]; var n23 = me[ 9 ]; var n33 = me[ 10 ]; var n43 = me[ 11 ]; var n14 = me[ 12 ]; var n24 = me[ 13 ]; var n34 = me[ 14 ]; var n44 = me[ 15 ]; var t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; var t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; var t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; var t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; if (det === 0) { var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; if (throwOnDegenerate === true) { throw new Error(msg); } else { console.warn(msg); } return this.identity(); } var detInv = 1 / det; te[ 0 ] = t11 * detInv; te[ 1 ] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; te[ 2 ] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; te[ 3 ] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; te[ 4 ] = t12 * detInv; te[ 5 ] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; te[ 6 ] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; te[ 7 ] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; te[ 8 ] = t13 * detInv; te[ 9 ] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; te[ 10 ] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; te[ 11 ] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; te[ 12 ] = t14 * detInv; te[ 13 ] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; te[ 14 ] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; te[ 15 ] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; return this; }, scale: function (v) { var te = this.elements; var x = v.x; var y = v.y; var z = v.z; te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; return this; }, getMaxScaleOnAxis: function () { var te = this.elements; var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); }, makeTranslation: function (x, y, z) { this.set( 1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1 ); return this; }, makeRotationX: function (theta) { var c = Math.cos(theta); var s = Math.sin(theta); this.set( 1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1 ); return this; }, makeRotationY: function (theta) { var c = Math.cos(theta); var s = Math.sin(theta); this.set( c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1 ); return this; }, makeRotationZ: function (theta) { var c = Math.cos(theta); var s = Math.sin(theta); this.set( c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); return this; }, makeRotationAxis: function (axis, angle) { // Based on http://www.gamedev.net/reference/articles/article1199.asp var c = Math.cos(angle); var s = Math.sin(angle); var t = 1.0 - c; var x = axis.x; var y = axis.y; var z = axis.z; var tx = t * x; var ty = t * y; this.set( tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1 ); return this; }, makeScale: function (x, y, z) { this.set( x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 ); return this; }, makeShear: function (x, y, z) { this.set( 1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1 ); return this; }, compose: function (position, quaternion, scale) { this.makeRotationFromQuaternion(quaternion); this.scale(scale); this.setPosition(position); return this; }, decompose: (function () { var vector = new Vector3(); var matrix = new Matrix4(); return function decompose (position, quaternion, scale) { var te = this.elements; var sx = vector.set(te[ 0 ], te[ 1 ], te[ 2 ]).length(); var sy = vector.set(te[ 4 ], te[ 5 ], te[ 6 ]).length(); var sz = vector.set(te[ 8 ], te[ 9 ], te[ 10 ]).length(); // if determine is negative, we need to invert one scale var det = this.determinant(); if (det < 0) { sx = -sx; } position.x = te[ 12 ]; position.y = te[ 13 ]; position.z = te[ 14 ]; // scale the rotation part matrix.copy(this); var invSX = 1 / sx; var invSY = 1 / sy; var invSZ = 1 / sz; matrix.elements[ 0 ] *= invSX; matrix.elements[ 1 ] *= invSX; matrix.elements[ 2 ] *= invSX; matrix.elements[ 4 ] *= invSY; matrix.elements[ 5 ] *= invSY; matrix.elements[ 6 ] *= invSY; matrix.elements[ 8 ] *= invSZ; matrix.elements[ 9 ] *= invSZ; matrix.elements[ 10 ] *= invSZ; quaternion.setFromRotationMatrix(matrix); scale.x = sx; scale.y = sy; scale.z = sz; return this; }; }()), makePerspective: function (left, right, top, bottom, near, far) { if (far === undefined) { console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.'); } var te = this.elements; var x = 2 * near / (right - left); var y = 2 * near / (top - bottom); var a = (right + left) / (right - left); var b = (top + bottom) / (top - bottom); var c = -(far + near) / (far - near); var d = -2 * far * near / (far - near); te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0; return this; }, makeOrthographic: function (left, right, top, bottom, near, far) { var te = this.elements; var w = 1.0 / (right - left); var h = 1.0 / (top - bottom); var p = 1.0 / (far - near); var x = (right + left) * w; var y = (top + bottom) * h; var z = (far + near) * p; te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = -x; te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = -y; te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = -2 * p; te[ 14 ] = -z; te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; return this; }, equals: function (matrix) { var te = this.elements; var me = matrix.elements; for (var i = 0; i < 16; i++) { if (te[ i ] !== me[ i ]) { return false; } } return true; }, fromArray: function (array, offset) { if (offset === undefined) { offset = 0; } for (var i = 0; i < 16; i++) { this.elements[ i ] = array[ i + offset ]; } return this; }, toArray: function (array, offset) { if (array === undefined) { array = []; } if (offset === undefined) { offset = 0; } var te = this.elements; array[ offset ] = te[ 0 ]; array[ offset + 1 ] = te[ 1 ]; array[ offset + 2 ] = te[ 2 ]; array[ offset + 3 ] = te[ 3 ]; array[ offset + 4 ] = te[ 4 ]; array[ offset + 5 ] = te[ 5 ]; array[ offset + 6 ] = te[ 6 ]; array[ offset + 7 ] = te[ 7 ]; array[ offset + 8 ] = te[ 8 ]; array[ offset + 9 ] = te[ 9 ]; array[ offset + 10 ] = te[ 10 ]; array[ offset + 11 ] = te[ 11 ]; array[ offset + 12 ] = te[ 12 ]; array[ offset + 13 ] = te[ 13 ]; array[ offset + 14 ] = te[ 14 ]; array[ offset + 15 ] = te[ 15 ]; return array; } }); module.exports = Matrix4;
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'sourcedialog', 'el', { toolbar: 'Κώδικας', title: 'Κώδικας' } );
const { readFileToArray } = require('./utils'); async function day1() { const results = await readFileToArray('./day1-input.txt', function (line) { return Number(line); }) const frequency = results.reduce((acc, item) => (acc + item), 0) console.log(frequency); } day1();
import { pipeP } from 'ramda'; import { getResultsFromResponse } from 'utils'; import categoryStore from './categoryStore'; import { getCategoriesApi } from '../apis'; // TODO handle try catch export const getCategories = (categoryCode) => pipeP( getCategoriesApi, getResultsFromResponse, categoryStore.setCategories )(categoryCode);
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _areSimilar = require('./areSimilar'); var _areSimilar2 = _interopRequireDefault(_areSimilar); var _deny = require('./deny'); var _deny2 = _interopRequireDefault(_deny); var _equals = require('./equals'); var _equals2 = _interopRequireDefault(_equals); var _id = require('./id'); var _id2 = _interopRequireDefault(_id); var _ofType = require('./ofType'); var _ofType2 = _interopRequireDefault(_ofType); var _replicate = require('./replicate'); var _replicate2 = _interopRequireDefault(_replicate); var _typeOf = require('./typeOf'); var _typeOf2 = _interopRequireDefault(_typeOf); exports['default'] = { areSimilar: _areSimilar2['default'], deny: _deny2['default'], equals: _equals2['default'], id: _id2['default'], ofType: _ofType2['default'], replicate: _replicate2['default'], typeOf: _typeOf2['default'] }; module.exports = exports['default'];
var http = require("http"); var https = require("https"); var cheerio = require('cheerio'); var Logger = require("./logger.js"); var Media = require("./media"); var CustomEmbedFilter = require("./customembed").filter; var Server = require("./server"); var Config = require("./config"); var ffmpeg = require("./ffmpeg"); var mediaquery = require("cytube-mediaquery"); var YouTube = require("cytube-mediaquery/lib/provider/youtube"); var Vimeo = require("cytube-mediaquery/lib/provider/vimeo"); var Vidme = require("cytube-mediaquery/lib/provider/vidme"); var Streamable = require("cytube-mediaquery/lib/provider/streamable"); var GoogleDrive = require("cytube-mediaquery/lib/provider/googledrive"); /* * Preference map of quality => youtube formats. * see https://en.wikipedia.org/wiki/Youtube#Quality_and_codecs * * Prefer WebM over MP4, ignore other codecs (e.g. FLV) */ const GOOGLE_PREFERENCE = { "hd1080": [37, 46], "hd720": [22, 45], "large": [59, 44], "medium": [18, 43, 34] // 34 is 360p FLV as a last-ditch }; const CONTENT_TYPES = { 43: "webm", 44: "webm", 45: "webm", 46: "webm", 18: "mp4", 22: "mp4", 37: "mp4", 59: "mp4", 34: "flv" }; var urlRetrieve = function (transport, options, callback) { var req = transport.request(options, function (res) { res.on("error", function (err) { Logger.errlog.log("HTTP response " + options.host + options.path + " failed: "+ err); callback(503, ""); }); var buffer = ""; res.setEncoding("utf-8"); res.on("data", function (chunk) { buffer += chunk; }); res.on("end", function () { callback(res.statusCode, buffer); }); }); req.on("error", function (err) { Logger.errlog.log("HTTP request " + options.host + options.path + " failed: " + err); callback(503, ""); }); req.end(); }; var mediaTypeMap = { "youtube": "yt", "googledrive": "gd", "google+": "gp" }; function convertMedia(media) { return new Media(media.id, media.title, media.duration, mediaTypeMap[media.type], media.meta); } var Getters = { /* youtube.com */ yt: function (id, callback) { if (!Config.get("youtube-v3-key")) { return callback("The YouTube API now requires an API key. Please see the " + "documentation for youtube-v3-key in config.template.yaml"); } YouTube.lookup(id).then(function (video) { var meta = {}; if (video.meta.blocked) { meta.restricted = video.meta.blocked; } var media = new Media(video.id, video.title, video.duration, "yt", meta); callback(false, media); }).catch(function (err) { callback(err.message || err, null); }); }, /* youtube.com playlists */ yp: function (id, callback) { if (!Config.get("youtube-v3-key")) { return callback("The YouTube API now requires an API key. Please see the " + "documentation for youtube-v3-key in config.template.yaml"); } YouTube.lookupPlaylist(id).then(function (videos) { videos = videos.map(function (video) { var meta = {}; if (video.meta.blocked) { meta.restricted = video.meta.blocked; } return new Media(video.id, video.title, video.duration, "yt", meta); }); callback(null, videos); }).catch(function (err) { callback(err.message || err, null); }); }, /* youtube.com search */ ytSearch: function (query, callback) { if (!Config.get("youtube-v3-key")) { return callback("The YouTube API now requires an API key. Please see the " + "documentation for youtube-v3-key in config.template.yaml"); } YouTube.search(query).then(function (res) { var videos = res.results; videos = videos.map(function (video) { var meta = {}; if (video.meta.blocked) { meta.restricted = video.meta.blocked; } var media = new Media(video.id, video.title, video.duration, "yt", meta); media.thumb = { url: video.meta.thumbnail }; return media; }); callback(null, videos); }).catch(function (err) { callback(err.message || err, null); }); }, /* vimeo.com */ vi: function (id, callback) { var m = id.match(/([\w-]+)/); if (m) { id = m[1]; } else { callback("Invalid ID", null); return; } if (Config.get("vimeo-oauth.enabled")) { return Getters.vi_oauth(id, callback); } Vimeo.lookup(id).then(video => { video = new Media(video.id, video.title, video.duration, "vi"); callback(null, video); }).catch(error => { callback(error.message); }); }, vi_oauth: function (id, callback) { var OAuth = require("oauth"); var oa = new OAuth.OAuth( "https://vimeo.com/oauth/request_token", "https://vimeo.com/oauth/access_token", Config.get("vimeo-oauth.consumer-key"), Config.get("vimeo-oauth.secret"), "1.0", null, "HMAC-SHA1" ); oa.get("https://vimeo.com/api/rest/v2?format=json" + "&method=vimeo.videos.getInfo&video_id=" + id, null, null, function (err, data, res) { if (err) { return callback(err, null); } try { data = JSON.parse(data); if (data.stat !== "ok") { return callback(data.err.msg, null); } var video = data.video[0]; if (video.embed_privacy !== "anywhere") { return callback("Embedding disabled", null); } var id = video.id; var seconds = parseInt(video.duration); var title = video.title; callback(null, new Media(id, title, seconds, "vi")); } catch (e) { callback("Error handling Vimeo response", null); } }); }, /* dailymotion.com */ dm: function (id, callback) { var m = id.match(/([\w-]+)/); if (m) { id = m[1].split("_")[0]; } else { callback("Invalid ID", null); return; } var options = { host: "api.dailymotion.com", port: 443, path: "/video/" + id + "?fields=duration,title", method: "GET", dataType: "jsonp", timeout: 1000 }; urlRetrieve(https, options, function (status, data) { switch (status) { case 200: break; /* Request is OK, skip to handling data */ case 400: return callback("Invalid request", null); case 403: return callback("Private video", null); case 404: return callback("Video not found", null); case 500: case 503: return callback("Service unavailable", null); default: return callback("HTTP " + status, null); } try { data = JSON.parse(data); var title = data.title; var seconds = data.duration; /** * This is a rather hacky way to indicate that a video has * been deleted... */ if (title === "Deleted video" && seconds === 10) { callback("Video not found", null); return; } var media = new Media(id, title, seconds, "dm"); callback(false, media); } catch(e) { callback(e, null); } }); }, /* soundcloud.com */ sc: function (id, callback) { /* TODO: require server owners to register their own API key, put in config */ const SC_CLIENT = "2e0c82ab5a020f3a7509318146128abd"; var m = id.match(/([\w-\/\.:]+)/); if (m) { id = m[1]; } else { callback("Invalid ID", null); return; } var options = { host: "api.soundcloud.com", port: 443, path: "/resolve.json?url=" + id + "&client_id=" + SC_CLIENT, method: "GET", dataType: "jsonp", timeout: 1000 }; urlRetrieve(https, options, function (status, data) { switch (status) { case 200: case 302: break; /* Request is OK, skip to handling data */ case 400: return callback("Invalid request", null); case 403: return callback("Private sound", null); case 404: return callback("Sound not found", null); case 500: case 503: return callback("Service unavailable", null); default: return callback("HTTP " + status, null); } var track = null; try { data = JSON.parse(data); track = data.location; } catch(e) { callback(e, null); return; } var options2 = { host: "api.soundcloud.com", port: 443, path: track, method: "GET", dataType: "jsonp", timeout: 1000 }; /** * There has got to be a way to directly get the data I want without * making two requests to Soundcloud...right? * ...right? */ urlRetrieve(https, options2, function (status, data) { switch (status) { case 200: break; /* Request is OK, skip to handling data */ case 400: return callback("Invalid request", null); case 403: return callback("Private sound", null); case 404: return callback("Sound not found", null); case 500: case 503: return callback("Service unavailable", null); default: return callback("HTTP " + status, null); } try { data = JSON.parse(data); var seconds = data.duration / 1000; var title = data.title; var meta = {}; if (data.sharing === "private" && data.embeddable_by === "all") { meta.scuri = data.uri; } var media = new Media(id, title, seconds, "sc", meta); callback(false, media); } catch(e) { callback(e, null); } }); }); }, /* livestream.com */ li: function (id, callback) { var m = id.match(/([\w-]+)/); if (m) { id = m[1]; } else { callback("Invalid ID", null); return; } var title = "Livestream.com - " + id; var media = new Media(id, title, "--:--", "li"); callback(false, media); }, /* twitch.tv */ tw: function (id, callback) { var m = id.match(/([\w-]+)/); if (m) { id = m[1]; } else { callback("Invalid ID", null); return; } var title = "Twitch.tv - " + id; var media = new Media(id, title, "--:--", "tw"); callback(false, media); }, /* ustream.tv */ us: function (id, callback) { /** *2013-09-17 * They couldn't fucking decide whether channels should * be at http://www.ustream.tv/channel/foo or just * http://www.ustream.tv/foo so they do both. * [](/cleese) */ var m = id.match(/([^\?&#]+)|(channel\/[^\?&#]+)/); if (m) { id = m[1]; } else { callback("Invalid ID", null); return; } var options = { host: "www.ustream.tv", port: 80, path: "/" + id, method: "GET", timeout: 1000 }; urlRetrieve(http, options, function (status, data) { if(status !== 200) { callback("Ustream HTTP " + status, null); return; } /** * Regexing the ID out of the HTML because * Ustream's API is so horribly documented * I literally could not figure out how to retrieve * this information. * * [](/eatadick) */ var m = data.match(/https:\/\/www\.ustream\.tv\/embed\/(\d+)/); if (m) { var title = "Ustream.tv - " + id; var media = new Media(m[1], title, "--:--", "us"); callback(false, media); } else { callback("Channel ID not found", null); } }); }, /* JWPlayer */ jw: function (id, callback) { var title = "JWPlayer - " + id; var media = new Media(id, title, "--:--", "jw"); callback(false, media); }, /* rtmp stream */ rt: function (id, callback) { var title = "Livestream"; var media = new Media(id, title, "--:--", "rt"); callback(false, media); }, /* HLS stream */ hl: function (id, callback) { var title = "Livestream"; var media = new Media(id, title, "--:--", "hl"); callback(false, media); }, /* imgur.com albums */ im: function (id, callback) { /** * TODO: Consider deprecating this in favor of custom embeds */ var m = id.match(/([\w-]+)/); if (m) { id = m[1]; } else { callback("Invalid ID", null); return; } var title = "Imgur Album - " + id; var media = new Media(id, title, "--:--", "im"); callback(false, media); }, /* custom embed */ cu: function (id, callback) { var media; try { media = CustomEmbedFilter(id); } catch (e) { if (/invalid embed/i.test(e.message)) { return callback(e.message); } else { Logger.errlog.log(e.stack); return callback("Unknown error processing embed"); } } callback(false, media); }, /* google docs */ gd: function (id, callback) { GoogleDrive.setHTML5HackEnabled(Config.get("google-drive.html5-hack-enabled")); var data = { type: "googledrive", kind: "single", id: id }; mediaquery.lookup(data).then(function (video) { callback(null, convertMedia(video)); }).catch(function (err) { callback(err.message || err); }); }, /* Google+ videos */ gp: function (id, callback) { var data = { type: "google+", kind: "single", id: id }; mediaquery.lookup(data).then(function (video) { callback(null, convertMedia(video)); }).catch(function (err) { callback(err.message || err); }); }, /* ffmpeg for raw files */ fi: function (id, cb) { ffmpeg.query(id, function (err, data) { if (err) { return cb(err); } var m = new Media(id, data.title, data.duration, "fi", { bitrate: data.bitrate, codec: data.codec }); cb(null, m); }); }, /* hitbox.tv */ hb: function (id, callback) { var m = id.match(/([\w-]+)/); if (m) { id = m[1]; } else { callback("Invalid ID", null); return; } var title = "Hitbox.tv - " + id; var media = new Media(id, title, "--:--", "hb"); callback(false, media); }, /* vid.me */ vm: function (id, callback) { if (!/^[\w-]+$/.test(id)) { process.nextTick(callback, "Invalid vid.me ID"); return; } Vidme.lookup(id).then(video => { const media = new Media(video.id, video.title, video.duration, "vm", video.meta); process.nextTick(callback, false, media); }).catch(function (err) { callback(err.message || err, null); }); }, /* streamable */ sb: function (id, callback) { if (!/^[\w-]+$/.test(id)) { process.nextTick(callback, "Invalid streamable.com ID"); return; } Streamable.lookup(id).then(video => { const media = new Media(video.id, video.title, video.duration, "sb", video.meta); process.nextTick(callback, false, media); }).catch(function (err) { callback(err.message || err, null); }); } }; module.exports = { Getters: Getters, getMedia: function (id, type, callback) { if(type in this.Getters) { this.Getters[type](id, callback); } else { callback("Unknown media type '" + type + "'", null); } } };
'use strict'; angular.module('workingRoom') .controller('UserCtrl', function ($mdDialog, user, admin, User, Users, GroupsList) { var vm = this; vm.deleteUser = deleteUser; vm.user = user; vm.admin = admin; function deleteUser(event) { $mdDialog.show({ controller: 'DeleteUserCtrl as vm', templateUrl: 'partials/users/delete-user-modal.html', targetEvent: event, resolve: { email: function() { return user.email; } } }).then(function (res) { Users.delete(res, user, User); }); } });
const express = require('express'); const path = require('path'); const bodyParser= require('body-parser') const github = require('octonode'); const app = express(); const client = github.client(); app.set('view engine', 'jade') app.set('views', path.join(__dirname, 'templates')); app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/', (req, res) => { res.render('index', { title: 'Check who are following you on git hub' }); }) app.post('/', (req, res) => { var username = req.body['username']; var ghuser = client.user(username); ghuser.followers({}, (err, data, headers) => { if (!data) res.render('index', { title: 'Check who are following you on Github', user: username }); else { var users = []; data.forEach((user) => { users.push({ login: user['login'], avatar_url: user['avatar_url'], url: user['url'] }); }); res.render('index', { title: 'These guy following ' + username, user: username, followers: users }); } }); }); app.listen(3000)
import {get} from 'api/utils' export async function getPostsAPI () { return get('https://jsonplaceholder.typicode.com/posts?userId=1') }
/* ========================================================= * bootstrap-datepicker.js * http://www.eyecon.ro/bootstrap-datepicker * ========================================================= * Copyright 2012 Stefan Petre * Improvements by Andrew Rowls * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ !function( $ ) { function UTCDate(){ return new Date(Date.UTC.apply(Date, arguments)); } function UTCToday(){ var today = new Date(); return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()); } // Picker object var Datepicker = function(element, options) { var that = this; this.element = $(element); this.language = options.language||this.element.data('date-language')||"en"; this.language = this.language in dates ? this.language : this.language.split('-')[0]; //Check if "de-DE" style date is available, if not language should fallback to 2 letter code eg "de" this.language = this.language in dates ? this.language : "en"; this.isRTL = dates[this.language].rtl||false; this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||dates[this.language].format||'mm/dd/yyyy'); this.isInline = false; this.isInput = this.element.is('input'); this.component = this.element.is('.date') ? this.element.find('.add-on') : false; this.hasInput = this.component && this.element.find('input').length; if(this.component && this.component.length === 0) this.component = false; this._attachEvents(); this.forceParse = true; if ('forceParse' in options) { this.forceParse = options.forceParse; } else if ('dateForceParse' in this.element.data()) { this.forceParse = this.element.data('date-force-parse'); } this.picker = $(DPGlobal.template) .appendTo(this.isInline ? this.element : 'body') .on({ click: $.proxy(this.click, this), mousedown: $.proxy(this.mousedown, this) }); if(this.isInline) { this.picker.addClass('datepicker-inline'); } else { this.picker.addClass('datepicker-dropdown dropdown-menu'); } if (this.isRTL){ this.picker.addClass('datepicker-rtl'); this.picker.find('.prev i, .next i') .toggleClass('icon-arrow-left icon-arrow-right'); } $(document).on('mousedown', function (e) { // Clicked outside the datepicker, hide it if ($(e.target).closest('.datepicker.datepicker-inline, .datepicker.datepicker-dropdown').length === 0) { that.hide(); } }); this.autoclose = false; if ('autoclose' in options) { this.autoclose = options.autoclose; } else if ('dateAutoclose' in this.element.data()) { this.autoclose = this.element.data('date-autoclose'); } this.keyboardNavigation = true; if ('keyboardNavigation' in options) { this.keyboardNavigation = options.keyboardNavigation; } else if ('dateKeyboardNavigation' in this.element.data()) { this.keyboardNavigation = this.element.data('date-keyboard-navigation'); } this.viewMode = this.startViewMode = 0; switch(options.startView || this.element.data('date-start-view')){ case 2: case 'decade': this.viewMode = this.startViewMode = 2; break; case 1: case 'year': this.viewMode = this.startViewMode = 1; break; } this.todayBtn = (options.todayBtn||this.element.data('date-today-btn')||false); this.todayHighlight = (options.todayHighlight||this.element.data('date-today-highlight')||false); this.calendarWeeks = false; if ('calendarWeeks' in options) { this.calendarWeeks = options.calendarWeeks; } else if ('dateCalendarWeeks' in this.element.data()) { this.calendarWeeks = this.element.data('date-calendar-weeks'); } if (this.calendarWeeks) this.picker.find('tfoot th.today') .attr('colspan', function(i, val){ return parseInt(val) + 1; }); this.weekStart = ((options.weekStart||this.element.data('date-weekstart')||dates[this.language].weekStart||0) % 7); this.weekEnd = ((this.weekStart + 6) % 7); this.startDate = -Infinity; this.endDate = Infinity; this.daysOfWeekDisabled = []; this.setStartDate(options.startDate||this.element.data('date-startdate')); this.setEndDate(options.endDate||this.element.data('date-enddate')); this.setDaysOfWeekDisabled(options.daysOfWeekDisabled||this.element.data('date-days-of-week-disabled')); this.fillDow(); this.fillMonths(); this.update(); this.showMode(); if(this.isInline) { this.show(); } }; Datepicker.prototype = { constructor: Datepicker, _events: [], _attachEvents: function(){ this._detachEvents(); if (this.isInput) { // single input this._events = [ [this.element, { // focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this), click: $.proxy(this.show, this) }] ]; } else if (this.component && this.hasInput){ // component: input + button this._events = [ // For components that are not readonly, allow keyboard nav [this.element.find('input'), { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }], [this.component, { click: $.proxy(this.show, this) }] ]; } else if (this.element.is('div')) { // inline datepicker this.isInline = true; } else { this._events = [ [this.element, { click: $.proxy(this.show, this) }] ]; } for (var i=0, el, ev; i<this._events.length; i++){ el = this._events[i][0]; ev = this._events[i][1]; el.on(ev); } }, _detachEvents: function(){ for (var i=0, el, ev; i<this._events.length; i++){ el = this._events[i][0]; ev = this._events[i][1]; el.off(ev); } this._events = []; }, show: function(e) { this.picker.show(); this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(); this.update(); this.place(); $(window).on('resize', $.proxy(this.place, this)); if (e ) { e.stopPropagation(); e.preventDefault(); } this.element.trigger({ type: 'show', date: this.date }); }, hide: function(e){ if(this.isInline) return; if (!this.picker.is(':visible')) return; this.picker.hide(); $(window).off('resize', this.place); this.viewMode = this.startViewMode; this.showMode(); if (!this.isInput) { $(document).off('mousedown', this.hide); } if ( this.forceParse && ( this.isInput && this.element.val() || this.hasInput && this.element.find('input').val() ) ) this.setValue(); this.element.trigger({ type: 'hide', date: this.date }); }, remove: function() { this._detachEvents(); this.picker.remove(); delete this.element.data().datepicker; }, getDate: function() { var d = this.getUTCDate(); return new Date(d.getTime() + (d.getTimezoneOffset()*60000)); }, getUTCDate: function() { return this.date; }, setDate: function(d) { this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000))); }, setUTCDate: function(d) { this.date = d; this.setValue(); }, setValue: function() { var formatted = this.getFormattedDate(); if (!this.isInput) { if (this.component){ this.element.find('input').val(formatted); } this.element.data('date', formatted); } else { this.element.val(formatted); } }, getFormattedDate: function(format) { if (format === undefined) format = this.format; return DPGlobal.formatDate(this.date, format, this.language); }, setStartDate: function(startDate){ this.startDate = startDate||-Infinity; if (this.startDate !== -Infinity) { this.startDate = DPGlobal.parseDate(this.startDate, this.format, this.language); } this.update(); this.updateNavArrows(); }, setEndDate: function(endDate){ this.endDate = endDate||Infinity; if (this.endDate !== Infinity) { this.endDate = DPGlobal.parseDate(this.endDate, this.format, this.language); } this.update(); this.updateNavArrows(); }, setDaysOfWeekDisabled: function(daysOfWeekDisabled){ this.daysOfWeekDisabled = daysOfWeekDisabled||[]; if (!$.isArray(this.daysOfWeekDisabled)) { this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/); } this.daysOfWeekDisabled = $.map(this.daysOfWeekDisabled, function (d) { return parseInt(d, 10); }); this.update(); this.updateNavArrows(); }, place: function(){ if(this.isInline) return; var zIndex = parseInt(this.element.parents().filter(function() { return $(this).css('z-index') != 'auto'; }).first().css('z-index'))+10; var offset = this.component ? this.component.offset() : this.element.offset(); var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true); this.picker.css({ top: offset.top + height, left: offset.left, zIndex: zIndex }); }, update: function(){ var date, fromArgs = false; if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) { date = arguments[0]; fromArgs = true; } else { date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val(); } this.date = DPGlobal.parseDate(date, this.format, this.language); if(fromArgs) this.setValue(); if (this.date < this.startDate) { this.viewDate = new Date(this.startDate); } else if (this.date > this.endDate) { this.viewDate = new Date(this.endDate); } else { this.viewDate = new Date(this.date); } this.fill(); }, fillDow: function(){ var dowCnt = this.weekStart, html = '<tr>'; if(this.calendarWeeks){ var cell = '<th class="cw">&nbsp;</th>'; html += cell; this.picker.find('.datepicker-days thead tr:first-child').prepend(cell); } while (dowCnt < this.weekStart + 7) { html += '<th class="dow">'+dates[this.language].daysMin[(dowCnt++)%7]+'</th>'; } html += '</tr>'; this.picker.find('.datepicker-days thead').append(html); }, fillMonths: function(){ var html = '', i = 0; while (i < 12) { html += '<span class="month">'+dates[this.language].monthsShort[i++]+'</span>'; } this.picker.find('.datepicker-months td').html(html); }, fill: function() { var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(), startYear = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity, startMonth = this.startDate !== -Infinity ? this.startDate.getUTCMonth() : -Infinity, endYear = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity, endMonth = this.endDate !== Infinity ? this.endDate.getUTCMonth() : Infinity, currentDate = this.date && this.date.valueOf(), today = new Date(); this.picker.find('.datepicker-days thead th.switch') .text(dates[this.language].months[month]+' '+year); this.picker.find('tfoot th.today') .text(dates[this.language].today) .toggle(this.todayBtn !== false); this.updateNavArrows(); this.fillMonths(); var prevMonth = UTCDate(year, month-1, 28,0,0,0,0), day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth()); prevMonth.setUTCDate(day); prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7)%7); var nextMonth = new Date(prevMonth); nextMonth.setUTCDate(nextMonth.getUTCDate() + 42); nextMonth = nextMonth.valueOf(); var html = []; var clsName; while(prevMonth.valueOf() < nextMonth) { if (prevMonth.getUTCDay() == this.weekStart) { html.push('<tr>'); if(this.calendarWeeks){ // ISO 8601: First week contains first thursday. // ISO also states week starts on Monday, but we can be more abstract here. var // Start of current week: based on weekstart/current date ws = new Date(+prevMonth + (this.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5), // Thursday of this week th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5), // First Thursday of year, year from thursday yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5), // Calendar week: ms between thursdays, div ms per day, div 7 days calWeek = (th - yth) / 864e5 / 7 + 1; html.push('<td class="cw">'+ calWeek +'</td>'); } } clsName = ''; if (prevMonth.getUTCFullYear() < year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() < month)) { clsName += ' old'; } else if (prevMonth.getUTCFullYear() > year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() > month)) { clsName += ' new'; } // Compare internal UTC date with local today, not UTC today if (this.todayHighlight && prevMonth.getUTCFullYear() == today.getFullYear() && prevMonth.getUTCMonth() == today.getMonth() && prevMonth.getUTCDate() == today.getDate()) { clsName += ' today'; } if (currentDate && prevMonth.valueOf() == currentDate) { clsName += ' active'; } if (prevMonth.valueOf() < this.startDate || prevMonth.valueOf() > this.endDate || $.inArray(prevMonth.getUTCDay(), this.daysOfWeekDisabled) !== -1) { clsName += ' disabled'; } html.push('<td class="day'+clsName+'">'+prevMonth.getUTCDate() + '</td>'); if (prevMonth.getUTCDay() == this.weekEnd) { html.push('</tr>'); } prevMonth.setUTCDate(prevMonth.getUTCDate()+1); } this.picker.find('.datepicker-days tbody').empty().append(html.join('')); var currentYear = this.date && this.date.getUTCFullYear(); var months = this.picker.find('.datepicker-months') .find('th:eq(1)') .text(year) .end() .find('span').removeClass('active'); if (currentYear && currentYear == year) { months.eq(this.date.getUTCMonth()).addClass('active'); } if (year < startYear || year > endYear) { months.addClass('disabled'); } if (year == startYear) { months.slice(0, startMonth).addClass('disabled'); } if (year == endYear) { months.slice(endMonth+1).addClass('disabled'); } html = ''; year = parseInt(year/10, 10) * 10; var yearCont = this.picker.find('.datepicker-years') .find('th:eq(1)') .text(year + '-' + (year + 9)) .end() .find('td'); year -= 1; for (var i = -1; i < 11; i++) { html += '<span class="year'+(i == -1 || i == 10 ? ' old' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>'; year += 1; } yearCont.html(html); }, updateNavArrows: function() { var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(); switch (this.viewMode) { case 0: if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; case 1: case 2: if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; } }, click: function(e) { e.stopPropagation(); e.preventDefault(); var target = $(e.target).closest('span, td, th'); if (target.length == 1) { switch(target[0].nodeName.toLowerCase()) { case 'th': switch(target[0].className) { case 'switch': this.showMode(1); break; case 'prev': case 'next': var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1); switch(this.viewMode){ case 0: this.viewDate = this.moveMonth(this.viewDate, dir); break; case 1: case 2: this.viewDate = this.moveYear(this.viewDate, dir); break; } this.fill(); break; case 'today': var date = new Date(); date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); this.showMode(-2); var which = this.todayBtn == 'linked' ? null : 'view'; this._setDate(date, which); break; } break; case 'span': if (!target.is('.disabled')) { this.viewDate.setUTCDate(1); if (target.is('.month')) { var month = target.parent().find('span').index(target); this.viewDate.setUTCMonth(month); this.element.trigger({ type: 'changeMonth', date: this.viewDate }); } else { var year = parseInt(target.text(), 10)||0; this.viewDate.setUTCFullYear(year); this.element.trigger({ type: 'changeYear', date: this.viewDate }); } this.showMode(-1); this.fill(); } break; case 'td': if (target.is('.day') && !target.is('.disabled')){ var day = parseInt(target.text(), 10)||1; var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(); if (target.is('.old')) { if (month === 0) { month = 11; year -= 1; } else { month -= 1; } } else if (target.is('.new')) { if (month == 11) { month = 0; year += 1; } else { month += 1; } } this._setDate(UTCDate(year, month, day,0,0,0,0)); } break; } } }, _setDate: function(date, which){ if (!which || which == 'date') this.date = date; if (!which || which == 'view') this.viewDate = date; this.fill(); this.setValue(); this.element.trigger({ type: 'changeDate', date: this.date }); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); if (this.autoclose && (!which || which == 'date')) { this.hide(); } } }, moveMonth: function(date, dir){ if (!dir) return date; var new_date = new Date(date.valueOf()), day = new_date.getUTCDate(), month = new_date.getUTCMonth(), mag = Math.abs(dir), new_month, test; dir = dir > 0 ? 1 : -1; if (mag == 1){ test = dir == -1 // If going back one month, make sure month is not current month // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02) ? function(){ return new_date.getUTCMonth() == month; } // If going forward one month, make sure month is as expected // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02) : function(){ return new_date.getUTCMonth() != new_month; }; new_month = month + dir; new_date.setUTCMonth(new_month); // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11 if (new_month < 0 || new_month > 11) new_month = (new_month + 12) % 12; } else { // For magnitudes >1, move one month at a time... for (var i=0; i<mag; i++) // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)... new_date = this.moveMonth(new_date, dir); // ...then reset the day, keeping it in the new month new_month = new_date.getUTCMonth(); new_date.setUTCDate(day); test = function(){ return new_month != new_date.getUTCMonth(); }; } // Common date-resetting loop -- if date is beyond end of month, make it // end of month while (test()){ new_date.setUTCDate(--day); new_date.setUTCMonth(new_month); } return new_date; }, moveYear: function(date, dir){ return this.moveMonth(date, dir*12); }, dateWithinRange: function(date){ return date >= this.startDate && date <= this.endDate; }, keydown: function(e){ if (this.picker.is(':not(:visible)')){ if (e.keyCode == 27) // allow escape to hide and re-show picker this.show(); return; } var dateChanged = false, dir, day, month, newDate, newViewDate; switch(e.keyCode){ case 27: // escape this.hide(); e.preventDefault(); break; case 37: // left case 39: // right if (!this.keyboardNavigation) break; dir = e.keyCode == 37 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 38: // up case 40: // down if (!this.keyboardNavigation) break; dir = e.keyCode == 38 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir * 7); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 13: // enter this.hide(); e.preventDefault(); break; case 9: // tab this.hide(); break; } if (dateChanged){ this.element.trigger({ type: 'changeDate', date: this.date }); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); } } }, showMode: function(dir) { if (dir) { this.viewMode = Math.max(0, Math.min(2, this.viewMode + dir)); } /* vitalets: fixing bug of very special conditions: jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover. Method show() does not set display css correctly and datepicker is not shown. Changed to .css('display', 'block') solve the problem. See https://github.com/vitalets/x-editable/issues/37 In jquery 1.7.2+ everything works fine. */ //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show(); this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block'); this.updateNavArrows(); } }; $.fn.datepicker = function ( option ) { var args = Array.apply(null, arguments); args.shift(); return this.each(function () { var $this = $(this), data = $this.data('datepicker'), options = typeof option == 'object' && option; if (!data) { $this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options)))); } if (typeof option == 'string' && typeof data[option] == 'function') { data[option].apply(data, args); } }); }; $.fn.datepicker.defaults = { }; $.fn.datepicker.Constructor = Datepicker; var dates = $.fn.datepicker.dates = { en: { days: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"], months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], today: "Today" } }; var DPGlobal = { modes: [ { clsName: 'days', navFnc: 'Month', navStep: 1 }, { clsName: 'months', navFnc: 'FullYear', navStep: 1 }, { clsName: 'years', navFnc: 'FullYear', navStep: 10 }], isLeapYear: function (year) { return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); }, getDaysInMonth: function (year, month) { return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }, validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g, nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g, parseFormat: function(format){ // IE treats \0 as a string end in inputs (truncating the value), // so it's a bad format delimiter, anyway var separators = format.replace(this.validParts, '\0').split('\0'), parts = format.match(this.validParts); if (!separators || !separators.length || !parts || parts.length === 0){ throw new Error("Invalid date format."); } return {separators: separators, parts: parts}; }, parseDate: function(date, format, language) { if (date instanceof Date) return date; if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) { var part_re = /([\-+]\d+)([dmwy])/, parts = date.match(/([\-+]\d+)([dmwy])/g), part, dir; date = new Date(); for (var i=0; i<parts.length; i++) { part = part_re.exec(parts[i]); dir = parseInt(part[1]); switch(part[2]){ case 'd': date.setUTCDate(date.getUTCDate() + dir); break; case 'm': date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir); break; case 'w': date.setUTCDate(date.getUTCDate() + dir * 7); break; case 'y': date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir); break; } } return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0); } var parts = date && date.match(this.nonpunctuation) || [], date = new Date(), parsed = {}, setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'], setters_map = { yyyy: function(d,v){ return d.setUTCFullYear(v); }, yy: function(d,v){ return d.setUTCFullYear(2000+v); }, m: function(d,v){ v -= 1; while (v<0) v += 12; v %= 12; d.setUTCMonth(v); while (d.getUTCMonth() != v) d.setUTCDate(d.getUTCDate()-1); return d; }, d: function(d,v){ return d.setUTCDate(v); } }, val, filtered, part; setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m']; setters_map['dd'] = setters_map['d']; date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); var fparts = format.parts.slice(); // Remove noop parts if (parts.length != fparts.length) { fparts = $(fparts).filter(function(i,p){ return $.inArray(p, setters_order) !== -1; }).toArray(); } // Process remainder if (parts.length == fparts.length) { for (var i=0, cnt = fparts.length; i < cnt; i++) { val = parseInt(parts[i], 10); part = fparts[i]; if (isNaN(val)) { switch(part) { case 'MM': filtered = $(dates[language].months).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].months) + 1; break; case 'M': filtered = $(dates[language].monthsShort).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].monthsShort) + 1; break; } } parsed[part] = val; } for (var i=0, s; i<setters_order.length; i++){ s = setters_order[i]; if (s in parsed && !isNaN(parsed[s])) setters_map[s](date, parsed[s]); } } return date; }, formatDate: function(date, format, language){ var val = { d: date.getUTCDate(), D: dates[language].daysShort[date.getUTCDay()], DD: dates[language].days[date.getUTCDay()], m: date.getUTCMonth() + 1, M: dates[language].monthsShort[date.getUTCMonth()], MM: dates[language].months[date.getUTCMonth()], yy: date.getUTCFullYear().toString().substring(2), yyyy: date.getUTCFullYear() }; val.dd = (val.d < 10 ? '0' : '') + val.d; val.mm = (val.m < 10 ? '0' : '') + val.m; var date = [], seps = $.extend([], format.separators); for (var i=0, cnt = format.parts.length; i < cnt; i++) { if (seps.length) date.push(seps.shift()); date.push(val[format.parts[i]]); } return date.join(''); }, headTemplate: '<thead>'+ '<tr>'+ '<th class="prev"><i class="icon-arrow-left"/></th>'+ '<th colspan="5" class="switch"></th>'+ '<th class="next"><i class="icon-arrow-right"/></th>'+ '</tr>'+ '</thead>', contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>', footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr></tfoot>' }; DPGlobal.template = '<div class="datepicker">'+ '<div class="datepicker-days">'+ '<table class=" table-condensed">'+ DPGlobal.headTemplate+ '<tbody></tbody>'+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-months">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-years">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '</div>'; $.fn.datepicker.DPGlobal = DPGlobal; }( window.jQuery );
/* * grunt-clopp * https://github.com/boostermedia/clopp * * Copyright (c) 2015 Riko Ophorst * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.initConfig({ clean: { tests: ['test/functional/dest/*', '!test/functional/dest/*.md'] }, clopp: { preprocess: { options: { verbose: true, filetypes: true, context: { __ads: true, __environment: 'stage' } }, files: [ { src: 'test/functional/src/test.html', dest: 'test/functional/dest/'}, { src: 'test/functional/src/test.js', dest: 'test/functional/dest/'} ] } }, mochaTest: { 'spec': { options: { reporter: 'spec', // tests are quite slow as thy spawn node processes timeout: 10000 }, src: ['test/unit/**/*.js'] } } }); grunt.registerTask('default', ['clean', 'clopp']); };
'use strict'; describe('planRowDirective', function() { beforeEach(module('gc.planRowList')); var elm, scope; beforeEach(inject(function($rootScope, $compile) { scope = $rootScope.$new(); scope.plans = [ { status: 'active', id: 11 }, { status: 'inactive', id: 22 } ]; elm = angular.element( '<plan-row-list plans="plans" url="url" ' + '></plan-row-list>' ); $compile(elm)(scope); scope.$digest(); })); it('has plan row items', function() { var listItem = elm.find('.payments__list__item'); expect(listItem.length).toBe(2); }); });
// Inisde this function we could diptch other actions. // .e.g to activate spinners/signal errors and so. import axios from 'axios' export const TALKS_UPDATED = 'TALKS_UPDATED' // Do the vote, reload talks from server // then return the TALKS_UPDATED action export function vote(id) { console.log("VOTING", id) return dispatch => axios.post('/api/talk/vote', {id}).then(dispatch(loadData())) .catch(err => console.log(err)) } export function loadData() { return dispatch => axios.get('/api/talks') .then(res => dispatch(talksUpdated(res.data))) // we should manage errors... .catch(err => console.log(err)) } function talksUpdated(talks) { console.log("TALKS_UPDATED ACTION") return { type: TALKS_UPDATED, talks } }
import * as constants from "./constants"; import Attractor from "./Attractor"; let initNum = 1; export default class Deflector extends Attractor { constructor(game, center) { super(game, center); this.type = "deflector"; this.id = initNum; this.isAlive = true; this.game = game; this.center = center; this.mass = constants.EarthMass * 4; this.radius = this.mass / constants.EarthMass * constants.EarthRadius; this.color = `#2b008f`; initNum++; } calculateMass() { this.mass = this.radius / constants.EarthRadius * constants.EarthMass; } }
import PropTypes from 'prop-types'; import React, { Fragment } from 'react'; const FragmentComponent = props => (<Fragment> {props.children} </Fragment>); FragmentComponent.propTypes = { children: PropTypes.node, id: PropTypes.string }; FragmentComponent.defaultProps = {}; export default FragmentComponent;
'use strict'; const Window = (() => { const _window = document.getElementById('gameCanvas'); const _context = _window.getContext('2d'); let _width = 800; let _height = 600; _window.width = _width; _window.height = _height; const setWidth = width => { _window.width =_width = width; }; const setHeight = height => { _window.height = _height = height; }; const setSize = (width, height) => { setWidth(width); setHeight(height); }; const getWidth = () => _width; const getHeight = () => _height; const getSize = () => { return {width: _width, height: _height}; }; const getContext = () => _context; const showCursor = (show) => { if (show) { _window.style.cursor = 'auto'; } else { _window.style.cursor = 'none'; } }; return { handle: _window, setWidth: setWidth, getWidth: getWidth, setHeight: setHeight, getHeight: getHeight, setSize: setSize, getSize: getSize, getContext: getContext, showCursor: showCursor }; })(); const Graphics = (context => { const font = { color: '#000000', size: 26, name: 'arial' }; const clear = () => { context.clearRect(0, 0, Window.getWidth(), Window.getHeight()); }; const setFont = (name, size, color) => { font.name = name; font.size = size; font.color = color; context.font = font.size + 'px ' + font.name; }; const setFontColor = color => { context.strokeStyle = context.fillStyle = font.color = color; }; const setFontName = name => { font.name = name; context.font = font.size + 'px ' + font.name; }; const setFontSize = size => { font.size = size; context.font = font.size + 'px ' + font.name; }; const getTextWidth = txt => context.measureText(txt).width; const drawText = (text, x, y) => { context.beginPath(); context.fillText(text, x, y); context.closePath(); }; const drawRect = (x, y, width, height) => { context.beginPath(); context.fillRect(x, y, width, height); context.closePath(); }; return { clear: clear, drawText: drawText, drawRect: drawRect, setFontColor: setFontColor, setFontSize: setFontSize, setFontName: setFontName, getTextWidth: getTextWidth, getContext: () => context }; })(Window.getContext()); const Sound = (() => { const backgroundAudio = new Audio(); const effectAudios = []; const playBackgroundMusic = (src, loop) => { backgroundAudio.src = src; backgroundAudio.loop = loop; backgroundAudio.play(); }; const backgroundProgress = (handler) => { backgroundAudio.ontimeupdate = (e) => { handler(e); } }; const currentTime = function () { return backgroundAudio.currentTime; }; const playEffect = (src, over) => { const dir = new Audio(); dir.src = src; for (let effect of effectAudios) { if (effect.src == dir.src) { if (effect.paused || over) { effect.currentTime = 0; effect.play(); } return effectAudios.indexOf(effect); } } let effect = new Audio(); effect.src = src; effect.play(); effectAudios.push(effect); return effectAudios.length - 1; }; const pauseBackgroundMusic = () => { if (backgroundAudio) { backgroundAudio.pause(); } }; const pauseEffect = (id) => { if (effectAudios[id]) { effectAudios[id].pause(); } }; const pauseAllEffects = () => { for (let effect of effectAudios) { effect.pause(); } }; const stopBackgroundMusic = () => { if (backgroundAudio) { backgroundAudio.currentTime = 0; backgroundAudio.pause(); } }; const stopEffect = (id) => { if (effectAudios[id]) { effectAudios[id].currentTime = 0; effectAudios[id].pause(); } }; const stopAllEffects = () => { for (let effect of effectAudios) { effect.currentTime = 0; effect.pause(); } }; const resumeBackgroundMusic = () => { if (backgroundAudio) { backgroundAudio.play(); } }; const resumeEffect = (id) => { if (effectAudios[id]) { effectAudios[id].play(); } }; const resumeAllEffects = () => { for (let effect of effectAudios) { effect.play(); } }; return { playBackgroundMusic: playBackgroundMusic, pauseBackgroundMusic: pauseBackgroundMusic, stopBackgroundMusic: stopBackgroundMusic, playEffect: playEffect, pauseEffect: pauseEffect, stopEffect: stopEffect, pauseAllEffects: pauseAllEffects, stopAllEffects: stopAllEffects, backgroundProgress: backgroundProgress, currentTime: currentTime }; })(); const Preloader = ((loadList) => { const formats = ['jpg', 'png', 'gif']; let loadCount = 0; let loadCompleteCount = 0; const getFormat = src => { let fmt = src.split('.'); fmt = fmt[fmt.length - 1]; return fmt; }; const loads = list => { for (let src of list) { load(src); } }; const load = src => { for (let fmt of formats) { if (fmt == getFormat(src)) { loadImage(src); return; } } loadSound(src); }; const loadImage = src => { const image = new Image(); image.src = src; image.onload = () => { loadCompleteCount++; }; loadCount++; }; const loadSound = src => { const sound = new Audio(); sound.src = src; sound.onloadeddata = () => { loadCompleteCount++; }; loadCount++; }; const getScene = () => { const PreloadScene = Director.createScene(function () {}); PreloadScene.prototype.update = delta => { if (isLoadComplete()) Director.popScene(); }; PreloadScene.prototype.render = () => { Graphics.setFontColor('#000'); Graphics.drawText(getProgress(), Window.getWidth() / 2, Window.getHeight() / 2); }; return new PreloadScene(); }; const getProgress = () => { return parseInt(loadCompleteCount / loadCount * 100); } const isLoadComplete = () => { return loadCompleteCount == loadCompleteCount; }; return { load: load, loads: loads, getScene: getScene, getProgress: getProgress, isLoadComplete: isLoadComplete }; })([]); const Scene = function(){ this._childs = []; }; Scene.prototype.update = function(delta){}; Scene.prototype.render = function(){}; Scene.prototype.addChild = function(child){ this._childs.push(child); this._childs.sort((a, b) => b.z - a.z); }; Scene.prototype.childsProcess = function(delta){ for (let child of this._childs) { child.update(delta); child.render(); } }; const Director = (() => { const _scene = []; const createScene = (init) => { init.prototype = new Scene(); return init; }; const pushScene = scene => { _scene.push(scene); }; const popScene = () => { _scene.pop(); }; const replaceScene = scene => { while (_scene.length) popScene(); pushScene(scene); }; const getScene = () => _scene[_scene.length - 1]; const render = () => { getScene().render(); getScene().childsProcess(); }; const update = delta => { getScene().update(delta); }; return { createScene: createScene, pushScene: pushScene, popScene: popScene, getScene: getScene, replaceScene: replaceScene, render: render, update: update, scenes: () => _scene }; })(); const keyCodes = { Q: 81, W: 87, E: 69, R: 82, T: 84, Y: 89, U: 85, I: 73, O: 79, P: 80, A: 65, S: 83, D: 68, F: 70, G: 71, H: 72, J: 74, K: 75, L: 76, Z: 90, X: 88, C: 67, V: 86, B: 66, N: 78, M: 77, ZERO: 48, ONE: 49, TWO: 50, THREE: 51, FOUR: 52, FIVE: 53, SIX: 54, SEVEN: 55, EIGHT: 56, NINE: 57, UP: 38, DOWN: 40, LEFT: 37, RIGHT: 39, ENTER: 13, ESC: 27, SHIFT: 16, BACKSPACE: 8, CTRL: 17, ALT: 18, SPACE: 32 }; const InputSystem = (() => { const keyTable = []; let hasTrigger = false; let x = 0; let y = 0; let prevButton = 0; const hasClick = []; document.addEventListener('keydown', e => { if (!hasTrigger) { keyTable[e.keyCode] = true; } }); document.addEventListener('keyup', e => { hasTrigger = false; keyTable[e.keyCode] = false; }); Window.handle.addEventListener('mousemove', e => { x = e.pageX; y = e.pageY; }); Window.handle.addEventListener('mousedown', e => { hasClick[prevButton = e.button] = true; }); Window.handle.addEventListener('mouseup', e => { hasClick[prevButton] = false; }); const hasKeyDown = code => keyTable[code]; const hasKeyTrigger = code => { if (keyTable[code]) { hasTrigger = true; keyTable[code] = false; return true; } return false; }; const hasMouseClick = code => { if (hasClick[code]) { hasClick[code] = false; return true; } hasClick[code] = false; return false; }; const getX = () => x; const getY = () => y; return { hasKeyDown: hasKeyDown, hasKeyTrigger: hasKeyTrigger, hasMouseClick: hasMouseClick, getX: getX, getY: getY }; })(); const Parameter = ((dictionary) => { const getValueForKey = (self, key, defaults) => { if (dictionary.hasOwnProperty(self)) { if (!dictionary[self]) { return undefined; } var value = dictionary[self][key]; delete dictionary[self][key]; return value; } return undefined; }; const setValueForKey = (self, key, value) => { if (!dictionary[self]) dictionary[self] = {}; dictionary[self][key] = value; }; return { getValueForKey: getValueForKey, setValueForKey: setValueForKey }; })({}); const UserDefault = ((dictionary) => { const getValueForKey = (key, defaults) => { if (dictionary.hasOwnProperty(key)) { return dictionary[key]; } return defaults; }; const setValueForKey = (key, value) => { dictionary[key] = value; }; const loadValueToSystemKey = () => { for (let key in localStorage) { try { dictionary[key] = JSON.parse(localStorage.getItem(key)); } catch (e) { dictionary[key] = localStorage.getItem(key); } } }; const saveValueToSystemKey = () => { for (let key in dictionary) { localStorage[key] = JSON.stringify(dictionary[key]); } } return { getValueForKey: getValueForKey, setValueForKey: setValueForKey, loadValueToSystemKey: loadValueToSystemKey, saveValueToSystemKey: saveValueToSystemKey }; })({}); const Sprite = function(src) { this.image = new Image(); this.image.src = src; this.rect = new Rect(); this.rect.x = this.x = 0; this.rect.y = this.y = 0; this.rect.width = this.image.width; this.rect.height = this.image.height; this.z = 999; this.mouseOver = false; this.onMouseHandler = { click: [], over: [], out: [] }; }; Sprite.prototype.setX = function(x){ this.rect.x = this.x = x; }; Sprite.prototype.setY = function(y){ this.rect.y = this.y = y; }; Sprite.prototype.setZ = function(z){ this.z = z; }; Sprite.prototype.getX = function(){ return this.x; }; Sprite.prototype.getY = function(){ return this.y; }; Sprite.prototype.getZ = function(){ return this.z; }; Sprite.prototype.addEventListener = function(eventName, eventHandler){ if (!this.onMouseHandler.hasOwnProperty(eventName)) return; if (typeof this.onMouseHandler[eventName] != 'object') { this.onMouseHandler[eventName] = []; } this.onMouseHandler[eventName][this.onMouseHandler[eventName].length] = eventHandler; } Sprite.prototype.removeEventListener = function(eventName, eventHandler) { if (!this.onMouseHandler.hasOwnProperty(eventName)) return; if (typeof this.onMouseHandler[eventName] != 'object') return; this.onMouseHandler[eventName].splice(this.onMouseHandler[eventName].indexOf(eventHandler), 1); } Sprite.prototype.update = function(delta){ if (this.rect.containsPoint(new Point(InputSystem.getX(), InputSystem.getY()))) { for (let callback of this.onMouseHandler['over']) { callback(); } this.mouseOver = true; if (InputSystem.hasMouseClick(0)) { for (let callback of this.onMouseHandler['click']) { callback(); } } } else { if (this.mouseOver) { for (let callback of this.onMouseHandler['out']) { callback(); } this.mouseOver = false; } } }; Sprite.prototype.render = function(){ const context = Graphics.getContext(); context.drawImage(this.image, this.x, this.y, this.image.width, this.image.height); }; const Point = function(x, y) { this.x = x; this.y = y; }; const Rect = function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; }; Rect.prototype.intersectsRect = function(rect){ return this.x <= rect.x + rect.width && this.x + this.width >= rect.x && this.y <= rect.y + rect.height && this.y + this.height >= rect.y; }; Rect.prototype.containsPoint = function(point){ return this.x <= point.x && this.x + this.width >= point.x && this.y <= point.y && this.y + this.height >= point.y; }; const commaValue = function(value) { let str = '' + value; let result = str[str.length - 1]; for (let i = 1; i < str.length; i++) { let num = str[str.length - 1 - i]; if (i % 3 == 0) { result = ',' + result; } result = num + result; } return result; }; const Main = (() => { const idealDeltaTime = 1 / 60; let prevTime; let accumulator = 0.0; const render = () => { Graphics.clear(); Director.render(); }; const update = currTime => { let frameTime = (currTime - prevTime) / 1000; if (frameTime > idealDeltaTime * 2 - 0.001) frameTime = idealDeltaTime * 2 - 0.001; prevTime = currTime; accumulator += frameTime; while (accumulator >= idealDeltaTime) { Director.update(idealDeltaTime); accumulator -= idealDeltaTime; } }; const mainLoop = currTime => { update(currTime); render(); requestAnimationFrame(currTime => { mainLoop(currTime); }); }; const init = callback => { callback(); Director.pushScene(Preloader.getScene()); prevTime = 0; requestAnimationFrame(currTime => { mainLoop(currTime); }); }; return { init: init }; })();
/** * @depends {3rdparty/jquery-2.1.0.js} * @depends {3rdparty/bootstrap.js} * @depends {3rdparty/big.js} * @depends {3rdparty/jsbn.js} * @depends {3rdparty/jsbn2.js} * @depends {3rdparty/pako.js} * @depends {3rdparty/webdb.js} * @depends {3rdparty/ajaxmultiqueue.js} * @depends {3rdparty/growl.js} * @depends {3rdparty/zeroclipboard.js} * @depends {crypto/curve25519.js} * @depends {crypto/curve25519_.js} * @depends {crypto/passphrasegenerator.js} * @depends {crypto/sha256worker.js} * @depends {crypto/3rdparty/cryptojs/aes.js} * @depends {crypto/3rdparty/cryptojs/sha256.js} * @depends {crypto/3rdparty/jssha256.js} * @depends {crypto/3rdparty/seedrandom.js} * @depends {util/converters.js} * @depends {util/extensions.js} * @depends {util/nxtaddress.js} */ var NRS = (function(NRS, $, undefined) { "use strict"; NRS.server = ""; NRS.state = {}; NRS.blocks = []; NRS.genesis = "1739068987193023818"; NRS.genesisRS = "NXT-MRCC-2YLS-8M54-3CMAJ"; NRS.account = ""; NRS.accountRS = ""; NRS.publicKey = ""; NRS.accountInfo = {}; NRS.database = null; NRS.databaseSupport = false; NRS.serverConnect = false; NRS.peerConnect = false; NRS.settings = {}; NRS.contacts = {}; NRS.isTestNet = false; NRS.isLocalHost = false; NRS.isForging = false; NRS.isLeased = false; NRS.needsAdminPassword = true; NRS.lastBlockHeight = 0; NRS.downloadingBlockchain = false; NRS.rememberPassword = false; NRS.selectedContext = null; NRS.currentPage = "dashboard"; NRS.currentSubPage = ""; NRS.pageNumber = 1; //NRS.itemsPerPage = 50; /* Now set in nrs.settings.js */ NRS.pages = {}; NRS.incoming = {}; if (!_checkDOMenabled()) { NRS.hasLocalStorage = false; } else { NRS.hasLocalStorage = true; } NRS.inApp = false; NRS.appVersion = ""; NRS.appPlatform = ""; NRS.assetTableKeys = []; var stateInterval; var stateIntervalSeconds = 30; var isScanning = false; NRS.init = function() { NRS.sendRequest("getState", { "includeCounts": "false" }, function (response) { var isTestnet = false; var isOffline = false; var peerPort = 0; for (var key in response) { if (key == "isTestnet") { isTestnet = response[key]; } if (key == "isOffline") { isOffline = response[key]; } if (key == "peerPort") { peerPort = response[key]; } if (key == "needsAdminPassword") { NRS.needsAdminPassword = response[key]; } } if (!isTestnet) { $(".testnet_only").hide(); } else { NRS.isTestNet = true; var testnetWarningDiv = $("#testnet_warning"); var warningText = testnetWarningDiv.text() + " The testnet peer port is " + peerPort + (isOffline ? ", the peer is working offline." : "."); testnetWarningDiv.text(warningText); $(".testnet_only, #testnet_login, #testnet_warning").show(); } }); if (!NRS.server) { var hostName = window.location.hostname.toLowerCase(); NRS.isLocalHost = hostName == "localhost" || hostName == "127.0.0.1" || NRS.isPrivateIP(hostName); } if (!NRS.isLocalHost) { $(".remote_warning").show(); } try { window.localStorage; } catch (err) { NRS.hasLocalStorage = false; } if (NRS.getCookie("remember_passphrase")) { $("#remember_password").prop("checked", true); } NRS.createDatabase(function() { NRS.getSettings(); }); NRS.getState(function() { setTimeout(function() { NRS.checkAliasVersions(); }, 5000); }); NRS.showLockscreen(); if (window.parent) { var match = window.location.href.match(/\?app=?(win|mac|lin)?\-?([\d\.]+)?/i); if (match) { NRS.inApp = true; if (match[1]) { NRS.appPlatform = match[1]; } if (match[2]) { NRS.appVersion = match[2]; } if (!NRS.appPlatform || NRS.appPlatform == "mac") { var macVersion = navigator.userAgent.match(/OS X 10_([0-9]+)/i); if (macVersion && macVersion[1]) { macVersion = parseInt(macVersion[1]); if (macVersion < 9) { $(".modal").removeClass("fade"); } } } $("#show_console").hide(); parent.postMessage("loaded", "*"); window.addEventListener("message", receiveMessage, false); } } NRS.setStateInterval(30); if (!NRS.isTestNet) { setInterval(NRS.checkAliasVersions, 1000 * 60 * 60); } NRS.allowLoginViaEnter(); NRS.automaticallyCheckRecipient(); $(".show_popover").popover({ "trigger": "hover" }); $("#dashboard_transactions_table, #transactions_table").on("mouseenter", "td.confirmations", function() { $(this).popover("show"); }).on("mouseleave", "td.confirmations", function() { $(this).popover("destroy"); $(".popover").remove(); }); _fix(); $(window).on("resize", function() { _fix(); if (NRS.currentPage == "asset_exchange") { NRS.positionAssetSidebar(); } }); $("[data-toggle='tooltip']").tooltip(); $(".sidebar .treeview").tree(); $("#dgs_search_account_top, #dgs_search_account_center").mask("NXT-****-****-****-*****", { "unmask": false }); /* $("#asset_exchange_search input[name=q]").addClear({ right: 0, top: 4, onClear: function(input) { $("#asset_exchange_search").trigger("submit"); } }); $("#id_search input[name=q], #alias_search input[name=q]").addClear({ right: 0, top: 4 });*/ }; function _fix() { var height = $(window).height() - $("body > .header").height(); //$(".wrapper").css("min-height", height + "px"); var content = $(".wrapper").height(); $(".content.content-stretch:visible").width($(".page:visible").width()); if (content > height) { $(".left-side, html, body").css("min-height", content + "px"); } else { $(".left-side, html, body").css("min-height", height + "px"); } } NRS.setStateInterval = function(seconds) { if (seconds == stateIntervalSeconds && stateInterval) { return; } if (stateInterval) { clearInterval(stateInterval); } stateIntervalSeconds = seconds; stateInterval = setInterval(function() { NRS.getState(); }, 1000 * seconds); }; NRS.getState = function(callback) { NRS.sendRequest("getBlockchainStatus", function(response) { if (response.errorCode) { NRS.serverConnect = false; //todo } else { var firstTime = !("lastBlock" in NRS.state); var previousLastBlock = (firstTime ? "0" : NRS.state.lastBlock); NRS.state = response; NRS.serverConnect = true; if (firstTime) { $("#nrs_version").html(NRS.state.version).removeClass("loading_dots"); NRS.getBlock(NRS.state.lastBlock, NRS.handleInitialBlocks); } else if (NRS.state.isScanning) { //do nothing but reset NRS.state so that when isScanning is done, everything is reset. isScanning = true; } else if (isScanning) { //rescan is done, now we must reset everything... isScanning = false; NRS.blocks = []; NRS.tempBlocks = []; NRS.getBlock(NRS.state.lastBlock, NRS.handleInitialBlocks); if (NRS.account) { NRS.getInitialTransactions(); NRS.getAccountInfo(); } } else if (previousLastBlock != NRS.state.lastBlock) { NRS.tempBlocks = []; if (NRS.account) { NRS.getAccountInfo(); } NRS.getBlock(NRS.state.lastBlock, NRS.handleNewBlocks); if (NRS.account) { NRS.getNewTransactions(); } } else { if (NRS.account) { NRS.getUnconfirmedTransactions(function(unconfirmedTransactions) { NRS.handleIncomingTransactions(unconfirmedTransactions, false); }); } } if (callback) { callback(); } } /* Checks if the client is connected to active peers */ NRS.checkConnected(); //only done so that download progress meter updates correctly based on lastFeederHeight if (NRS.downloadingBlockchain) { NRS.updateBlockchainDownloadProgress(); } }); }; $("#logo, .sidebar-menu a").click(function(e, data) { if ($(this).hasClass("ignore")) { $(this).removeClass("ignore"); return; } e.preventDefault(); if ($(this).data("toggle") == "modal") { return; } var page = $(this).data("page"); if (page == NRS.currentPage) { if (data && data.callback) { data.callback(); } return; } $(".page").hide(); $(document.documentElement).scrollTop(0); $("#" + page + "_page").show(); $(".content-header h1").find(".loading_dots").remove(); var changeActive = !($(this).closest("ul").hasClass("treeview-menu")); if (changeActive) { var currentActive = $("ul.sidebar-menu > li.active"); if (currentActive.hasClass("treeview")) { currentActive.children("a").first().addClass("ignore").click(); } else { currentActive.removeClass("active"); } if ($(this).attr("id") && $(this).attr("id") == "logo") { $("#dashboard_link").addClass("active"); } else { $(this).parent().addClass("active"); } } if (NRS.currentPage != "messages") { $("#inline_message_password").val(""); } //NRS.previousPage = NRS.currentPage; NRS.currentPage = page; NRS.currentSubPage = ""; NRS.pageNumber = 1; NRS.showPageNumbers = false; if (NRS.pages[page]) { NRS.pageLoading(); if (data && data.callback) { NRS.pages[page](data.callback); } else if (data) { NRS.pages[page](data); } else { NRS.pages[page](); } } }); $("button.goto-page, a.goto-page").click(function(event) { event.preventDefault(); NRS.goToPage($(this).data("page")); }); NRS.loadPage = function(page, callback) { NRS.pageLoading(); NRS.pages[page](callback); }; NRS.goToPage = function(page, callback) { var $link = $("ul.sidebar-menu a[data-page=" + page + "]"); if ($link.length > 1) { if ($link.last().is(":visible")) { $link = $link.last(); } else { $link = $link.first(); } } if ($link.length == 1) { if (callback) { $link.trigger("click", [{ "callback": callback }]); } else { $link.trigger("click"); } } else { NRS.currentPage = page; NRS.currentSubPage = ""; NRS.pageNumber = 1; NRS.showPageNumbers = false; $("ul.sidebar-menu a.active").removeClass("active"); $(".page").hide(); $("#" + page + "_page").show(); if (NRS.pages[page]) { NRS.pageLoading(); NRS.pages[page](callback); } } }; NRS.pageLoading = function() { NRS.hasMorePages = false; var $pageHeader = $("#" + NRS.currentPage + "_page .content-header h1"); $pageHeader.find(".loading_dots").remove(); $pageHeader.append("<span class='loading_dots'><span>.</span><span>.</span><span>.</span></span>"); }; NRS.pageLoaded = function(callback) { var $currentPage = $("#" + NRS.currentPage + "_page"); $currentPage.find(".content-header h1 .loading_dots").remove(); if ($currentPage.hasClass("paginated")) { NRS.addPagination(); } if (callback) { callback(); } }; NRS.addPagination = function(section) { var firstStartNr = 1; var firstEndNr = NRS.itemsPerPage; var currentStartNr = (NRS.pageNumber-1) * NRS.itemsPerPage + 1; var currentEndNr = NRS.pageNumber * NRS.itemsPerPage; var prevHTML = '<span style="display:inline-block;width:48px;text-align:right;">'; var firstHTML = '<span style="display:inline-block;min-width:48px;text-align:right;vertical-align:top;margin-top:4px;">'; var currentHTML = '<span style="display:inline-block;min-width:48px;text-align:left;vertical-align:top;margin-top:4px;">'; var nextHTML = '<span style="display:inline-block;width:48px;text-align:left;">'; if (NRS.pageNumber > 1) { prevHTML += "<a href='#' data-page='" + (NRS.pageNumber - 1) + "' title='" + $.t("previous") + "' style='font-size:20px;'>"; prevHTML += "<i class='fa fa-arrow-circle-left'></i></a>"; } else { prevHTML += '&nbsp;'; } if (NRS.hasMorePages) { currentHTML += currentStartNr + "-" + currentEndNr + "&nbsp;"; nextHTML += "<a href='#' data-page='" + (NRS.pageNumber + 1) + "' title='" + $.t("next") + "' style='font-size:20px;'>"; nextHTML += "<i class='fa fa-arrow-circle-right'></i></a>"; } else { if (NRS.pageNumber > 1) { currentHTML += currentStartNr + "+"; } else { currentHTML += "&nbsp;"; } nextHTML += "&nbsp;"; } if (NRS.pageNumber > 1) { firstHTML += "&nbsp;<a href='#' data-page='1'>" + firstStartNr + "-" + firstEndNr + "</a>&nbsp;|&nbsp;"; } else { firstHTML += "&nbsp;"; } prevHTML += '</span>'; firstHTML += '</span>'; currentHTML += '</span>'; nextHTML += '</span>'; var output = prevHTML + firstHTML + currentHTML + nextHTML; var $paginationContainer = $("#" + NRS.currentPage + "_page .data-pagination"); if ($paginationContainer.length) { $paginationContainer.html(output); } }; $(".data-pagination").on("click", "a", function(e) { e.preventDefault(); NRS.goToPageNumber($(this).data("page")); }); NRS.goToPageNumber = function(pageNumber) { /*if (!pageLoaded) { return; }*/ NRS.pageNumber = pageNumber; NRS.pageLoading(); NRS.pages[NRS.currentPage](); }; NRS.createDatabase = function(callback) { var schema = { contacts: { id: { "primary": true, "autoincrement": true, "type": "NUMBER" }, name: "VARCHAR(100) COLLATE NOCASE", email: "VARCHAR(200)", account: "VARCHAR(25)", accountRS: "VARCHAR(25)", description: "TEXT" }, assets: { account: "VARCHAR(25)", accountRS: "VARCHAR(25)", asset: { "primary": true, "type": "VARCHAR(25)" }, description: "TEXT", name: "VARCHAR(10)", decimals: "NUMBER", quantityQNT: "VARCHAR(15)", groupName: "VARCHAR(30) COLLATE NOCASE" }, data: { id: { "primary": true, "type": "VARCHAR(40)" }, contents: "TEXT" } }; NRS.assetTableKeys = ["account", "accountRS", "asset", "description", "name", "position", "decimals", "quantityQNT", "groupName"]; try { NRS.database = new WebDB("NRS_USER_DB", schema, 2, 4, function(error, db) { if (!error) { NRS.databaseSupport = true; NRS.loadContacts(); NRS.database.select("data", [{ "id": "asset_exchange_version" }], function(error, result) { if (!result || !result.length) { NRS.database.delete("assets", [], function(error, affected) { if (!error) { NRS.database.insert("data", { "id": "asset_exchange_version", "contents": 2 }); } }); } }); NRS.database.select("data", [{ "id": "closed_groups" }], function(error, result) { if (result && result.length) { NRS.closedGroups = result[0].contents.split("#"); } else { NRS.database.insert("data", { id: "closed_groups", contents: "" }); } }); if (callback) { callback(); } } else { if (callback) { callback(); } } }); } catch (err) { NRS.database = null; NRS.databaseSupport = false; if (callback) { callback(); } } }; /* Display connected state in Sidebar */ NRS.checkConnected = function() { NRS.sendRequest("getPeers+", { "state": "CONNECTED" }, function(response) { if (response.peers && response.peers.length) { NRS.peerConnect = true; $("#connected_indicator").addClass("connected"); $("#connected_indicator span").html($.t("Connected")).attr("data-i18n", "connected"); $("#connected_indicator").show(); } else { NRS.peerConnect = false; $("#connected_indicator").removeClass("connected"); $("#connected_indicator span").html($.t("Not Connected")).attr("data-i18n", "not_connected"); $("#connected_indicator").show(); } }); }; NRS.getAccountInfo = function(firstRun, callback) { NRS.sendRequest("getAccount", { "account": NRS.account }, function(response) { var previousAccountInfo = NRS.accountInfo; NRS.accountInfo = response; if (response.errorCode) { $("#account_balance, #account_balance_sidebar, #account_nr_assets, #account_assets_balance, #account_currency_count, #account_purchase_count, #account_pending_sale_count, #account_completed_sale_count, #account_message_count, #account_alias_count").html("0"); if (NRS.accountInfo.errorCode == 5) { if (NRS.downloadingBlockchain) { if (NRS.newlyCreatedAccount) { $("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_new_account", { "account_id": String(NRS.accountRS).escapeHTML(), "public_key": String(NRS.publicKey).escapeHTML() }) + "<br /><br />" + $.t("status_blockchain_downloading")).show(); } else { $("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_blockchain_downloading")).show(); } } else if (NRS.state && NRS.state.isScanning) { $("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html($.t("status_blockchain_rescanning")).show(); } else { $("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_new_account", { "account_id": String(NRS.accountRS).escapeHTML(), "public_key": String(NRS.publicKey).escapeHTML() })).show(); } } else { $("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html(NRS.accountInfo.errorDescription ? NRS.accountInfo.errorDescription.escapeHTML() : $.t("error_unknown")).show(); } } else { if (NRS.accountRS && NRS.accountInfo.accountRS != NRS.accountRS) { $.growl("Generated Reed Solomon address different from the one in the blockchain!", { "type": "danger" }); NRS.accountRS = NRS.accountInfo.accountRS; } if (NRS.downloadingBlockchain) { $("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_blockchain_downloading")).show(); } else if (NRS.state && NRS.state.isScanning) { $("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html($.t("status_blockchain_rescanning")).show(); } else if (!NRS.accountInfo.publicKey) { $("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html($.t("no_public_key_warning") + " " + $.t("public_key_actions")).show(); } else { $("#dashboard_message").hide(); } //only show if happened within last week var showAssetDifference = (!NRS.downloadingBlockchain || (NRS.blocks && NRS.blocks[0] && NRS.state && NRS.state.time - NRS.blocks[0].timestamp < 60 * 60 * 24 * 7)); if (NRS.databaseSupport) { NRS.database.select("data", [{ "id": "asset_balances_" + NRS.account }], function(error, asset_balance) { if (asset_balance && asset_balance.length) { var previous_balances = asset_balance[0].contents; if (!NRS.accountInfo.assetBalances) { NRS.accountInfo.assetBalances = []; } var current_balances = JSON.stringify(NRS.accountInfo.assetBalances); if (previous_balances != current_balances) { if (previous_balances != "undefined" && typeof previous_balances != "undefined") { previous_balances = JSON.parse(previous_balances); } else { previous_balances = []; } NRS.database.update("data", { contents: current_balances }, [{ id: "asset_balances_" + NRS.account }]); if (showAssetDifference) { NRS.checkAssetDifferences(NRS.accountInfo.assetBalances, previous_balances); } } } else { NRS.database.insert("data", { id: "asset_balances_" + NRS.account, contents: JSON.stringify(NRS.accountInfo.assetBalances) }); } }); } else if (showAssetDifference && previousAccountInfo && previousAccountInfo.assetBalances) { var previousBalances = JSON.stringify(previousAccountInfo.assetBalances); var currentBalances = JSON.stringify(NRS.accountInfo.assetBalances); if (previousBalances != currentBalances) { NRS.checkAssetDifferences(NRS.accountInfo.assetBalances, previousAccountInfo.assetBalances); } } $("#account_balance, #account_balance_sidebar").html(NRS.formatStyledAmount(response.unconfirmedBalanceNQT)); $("#account_forged_balance").html(NRS.formatStyledAmount(response.forgedBalanceNQT)); /*** Need to clean up and optimize code if possible ***/ var nr_assets = 0; var assets = { "asset": [], "quantity": {}, "trades": {} }; var tradeNum = 0; var assets_LastTrade = []; if (response.assetBalances) { for (var i = 0; i < response.assetBalances.length; i++) { if (response.assetBalances[i].balanceQNT != "0") { nr_assets++; assets.quantity[response.assetBalances[i].asset] = response.assetBalances[i].balanceQNT; assets.asset.push(response.assetBalances[i].asset); NRS.sendRequest("getTrades", { "asset": response.assetBalances[i].asset, "firstIndex": 0, "lastIndex": 0 }, function(responseTrade, input) { if (responseTrade.trades && responseTrade.trades.length) { assets.trades[input.asset] = responseTrade.trades[0].priceNQT/100000000; } else{ assets.trades[input.asset] = 0; } if (tradeNum == nr_assets-1) NRS.updateAssetsValue(assets); else tradeNum++; }); } } } else { $("#account_assets_balance").html(0); } $("#account_nr_assets").html(nr_assets); if (NRS.accountInfo.accountCurrencies && NRS.accountInfo.accountCurrencies.length) { $("#account_currency_count").empty().append(NRS.accountInfo.accountCurrencies.length); } else { $("#account_currency_count").empty().append("0"); } /* Display message count in top and limit to 100 for now because of possible performance issues*/ NRS.sendRequest("getAccountTransactions+", { "account": NRS.account, "type": 1, "subtype": 0, "firstIndex": 0, "lastIndex": 99 }, function(response) { if (response.transactions && response.transactions.length) { if (response.transactions.length > 99) $("#account_message_count").empty().append("99+"); else $("#account_message_count").empty().append(response.transactions.length); } else { $("#account_message_count").empty().append("0"); } }); /*** ****************** ***/ NRS.sendRequest("getAliasCount+", { "account":NRS.account }, function(response) { if (response.numberOfAliases != null) { $("#account_alias_count").empty().append(response.numberOfAliases); } }); NRS.sendRequest("getDGSPurchaseCount+", { "buyer": NRS.account }, function(response) { if (response.numberOfPurchases != null) { $("#account_purchase_count").empty().append(response.numberOfPurchases); } }); NRS.sendRequest("getDGSPendingPurchases+", { "seller": NRS.account }, function(response) { if (response.purchases && response.purchases.length) { $("#account_pending_sale_count").empty().append(response.purchases.length); } else { $("#account_pending_sale_count").empty().append("0"); } }); NRS.sendRequest("getDGSPurchaseCount+", { "seller": NRS.account, "completed": true }, function(response) { if (response.numberOfPurchases != null) { $("#account_completed_sale_count").empty().append(response.numberOfPurchases); } }); if (NRS.lastBlockHeight) { var isLeased = NRS.lastBlockHeight >= NRS.accountInfo.currentLeasingHeightFrom; if (isLeased != NRS.IsLeased) { var leasingChange = true; NRS.isLeased = isLeased; } } else { var leasingChange = false; } if (leasingChange || (response.currentLeasingHeightFrom != previousAccountInfo.currentLeasingHeightFrom) || (response.lessors && !previousAccountInfo.lessors) || (!response.lessors && previousAccountInfo.lessors) || (response.lessors && previousAccountInfo.lessors && response.lessors.sort().toString() != previousAccountInfo.lessors.sort().toString())) { NRS.updateAccountLeasingStatus(); } if (response.name) { $("#account_name").html(response.name.escapeHTML()).removeAttr("data-i18n"); } } if (firstRun) { $("#account_balance, #account_balance_sidebar, #account_assets_balance, #account_nr_assets, #account_currency_count, #account_purchase_count, #account_pending_sale_count, #account_completed_sale_count, #account_message_count, #account_alias_count").removeClass("loading_dots"); } if (callback) { callback(); } }); }; NRS.updateAssetsValue = function(assets) { var assetTotal = 0; for (var i = 0; i < assets.asset.length; i++) { if (assets.quantity[assets.asset[i]] && assets.trades[assets.asset[i]]) assetTotal += assets.quantity[assets.asset[i]]*assets.trades[assets.asset[i]]; } $("#account_assets_balance").html(NRS.formatStyledAmount(new Big(assetTotal).toFixed(8))); }; NRS.updateAccountLeasingStatus = function() { var accountLeasingLabel = ""; var accountLeasingStatus = ""; var nextLesseeStatus = ""; if (NRS.accountInfo.nextLeasingHeightFrom < 2147483647) { nextLesseeStatus = $.t("next_lessee_status", { "start": String(NRS.accountInfo.nextLeasingHeightFrom).escapeHTML(), "end": String(NRS.accountInfo.nextLeasingHeightTo).escapeHTML(), "account": String(NRS.convertNumericToRSAccountFormat(NRS.accountInfo.nextLessee)).escapeHTML() }) } if (NRS.lastBlockHeight >= NRS.accountInfo.currentLeasingHeightFrom) { accountLeasingLabel = $.t("leased_out"); accountLeasingStatus = $.t("balance_is_leased_out", { "blocks": String(NRS.accountInfo.currentLeasingHeightTo - NRS.lastBlockHeight).escapeHTML(), "end": String(NRS.accountInfo.currentLeasingHeightTo).escapeHTML(), "account": String(NRS.accountInfo.currentLesseeRS).escapeHTML() }); $("#lease_balance_message").html($.t("balance_leased_out_help")); } else if (NRS.lastBlockHeight < NRS.accountInfo.currentLeasingHeightTo) { accountLeasingLabel = $.t("leased_soon"); accountLeasingStatus = $.t("balance_will_be_leased_out", { "blocks": String(NRS.accountInfo.currentLeasingHeightFrom - NRS.lastBlockHeight).escapeHTML(), "start": String(NRS.accountInfo.currentLeasingHeightFrom).escapeHTML(), "end": String(NRS.accountInfo.currentLeasingHeightTo).escapeHTML(), "account": String(NRS.accountInfo.currentLesseeRS).escapeHTML() }); $("#lease_balance_message").html($.t("balance_leased_out_help")); } else { accountLeasingStatus = $.t("balance_not_leased_out"); $("#lease_balance_message").html($.t("balance_leasing_help")); } if (nextLesseeStatus != "") { accountLeasingStatus += "<br>" + nextLesseeStatus; } if (NRS.accountInfo.effectiveBalanceNXT == 0) { $("#forging_indicator").removeClass("forging"); $("#forging_indicator span").html($.t("not_forging")).attr("data-i18n", "not_forging"); $("#forging_indicator").show(); NRS.isForging = false; } //no reed solomon available? do it myself? todo if (NRS.accountInfo.lessors) { if (accountLeasingLabel) { accountLeasingLabel += ", "; accountLeasingStatus += "<br /><br />"; } accountLeasingLabel += $.t("x_lessor", { "count": NRS.accountInfo.lessors.length }); accountLeasingStatus += $.t("x_lessor_lease", { "count": NRS.accountInfo.lessors.length }); var rows = ""; for (var i = 0; i < NRS.accountInfo.lessorsRS.length; i++) { var lessor = NRS.accountInfo.lessorsRS[i]; var lessorInfo = NRS.accountInfo.lessorsInfo[i]; var blocksLeft = lessorInfo.currentHeightTo - NRS.lastBlockHeight; var blocksLeftTooltip = "From block " + lessorInfo.currentHeightFrom + " to block " + lessorInfo.currentHeightTo; var nextLessee = "Not set"; var nextTooltip = "Next lessee not set"; if (lessorInfo.nextLesseeRS == NRS.accountRS) { nextLessee = "You"; nextTooltip = "From block " + lessorInfo.nextHeightFrom + " to block " + lessorInfo.nextHeightTo; } else if (lessorInfo.nextHeightFrom < 2147483647) { nextLessee = "Not you"; nextTooltip = "Account " + NRS.getAccountTitle(lessorInfo.nextLesseeRS) +" from block " + lessorInfo.nextHeightFrom + " to block " + lessorInfo.nextHeightTo; } rows += "<tr>" + "<td><a href='#' data-user='" + String(lessor).escapeHTML() + "'>" + NRS.getAccountTitle(lessor) + "</a></td>" + "<td>" + String(lessorInfo.effectiveBalanceNXT).escapeHTML() + "</td>" + "<td><label>" + String(blocksLeft).escapeHTML() + " <i class='fa fa-question-circle show_popover' data-toggle='tooltip' title='" + blocksLeftTooltip + "' data-placement='right' style='color:#4CAA6E'></i></label></td>" + "<td><label>" + String(nextLessee).escapeHTML() + " <i class='fa fa-question-circle show_popover' data-toggle='tooltip' title='" + nextTooltip + "' data-placement='right' style='color:#4CAA6E'></i></label></td>" + "</tr>"; } $("#account_lessor_table tbody").empty().append(rows); $("#account_lessor_container").show(); $("#account_lessor_table [data-toggle='tooltip']").tooltip(); } else { $("#account_lessor_table tbody").empty(); $("#account_lessor_container").hide(); } if (accountLeasingLabel) { $("#account_leasing").html(accountLeasingLabel).show(); } else { $("#account_leasing").hide(); } if (accountLeasingStatus) { $("#account_leasing_status").html(accountLeasingStatus).show(); } else { $("#account_leasing_status").hide(); } }; NRS.checkAssetDifferences = function(current_balances, previous_balances) { var current_balances_ = {}; var previous_balances_ = {}; if (previous_balances.length) { for (var k in previous_balances) { previous_balances_[previous_balances[k].asset] = previous_balances[k].balanceQNT; } } if (current_balances.length) { for (var k in current_balances) { current_balances_[current_balances[k].asset] = current_balances[k].balanceQNT; } } var diff = {}; for (var k in previous_balances_) { if (!(k in current_balances_)) { diff[k] = "-" + previous_balances_[k]; } else if (previous_balances_[k] !== current_balances_[k]) { var change = (new BigInteger(current_balances_[k]).subtract(new BigInteger(previous_balances_[k]))).toString(); diff[k] = change; } } for (k in current_balances_) { if (!(k in previous_balances_)) { diff[k] = current_balances_[k]; // property is new } } var nr = Object.keys(diff).length; if (nr == 0) { return; } else if (nr <= 3) { for (k in diff) { NRS.sendRequest("getAsset", { "asset": k, "_extra": { "asset": k, "difference": diff[k] } }, function(asset, input) { if (asset.errorCode) { return; } asset.difference = input["_extra"].difference; asset.asset = input["_extra"].asset; if (asset.difference.charAt(0) != "-") { var quantity = NRS.formatQuantity(asset.difference, asset.decimals) if (quantity != "0") { $.growl($.t("you_received_assets", { "asset": String(asset.asset).escapeHTML(), "name": String(asset.name).escapeHTML(), "count": quantity }), { "type": "success" }); NRS.loadAssetExchangeSidebar(); } } else { asset.difference = asset.difference.substring(1); var quantity = NRS.formatQuantity(asset.difference, asset.decimals) if (quantity != "0") { $.growl($.t("you_sold_assets", { "asset": String(asset.asset).escapeHTML(), "name": String(asset.name).escapeHTML(), "count": quantity }), { "type": "success" }); NRS.loadAssetExchangeSidebar(); } } }); } } else { $.growl($.t("multiple_assets_differences"), { "type": "success" }); } }; NRS.checkLocationHash = function(password) { if (window.location.hash) { var hash = window.location.hash.replace("#", "").split(":") if (hash.length == 2) { if (hash[0] == "message") { var $modal = $("#send_message_modal"); } else if (hash[0] == "send") { var $modal = $("#send_money_modal"); } else if (hash[0] == "asset") { NRS.goToAsset(hash[1]); return; } else { var $modal = ""; } if ($modal) { var account_id = String($.trim(hash[1])); if (!/^\d+$/.test(account_id) && account_id.indexOf("@") !== 0) { account_id = "@" + account_id; } $modal.find("input[name=recipient]").val(account_id.unescapeHTML()).trigger("blur"); if (password && typeof password == "string") { $modal.find("input[name=secretPhrase]").val(password); } $modal.modal("show"); } } window.location.hash = "#"; } }; NRS.updateBlockchainDownloadProgress = function() { var lastNumBlocks = 5000; $('#downloading_blockchain .last_num_blocks').html($.t('last_num_blocks', { "blocks": lastNumBlocks })); if (!NRS.serverConnect || !NRS.peerConnect) { $("#downloading_blockchain .db_active").hide(); $("#downloading_blockchain .db_halted").show(); } else { $("#downloading_blockchain .db_halted").hide(); $("#downloading_blockchain .db_active").show(); var percentageTotal = 0; var blocksLeft = undefined; var percentageLast = 0; if (NRS.state.lastBlockchainFeederHeight && NRS.state.numberOfBlocks <= NRS.state.lastBlockchainFeederHeight) { percentageTotal = parseInt(Math.round((NRS.state.numberOfBlocks / NRS.state.lastBlockchainFeederHeight) * 100), 10); blocksLeft = NRS.state.lastBlockchainFeederHeight - NRS.state.numberOfBlocks; if (blocksLeft <= lastNumBlocks && NRS.state.lastBlockchainFeederHeight > lastNumBlocks) { percentageLast = parseInt(Math.round(((lastNumBlocks - blocksLeft) / lastNumBlocks) * 100), 10); } } if (!blocksLeft || blocksLeft < parseInt(lastNumBlocks / 2)) { $("#downloading_blockchain .db_progress_total").hide(); } else { $("#downloading_blockchain .db_progress_total").show(); $("#downloading_blockchain .db_progress_total .progress-bar").css("width", percentageTotal + "%"); $("#downloading_blockchain .db_progress_total .sr-only").html($.t("percent_complete", { "percent": percentageTotal })); } if (!blocksLeft || blocksLeft >= (lastNumBlocks * 2) || NRS.state.lastBlockchainFeederHeight <= lastNumBlocks) { $("#downloading_blockchain .db_progress_last").hide(); } else { $("#downloading_blockchain .db_progress_last").show(); $("#downloading_blockchain .db_progress_last .progress-bar").css("width", percentageLast + "%"); $("#downloading_blockchain .db_progress_last .sr-only").html($.t("percent_complete", { "percent": percentageLast })); } if (blocksLeft) { $("#downloading_blockchain .blocks_left_outer").show(); $("#downloading_blockchain .blocks_left").html($.t("blocks_left", { "numBlocks": blocksLeft })); } } }; NRS.checkIfOnAFork = function() { if (!NRS.downloadingBlockchain) { var onAFork = true; if (NRS.blocks && NRS.blocks.length >= 10) { for (var i = 0; i < 10; i++) { if (NRS.blocks[i].generator != NRS.account) { onAFork = false; break; } } } else { onAFork = false; } if (onAFork) { $.growl($.t("fork_warning"), { "type": "danger" }); } } }; $("#id_search").on("submit", function(e) { e.preventDefault(); var id = $.trim($("#id_search input[name=q]").val()); if (/NXT\-/i.test(id)) { NRS.sendRequest("getAccount", { "account": id }, function(response, input) { if (!response.errorCode) { response.account = input.account; NRS.showAccountModal(response); } else { $.growl($.t("error_search_no_results"), { "type": "danger" }); } }); } else { if (!/^\d+$/.test(id)) { $.growl($.t("error_search_invalid"), { "type": "danger" }); return; } NRS.sendRequest("getTransaction", { "transaction": id }, function(response, input) { if (!response.errorCode) { response.transaction = input.transaction; NRS.showTransactionModal(response); } else { NRS.sendRequest("getAccount", { "account": id }, function(response, input) { if (!response.errorCode) { response.account = input.account; NRS.showAccountModal(response); } else { NRS.sendRequest("getBlock", { "block": id }, function(response, input) { if (!response.errorCode) { response.block = input.block; NRS.showBlockModal(response); } else { $.growl($.t("error_search_no_results"), { "type": "danger" }); } }); } }); } }); } }); return NRS; }(NRS || {}, jQuery)); $(document).ready(function() { NRS.init(); }); function receiveMessage(event) { if (event.origin != "file://") { return; } //parent.postMessage("from iframe", "file://"); } function _checkDOMenabled() { var storage; var fail; var uid; try { uid = new Date; (storage = window.localStorage).setItem(uid, uid); fail = storage.getItem(uid) != uid; storage.removeItem(uid); fail && (storage = false); } catch (exception) {} return storage; }
const styles = { container: { minHeight: '100vh', backgroundColor: 'white' }, header: { textAlign: 'right', justifyContent: 'space-between', borderBottomWidth: 'thin', borderBottomStyle: 'solid', borderColor: '#8b9dc3', padding: '2vh 4vh' }, logoGithub: { width: '4vh', height: '4vh' }, content: { minHeight: '80vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }, description: { margin: '2vh 0 8vh 0', textAlign: 'center', fontSize: '20pt', fontWeight: 'lighter' }, loginBtn: { cursor: 'pointer', width: '30vh' }, }; export default styles;
angular.module('app').factory('Recipe', ['$q', 'MealPlan', 'Marklogic', 'Utilities', function ($q, MealPlan, Marklogic, Utilities) { function initSearch(options) { var deferred = $q.defer(); //Create Additional Query var additionalQuery = ""; additionalQuery += "<cts:and-query xmlns:cts='http://marklogic.com/cts'>"; additionalQuery += "<cts:directory-query xmlns:cts='http://marklogic.com/cts'><cts:uri>/recipes/</cts:uri></cts:directory-query>"; if (options.archived) { additionalQuery += "<cts:element-range-query operator='=' xmlns:cts='http://marklogic.com/cts'><cts:element xmlns:json='http://marklogic.com/xdmp/json/basic'>json:archived</cts:element><cts:value xsi:type='xs:string' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>true</cts:value></cts:element-range-query>"; } else { additionalQuery += "<cts:not-query xmlns:cts='http://marklogic.com/cts'><cts:element-range-query operator='='><cts:element xmlns:json='http://marklogic.com/xdmp/json/basic'>json:archived</cts:element><cts:value xsi:type='xs:string' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>true</cts:value></cts:element-range-query></cts:not-query>"; } additionalQuery += "</cts:and-query>"; var marklogicSearchOptions = { "additional-query": [additionalQuery], "constraint": [ { "name": 'rating', "range": { "type": "xs:int", "json-key": "rating", "facet": true } }, { "name": 'category', "range": { "type": "xs:string", "json-key": "category", "facet": true } } ], "page-length": 999999, "return-facets": true, "return-results": true, "term": { "empty": { "apply": "all-results" } }, "transform-results": { "apply": "raw" } }; if (options.sortorder && options.direction) { if (options.direction !== 'ascending' && options.direction !== 'descending') { options.direction = 'descending'; } switch (options.sortorder) { case 'random': //randomized later break; case 'created': marklogicSearchOptions['sort-order'] = { 'json-key': 'created', 'direction': options.direction }; break; case 'updated': marklogicSearchOptions['sort-order'] = { 'json-key': 'updated', 'direction': options.direction }; break; case 'score': marklogicSearchOptions['sort-order'] = { 'score': null, 'direction': options.direction }; break; } } if (jQuery.isNumeric(options.pageLength)) { marklogicSearchOptions['page-length'] = options.pageLength; } Marklogic.callMarklogic('PUT', 'config/query/default', {}, { "options": marklogicSearchOptions }, function () { deferred.resolve(); }, function () { deferred.resolve(); }); return deferred.promise; } function search(query, params, successCallback, errorCallback) { if (!query) { query = ''; } else { query = '*' + query + '*'; } if (params.rating) { query += ' rating:' + params.rating; } if (angular.isObject(params.categories)) { angular.forEach(params.categories, function (value, key) { if (value) { query += ' category:"' + key + '"'; } }); } initSearch(params).then(function () { Marklogic.callMarklogic('GET', 'search', { 'q': query }, {}, successCallback, errorCallback); }); } function initCategories(options) { var deferred = $q.defer(); Marklogic.callMarklogic('PUT', 'config/query/categories', {}, { "options": { "sort-order": [ { "direction": "ascending", "json-key": "category", "score": null } ], "values": [ { "name": "category", "range": { "type": "xs:string", "json-key": "category" } } ] } }, function () { deferred.resolve(); }, function () { deferred.resolve(); }); return deferred.promise; } function getCategories(query, params, successCallback, errorCallback) { if (!query) { query = ''; } else { query = '*' + query + '*'; } initCategories(params).then(function () { Marklogic.callMarklogic('GET', 'values/category', { 'q': query, 'options': 'categories' }, {}, successCallback, errorCallback); }); } function getRecipe(id, successCallback, errorCallback) { Marklogic.callMarklogic('GET', 'documents', { 'uri': '/recipes/' + id + '.json' }, {}, successCallback, errorCallback); } //save Recipe function saveRecipe(recipe, successCallback, errorCallback) { //Make sure created is set if (!recipe.created) { try { recipe.created = new Date().toISOString(); } catch (e1) { console.log('Error:created'); } } //Update updated try { recipe.updated = new Date().toISOString(); } catch (e2) { console.log('Error:updated'); } //Make sure instructions is set if (!recipe.instructions) { recipe.instructions = ""; } //get list of images recipe.images = jQuery(recipe.instructions).find('img[src]').map(function () { return $(this).attr("src"); }).get(); //insert uploaded image first if (recipe.image) { if (!recipe.images) { recipe.images = []; } recipe.images.unshift(recipe.image); } //get text to show in search result recipe.text = jQuery(recipe.instructions).text(); //Remove duplicates and empty values from categories recipe.categories = Utilities.cleanArray(recipe.categories, 'category'); //make sure recipe has number of times viewed if (!recipe.view) { recipe.view = 1; } //make sure recipe has an id if (!recipe.id) { recipe.id = getUUID(); } //Make sure recipe is wrapped recipe = { recipe: recipe }; Marklogic.callMarklogic('PUT', 'documents', { 'uri': '/recipes/' + recipe.recipe.id + '.json' }, recipe, successCallback, errorCallback); } function deleteRecipe(id, successCallback, errorCallback) { MealPlan.removeMealPlan(id, function () { Marklogic.callMarklogic('DELETE', 'documents', { 'uri': '/recipes/' + id + '.json' }, {}, successCallback, errorCallback); }, errorCallback); } function getUUID() { return uuid.v4().replace(/-/g, ''); } return { 'search': search, 'get': getRecipe, 'save': saveRecipe, 'delete': deleteRecipe, 'uuid': getUUID, 'getCategories': getCategories }; }]);
import type NodePath from "./index"; // This file contains Babels metainterpreter that can evaluate static code. const VALID_CALLEES = ["String", "Number", "Math"]; const INVALID_METHODS = ["random"]; /** * Walk the input `node` and statically evaluate if it's truthy. * * Returning `true` when we're sure that the expression will evaluate to a * truthy value, `false` if we're sure that it will evaluate to a falsy * value and `undefined` if we aren't sure. Because of this please do not * rely on coercion when using this method and check with === if it's false. * * For example do: * * if (t.evaluateTruthy(node) === false) falsyLogic(); * * **AND NOT** * * if (!t.evaluateTruthy(node)) falsyLogic(); * */ export function evaluateTruthy(): boolean { const res = this.evaluate(); if (res.confident) return !!res.value; } /** * Deopts the evaluation */ function deopt(path, state) { if (!state.confident) return; state.deoptPath = path; state.confident = false; } /** * We wrap the _evaluate method so we can track `seen` nodes, we push an item * to the map before we actually evaluate it so we can deopt on self recursive * nodes such as: * * var g = a ? 1 : 2, * a = g * this.foo */ function evaluateCached(path, state) { const { node } = path; const { seen } = state; if (seen.has(node)) { const existing = seen.get(node); if (existing.resolved) { return existing.value; } else { deopt(path, state); return; } } else { const item = { resolved: false }; seen.set(node, item); const val = _evaluate(path, state); if (state.confident) { item.resolved = true; item.value = val; } return val; } } function _evaluate(path, state) { if (!state.confident) return; const { node } = path; if (path.isSequenceExpression()) { const exprs = path.get("expressions"); return evaluateCached(exprs[exprs.length - 1], state); } if ( path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral() ) { return node.value; } if (path.isNullLiteral()) { return null; } if (path.isTemplateLiteral()) { return evaluateQuasis(path, node.quasis, state); } if ( path.isTaggedTemplateExpression() && path.get("tag").isMemberExpression() ) { const object = path.get("tag.object"); const { node: { name }, } = object; const property = path.get("tag.property"); if ( object.isIdentifier() && name === "String" && !path.scope.getBinding(name, true) && property.isIdentifier && property.node.name === "raw" ) { return evaluateQuasis(path, node.quasi.quasis, state, true); } } if (path.isConditionalExpression()) { const testResult = evaluateCached(path.get("test"), state); if (!state.confident) return; if (testResult) { return evaluateCached(path.get("consequent"), state); } else { return evaluateCached(path.get("alternate"), state); } } if (path.isExpressionWrapper()) { // TypeCastExpression, ExpressionStatement etc return evaluateCached(path.get("expression"), state); } // "foo".length if ( path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: node }) ) { const property = path.get("property"); const object = path.get("object"); if (object.isLiteral() && property.isIdentifier()) { const value = object.node.value; const type = typeof value; if (type === "number" || type === "string") { return value[property.node.name]; } } } if (path.isReferencedIdentifier()) { const binding = path.scope.getBinding(node.name); if (binding && binding.constantViolations.length > 0) { return deopt(binding.path, state); } if (binding && path.node.start < binding.path.node.end) { return deopt(binding.path, state); } if (binding?.hasValue) { return binding.value; } else { if (node.name === "undefined") { return binding ? deopt(binding.path, state) : undefined; } else if (node.name === "Infinity") { return binding ? deopt(binding.path, state) : Infinity; } else if (node.name === "NaN") { return binding ? deopt(binding.path, state) : NaN; } const resolved = path.resolve(); if (resolved === path) { return deopt(path, state); } else { return evaluateCached(resolved, state); } } } if (path.isUnaryExpression({ prefix: true })) { if (node.operator === "void") { // we don't need to evaluate the argument to know what this will return return undefined; } const argument = path.get("argument"); if ( node.operator === "typeof" && (argument.isFunction() || argument.isClass()) ) { return "function"; } const arg = evaluateCached(argument, state); if (!state.confident) return; switch (node.operator) { case "!": return !arg; case "+": return +arg; case "-": return -arg; case "~": return ~arg; case "typeof": return typeof arg; } } if (path.isArrayExpression()) { const arr = []; const elems: Array<NodePath> = path.get("elements"); for (const elem of elems) { const elemValue = elem.evaluate(); if (elemValue.confident) { arr.push(elemValue.value); } else { return deopt(elemValue.deopt, state); } } return arr; } if (path.isObjectExpression()) { const obj = {}; const props: Array<NodePath> = path.get("properties"); for (const prop of props) { if (prop.isObjectMethod() || prop.isSpreadElement()) { return deopt(prop, state); } const keyPath = prop.get("key"); let key = keyPath; if (prop.node.computed) { key = key.evaluate(); if (!key.confident) { return deopt(key.deopt, state); } key = key.value; } else if (key.isIdentifier()) { key = key.node.name; } else { key = key.node.value; } const valuePath = prop.get("value"); let value = valuePath.evaluate(); if (!value.confident) { return deopt(value.deopt, state); } value = value.value; obj[key] = value; } return obj; } if (path.isLogicalExpression()) { // If we are confident that the left side of an && is false, or the left // side of an || is true, we can be confident about the entire expression const wasConfident = state.confident; const left = evaluateCached(path.get("left"), state); const leftConfident = state.confident; state.confident = wasConfident; const right = evaluateCached(path.get("right"), state); const rightConfident = state.confident; switch (node.operator) { case "||": // TODO consider having a "truthy type" that doesn't bail on // left uncertainty but can still evaluate to truthy. state.confident = leftConfident && (!!left || rightConfident); if (!state.confident) return; return left || right; case "&&": state.confident = leftConfident && (!left || rightConfident); if (!state.confident) return; return left && right; } } if (path.isBinaryExpression()) { const left = evaluateCached(path.get("left"), state); if (!state.confident) return; const right = evaluateCached(path.get("right"), state); if (!state.confident) return; switch (node.operator) { case "-": return left - right; case "+": return left + right; case "/": return left / right; case "*": return left * right; case "%": return left % right; case "**": return left ** right; case "<": return left < right; case ">": return left > right; case "<=": return left <= right; case ">=": return left >= right; case "==": return left == right; // eslint-disable-line eqeqeq case "!=": return left != right; case "===": return left === right; case "!==": return left !== right; case "|": return left | right; case "&": return left & right; case "^": return left ^ right; case "<<": return left << right; case ">>": return left >> right; case ">>>": return left >>> right; } } if (path.isCallExpression()) { const callee = path.get("callee"); let context; let func; // Number(1); if ( callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0 ) { func = global[node.callee.name]; } if (callee.isMemberExpression()) { const object = callee.get("object"); const property = callee.get("property"); // Math.min(1, 2) if ( object.isIdentifier() && property.isIdentifier() && VALID_CALLEES.indexOf(object.node.name) >= 0 && INVALID_METHODS.indexOf(property.node.name) < 0 ) { context = global[object.node.name]; func = context[property.node.name]; } // "abc".charCodeAt(4) if (object.isLiteral() && property.isIdentifier()) { const type = typeof object.node.value; if (type === "string" || type === "number") { context = object.node.value; func = context[property.node.name]; } } } if (func) { const args = path.get("arguments").map(arg => evaluateCached(arg, state)); if (!state.confident) return; return func.apply(context, args); } } deopt(path, state); } function evaluateQuasis(path, quasis: Array<Object>, state, raw = false) { let str = ""; let i = 0; const exprs = path.get("expressions"); for (const elem of quasis) { // not confident, evaluated an expression we don't like if (!state.confident) break; // add on element str += raw ? elem.value.raw : elem.value.cooked; // add on interpolated expression if it's present const expr = exprs[i++]; if (expr) str += String(evaluateCached(expr, state)); } if (!state.confident) return; return str; } /** * Walk the input `node` and statically evaluate it. * * Returns an object in the form `{ confident, value, deopt }`. `confident` * indicates whether or not we had to drop out of evaluating the expression * because of hitting an unknown node that we couldn't confidently find the * value of, in which case `deopt` is the path of said node. * * Example: * * t.evaluate(parse("5 + 5")) // { confident: true, value: 10 } * t.evaluate(parse("!true")) // { confident: true, value: false } * t.evaluate(parse("foo + foo")) // { confident: false, value: undefined, deopt: NodePath } * */ export function evaluate(): { confident: boolean, value: any, deopt?: NodePath, } { const state = { confident: true, deoptPath: null, seen: new Map(), }; let value = evaluateCached(this, state); if (!state.confident) value = undefined; return { confident: state.confident, deopt: state.deoptPath, value: value, }; }
require(['common', 'layui', 'tools', 'ajaxurl', 'layers', 'page', 'moment', 'jquery.metisMenu'], function (common, layui, tools, ajaxurl, layers, page, moment) { var main = { form: '', /** * 初始化全局树形菜单 */ sideMenu: function (callback) { Vue.nextTick(function () { $('#org-framework').metisMenu(); typeof callback === 'function' && callback.call(this); }) }, /** * 搜索框: 手机/姓名 */ createForm: function () { var that = this; layui.use(['form'], function () { var form = layui.form; //搜索 关键字 form.on('submit(formSearch)', function (data) { vm.keywords = $.trim(data.field.keywords); vm.keywordsName = $.trim(data.field.keywordsName); // 其中之一有值时搜索 if (vm.keywords || vm.keywordsName) { that.getCountAll(); that.getCallRecordAll(); } return false; }); that.form = form; }); }, /** * 获取所有记录列表数据 */ getCallRecordAll: function (cur_page, callback) { var loadingIndex; tools.ajax({ url: ajaxurl.ivr.getCallRecordAll, type: 'post', data: { callType: vm.callType, //呼出:只能传1 talked: vm.talked, //接通:只能传3 employee_and_dep: vm.employeeAndDep, //员工/部门,传员工的id,逗号分隔 start_date: vm.filterTime[0], //筛选时间/统计时间 end_date: vm.filterTime[1], //筛选时间/统计时间 callime_start: vm.filterTimeLong[0], //筛选时间/通话时长 callime_end: vm.filterTimeLong[1], //筛选时间/通话时长 phone_num: vm.keywords, //搜索手机号 customer_name: vm.keywordsName, //搜索姓名 page_size: vm.page_limit, cur_page: cur_page || 1, //分页参数 searchFlag: 1,// 1所有记录 2绑定记录 3我的记录 order: vm.order, asc: vm.asc }, beforeSend: function () { layers.load(function (index) { loadingIndex = index; }); }, success: function (result) { if (result.code == 1) { if (result.data.list != undefined) { vm.callRecord = result.data.list; vm.total_page = result.data.total_page; //vm.total_num = result.data.total_number; //Math.ceil(result.data.total_number / vm.page_limit) typeof callback === 'function' && callback.call(this); } } else { layers.toast(result.message); } }, complete: function () { setTimeout(function () { layers.closed(loadingIndex); }, 50); } }) }, /** * 获取所以后记录总条数 */ getCountAll: function (callback) { var _this = this; tools.ajax({ url: ajaxurl.ivr.getCallRecordAllCount, type: 'post', data: { callType: vm.callType, //呼出:只能传1 talked: vm.talked, //接通:只能传3 employee_and_dep: vm.employeeAndDep, //员工/部门,传员工的id,逗号分隔 start_date: vm.filterTime[0], //筛选时间/统计时间 end_date: vm.filterTime[1], //筛选时间/统计时间 callime_start: vm.filterTimeLong[0], //筛选时间/通话时长 callime_end: vm.filterTimeLong[1], //筛选时间/通话时长 phone_num: vm.keywords, //搜索手机号 customer_name: vm.keywordsName, //搜索姓名 page_size: vm.page_limit, searchFlag: 1// 1所有记录 2绑定记录 3我的记录s }, success: function (res) { if (res.code === 1) { vm.total_num = res.data; _this.pages(); typeof callback === 'function' && callback.call(this); } else { layers.toast(res.message); } } }) }, /** * 获取组织结构 */ getdepartment: function () { var that = this; tools.ajax({ url: ajaxurl.department.getdepartment, data: {}, type: 'post', success: function (result) { if (result.code == 1) { // var lens = result.data.length; // if(lens){ // for(var i = 0; i < lens; i++){ // if(result.data[i].active == undefined){ // result.data[i].active = false; // } // } // } vm.epartment = result.data; that.sideMenu(function () { that.filterOrgSearch(); }); } else { layers.toast(result.message); } } }) }, /** * 数组对象简单去重 对 id 去重, 名字可以有重复 */ unique: function (arr) { var result = {}; var finalResult = []; for (var i = 0; i < arr.length; i++) { result[arr[i].id] = arr[i]; } for (var item in result) { finalResult.push(result[item]); } return finalResult; }, /** * 返回时间段, 返回 {Array}: 今天/昨天/最近7天/最近30天 */ timeArea: function () { return { today: [moment().format('YYYY-MM-DD')], yesterday: [moment().subtract(1, 'days').format('YYYY-MM-DD')], recent7day: [moment().subtract(6, 'days').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')], recent30day: [moment().subtract(29, 'days').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')] }; }, /** * 渲染筛选条件--自定义时间选择器 */ renderLayDate: function () { layui.use('laydate', function () { var laydate = layui.laydate; laydate.render({ elem: '.lay-date-a', done: function (value) { vm.inputTimeA = value; } }); laydate.render({ elem: '.lay-date-b', done: function (value) { vm.inputTimeB = value; } }) }); }, /** * 处理分页 */ pages: function () { var that = this; if (page) { page.init({ elem: 'callpages', count: vm.total_num, limit: vm.page_limit, jump: function (obj, flag) { if (!flag) { //vm.curPage = obj.curr; that.getCallRecordAll(obj.curr); $('.main-wrap').animate({scrollTop: 0}, 200); } } }) } }, /** * 筛选--组织架构搜索 */ filterOrgSearch: function () { Vue.nextTick(function () { var $item = $('#org-framework').find('a').not('.has-arrow'); $item.each(function () { var newItem = {id: $(this).data('id'), name: $(this).data('text')}; vm.OrgSearchArr.push(newItem); }); }); this.form.on('select(search-org)', function (data) { var addItem = {id: data.value.split(',')[0] * 1, name: data.value.split(',')[1]}; vm.selectedOrgUsr.push(addItem); vm.selectedOrgUsr = main.unique(vm.selectedOrgUsr).reverse(); }); //this.form.render(); // layui.use(['form'], function () { // var form = layui.form; // form.on('select(search-org)', function (data) { // var addItem = {id: data.value.split(',')[0] * 1, name: data.value.split(',')[1]}; // vm.selectedOrgUsr.push(addItem); // vm.selectedOrgUsr = main.unique(vm.selectedOrgUsr).reverse(); // }); // form.render(); // }); } }; /** * 实例化 ViewModel */ var vm = new Vue({ el: '#app', data: { states: [ {name: '不限', id: '', active: true, type: 'all'}, {name: '呼出', id: '0', active: false, type: 'call'}, {name: '呼入', id: '1', active: false, type: 'call'}, {name: '接通', id: '1', active: false, type: 'talk'}, {name: '未接通', id: '2', active: false, type: 'talk'} ], total_num: '', //总条数 page_limit: 20, //分页size curPage: '',// 当前页 page_limit_arr: [ {id: 20, active: true}, {id: 50, active: false}, {id: 100, active: false}, {id: 500, active: false}, {id: 1000, active: false} ], keywords: '', //搜索手机号 keywordsName: '', //搜索姓名 callRecord: [], //通话记录列表 epartment: [], //组织架构筛选 callTypeAndStatus: '', //呼叫方式/状态 employeeAndDep: [], //员工/部门,传员工的id,逗号分隔 callType: '', //呼叫类型:1呼入,0呼出 talked: '', //1表示通,2表示未通 employee_and_dep: '', //员工/部门,传员工的id,逗号分隔 selectedOrgUsr: [], //全局组织架构已选用户 {id:1, name: '张三'},{id:2, name: '李四'} selectedOrgUsrShow: [], //回显书记 showpop: false, //显示与隐藏筛选框 showpopActive: false, //筛选状态激活状态 showDate: false, //日期筛选的显示与隐藏 showDateActive: false, //日期选择框激活状态 conditionStr: ['今天', '昨天', '最近7天', '最近30天', '自定义'], //缓存数据 conditionStrTime: ['0秒', '1-30秒', '31-60秒', '61-120秒', '120秒以上'], //缓存数据 filterTime: [], //筛选日期 filterTimeLong: [], //筛选时长 inputTimeA: '', inputTimeB: '', dateName: '统计时间', dateTimeName: '通话时长', showTime: false, //语音时长显示与隐藏 showTimeActive: false, //语音时长的激活状态 OrgSearchArr: [], //缓存组织架构搜索结果 BasicRoom: [], //楼栋 build: 'D', //选择的楼栋 order: '',// 列表排序项 asc: ''// 列表排序类型 }, methods: { // 表头排序 type : 0最近联系 1通话时间 orderFilter: function (e, type) { var $that = $(e.currentTarget); var sortFlag = $that.data('type'); var order = ['start_time', 'call_time']; var orderType = ['asc', 'desc']; $that.closest('th').siblings('th').find('a').removeClass('asc desc').data('type', 0); if (sortFlag === 0) {// 升序 $that.prop('class', 'asc'); $that.data('type', 1); if (type === 0) { vm.order = order[0]; vm.asc = orderType[0]; } if (type === 1) { vm.order = order[1]; vm.asc = orderType[0]; } } else {// 降序 $that.prop('class', 'desc'); $that.data('type', 0); if (type === 0) { vm.order = order[0]; vm.asc = orderType[1]; } if (type === 1) { vm.order = order[1]; vm.asc = orderType[1]; } } main.getCallRecordAll(); main.getCountAll(); }, //列表播放音频 play: function (url, title, time) { window.top.jplayer(url, title, time); }, choicepart: function (index, id) { if (index != null && id != null) { this.epartment[index].active = !this.epartment[index].active; } }, choiceState: function (event, index, id, type) {//选择状态条件 var lens = this.states.length; if (index != undefined && id != undefined) { switch (type) { case 'all': this.callType = ''; //呼叫类型:1呼入,0呼出 this.talked = ''; //1表示通,2表示未通 for (var i = 0; i < lens; i++) { if (i == 0) { this.states[i].active = true; } else { this.states[i].active = false; } } break; case 'call': if (this.states[index].active) { this.callType = ''; this.states[index].active = false; var flag = false; for (var i = 0; i < lens; i++) { if (i === 0) continue; if (this.states[i].active) { flag = true; break; } } !flag && (this.states[0].active = true); } else { this.callType = id; this.states[index].active = true; if (id == 1) { //index = 1 this.states[1].active = false; } else { // id = 0 index = 2 this.states[2].active = false; } this.states[0].active = false; } break; case 'talk': if (this.states[index].active) { this.talked = ''; this.states[index].active = false; var flag2 = false; for (var i = 0; i < lens; i++) { if (i === 0) continue; if (this.states[i].active) { flag2 = true; break; } } !flag2 && (this.states[0].active = true); } else { this.talked = id; this.states[index].active = true; if (id == 1) { // index = 3 this.states[4].active = false; } else { // id = 2 index 4 this.states[3].active = false; } this.states[0].active = false; } break; } main.getCallRecordAll(); main.getCountAll(); } }, choiceRoom: function (index, id) { //筛选楼栋 if (index != undefined && id != undefined) { this.build = id; var lens = this.BasicRoom.length; for (var i = 0; i < lens; i++) { if (i == index) { this.BasicRoom[index].active = true; } else { this.BasicRoom[i].active = false; } } main.getCallRecordAll(); main.getCountAll(); } }, choiceLimit: function (index, id) { //选择每页展示的条数 if (index != undefined && id != undefined) { var lens = this.page_limit_arr.length; for (var i = 0; i < lens; i++) { this.page_limit_arr[i].active = false; if (index == i) { this.page_limit_arr[i].active = true; } } this.page_limit = id; main.getCallRecordAll(); main.getCountAll(); } }, //筛选的弹窗框的全选 orgSelectAll: function (event, id) { var $ul = $(event.target).parent().siblings(); var $item = $ul.find('a').not('.has-arrow'); $item.each(function () { var newItem = {id: $(this).data('id'), name: $(this).data('text')}; vm.selectedOrgUsr.push(newItem); }); this.selectedOrgUsr = main.unique(vm.selectedOrgUsr).reverse(); }, //筛选的弹窗框的单个选择 orgSelectItem: function (e) { if (!$(e.target).hasClass('has-arrow')) { var newItem = {id: $(e.target).data('id'), name: $(e.target).data('text')}; this.selectedOrgUsr.push(newItem); this.selectedOrgUsr = main.unique(this.selectedOrgUsr).reverse(); } }, //点击筛选框确定按钮 addConditonsOrg: function () { if (this.selectedOrgUsr.length) { var tmpArr = [];// 已选员工 id var selectedArr = [];// 已选员工 var $selectedOrgUsr = $(".choose-people ul").find("li"); $selectedOrgUsr.each(function () { tmpArr.push($(this).attr("data-id")); selectedArr.push({id: $(this).attr("data-id"), name: $(this).text()}); }); this.selectedOrgUsrShow = selectedArr; this.employeeAndDep = tmpArr.join(','); main.getCallRecordAll(); main.getCountAll(); this.showpop = false; } else { layers.toast('请选择人员'); } }, //删除单个选项 delChoose: function (index) { if (index != undefined) { this.selectedOrgUsr.splice(index, 1); } }, // 筛选不限 日期 cancelCondition: function (e) { $(e.target).parent().find('a').each(function () { $(this).removeClass('active'); }); this.showDate = false; this.showDateActive = false; this.dateName = '统计时间'; this.filterTime = []; }, // 筛选不限 通话时长 cancelTime: function (e) { $(e.target).parent().find('a').each(function () { $(this).removeClass('active'); }); this.dateTimeName = '通话时长'; this.showTime = false; //语音时长显示与隐藏 this.showTimeActive = false; //语音时长的激活状态 this.filterTimeLong = []; }, // 日期筛选 choiceTime: function (e, custom) { if (custom) {// 自定义 $(e.target).toggleClass('active'); } else {// 快速时间筛选 $(e.target).parent().find('a').each(function () { $(this).removeClass('active'); }); this.showDate = false; this.showDateActive = true; this.dateName = '统计时间'; this.dateName += ':' + $(e.target).text(); var quicklyTime = []; switch ($(e.target).text()) { case vm.conditionStr[0]: quicklyTime = main.timeArea().today; break; case vm.conditionStr[1]: quicklyTime = main.timeArea().yesterday; break; case vm.conditionStr[2]: quicklyTime = main.timeArea().recent7day; break; case vm.conditionStr[3]: quicklyTime = main.timeArea().recent30day; break; default: } this.filterTime = quicklyTime; } }, // 通话时长筛选 choiceTimeLong: function (e, custom) { if (custom) {// 自定义 $(e.target).toggleClass('active'); } else {// 快速时间筛选 $(e.target).parent().find('a').each(function () { $(this).removeClass('active'); }); this.showTime = false; this.showTimeActive = true; this.dateTimeName = '通话时长'; this.dateTimeName += ':' + $(e.target).text(); var quicklyTime = []; switch ($(e.target).text()) { case '0秒': quicklyTime = ['0']; break; case '1-30秒': quicklyTime = ['1', '30']; break; case '31-60秒': quicklyTime = ['31', '60']; break; case '61-120秒': quicklyTime = ['61', '120']; break; case '120秒以上': quicklyTime = ['120']; break; } this.filterTimeLong = quicklyTime; } }, // 添加筛选: 自定义时间录入的情况 addConditons: function (e) { // 时间范围验证 if ((new Date(this.inputTimeB) - new Date(this.inputTimeA)) < 0) { layers.toast('开始时间不能大于结束时间', {time: 2500}); } else { var domValA = $('.lay-date-a').val(); var domValB = $('.lay-date-b').val(); // 添加自定义时间 if (domValA && domValB) { this.inputTimeA = domValA; this.inputTimeB = domValB; // 关闭筛选框 this.showDate = false; this.showDateActive = true; this.dateName = '统计时间'; this.dateName += (':' + this.inputTimeA + '到' + this.inputTimeB); this.filterTime = [this.inputTimeA, this.inputTimeB] } else { layers.toast('请填入自定义时间范围'); } } }, addConditonsTime: function () { var domValA = $.trim($('.lay-date-t-a').val()); var domValB = $.trim($('.lay-date-t-b').val()); if (!(domValA && domValB)) { layers.toast('请填入自定义秒数范围'); return; } if (+domValA > +domValB) { layers.toast('开始秒数不能大于结束秒数', {time: 2500}); return; } // 关闭筛选框 this.showTime = false; this.showTimeActive = true; this.dateTimeName = '通话时长'; this.dateTimeName += (':' + domValA + '秒到' + domValB + '秒'); this.filterTimeLong = [domValA, domValB] }, delUsr: function (index) {//删除组织架构中已经选择的展示出来的选项 if (index != undefined) { this.selectedOrgUsr.splice(index, 1); this.selectedOrgUsrShow.splice(index, 1); var tmpArr = []; this.selectedOrgUsr.forEach(function (t) { tmpArr.push(t.id); }); this.selectedOrgUsrShow = this.selectedOrgUsr; this.employeeAndDep = tmpArr.join(','); main.getCallRecordAll(); main.getCountAll(); } } }, watch: { showpop: { handler: function (val, oldVal) { this.showpopActive = val; if (val) { main.form.render(); this.showTime = false; this.showDate = false; } }, deep: true }, showDate: { handler: function (val, oldVal) { if (this.filterTime.length) { this.showDateActive = true; } else { this.showDateActive = val; } if (val) { this.showTime = false; this.showpop = false; } }, deep: true }, showTime: { handler: function (val, oldVal) { if (this.filterTimeLong.length) { this.showTimeActive = true; } else { this.showTimeActive = val; } if (val) { this.showDate = false; this.showpop = false; } }, deep: true }, filterTime: { handler: function (val, oldVal) { main.getCallRecordAll(); main.getCountAll(); }, deep: true }, filterTimeLong: { handler: function () { main.getCallRecordAll(); main.getCountAll(); }, deep: true }, keywords: function (val) { if (val === '') { main.getCallRecordAll(); main.getCountAll(); } }, keywordsName: function (val) { if (val === '') { main.getCallRecordAll(); main.getCountAll(); } } } }); /** * vue过滤器 */ Vue.filter('VformatM', function (value) { if (value < 60) { return '00:' + (value >= 10 ? value : '0' + value); } if (60 <= value < 3600) { return (Math.floor(value / 60) >= 10 ? Math.floor(value / 60) : '0' + Math.floor(value / 60)) + ':' + (value % 60 >= 10 ? value % 60 : '0' + value % 60) } if (value >= 3600) { var H = Math.floor(value / 3600) >= 10 ? Math.floor(value / 3600) : '0' + Math.floor(value / 3600); var M = Math.floor((value % 3600) / 60) >= 10 ? Math.floor((value % 3600) / 60) : '0' + Math.floor((value % 3600) / 60); var S = Math.floor((value % 3600) / 60 * 60) >= 10 ? Math.floor((value % 3600) / 60 * 60) : '0' + Math.floor((value % 3600) / 60 * 60); return H + M + S; } }); /** * 初始化 * @private */ var _init = function () { main.createForm(); common.getTabLink(); main.getCallRecordAll('', function () { main.getCountAll(); }); main.getdepartment(); main.renderLayDate(); }; _init(); });
module.exports = TheGreatFlat; var BaseTerritory = require("./Base.js"); TheGreatFlat.prototype = new BaseTerritory(); TheGreatFlat.prototype.constructor = TheGreatFlat; function TheGreatFlat() { this.name = "The Great Flat"; var neighbors = new Array( "FuneralPlain", "PlasticBasin", "WindPass", "TheGreaterFlat" ); this.setNeighbors(neighbors); }
(function() { module.exports = function(connect, options) { var app, express, routes; express = require('express'); routes = require('./routes'); app = express(); app.configure(function() { app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.errorHandler()); app.use(express.directory(options.base)); app.use(express["static"](options.base)); app.use(app.router); return routes(app, options); }); return [connect(app)]; }; }).call(this);
/** * @constructor * * @param {RegExp} test - Remove match from html */ function HtmlWebpackPluginRemove (test) { this.test = test; } HtmlWebpackPluginRemove.prototype.apply = function(compiler) { var test = this.test; compiler.plugin("compilation", function(compilation) { // Hook into html-webpack-plugin event compilation.plugin('html-webpack-plugin-after-html-processing', function(pluginData, cb) { pluginData.html = pluginData.html.replace(test, ''); if (cb) { cb(null, pluginData); } else { return Promise.resolve(pluginData) } }); }); }; module.exports = HtmlWebpackPluginRemove;
version https://git-lfs.github.com/spec/v1 oid sha256:b73bee18e289bd7150cdfe8bf69b971a30f710635f951d3303b9da5beea5541e size 32880
/** * Class that handles the products * @type {*} */ window.themingStore.models.ProductModel = window.themingStore.models.AbstractModel.extend({ defaults: { 'template[title]': 'dsa' }, /** * the type of the model, required for save operations */ type: 'template' });
export { default } from 'ilios-common/models/curriculum-inventory-sequence-block';
/** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; module.exports = require('../src/traces/box');
$(function(){ $.BaseStorage = Class.extend(function(){ var storage = this; storage.key = null; storage.data = {}; storage.constructor = function(storageKey, callback){ storage.key = storageKey; if(callback && typeof callback == 'function'){ callback(storage); } }; storage.getData = function(){ return storage.data; }; storage.setData = function(data){ storage.data = data; return storage; }; storage.save = function(options, callback){ if(callback && typeof callback == 'function'){ callback(storage.data); } return storage; }; return storage; }); $.CookieStorage = $.BaseStorage.extend(function(){ var storage = this; storage.constructor = function(storageKey, callback){ $.cookie.json = true; storage.data = $.cookie(storageKey); storage.super(storageKey, callback); }; storage.save = function(options, callback){ $.cookie(storage.key, storage.data, { path: '/' }); storage.super.save(options, callback); }; return storage; }); });
$(document).ready(function(){ newGame = new Game; $("#board").on("click", '.board-column', function(){ $("#player2").toggle(); $("#player1").toggle(); }) $("#board").on("click", '.cell', function(event){ // debugger; var player_1_color = "white" var player_2_color = "black" if($("#player1").is(":visible")){ var column_id = $(event.target).parent().attr('id'); newGame.drop(column_id, player_1_color); // newGame.drop(column_id, player_2_color); // console.log(newGame.board); // $(event.target).html(''); var index = 1; newGame.board[column_id].forEach(function(cell){ if (cell === player_1_color) { $('#'+ column_id + ' .cell:nth-child(' + (7 - index) +')').css('background-color', player_1_color); index++; } else { $('#'+ column_id + ' .cell:nth-child(' + (7 - index) +')').css('background-color', player_2_color); index++; } }); } else { var column_id = $(event.target).parent().attr('id'); newGame.drop(column_id, player_2_color); // console.log(newGame.board); var index = 1; newGame.board[column_id].forEach(function(cell){ if (cell === player_1_color) { $('#'+ column_id + ' .cell:nth-child(' + (7 - index) +')').css('background-color', player_1_color); index++; } else { $('#'+ column_id + ' .cell:nth-child(' + (7 - index) +')').css('background-color', player_2_color); index++; } }); } if (newGame.checkWin() === true) { alert('You Win!!!!!!!!!!'); location.reload(); }; }); });
/*global define:false, describe: false, before:false, after: false, beforeEach: false, afterEach: false, it:false, expect: false, i18n: false */ define([ // Libraries. 'jquery', 'underscore', 'backbone', // Modules. 'modules/meta', 'modules/session', 'modules/nls' ], function($, _, Backbone, Meta, Session, i18n) { 'use strict'; describe('NLS Module', function() { describe('Native text', function() { beforeEach(function(done) { console.log('[TEST] Entering NLS Module / Native text before()...'); done(); }); afterEach(function(done) { console.log('[TEST] Entering NLS Module / Native text after()...'); done(); }); it('should be rendered in French for French Canadian user.', function(done) { localStorage.setItem('locale', 'fr-ca'); expect(i18n.gettext('About Us')).to.equal('À propos de nous'); done(); }); /*it('should be rendered in English for English American user.', function(done) { localStorage.clear(); localStorage.setItem('locale', 'en-us'); expect(i18n.gettext('About Us')).to.equal('About Us'); done(); });*/ }); }); });
/* * IndexController from errorPage Module */ app.registerService(function() { var self = this; self.moduleName = "files"; self.serviceName = "$filesService"; self.initService = function() { angular.module(self.moduleName).factory([self.moduleName, self.serviceName].join("."), ['$resource', function($resource) { return $resource(app.api.url("files", "resource"), {directory: '@directory'}, { list: { method: 'POST', url : app.api.url("files", "list") }, create: { method: 'PUT', url : app.api.url("files", "create") }, "delete" : { method: 'POST', url : app.api.url("files", "delete") } }); }]); }; /** * Return config */ return { name: self.moduleName, serviceName: self.serviceName, bootstrap: function() { self.initService(); } }; });
buttonToOpenPopUp("#newEmployee", "showAddEmployee.html", "#addEmployee"); buttonToOpenPopUp("#employeeToProject", "employeeProject.html", "#employeeProject"); var activeEmployeeToProject = null; var list = $("#employeesPopUp .list-group"); list.empty(); for(c of empresa.funcionarios.membros){ list.append(c.html); } initializeList("#employeesPopUp", function(item){ activeEmployeeToProject = $(item).attr("data-id"); });
/*jslint node: true, nomen: true, white: true, unparam: true*/ /*globals describe, beforeEach, afterEach, it, expect, spyOn*/ /*! * Sitegear3 * Copyright(c) 2014 Ben New, Sitegear.org * MIT Licensed */ (function (templateObject) { "use strict"; describe('Utility Function: expandSettings()', function () { describe('Using ERB style templates by default', function () { describe('With valid data', function () { var settings; beforeEach(function () { settings = templateObject(require('./_input/settings-erb.json')); }); it('Does not affect static keys', function () { expect(settings.foo).toBe('bar'); }); it('Expands dynamic keys that refer to a static key', function () { expect(settings.expando).toBe('bar'); }); it('Expands dynamic keys that refer to another dynamic key', function () { expect(settings.expando2).toBe('bar'); }); it('Expands dynamic keys without affecting static text', function () { expect(settings.expando3).toBe('prefix-bar'); expect(settings.expando4).toBe('bar-suffix'); expect(settings.expando5).toBe('prefix-bar-suffix'); }); it('Expands dynamic keys that are nested', function () { expect(settings.nested).toBe('child value'); expect(settings.deeplyNested).toBe('deeply nested value'); }); it('Expands dynamic keys that are nested, that refer to a key within a different parent', function () { expect(settings.otherParent.nested).toBe('child value'); }); it('Expands dynamic keys that are nested, that refer to a key at the root level', function () { expect(settings.otherParent.fromRoot).toBe('bar'); }); }); describe('With invalid data', function () { var settings, error; beforeEach(function () { try { settings = templateObject(require('./_input/settings-erb-with-unresolved.json')); } catch (e) { error = e; } }); it('Does not return', function () { expect(settings).toBeUndefined(); }); it('Throws an error on unresolved reference', function () { expect(error).not.toBeUndefined(); expect(error.message).toBe('unknown is not defined'); }); }); describe('With data that is invalid due to an unqualified reference (Issue #1)', function () { var settings, error; beforeEach(function () { try { settings = templateObject(require('./_input/settings-erb-with-unqualified-reference.json')); } catch (e) { error = e; } }); it('Does not return', function () { expect(settings).toBeUndefined(); }); it('Throws an error on unresolved reference', function () { expect(error).not.toBeUndefined(); expect(error.message).toBe('foo is not defined'); }); }); }); describe('Using mustache style templates', function () { describe('With valid data', function () { var settings; beforeEach(function () { settings = templateObject(require('./_input/settings-mustache.json'), 'mustache'); }); it('Does not affect static keys', function () { expect(settings.foo).toBe('bar'); }); it('Expands dynamic keys that refer to a static key', function () { expect(settings.expando).toBe('bar'); }); it('Expands dynamic keys that refer to another dynamic key', function () { expect(settings.expando2).toBe('bar'); }); it('Expands dynamic keys without affecting static text', function () { expect(settings.expando3).toBe('prefix-bar'); expect(settings.expando4).toBe('bar-suffix'); expect(settings.expando5).toBe('prefix-bar-suffix'); }); it('Expands dynamic keys that are nested', function () { expect(settings.nested).toBe('child value'); expect(settings.deeplyNested).toBe('deeply nested value'); }); it('Expands dynamic keys that are nested, within a different parent', function () { expect(settings.otherParent.nested).toBe('child value'); }); it('Expands dynamic keys that are nested, that refer to a key at the root level', function () { expect(settings.otherParent.fromRoot).toBe('bar'); }); }); describe('With invalid data', function () { var settings, error; beforeEach(function () { try { settings = templateObject(require('./_input/settings-mustache-with-unresolved.json'), 'mustache'); } catch (e) { error = e; } }); it('Does not return', function () { expect(settings).toBeUndefined(); }); it('Throws an error on unresolved reference', function () { expect(error).not.toBeUndefined(); expect(error.message).toBe('unknown is not defined'); }); }); describe('With data that is invalid due to an unqualified reference (Issue #1)', function () { var settings, error; beforeEach(function () { try { settings = templateObject(require('./_input/settings-mustache-with-unqualified-reference.json'), 'mustache'); } catch (e) { error = e; } }); it('Does not return', function () { expect(settings).toBeUndefined(); }); it('Throws an error on unresolved reference', function () { expect(error).not.toBeUndefined(); expect(error.message).toBe('foo is not defined'); }); }); }); }); }(require('../')));
var events = require('events'); var spawn = require('child_process').spawn; var split = require('split'); var path = require('path'); var util = require('util'); var rtf2htmlPythonScript = path.join(__dirname, 'rtf2html.py'); function Processor() { events.EventEmitter.call(this); this.killTimer = null; this.child = null; this.tasks = []; } util.inherits(Processor, events.EventEmitter); Processor.prototype.waitToKill = function() { var self = this; if (self.killTimer) { clearTimeout(self.killTimer); } self.killTimer = setTimeout(function() { self.kill(); }, 2000); }; Processor.prototype.kill = function ProcessorKill() { var self = this; if (self.killTimer) { clearTimeout(self.killTimer); self.killTimer = null; } if (self.child) { self.child.kill(); self.child = null; } }; Processor.prototype.addTask = function ProcessorAddTask(rtf, callback) { var self = this; if (self.child) { self.waitToKill(); } else { self.respawn(); } var task = [rtf, callback]; self.tasks.push(task); self._addTask(task); }; Processor.prototype._addTask = function ProcessorInternalAddTask(task) { var self = this; self.child.stdin.write(JSON.stringify(task[0]) + '\n'); }; Processor.prototype.respawn = function ProcessorRespawn() { var self = this; self.kill(); var child = spawn('python', [rtf2htmlPythonScript], { env: { PATH: process.env.PATH } }); self.child = child; child.stdin.on('error', function(error) { self.emit('error', error); }); child.stdout.pipe(split()) .on('data', function(line) { if (!line) return; var obj; try { obj = JSON.parse(line); } catch (error) { return self.emit('error', error); } var task = self.tasks.shift(); if (task) { var callback = task[1]; if (obj.error) { callback(new Error('unrtf: ' + obj.error)); } else { callback(null, obj); } } else { self.emit('error', new Error('Got result without any active tasks')); } }) .on('error', function(error) { self.emit('error', error); }); child.stderr.pipe(split()) .on('data', function(line) { line = ('' + line).replace(/\s+$/, ''); if (line) { console.error('unrtf: ' + line); } }) .on('error', function(error) { self.emit('error', error); }); self.tasks.forEach(function(task) { self._addTask(task); }); self.waitToKill(); return self; }; var processor = new Processor(); processor.on('error', function(error) { console.error('unrtf:', error); processor.respawn(); }); function noop() {} function pyth(rtf, options, callback) { if (!callback) { callback = options; options = null; } callback = callback || noop; if (!rtf) return callback(null, { html: '' }); // Encode Unicode characters as RTF commands, fixes encoding issue in Pyth library. rtf = ('' + [rtf]).replace(/[\u0080-\uFFFF]/g, function(ch) { var code = ch.charCodeAt(0); if (code > 32767) code -= 65536; return '\\uc1\\u' + code + '?'; }); processor.addTask(rtf, function(error, result) { if (error) { callback(error); } else { var html = '' + result.html; if (/^<div>/.test(html) && /<\/div>$/.test(html)) { html = html.slice(5,-6); } callback(null, { html: html }); } callback = noop; }); } module.exports = pyth;
'use strict'; let constants = require('./constants'); const NIL = '-'; const EMPTY = ''; const FILTER_PRINT_US_ASCII = /([\x21-\x7e])+/g; /** * @param {string} str * @param {number} maxLength * @returns {string} */ function filterPrintUsASCII (str, maxLength) { if (typeof str === constants.TYPE_OF.NUMBER || typeof str === constants.TYPE_OF.BOOLEAN) { str += EMPTY; } if (typeof str === constants.TYPE_OF.STRING && str.length > 0) { let strArray = str.match(FILTER_PRINT_US_ASCII); if (strArray instanceof Array && strArray.length > 0) { return strArray.join(EMPTY).substring(0, maxLength); } } return NIL; } module.exports = { filterPrintUsASCII: filterPrintUsASCII };
define('getSpreadsheetFromFile', ['papaparse', 'xlsx' ], function (Papa, xlsx, __createReactClass) { return (f, callback) => { if (! f) return callback(null, null); if (! (window.File && window.FileReader && window.FileList && window.Blob)) return callback(null, null); if (f.name.match(/\.csv$/i)) { Papa.parse(f, { error: (err) => { console.log("Error parsing CSV file", err); }, complete: (results) => { let data = results.data; // The parser we're using will yield [""] as the last // line if the file ends with a newline. Remove all // such empty rows from end of file. let i; for (i = data.length-1; i >= 0 && (data[i].length == 1 && data[i][0] == ""); --i) ; data.length = i + 1; callback(null, { Sheet1: data }); } }); } else if (f.name.match(/\.xlsx$/i)) { let reader = new FileReader(); reader.readAsArrayBuffer(f); reader.onerror = callback; reader.onloadend = () => { let bstr = arrayBufferToBString(reader.result); let workbook = xlsx.read(bstr, { type: 'binary' }); callback(null, excelWorkbookToJson(workbook)) }; } else { return callback(new Error("Spreadsheet file \u2018" + f.name + "\u2019 has unrecognized extension")); } } });
'use strict'; var winston = require('winston'); module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.addColumn('settings', 'help_page', { type: Sequelize.STRING(255), defaultValue: '', allowNull: false }) .catch(function (err) { winston.error('Adding column settings.help_page failed with error message: ', err.message); }); }, down: function (queryInterface, Sequelize) { return queryInterface.removeColumn('settings', 'help_page') .catch(function (err) { winston.error('Removing column settings.help_page failed with error message: ', err.message); }); } };
import { ContactEmailsModel } from '@proton/shared/lib/models/contactEmailsModel'; import createUseModelHook from './helpers/createModelHook'; export default createUseModelHook(ContactEmailsModel);
'use strict'; const EasyObjectValue = require('../values/EasyObjectValue'); class NumberPrototype extends EasyObjectValue { static *valueOf$e(thiz) { if ( thiz.specTypeName === 'number' ) return thiz; if ( thiz.specTypeName === 'object' ) { let pv = thiz.primativeValue; if ( pv.specTypeName === 'number' ) return pv; } throw new TypeError('Couldnt get there.'); } static *toExponential$e(thiz, argz, s) { let a; if ( argz.length > 0 ) { a = yield * argz[0].toNumberNative(); } let num = yield * thiz.toNumberNative(thiz); return s.realm.fromNative(num.toExponential(a)); } static *toFixed$e(thiz, argz, s) { let a; if ( argz.length > 0 ) { a = yield * argz[0].toNumberNative(); } let num = yield * thiz.toNumberNative(thiz); return s.realm.fromNative(num.toFixed(a)); } static *toPrecision$e(thiz, argz, s) { let a; if ( argz.length > 0 ) { a = yield * argz[0].toNumberNative(); } let num = yield * thiz.toNumberNative(thiz); return s.realm.fromNative(num.toPrecision(a)); } static *toString$e(thiz, argz, s) { let a; if ( argz.length > 0 ) { a = yield * argz[0].toNumberNative(); } let num = yield * thiz.toNumberNative(thiz); return s.realm.fromNative(num.toString(a)); } } NumberPrototype.prototype.wellKnownName = '%NumberPrototype%'; module.exports = NumberPrototype;
// app.js (function() { "use strict"; angular.module("myFirstApp") .controller("MyFirstController", MyFirstController); function MyFirstController() { let vm = this; vm.name = "Vitalii"; /* $scope.sayHello = () => { return "Hello, world!"; }; */ } })();
function solve(input) { let arraySize = input[0]; let arr = []; for(k = 0; k < arraySize; k++){ arr[k] = 0; } for(i = 1; i <= input.length-1; i++){ let currentCommand = input[i].split(" - "); arr[currentCommand[0]] = currentCommand[1]; } arr.forEach(a => console.log(a)) }
var app = require('http').createServer(handler), io = require('socket.io').listen(app), fs = require('fs'), qs = require('querystring') io.sockets.on('connection', function(socket) { console.log('client connected'); socket.on('disconnect', function() { console.log('client disconnected'); }); }); function handler(req, res) { var buffer = ''; req.on('data', function(data) { buffer += data; }); req.on('end', function() { var message = qs.parse(buffer); console.log(message.event); try { data = JSON.parse(message.data); } catch(e) { data = message.data; } io.sockets.emit(message.event, data); res.writeHead(200); res.end('ok'); }); } var port = process.env.PORT || 5000; app.listen(port, function() { console.log("Listening on " + port); });
'use strict' const test = require('tape') const { checkSingle } = require('./util/util') test('\npreflop:single: pair vs. pair', function(t) { [ [ 'AsAh', 'KsKh', 82 ] , [ 'JsJh', '7s7h', 81 ] , [ 'JsJh', 'TsTh', 82 ] , [ 'AsAh', '2s2h', 83 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() }) test('\npreflop:single: pair vs. overcards', function(t) { [ [ 'JsJh', 'KsQh', 56 ] , [ 'JsJh', 'AsQh', 56 ] , [ 'JsJh', 'AcQc', 54 ] , [ 'JsJh', 'KcQc', 53 ] , [ '2s2h', 'KcQc', 48 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() }) test('\npreflop:single: pair vs. undercards', function(t) { [ [ 'JsJh', 'Ts9h', 86 ] , [ 'JsJh', '6s2h', 88 ] , [ 'JsJh', 'Tc9c', 81 ] , [ 'JsJh', '6c2c', 82 ] , [ '6s6h', '2c3c', 79 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() }) test('\npreflop:single: pair vs. overcard and undercard', function(t) { [ [ 'JsJh', 'Ks9h', 72 ] , [ 'JsJh', 'Qs6h', 72 ] , [ 'JsJh', 'Kc9c', 68 ] , [ 'JsJh', 'Kc6c', 68 ] , [ '6s6h', 'Tc3c', 65 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() }) test('\npreflop:single: pair vs. overcard and card match', function(t) { [ [ 'JsJh', 'KsJh', 70 ] , [ 'JsJh', 'QsJh', 69 ] , [ 'JsJh', 'KcJc', 63 ] , [ 'JsJh', 'KcJc', 63 ] , [ '6s6h', 'Tc6c', 61 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() }) test('\npreflop:single: pair vs. undercard and card match', function(t) { [ [ 'JsJh', 'Js9h', 89 ] , [ 'JsJh', 'Js6h', 93 ] , [ 'JsJh', 'Jc9c', 81 ] , [ 'JsJh', 'Jc6c', 85 ] , [ '6s6h', '6c3c', 83 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() }) test('\npreflop:single: two high cards vs. two undercards', function(t) { [ [ 'KsTh', '7s4h', 66 ] , [ 'AsQh', 'Js6h', 68 ] , [ 'KsTh', '7c4c', 60 ] , [ 'AsQh', 'Jc6c', 63 ] , [ 'Js8h', '6c3c', 60 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() }) test('\npreflop:single: high low card vs. two cards in between', function(t) { [ [ 'Ks3h', 'Js4h', 59 ] , [ 'As8h', 'Js9h', 57 ] , [ 'Ks3h', '7c4c', 53 ] , [ 'As8h', 'JcTc', 52 ] , [ 'Js3h', '6c4c', 52 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() }) test('\npreflop:single: high and mid card vs. one between and one below', function(t) { [ [ 'Ks8h', 'Ts6h', 63 ] , [ 'As8h', 'Js6h', 64 ] , [ 'Ks3h', '7c2c', 59 ] , [ 'As8h', 'Jc5c', 59 ] , [ 'Js3h', '6c2c', 57 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() }) test('\npreflop:single: high and low, matched low card', function(t) { [ [ 'Ks8h', 'Ts8d', 69 ] , [ 'As8h', 'Js8d', 71 ] , [ 'Ks3h', '7c3c', 65 ] , [ 'As8h', 'Jc8c', 65 ] , [ 'Js3h', '6c3c', 61 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() }) test('\npreflop:single: high vs. matched high and low', function(t) { [ [ 'Ks8h', 'Kd6h', 56 ] , [ 'As8h', 'Ad6h', 57 ] , [ 'Ks3h', 'Kc2c', 26 ] , [ 'As8h', 'Ac5c', 52 ] , [ 'Js3h', 'Jd2c', 28 ] , [ 'AsKh', 'Ad9c', 71 ] ].forEach(x => checkSingle.apply(null, [ t ].concat(x))) t.end() })
$(function() { $.widget('sense2party.eventEdit', { // Default options options: { }, // Private variables /** * The constructor * * @private */ _create: function() { this._on(this.document, { 'click.delete': function(event) { event.preventDefault(); var location = $(event.currentTarget).attr('href'); bootbox.confirm("Are you sure?", function(result) { if (result !== false) { window.location.replace(location); } }); } }); $('.datepicker').datepicker({ 'format': 'dd-mm-yyyy' }); }, /** * Is called with a hash of all options that are changing always refresh when changing options * * @private */ _setOptions: function() { // _super and _superApply handle keeping the right this-context this._superApply(arguments); }, /** * Is called for each individual option that is changing * * @param key * @param value * @private */ _setOption: function(key, value) { this._super(key, value); }, /** * Called when created, and later when changing options * * @private */ _refresh: function() { }, /** * Events bound via _on are removed automatically * * @private */ _destroy: function() { // Revert other modifications here this.element.removeClass('hotflo-clock'); // Call the base destroy function $.Widget.prototype.destroy.call(this); } }); }(jQuery));
/* global firebase */ import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { Router, Route, useRouterHistory } from 'react-router'; import { createHashHistory } from 'history'; import { syncHistoryWithStore } from 'react-router-redux'; import reducer from './reducers/'; import { startSession, changeAuthoring } from './actions'; import AuthoringUpload from './containers/authoring-upload'; import Navigation from "./containers/navigation"; import ChallengeContainerSelector from "./containers/challenge-container-selector"; import loggerMiddleware from './middleware/gv-log'; import itsMiddleware, { initializeITSSocket } from './middleware/its-log'; import routerMiddleware from './middleware/router-history'; import stateSaveMiddleware, {authoringVersionNumber} from './middleware/state-save'; import soundsMiddleware from 'redux-sounds'; import thunk from 'redux-thunk'; import GeneticsUtils from './utilities/genetics-utils'; import urlParams from './utilities/url-params'; import uuid from 'uuid'; import { initFirebase, userAuth } from "./utilities/firebase-auth"; // trivial check for Windows as part of user agent string if (navigator.userAgent.indexOf('Windows') >= 0) document.body.className += ' os-windows'; let store, history; initFirebase.then(function (auth) { window.sessionStorage.setItem('portalAuth', true); postAuthInitialization(auth); }, function(err){ console.log(err); window.sessionStorage.setItem('portalAuth', false); postAuthInitialization(userAuth()); }); const ITSServers = { ncsuProduction: { url: "wss://guide.intellimedia.ncsu.edu:/guide-protocol", path: "/v3/socket.io" }, ncsuStaging: { url: "wss://imediadev.csc.ncsu.edu:/guide-protocol", path: "/guide/v3/socket.io" }, ccProduction: { url: "wss://geniventure-its.herokuapp.com:/guide-protocol", path: "/socket.io" }, ccStaging: { url: "wss://geniventure-its-staging.herokuapp.com:/guide-protocol", path: "/socket.io" } }; // default to CC's staging ITS server and NCSU's production ITS server for now ITSServers.staging = ITSServers.ccStaging; ITSServers.production = ITSServers.ccProduction; ITSServers.ncsu = ITSServers.ncsuProduction; ITSServers.cc = ITSServers.ccProduction; const postAuthInitialization = function (auth) { store = configureStore(); const isStagingBranch = window.location.pathname.indexOf('/branch/staging') >= 0; const isLocalhost = (window.location.host.indexOf('localhost') >= 0) || (window.location.host.indexOf('127.0.0.1') >= 0); const instance = urlParams.itsInstance || (isStagingBranch || isLocalhost ? "staging" : "production"); const ITSServer = urlParams.itsUrl && urlParams.itsPath ? { url: urlParams.itsUrl, path: urlParams.itsPath } : ITSServers[instance]; initializeITSSocket(ITSServer.url, ITSServer.path, store); // generate pseudo-random sessionID const sessionID = uuid.v4(); loggingMetadata.userName = auth.domain_uid; loggingMetadata.classInfo = auth.class_info_url; loggingMetadata.studentId = auth.domain_uid; loggingMetadata.externalId = auth.externalId; loggingMetadata.returnUrl = auth.returnUrl; // start the session before syncing history, which triggers navigation store.dispatch(startSession(sessionID)); history = syncHistoryWithStore(hashHistory, store); loadAuthoring(); }; function convertAuthoring(authoring) { return GeneticsUtils.convertDashAllelesObjectToABAlleles(authoring, ["alleles", "baseDrake","initialDrakeCombos", "targetDrakeCombos"]); } // TODO: session ID and application name could be passed in via a container // use placeholder ID for duration of session and hard-coded name for now. let loggingMetadata = { applicationName: "GeniStarDev" }; const hashHistory = useRouterHistory(createHashHistory)({ queryKey: false }); const soundsData = { hatchDrake: "resources/audio/BabyDragon.mp3", receiveCoin: "resources/audio/coin.mp3" }; // Pre-load middleware with our sounds. const loadedSoundsMiddleware = soundsMiddleware(soundsData); const createStoreWithMiddleware = applyMiddleware( thunk, loggerMiddleware(loggingMetadata), itsMiddleware(loggingMetadata), routerMiddleware(hashHistory), stateSaveMiddleware(), loadedSoundsMiddleware )(createStore); export default function configureStore(initialState) { return createStoreWithMiddleware(reducer, initialState, window.devToolsExtension && window.devToolsExtension()); } const isAuthorUploadRequested = (urlParams.author === "upload"); let isAuthorUploadEnabled = isAuthorUploadRequested; // e.g. check PRODUCTION flag function loadAuthoring() { const localAuthoring = urlParams.localAuthoring || false; if (localAuthoring) { const url = `resources/authoring/${localAuthoring}.json`; fetch(url) .then(response => response.json()) .then(handleAuthoringLoad, () => alert(`Cannot load ${url}`)); } else { const db = firebase.database(), ref = db.ref(authoringVersionNumber + "/authoring"); ref.once("value", function(authoringData) { handleAuthoringLoad(authoringData.val()); }); } } function handleCompleteUpload(authoring) { store.dispatch(changeAuthoring(convertAuthoring(authoring))); isAuthorUploadEnabled = false; renderApp(); } function handleAuthoringLoad(authoring) { let convertedAuthoring = convertAuthoring(authoring); window.GV2Authoring = convertedAuthoring; store.dispatch(changeAuthoring(convertedAuthoring)); renderApp(); } function renderApp() { const content = isAuthorUploadEnabled ? <AuthoringUpload isEnabled={isAuthorUploadEnabled} onCompleteUpload={handleCompleteUpload} /> : <div> <Router history={history}> <Route path="/navigation" component={Navigation} /> <Route path="/(:level/:mission/:challenge)" component={ChallengeContainerSelector} /> <Route path="/(:challengeId)" component={ChallengeContainerSelector} /> </Router> </div>; render( <Provider store={store}> {content} </Provider> , document.getElementById("gv")); }
/* @flow */ import { InputTypeComposer } from 'graphql-compose'; import { getTypeName, type CommonOpts, desc } from '../../../utils'; export function getCumulativeSumITC<TContext>( opts: CommonOpts<TContext> ): InputTypeComposer<TContext> { const name = getTypeName('AggsCumulativeSum', opts); const description = desc( ` A parent pipeline aggregation which calculates the cumulative sum of a specified metric in a parent histogram (or date_histogram) aggregation. The specified metric must be numeric and the enclosing histogram must have min_doc_count set to 0 (default for histogram aggregations). [Documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-cumulative-sum-aggregation.html) ` ); return opts.getOrCreateITC(name, () => ({ name, description, fields: { buckets_path: 'String!', format: 'String', }, })); }
/** * Created with IntelliJ IDEA. * User: davidtudury * Date: 9/14/13 * Time: 2:05 PM */ var Q = require('q'); module.exports = denodeifyErrorless; function denodeifyErrorless(f) { var args = [].slice.call(arguments, 1); return function () { var deferred = Q.defer(); f.apply(void 0, args.concat([].slice.call(arguments), deferred.resolve)); return deferred.promise; } }
/* StorageTweetenImport.js Copyright (c) 2014-2022 dangered wolf, et al Released under the MIT License */ import { getPref, setPref } from "./StoragePreferences.js"; import { exists } from "./Utils.js" /* Processes Tweeten Settings import obj = object converted from the raw JSON */ export function importTweetenSettings(obj) { setPref("mtd_customcss",(!!obj.dev ? obj.dev.customCSS || "" : "")) if (exists(obj.dev)) { setPref("mtd_inspectElement",obj.dev.mode); } if (exists(obj.TDSettings)) { TD.settings.setAutoPlayGifs(obj.TDSettings.gifAutoplay); if (exists(obj.TDSettings.gifAutoplay)) { TD.settings.setAutoPlayGifs(obj.TDSettings.gifAutoplay); } if (exists(obj.TDSettings.sensitiveData)) { TD.settings.setDisplaySensitiveMedia(obj.TDSettings.sensitiveData); } if (exists(obj.TDSettings.tweetStream)) { TD.settings.setUseStream(obj.TDSettings.tweetStream); } if (exists(obj.TDSettings.linkShortener)) { TD.settings.setLinkShortener(obj.TDSettings.linkShortener ? "bitly" : "twitter"); if (obj.TDSettings.linkShortener.toggle === true && !!obj.TDSettings.linkShortener.bitlyApiKey && !!obj.TDSettings.linkShortener.bitlyUsername) { TD.settings.setBitlyAccount({ login:obj.TDSettings.linkShortener.bitlyUsername || TD.settings.getBitlyAccount().login, apiKey:obj.TDSettings.linkShortener.bitlyApiKey || TD.settings.getBitlyAccount().apiKey }); } } } if (exists(obj.customTitlebar)) { setPref("mtd_nativetitlebar",!obj.customTitlebar); } if (exists(obj.customization)) { setPref("mtd_columnwidth",obj.customization.columnWidth || getPref("mtd_columnwidth")); if (obj.customization.completeBlack === true) { setPref("mtd_theme","amoled"); } setPref("mtd_noemojipicker",exists(obj.customization.emojis) ? obj.customization.emojis : false); setPref("mtd_newcharindicator",exists(obj.customization.charCount) ? !obj.customization.charCount : true); TD.settings.setTheme(obj.customization.theme || TD.settings.getTheme()); if (exists(obj.customization.thinSB)) { setPref("mtd_scrollbar_style", (obj.customization.thinSB ? "scrollbarsnarrow" : "scrollbarsdefault")); } setPref("mtd_round_avatars",exists(obj.customization.roundAvi) ? obj.customization.roundAvi : true); if (exists(obj.customization.font)) { let percentage = 100; switch(obj.customization.font) { case "smallest": percentage = 90; break; case "smaller": percentage = 95; break; case "small": percentage = 100; break; case "large": percentage = 105; break; case "largest": percentage = 110; break; } setPref("mtd_fontsize",percentage); } } }
function formatHeight(height) { var heightElement = document.createElement("span"); heightElement.id = "jriCacheHeightFt"; heightElement.innerHTML = (height >= 0) ? " +" : " "; heightElement.innerHTML += Math.round(height * 3.28084) + "ft"; return heightElement; }
"enable aexpr"; import Morph from 'src/components/widgets/lively-morph.js'; export default class FooBar extends Morph { async initialize() { this.windowTitle = "FooBar"; this.registerButtons() lively.html.registerKeys(this); // automatically installs handler for some methods lively.addEventListener("template", this, "dblclick", evt => this.onDblClick(evt)) // #Note 1 // ``lively.addEventListener`` automatically registers the listener // so that the the handler can be deactivated using: // ``lively.removeEventListener("template", this)`` // #Note 1 // registering a closure instead of the function allows the class to make // use of a dispatch at runtime. That means the ``onDblClick`` method can be // replaced during development this.get("#textField").value = this.getAttribute("data-mydata") || 0 } onDblClick() { this.animate([ {backgroundColor: "lightgray"}, {backgroundColor: "red"}, {backgroundColor: "lightgray"}, ], { duration: 1000 }) } // this method is autmatically registered through the ``registerKeys`` method onKeyDown(evt) { lively.notify("Key Down!" + evt.charCode) } // this method is automatically registered as handler through ``registerButtons`` onPlusButton() { this.get("#textField").value = parseFloat(this.get("#textField").value) + 1 } onMinusButton() { this.get("#textField").value = parseFloat(this.get("#textField").value) - 1 } /* Lively-specific API */ // store something that would be lost livelyPrepareSave() { this.setAttribute("data-mydata", this.get("#textField").value) } livelyPreMigrate() { // is called on the old object before the migration } livelyMigrate(other) { // whenever a component is replaced with a newer version during development // this method is called on the new object during migration, but before initialization this.someJavaScriptProperty = other.someJavaScriptProperty } livelyInspect(contentNode, inspector) { // do nothing } async livelyExample() { // this customizes a default instance to a pretty example // this is used by the this.style.backgroundColor = "lightgray" this.someJavaScriptProperty = 42 this.appendChild(<div>This is my content</div>) } }
function main() { var n = parseInt(readLine()); var binaryN = getBinaryRepresentationOf(n); console.log(getMaximumNumberOfConsecutiveOnes(binaryN)); function getBinaryRepresentationOf(base10Integer) { return (base10Integer >>> 0).toString(2); } function getMaximumNumberOfConsecutiveOnes(binaryNumber) { var arr = binaryNumber.split('').map(Number); var maximumNumber = 0; var currentNumber = 0; for (var i = 0; i < arr.length; ++i) { if (arr[i] === 1) { currentNumber++; if (currentNumber > maximumNumber) { maximumNumber = currentNumber; } } else { currentNumber = 0; } } return maximumNumber; } }
var mongoose = require('mongoose'); mongoose.connect('mongodb://yuuko:123456@hk.1234.sh/yuuko', { server: { auto_reconnect: true, socketOptions:{ keepAlive: 1 } }, db: { numberOfRetries: 3, retryMiliSeconds: 1000, safe: true } }); exports.mongoose = mongoose;
var game = require('../game/monty-hall-game'); 'use strict'; exports.action = { name: 'startGame', description: 'startGame', blockedConnectionTypes: [], outputExample: {gameId: 1}, matchExtensionMimeType: false, version: 1.0, toDocument: true, middleware: [], inputs: {}, run: function(api, data, next) { var r = game.startGame(); data.response.gameId = r.gameId; data.response.doors = r.doors; data.response.gameMessage = r.gameMessage; next(); } };
// DATA_TEMPLATE: empty_table oTest.fnStart("bAutoWidth"); /* It's actually a little tricky to test this. We can't test absolute numbers because * different browsers and different platforms will render the width of the columns slightly * differently. However, we certainly can test the principle of what should happen (column * width doesn't change over pages) */ $(document).ready(function () { /* Check the default */ var oTable = $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/objects.txt", "aoColumns": [ { "mData": "engine" }, { "mData": "browser" }, { "mData": "platform" }, { "mData": "version" }, { "mData": "grade" } ] }); var oSettings = oTable.fnSettings(); oTest.fnWaitTest( "Auto width is enabled by default", null, function () { return oSettings.oFeatures.bAutoWidth; } ); oTest.fnWaitTest( "First column has a width assigned to it", null, function () { return $('#example thead th:eq(0)').attr('style').match(/width/i); } ); /* This would seem like a better test - but there appear to be difficulties with tables which are bigger (calculated) than there is actually room for. I suspect this is actually a bug in datatables oTest.fnWaitTest( "Check column widths on first page match second page", null, function () { var anThs = $('#example thead th'); var a0 = anThs[0].offsetWidth; var a1 = anThs[1].offsetWidth; var a2 = anThs[2].offsetWidth; var a3 = anThs[3].offsetWidth; var a4 = anThs[4].offsetWidth; $('#example_next').click(); var b0 = anThs[0].offsetWidth; var b1 = anThs[1].offsetWidth; var b2 = anThs[2].offsetWidth; var b3 = anThs[3].offsetWidth; var b4 = anThs[4].offsetWidth; console.log( a0, b0, a1, b1, a2, b2, a3, b3 ); if ( a0==b0 && a1==b1 && a2==b2 && a3==b3 ) return true; else return false; } ); oTest.fnWaitTest( "Check column widths on second page match thid page", null, function () { var anThs = $('#example thead th'); var a0 = anThs[0].offsetWidth; var a1 = anThs[1].offsetWidth; var a2 = anThs[2].offsetWidth; var a3 = anThs[3].offsetWidth; var a4 = anThs[4].offsetWidth; $('#example_next').click(); var b0 = anThs[0].offsetWidth; var b1 = anThs[1].offsetWidth; var b2 = anThs[2].offsetWidth; var b3 = anThs[3].offsetWidth; var b4 = anThs[4].offsetWidth; if ( a0==b0 && a1==b1 && a2==b2 && a3==b3 ) return true; else return false; } ); */ /* Check can disable */ oTest.fnWaitTest( "Auto width can be disabled", function () { oSession.fnRestore(); oTable = $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/objects.txt", "aoColumnDefs": [ { "mData": "engine", "aTargets": [0] }, { "mData": "browser", "aTargets": [1] }, { "mData": "platform", "aTargets": [2] }, { "mData": "version", "aTargets": [3] }, { "mData": "grade", "aTargets": [4] } ], "bAutoWidth": false }); oSettings = oTable.fnSettings(); }, function () { return oSettings.oFeatures.bAutoWidth == false; } ); oTest.fnWaitTest( "First column does not have a width assigned to it", null, function () { return $('#example thead th:eq(0)').attr('style') == null; } ); /* oTest.fnWaitTest( "Check column widths on first page do not match second page", null, function () { var anThs = $('#example thead th'); var a0 = anThs[0].offsetWidth; var a1 = anThs[1].offsetWidth; var a2 = anThs[2].offsetWidth; var a3 = anThs[3].offsetWidth; var a4 = anThs[4].offsetWidth; $('#example_next').click(); var b0 = anThs[0].offsetWidth; var b1 = anThs[1].offsetWidth; var b2 = anThs[2].offsetWidth; var b3 = anThs[3].offsetWidth; var b4 = anThs[4].offsetWidth; if ( a0==b0 && a1==b1 && a2==b2 && a3==b3 ) return false; else return true; } ); */ /* Enable makes no difference */ oTest.fnWaitTest( "Auto width enabled override", function () { oSession.fnRestore(); oTable = $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/objects.txt", "aoColumnDefs": [ { "mData": "engine", "aTargets": [0] }, { "mData": "browser", "aTargets": [1] }, { "mData": "platform", "aTargets": [2] }, { "mData": "version", "aTargets": [3] }, { "mData": "grade", "aTargets": [4] } ], "bAutoWidth": true }); oSettings = oTable.fnSettings(); }, function () { return oSettings.oFeatures.bAutoWidth; } ); oTest.fnComplete(); });
module.exports = { build: { src: 'assets/js/app.min.js', dest: 'assets/js/app.min.js' } }
const { should, fixtures, } = require('../../lib/util/tests'); const parser = require('../../lib/decorate/parse'); describe('decorate/parse', () => { it('is function', () => { parser.should.be.a('function'); }); it('invalid', () => { const r = parser(fixtures.torrent.invalid.file); should.not.exist(r); }); it('valid movie', () => { const r = parser(fixtures.torrent.movie.file); r.should.be.an('object').and.have.properties(fixtures.torrent.movie.result); }); it('valid tv', () => { const p = fixtures.torrent.tv.file; const r = parser(p); r.should.be.an('object').and.have.properties(fixtures.torrent.tv.result); }); it('no dot', () => { const r = parser(fixtures.torrent.nodot.file); r.should.be.an('object').and.have.properties(fixtures.torrent.nodot.result); }); it('parent parsing', () => { const r = parser(fixtures.torrent.parent.file); r.should.be.an('object').and.have.properties(fixtures.torrent.parent.result); }); });
'use strict' var countn = require('./') var example = countn(2, function(err, results) { console.log(err, results) console.log('All examples executed.') }) // Example 1 // // When all calls are successful results are concatenated // and returned in callback function var cb = countn(5, function() { example(null, 'example 1 done') }) cb(null, 'this is example call') setTimeout(function() { cb(null, 'this is last call') }, 500) setTimeout(cb, 100) setTimeout(cb, 200) setTimeout(cb, 400) // Example 2 // // When first error occurs, execution is cancelled // and done is called with that error var cb2 = countn(3, function(err) { example(null, 'example 2 done with error: ' + err) }) cb2(null, 'this is first ok call') setTimeout(function() { cb2('this is first error call') }, 100) setTimeout(function() { cb2(null, 'this is second ok call') }, 200)
define(['angular'], function() { 'use strict'; return angular.module('app', [ 'ngRoute', 'app.configs', 'app.filters', 'app.services', 'app.directives', 'app.controllers' ]); });