text
stringlengths 2
6.14k
|
|---|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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 Numbering = function (_require) {
_inherits(Numbering, _require);
function Numbering() {
_classCallCheck(this, Numbering);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Numbering).apply(this, arguments));
}
return Numbering;
}(require("./converter"));
exports.default = Numbering;
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9zdHlsZS9udW1iZXJpbmcuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7O0lBQ3FCOzs7Ozs7Ozs7O0VBQWtCLFFBQVEsYUFBUjs7a0JBQWxCIiwiZmlsZSI6Im51bWJlcmluZy5qcyIsInNvdXJjZXNDb250ZW50IjpbIlxuZXhwb3J0IGRlZmF1bHQgY2xhc3MgTnVtYmVyaW5nIGV4dGVuZHMgcmVxdWlyZShcIi4vY29udmVydGVyXCIpIHtcblxufSJdfQ==
|
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticDragEvent
*/
'use strict';
var SyntheticMouseEvent = require('./SyntheticMouseEvent');
/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var DragEventInterface = {
dataTransfer: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
|
import React from 'react'
var Output = React.createClass({
prepareCorrection(index){
var correctOutput = this.props.output.map(function(o){
return 0.0
})
correctOutput[index] = 1.0
this.props.correction(correctOutput)
},
render: function(){
var component = this
var imagesSrc = [
"img/bed.png",
"img/working.png",
"img/pizza.png",
"img/party.png",
]
var imagesJSX = this.props.output.map(function(o, index){
var width = 50 + (100 * o)
return (
<span className="output-cell">
<img src={imagesSrc[index]} width={width} onClick={component.prepareCorrection.bind(component, index)}/>
</span>
)
})
return (
<div id="output-cells">
{imagesJSX}
</div>
)
}
})
export default Output
|
var CalendarJs = (function () {
'use strict';
function InvalidMonthError(message) {
this.message = message;
this.name = 'InvalidMonthError';
};
function InvalidMonthsAbbrError(message) {
this.message = message;
this.name = 'InvalidMonthsAbbrError';
};
function InvalidMonthsError(message) {
this.message = message;
this.name = 'InvalidMonthsError';
};
var MONTHS = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
var WEEKDAYS = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
];
function generateMonthsAbbr(months) {
return months.map(function(month) {
return month.slice(0, 3);
});
}
return (function(config) {
var _months = MONTHS;
var _monthsAbbr = generateMonthsAbbr(MONTHS);
if (config && config.months) {
if (! Array.isArray(config.months)) {
throw new InvalidMonthsError('Months array must have 12 values');
}
if (config.months.length !== 12) {
throw new InvalidMonthsError('Months array must have 12 values');
}
_months = config.months;
_monthsAbbr = generateMonthsAbbr(config.months);
}
if (config && config.monthsAbbr) {
if (! Array.isArray(config.monthsAbbr)) {
throw new InvalidMonthsAbbrError('Months array must have 12 values');
}
if (config.monthsAbbr.length !== 12) {
throw new InvalidMonthsAbbrError('Months array must have 12 values');
}
_monthsAbbr = config.monthsAbbr;
}
return {
months: function() {
return _months;
},
monthsAbbr: function() {
return _monthsAbbr;
},
years: function(from, to) {
if (from > to) {
throw new RangeError('The first year argument cannot be greater than the second');
}
var years = [ from.toString() ];
var totalYears = to - from + 1;
while (years.length < totalYears) {
var year = parseInt(years[years.length - 1], 10) + 1;
years.push(year.toString());
}
return years;
},
yearsAbbr: function(from, to) {
var years = this.years(from, to).map(function(year) {
return year.toString().substring(2);
});
return (years.length > 1)
? years
: years[0];
},
weekdays: function() {
return WEEKDAYS;
},
weekdaysAbbr: function() {
return this.weekdays().map(function(weekday) {
return weekday.slice(0, 3);
});
},
generateCalendar: function(numberOfDays, firstWeekday, lastWeekday) {
var lastDay = 0;
firstWeekday--;
if (firstWeekday < 0) firstWeekday = 6;
var flag = true;
var init = true;
var day = 0;
var calendar = [];
while (day < numberOfDays) {
var week = [];
for (var i = 0; i < 7; i++) {
if (day < numberOfDays) {
if (init) {
if (i === firstWeekday) {
week.push(++day);
init = false;
}
else {
week.push(0);
}
}
else {
week.push(++day);
}
}
else {
week.push(0);
}
}
calendar.push(week);
}
return calendar;
},
of: function(year, month, transformer) {
if (month < 0 || month > 11) {
throw new InvalidMonthError('Month should be beetwen 0 and 11');
}
if (typeof year !== 'number' || typeof month !== 'number') {
throw new Error('Arguments should be numbers');
}
var numberOfDays = new Date(year, month + 1, 0).getDate();
var firstWeekday = new Date(year, month, 1).getDay();
var lastWeekday = new Date(year, month, numberOfDays).getDay();
const data = {
year: year.toString(),
yearAbbr: this.yearsAbbr(year),
month: this.months()[month],
monthAbbr: this.monthsAbbr()[month],
weekdays: this.weekdays(),
weekdaysAbbr: this.weekdaysAbbr(),
days: numberOfDays,
firstWeekday: firstWeekday,
lastWeekday: lastWeekday,
calendar: this.generateCalendar(numberOfDays, firstWeekday, lastWeekday),
};
if (typeof transformer === 'function') {
return transformer(data);
}
return data;
},
};
})();
})();
|
var gulp = require('gulp');
var eventStream = require('event-stream');
var vulcanize = require('gulp-vulcanize');
gulp.task('copy', function() {
return eventStream.merge(
gulp.src(['www/frontend/bower_components/webcomponentsjs/**/*']).pipe(gulp.dest('build/frontend/bower_components/webcomponentsjs')),
gulp.src(['www/frontend/images/**/*']).pipe(gulp.dest('build/frontend/images')),
gulp.src(['www/frontend/scripts/**/*']).pipe(gulp.dest('build/frontend/scripts')),
gulp.src(['www/frontend/styles/**/*']).pipe(gulp.dest('build/frontend/styles')),
gulp.src(['www/frontend/index.html']).pipe(gulp.dest('build/frontend')),
gulp.src(['www/frontend/manifest.json']).pipe(gulp.dest('build/frontend')),
gulp.src(['www/frontend/favicon.ico']).pipe(gulp.dest('build/frontend')),
gulp.src(['www/frontend/robots.txt']).pipe(gulp.dest('build/frontend'))
);
});
gulp.task('vulcanize', ['copy'], function() {
return gulp.src('www/frontend/elements/elements.html')
.pipe(vulcanize({
stripComments: true,
inlineScripts: true,
inlineCss: true
}))
.pipe(gulp.dest('build/frontend/elements'));
});
gulp.task('default', ['copy','vulcanize']);
|
var util = require('util'),
AlphaShip = require('./alpha.js'),
BetaBullet = require('../bullets/beta.js');
function BetaShip (position, player, map) {
AlphaShip.call(this, position, player, map);
this.type = BetaShip.type;
this.ammo = BetaBullet;
this.velocity = 7;
this.bulletCooldown = 6;
// this.bulletsDeltaAngle = Math.PI / 9;
this.bulletsDeltaAngle = Math.PI / 12;
// this.bulletsPerShoot = 5;
this.bulletsPerShoot = 7;
}
util.inherits(BetaShip, AlphaShip);
BetaShip.type = 31;
module.exports = BetaShip;
|
var list_across0 = [
'_contents_xml.htm',
'_reference.xml',
'_index.xml',
'_search_xml.htm',
'_external.xml'
];
var list_up0 = [
'dismod_pde.xml',
'cpp.xml',
'optimize.xml',
'dismoditis.cpp.xml',
'dismoditis.sh.xml'
];
var list_down4 = [
'whats_new.xml',
'install.xml',
'csv.xml',
'cpp.xml',
'example.xml',
'wish_list.xml',
'bug_list.xml'
];
var list_down3 = [
'optimize.xml',
'create_grid.xml',
'pair2index.xml',
'csv_read.xml',
'str_char_vec.xml',
'atof_char_vec.xml'
];
var list_down2 = [
'ipopt_trace.xml',
'optimize_xam.cpp.xml',
'dismoditis.cpp.xml'
];
var list_down1 = [
'dismoditis.sh.xml'
];
function choose_across0(item)
{ var index = item.selectedIndex;
item.selectedIndex = 0;
if(index > 0)
document.location = list_across0[index-1];
}
function choose_up0(item)
{ var index = item.selectedIndex;
item.selectedIndex = 0;
if(index > 0)
document.location = list_up0[index-1];
}
function choose_down4(item)
{ var index = item.selectedIndex;
item.selectedIndex = 0;
if(index > 0)
document.location = list_down4[index-1];
}
function choose_down3(item)
{ var index = item.selectedIndex;
item.selectedIndex = 0;
if(index > 0)
document.location = list_down3[index-1];
}
function choose_down2(item)
{ var index = item.selectedIndex;
item.selectedIndex = 0;
if(index > 0)
document.location = list_down2[index-1];
}
function choose_down1(item)
{ var index = item.selectedIndex;
item.selectedIndex = 0;
if(index > 0)
document.location = list_down1[index-1];
}
function choose_down0(item)
{ var index = item.selectedIndex;
item.selectedIndex = 0;
if(index > 0)
document.location = list_down0[index-1];
}
function choose_current0(item)
{ var index = item.selectedIndex;
item.selectedIndex = 0;
if(index > 0)
document.location = list_current0[index-1];
}
|
Ext.define('Healthsurvey.view.searchengine.search.ReportChartController', {
extend : 'Ext.app.ViewController',
alias : 'controller.reportChartController',
onAfterrender : function() {
debugger;
currentView = this.getView()
chartjson = currentView.chartJson;
this.view.setHeight((this.view.chartJson.height * 1)+70);
resultPanel = this.view.up().up();
var Value = this.view.up().header.items.items[1].value;
newColumns = parseInt(Value);
totalWidth = (this.view.up().getWidth());
/* totalWidth = (mainPanel.getWidth())
- (defaultWidthToReduce + (newColumns * 5));*/
this.view.chartJson.width = (totalWidth - (10 + (newColumns * 5)))
/ newColumns;
if (chartjson.hasOwnProperty("group") && chartjson.group == true) {
this.loadGroupCharts(chartjson.groupCharts, chartjson,
this.view.chartJson.width);
} else {
var fusionchart = new FusionCharts(this.view.chartJson);
fusionchart.render(this.view.body.id);
}
},
loadGroupCharts : function(groupcharts, chart,totalCalculateWidth) {
var charts = [],
height=500;
for (var x = 0; x < groupcharts.length; x++) {
height= groupcharts[x].height*1+100;
charts.push({
xtype : "panel",
height : height,
scope : this,
margin : '0 5 0 0',
chartwidth : (totalCalculateWidth / groupcharts.length)-7,
chartJSON : groupcharts[x],
listeners : {
afterrender : function(panel) {
panel.chartJSON.width = panel.chartwidth;
var fusionchart = new FusionCharts(panel.chartJSON);
fusionchart.render(panel.body.id);
}
}
});
}
this.getView().add({
xtype : "panel",
margin : '0 5 0 0',
title : chart.chartTitle,
bodyStyle : 'background:#D8D8D8',
group : true,
scope : this,
width : "100%",
height:height,
layout : {
type : 'table',
columns : charts.length
},
items : charts
});
// this.resizeCharts(this.getView().down("#chartcolumnlayout"));
}
});
|
module.exports = {
create: {
key: {
type: 'string'
},
value: {
type: 'json'
}
}
};
|
var class_correlator =
[
[ "EConditions", "df/d86/class_correlator.html#a9520b711db5a9b2b4d04afef26600782", [
[ "INVALID_LOCATION", "df/d86/class_correlator.html#a9520b711db5a9b2b4d04afef26600782a56a991782a1881b95b11e506139d235f", null ],
[ "VALID_IMPLANT", "df/d86/class_correlator.html#a9520b711db5a9b2b4d04afef26600782a9ca76a3c26245dc43c3a92bc32aad3bc", null ],
[ "VALID_DECAY", "df/d86/class_correlator.html#a9520b711db5a9b2b4d04afef26600782a0c6f1ffa795be8f759c28b237e4d04c1", null ],
[ "BACK_TO_BACK_IMPLANT", "df/d86/class_correlator.html#a9520b711db5a9b2b4d04afef26600782a51d3d267509a9fd6ffa5c014d02ff963", null ],
[ "DECAY_TOO_LATE", "df/d86/class_correlator.html#a9520b711db5a9b2b4d04afef26600782acd6947d65414ba198118ae04ec810394", null ],
[ "IMPLANT_TOO_SOON", "df/d86/class_correlator.html#a9520b711db5a9b2b4d04afef26600782a968229b59757a7753a98452cb03d9df2", null ],
[ "UNKNOWN_CONDITION", "df/d86/class_correlator.html#a9520b711db5a9b2b4d04afef26600782a8175556fea5d64a09d0e09ed99c1c87f", null ]
] ],
[ "Correlator", "df/d86/class_correlator.html#a6114955836dba0b4b61138490cd3fe91", null ],
[ "~Correlator", "df/d86/class_correlator.html#a48307431ca91b41319c6b68c6684634d", null ],
[ "Correlate", "df/d86/class_correlator.html#a24bd6e7418fd89b55da9d0d4e6f0ac42", null ],
[ "CorrelateAll", "df/d86/class_correlator.html#a5365ba0cfee1d3ae3e11099fc90ce071", null ],
[ "CorrelateAllX", "df/d86/class_correlator.html#a9781c6812736459e2f996579a04ea1a3", null ],
[ "CorrelateAllY", "df/d86/class_correlator.html#aa7fb605cbe3261b5beae1e1ed7f9fa54", null ],
[ "DeclareHistogram1D", "df/d86/class_correlator.html#a1fd07a20132308aedb587a4f64bd4023", null ],
[ "DeclareHistogram2D", "df/d86/class_correlator.html#a78c13f9fbc37ab4ee62bdea80111172b", null ],
[ "DeclarePlots", "df/d86/class_correlator.html#af85499cc4980518c780cb245b6a9f447", null ],
[ "Flag", "df/d86/class_correlator.html#acfe7546a52ab5a8b653c3aa29f8da417", null ],
[ "GetCondition", "df/d86/class_correlator.html#a775b01a6d93e69ae650a5d6a41cf790c", null ],
[ "GetDecayTime", "df/d86/class_correlator.html#a4b8ccf4ed7593343a4fe9a7cfbbfd3c0", null ],
[ "GetDecayTime", "df/d86/class_correlator.html#ae6be7e320cba9e451a290e3ee14e1d7c", null ],
[ "GetImplantTime", "df/d86/class_correlator.html#ac8b3a6e8b93bbd34bc12765ae6903a73", null ],
[ "GetImplantTime", "df/d86/class_correlator.html#a8ae1f55e0c517dad940cd54987dd9ab2", null ],
[ "Init", "df/d86/class_correlator.html#a11b02e3bfa79669ca9d2087aa3c8fa4c", null ],
[ "IsFlagged", "df/d86/class_correlator.html#abb0dac63822efc9e18558c133ff2f1c5", null ],
[ "plot", "df/d86/class_correlator.html#a3581405ad5a68e25f1998648a2a66b0a", null ],
[ "PrintDecayList", "df/d86/class_correlator.html#a1f6a356d0fd4ff6d310889f7423dfb11", null ],
[ "arraySize", "df/d86/class_correlator.html#acb96c72e8646bf2e95260588cf86cbde", null ],
[ "condition", "df/d86/class_correlator.html#af576e919bbaa18ce6d3474ecc5dff300", null ],
[ "corrTime", "df/d86/class_correlator.html#ad5b5e44c6e56e1135beca52ee89fb33d", null ],
[ "decaylist", "df/d86/class_correlator.html#ab9ad70d0effc24524e488d1a05da63ad", null ],
[ "fastTime", "df/d86/class_correlator.html#a9b4cd5a5bac9f78142f3ad4a12db9f86", null ],
[ "histo", "df/d86/class_correlator.html#a937c1fc0d679d6c5d894d627654b8ad4", null ],
[ "lastDecay", "df/d86/class_correlator.html#a9ef633a6175d78901f9e12455ab4621c", null ],
[ "lastImplant", "df/d86/class_correlator.html#ad154495f2bd4197f0847f792847641b8", null ],
[ "minImpTime", "df/d86/class_correlator.html#a41f0544e6390256e63ff66b118404f1c", null ]
];
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import AlbumTitleLink from 'Album/AlbumTitleLink';
import TrackQuality from 'Album/TrackQuality';
import ArtistNameLink from 'Artist/ArtistNameLink';
import IconButton from 'Components/Link/IconButton';
import RelativeDateCellConnector from 'Components/Table/Cells/RelativeDateCellConnector';
import TableRowCell from 'Components/Table/Cells/TableRowCell';
import TableRow from 'Components/Table/TableRow';
import { icons } from 'Helpers/Props';
import HistoryDetailsModal from './Details/HistoryDetailsModal';
import HistoryEventTypeCell from './HistoryEventTypeCell';
import styles from './HistoryRow.css';
class HistoryRow extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
isDetailsModalOpen: false
};
}
componentDidUpdate(prevProps) {
if (
prevProps.isMarkingAsFailed &&
!this.props.isMarkingAsFailed &&
!this.props.markAsFailedError
) {
this.setState({ isDetailsModalOpen: false });
}
}
//
// Listeners
onDetailsPress = () => {
this.setState({ isDetailsModalOpen: true });
}
onDetailsModalClose = () => {
this.setState({ isDetailsModalOpen: false });
}
//
// Render
render() {
const {
artist,
album,
track,
quality,
qualityCutoffNotMet,
eventType,
sourceTitle,
date,
data,
isMarkingAsFailed,
columns,
shortDateFormat,
timeFormat,
onMarkAsFailedPress
} = this.props;
if (!artist || !album) {
return null;
}
return (
<TableRow>
{
columns.map((column) => {
const {
name,
isVisible
} = column;
if (!isVisible) {
return null;
}
if (name === 'eventType') {
return (
<HistoryEventTypeCell
key={name}
eventType={eventType}
data={data}
/>
);
}
if (name === 'artists.sortName') {
return (
<TableRowCell key={name}>
<ArtistNameLink
foreignArtistId={artist.foreignArtistId}
artistName={artist.artistName}
/>
</TableRowCell>
);
}
if (name === 'albums.title') {
return (
<TableRowCell key={name}>
<AlbumTitleLink
foreignAlbumId={album.foreignAlbumId}
title={album.title}
disambiguation={album.disambiguation}
/>
</TableRowCell>
);
}
if (name === 'trackTitle') {
return (
<TableRowCell key={name}>
{track.title}
</TableRowCell>
);
}
if (name === 'quality') {
return (
<TableRowCell key={name}>
<TrackQuality
quality={quality}
isCutoffMet={qualityCutoffNotMet}
/>
</TableRowCell>
);
}
if (name === 'date') {
return (
<RelativeDateCellConnector
key={name}
date={date}
/>
);
}
if (name === 'downloadClient') {
return (
<TableRowCell
key={name}
className={styles.downloadClient}
>
{data.downloadClient}
</TableRowCell>
);
}
if (name === 'indexer') {
return (
<TableRowCell
key={name}
className={styles.indexer}
>
{data.indexer}
</TableRowCell>
);
}
if (name === 'releaseGroup') {
return (
<TableRowCell
key={name}
className={styles.releaseGroup}
>
{data.releaseGroup}
</TableRowCell>
);
}
if (name === 'details') {
return (
<TableRowCell
key={name}
className={styles.details}
>
<IconButton
name={icons.INFO}
onPress={this.onDetailsPress}
/>
</TableRowCell>
);
}
return null;
})
}
<HistoryDetailsModal
isOpen={this.state.isDetailsModalOpen}
eventType={eventType}
sourceTitle={sourceTitle}
data={data}
isMarkingAsFailed={isMarkingAsFailed}
shortDateFormat={shortDateFormat}
timeFormat={timeFormat}
onMarkAsFailedPress={onMarkAsFailedPress}
onModalClose={this.onDetailsModalClose}
/>
</TableRow>
);
}
}
HistoryRow.propTypes = {
albumId: PropTypes.number,
artist: PropTypes.object.isRequired,
album: PropTypes.object,
track: PropTypes.object,
quality: PropTypes.object.isRequired,
qualityCutoffNotMet: PropTypes.bool.isRequired,
eventType: PropTypes.string.isRequired,
sourceTitle: PropTypes.string.isRequired,
date: PropTypes.string.isRequired,
data: PropTypes.object.isRequired,
isMarkingAsFailed: PropTypes.bool,
markAsFailedError: PropTypes.object,
columns: PropTypes.arrayOf(PropTypes.object).isRequired,
shortDateFormat: PropTypes.string.isRequired,
timeFormat: PropTypes.string.isRequired,
onMarkAsFailedPress: PropTypes.func.isRequired
};
HistoryRow.defaultProps = {
track: {
title: ''
}
};
export default HistoryRow;
|
/**
* Rirc - IRC client by rigor789
* Copyright (C) 2014 Igor Randjelovic <rigor789>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
exports.User = function(nick, permission, color) {
this.nick = nick;
this.permission = permission;
this.color = color;
}
|
/* @flow */
import {css} from 'glamor';
import Modal from 'react-modal';
import React from 'react';
import {t} from '../styles';
import CloseIcon from './CloseIcon';
const Modal_ = (
props: {
className?: string,
children?: React$Element<any>,
onRequestClose(): void,
},
) => {
const handleRequestClose = () => {
props.onRequestClose();
window.openModals -= 1;
if (window.openModals > 0) {
(document.body: any).classList.add('modal-open');
} else {
(document.body: any).classList.remove('modal-open');
}
};
return (
<Modal
{...props}
className={styles.modal}
onAfterOpen={() => {
const el = document.querySelector('.ReactModal__Overlay');
const modalEl = document.querySelector('.ReactModal__Content');
const handler = (e: Object) => {
const target = e.targetTouches.length > 0
? e.targetTouches[0]
: e.target;
if (modalEl && !modalEl.contains(target)) {
e.preventDefault();
el && el.removeEventListener('touchend', handler);
handleRequestClose();
}
};
el && el.addEventListener('touchend', handler);
window.openModals = window.openModals ? window.openModals + 1 : 1;
(document.body: any).classList.add('modal-open');
}}
onRequestClose={handleRequestClose}
>
<div className={styles.modalContentContainer}>
<button className={styles.closeButton} onClick={handleRequestClose}>
<CloseIcon size={40} />
</button>
<div
className={
`${styles.modalContentInner} ${props.className || ''}.trim()`
}
>
{props.children}
</div>
</div>
</Modal>
);
};
const styles = {
modal: css({
...t.absolute,
...t.absolute__fill,
...t.outline_0,
...t.overflow_hidden,
}),
modalContentContainer: css({
...t.flex,
...t.flex_column,
...t.h_100,
}),
closeButton: css({
...t.input_reset,
...t.button_reset,
...t.bg_transparent,
...t.outline_0,
...t.bn,
...t.w_100,
...t.dim,
...t.pv0,
...t.ph3,
height: '6rem',
'> svg': {
...t.fr,
},
}),
modalContentInner: css({
...t.overflow_x_hidden,
...t.overflow_y_auto,
flex: 1,
}),
};
export default Modal_;
|
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
config = {
context: __dirname + "/src",
output: {
path: __dirname + '/dist',
filename: 'kismet.[name].js',
library: "Kismet",
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel?cacheDirectory'],
},
{
test: /\.jison$/,
loader: '../loaders/jison-loader.js'
},
{
test: /jStat/,
loader: 'babel?cacheDirectory!imports?this=>module.exports'
},
{
test: /\.s?css$/,
loader: ExtractTextPlugin.extract("css!sass")
},
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=1000000&mimetype=application/font-woff'
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=1000000&mimetype=application/font-sfnt'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=1000000&mimetype=application/vnd.ms-fontobject'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=1000000&mimetype=image/svg+xml'
}
]
},
plugins: [
new ExtractTextPlugin("kismet.[name].css"),
],
};
if(process.argv.indexOf('--debug') == -1) {
config.plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin()
);
}
let cli_conf = Object.assign({},config, {
target: "node",
entry: {
cli: './cli.js'
},
output: {
path: __dirname + '/dist',
filename: 'kismet.[name].js',
library: "Kismet",
libraryTarget: "commonjs2",
},
});
let component_conf = Object.assign({},config, {
entry: {
component: './component.jsx',
},
node: {
fs: 'empty'
}
});
module.exports = [ cli_conf, component_conf ];
|
$(document).ready(function(){
$("button").click(function(){
var first = $("#first").val();
var second = $("#second").val();
var a = $("select").val();
var result;
if (a == "+") {
result = parseInt(first)+parseInt(second);
}else if (a == "-") {
result = parseInt(first)-parseInt(second);
}else if (a == "*") {
result = parseInt(first)*parseInt(second);
}else if (a == "/") {
result = parseInt(first)/parseInt(second);
}
var str = "" + result;
$("input[name='location[state_id]'").val(str);
});
});
|
// import
import styles from './BookView.css';
import React, {Component} from 'react';
import {withRouteData} from 'react-static';
import pt from 'prop-types';
import _ from 'lodash';
import Head from '../Head/Head';
import SiteMain from '../SiteMain/SiteMain';
import {emitPageMenu} from '../SiteHeader/SiteHeader';
import ContentSplash from '../ContentSplash/ContentSplash';
import {getStripeRepeater} from '../ContentStripe/ContentStripe';
import KitBookHeader from '../KitBookHeader/KitBookHeader';
import KitBookList from '../KitBookList/KitBookList';
import KitNewsEvents from '../KitNewsEvents/KitNewsEvents';
import KitPressAwards from '../KitPressAwards/KitPressAwards';
import KitArticlePubs from '../KitArticlePubs/KitArticlePubs';
import KitFaqList from '../KitFaqList/KitFaqList';
import KitQuotesReviews from '../KitQuotesReviews/KitQuotesReviews';
import KitBookClub from '../KitBookClub/KitBookClub';
import KitLikeList from '../KitLikeList/KitLikeList';
import KitAssets from '../KitAssets/KitAssets';
// component
@withRouteData
export default class BookView extends Component {
static propTypes = {
book: pt.object,
series: pt.object,
};
componentDidMount() {
emitPageMenu(this);
}
componentDidUpdate() {
emitPageMenu(this);
}
render() {
const {book, series} = this.props;
const Stripe = getStripeRepeater();
const project = series.meta.category === 'standard' ? series : book;
const {bookClub, pressRelease, ...rest} = _.groupBy(book.articleList, (n) => _.camelCase(n.meta.category));
const articleList = _.flatten(rest);
return (
<SiteMain className={styles.BookView} ref={(c) => this.root = c}>
<Head>
<title>{book.subtitle ? `${book.title}: ${book.subtitle}` : book.title}</title>
</Head>
<ContentSplash image={series.banner.head}/>
<KitBookHeader book={book} id="info" series={series}/>
{series.bookList.length > 1 ? (
<Stripe id="series">
<KitBookList bookList={series.bookList} cta series={series}/>
</Stripe>
) : null}
{book.newsList.length + book.eventList.length >= 4 ? (
<Stripe id="news">
<KitNewsEvents eventList={book.eventList} newsList={book.newsList}/>
</Stripe>
) : null}
{book.pressList.length ? (
<Stripe id="press">
<KitPressAwards awardList={book.awardList} pressList={book.pressList} pressReleaseList={pressRelease}/>
</Stripe>
) : null}
{articleList.length ? (
<Stripe id="articles">
<KitArticlePubs articleList={articleList}/>
</Stripe>
) : null}
{book.faqList.length ? (
<Stripe id="faq">
<KitFaqList faqList={book.faqList} project={project}/>
</Stripe>
) : null}
{book.quoteList.length || book.amazonReviews ? (
<Stripe id="reviews">
<KitQuotesReviews amazonReviews={book.amazonReviews} quoteList={book.quoteList}/>
</Stripe>
) : null}
{bookClub && bookClub.length ? (
<Stripe id="book club">
<KitBookClub bookClubList={bookClub} excerptList={book.excerptList} flashList={book.flashList}/>
</Stripe>
) : null}
{book.likeList.length ? (
<Stripe id="influence">
<KitLikeList likeList={book.likeList} project={project}/>
</Stripe>
) : null}
{book && series ? (
<Stripe id="kit">
<KitAssets node={book} pressReleaseList={pressRelease}/>
</Stripe>
) : null}
</SiteMain>
);
}
}
|
import {takeEvery} from 'redux-saga'
import {put, call} from 'redux-saga/effects'
import denodeify from '../../../lib/utils/denodeify'
import {getStore} from '../../store'
import {browserHistory} from 'react-router'
import {ACTION_VALIDATE} from '../validate'
import loggedIn from '../loggedIn'
export default function* signupWatcher() {
yield* takeEvery(ACTION_VALIDATE, function* (action){
console.log("validating user ", action);
try {
const result = yield call(denodeify(Meteor.call), 'verifyToken', action.authyId, action.token)
yield put(loggedIn(Meteor.user()))
browserHistory.push('/home')
} catch(error) {
console.log(error)
swal('verification failed', error.reason || "please check your token and try again", "error")
}
})
}
|
/* global jQuery */
(function (global, $, undefined) {
$(function () {
var play = '{"event":"command","func":"playVideo"}',
pause = '{"event":"command","func":"pauseVideo"}'
$.fn.carouselVideo = function (options) {
var iframes = this.find('iframe.yt'),
$carousel = this
var masks = iframes.map(function (i, obj) {
var mask = $('<div class="ytmask">')
return mask.appendTo($(obj).closest('.item'))
})
this.on('click', '.ytmask', function (e) {
var $this = $(this)
$carousel.carousel('pause')
$this
.hide()
.closest('.item')
.find('iframe.yt')
.get(0)
.contentWindow
.postMessage(play, '*')
})
this.on('slid.bs.carousel', function () {
$carousel.carousel('cycle')
iframes.each(function () {
this.contentWindow.postMessage(pause, '*')
})
masks.each(function () {
$(this).show()
})
})
}
$('.js-carousel-ytvideo').carouselVideo()
})
})(window, jQuery)
|
Ext.define('IW.view.wiki.Window', {
extend: 'Ext.window.Window',
xtype: 'basic-window',
alias: 'widget.wikiwindow',
title: 'Wikis',
height: 400,
width: 400,
layout: 'fit',
autoShow: true,
collapsible: true,
closable: false,
tools: [{
type: 'plus',
tooltip: 'Create new Wiki',
width: 16,
handler: function(event, target, owner, tool) {
this.up('window').fireEvent('itemnewbuttonclick');
}
}],
collapsible: true,
initComponent: function() {
this.items = [
{
xtype: 'wikilist'
}
];
this.callParent(arguments);
}
});
|
(function () {
'use strict';
function Config(DashboardItemsProvider, $stateProvider) {
DashboardItemsProvider.register('monitor', 'Monitor');
$stateProvider.state({
name: 'dashboard.monitor',
url: '/monitor',
component: 'monitor'
});
}
Config.$inject = ['DashboardItemsProvider', '$stateProvider'];
angular.module('isms.dashboard').config(Config);
}());
|
const StoriesComponent = require('./stories.component.js');
module.exports = {
StoriesComponent
};
|
const fs = require('fs');
const path = require('path');
const async = require('async');
const byline = require('byline');
const expect = require("chai").expect;
const resultFileName = './test/e2e/result/stream-default.txt';
const resultFileLangName = './test/e2e/result/stream-translation.txt';
const filenameData = path.parse(__filename);
const iterationIndex = filenameData.name.split('-').pop();
const filesCount = 8;
const gitCsvDiff = require("../../index");
describe("e2e: ddf--ws-testing || chore(update): change concepts", function() {
it("compare diff", function(done) {
const dataPackage = require(`./data/commit-${iterationIndex}-datapackage`);
const streamDefault = fs.createWriteStream(resultFileName);
const streamTranslation = fs.createWriteStream(resultFileLangName);
const iterationList = [];
for(let i = 1; i <= filesCount; i++) {
iterationList.push(`./data/commit-${iterationIndex}-${i}-metadata`);
}
async.mapSeries(
iterationList,
// iteration
function(iterationFile, doneMapLimit) {
const config = require(iterationFile);
// setup iteration data
config.metaData.datapackage = dataPackage;
config.streams.diff = streamDefault;
config.streams.lang = streamTranslation;
gitCsvDiff.process(config.metaData, config.dataDiff, config.streams, function() {
return doneMapLimit();
});
},
// callback
function () {
let rowCounter;
streamDefault.end();
streamTranslation.end();
rowCounter = 0;
const diffFixtureDefault = fs.readFileSync(`./test/e2e/data/commit-${iterationIndex}-fixture-default.txt`, 'utf8');
const diffFixtureDefaultRows = diffFixtureDefault.split("\n");
const streamReadDefault = byline(fs.createReadStream(resultFileName, { encoding: 'utf8' }));
streamReadDefault.on('data', function(line) {
expect(line).to.eql(diffFixtureDefaultRows[rowCounter]);
rowCounter++;
});
streamReadDefault.on('end', function() {
rowCounter = 0;
const diffFixtureTranslation = fs.readFileSync('./test/e2e/data/commit-1-fixture-translation.txt', 'utf8');
const diffFixtureTranslationRows = diffFixtureTranslation.split("\n");
const streamReadTranslation = byline(fs.createReadStream(resultFileLangName, { encoding: 'utf8' }));
streamReadTranslation.on('data', function(line) {
expect(line).to.eql(diffFixtureTranslationRows[rowCounter]);
rowCounter++;
});
streamReadTranslation.on('end', function() {
done();
});
});
}
);
});
});
|
/*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Olson the Toy Soldier
2040002
map: 922000010
quest: 3230
escape: 2040028
*/
var status = 0;
function start() {
if (cm.isQuestStarted(3230))
cm.sendNext("The pendulum is hidden inside a dollhouse that looks different than the others.");
else {
cm.sendOk("Hello there.");
cm.dispose();
}
}
function action(mode, type, selection) {
if (mode < 1)
cm.dispose();
else {
status++;
if (status == 1)
cm.sendYesNo("Are you ready to enter the dollhouse map?");
else if (status == 2) {
cm.warp(922000010,0);
cm.dispose();
}
}
}
|
/*!
* Copyright (c) 2014-present Cliqz GmbH. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
const env = (process.env.CLIQZ_ENVIRONMENT || 'development').toUpperCase();
const IS_BETA = process.env.CLIQZ_BETA === 'True';
module.exports = {
[env]: true,
IS_BETA,
INCLUDE_TESTS: process.env.CLIQZ_INCLUDE_TESTS,
SOURCE_MAPS: !(process.env.CLIQZ_SOURCE_MAPS === 'false'),
DEBUG_PAGES: !(process.env.CLIQZ_SOURCE_DEBUG === 'false'),
};
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import chai, { expect } from "chai";
import chaiEnzyme from "chai-enzyme";
import { Localized } from "fluent-react";
import React from "react";
import configureStore from "redux-mock-store";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import { initialState, filledState } from "../mock-redux-state";
import mountWithL10n from "test/mocks/l10n";
import { SELECT_ITEM_STARTING } from "src/webextension/list/actions";
import { NEW_ITEM_ID } from "src/webextension/list/common";
import { ItemListPlaceholder } from
"src/webextension/list/components/item-list";
import ItemSummary from "src/webextension/list/components/item-summary";
import AllItems from "src/webextension/list/manage/containers/all-items";
chai.use(chaiEnzyme());
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe("list > manage > containers > <AllItems/>", () => {
beforeEach(() => {
browser.runtime.onMessage.addListener(() => ({}));
});
afterEach(() => {
browser.runtime.onMessage.mockClearListener();
});
describe("empty state", () => {
let store, wrapper;
beforeEach(() => {
store = mockStore(initialState);
wrapper = mountWithL10n(
<Provider store={store}>
<AllItems/>
</Provider>
);
});
it("render items", () => {
expect(wrapper.find(ItemSummary)).to.have.length(0);
expect(wrapper.find(ItemListPlaceholder)).to.have.text(
"wHEn yOu cREATe an eNTRy..."
);
});
});
describe("filled state", () => {
let store, wrapper;
beforeEach(() => {
store = mockStore(filledState);
wrapper = mountWithL10n(
<Provider store={store}>
<AllItems/>
</Provider>
);
});
it("render items", () => {
const expectedTitle = filledState.cache.currentItem.title;
expect(wrapper.find(ItemSummary)).to.have.length(3);
expect(wrapper.find("li").filterWhere(
(x) => x.prop("data-selected")
).find(ItemSummary).prop("title")).to.equal(expectedTitle);
});
it("selectItem() dispatched", () => {
wrapper.find(ItemSummary).at(0).simulate("mousedown", {button: 0});
expect(store.getActions()[0].type).to.equal(SELECT_ITEM_STARTING);
});
});
describe("filled state (with filters)", () => {
let store, wrapper;
beforeEach(() => {
store = mockStore({
...filledState,
list: {
...filledState.list,
filter: {
query: "2",
userEntered: true,
},
},
});
wrapper = mountWithL10n(
<Provider store={store}>
<AllItems/>
</Provider>
);
});
it("render items", () => {
expect(wrapper.find(ItemSummary)).to.have.length(1);
});
});
describe("new item placeholder", () => {
let store, wrapper;
beforeEach(() => {
store = mockStore({
...initialState,
list: {
...initialState.list,
selectedItemId: NEW_ITEM_ID,
},
});
wrapper = mountWithL10n(
<Provider store={store}>
<AllItems/>
</Provider>
);
});
it("render items", () => {
const item = wrapper.find(ItemSummary);
expect(item).to.have.length(1);
expect(item.find(Localized).at(0)).to.have.prop(
"id", "item-summary-new-title"
);
});
});
});
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
var utils = require("./utils");
var readParam = utils.readParam;
var path = require("path");
var fs = require("fs");
var jpm = utils.run;
var sdk = path.join(__dirname, "..", "..");
var binary = process.env.JPM_FIREFOX_BINARY || "nightly";
var filterPattern = readParam("filter");
describe("jpm test sdk modules", function () {
it("SDK Modules", function (done) {
process.chdir(sdk);
var options = { cwd: sdk, env: { JPM_FIREFOX_BINARY: binary } };
if (process.env.DISPLAY) {
options.env.DISPLAY = process.env.DISPLAY;
}
options.filter = filterPattern;
jpm("test", options, process).then(done);
});
});
|
function changeSlide(){
navigator.requestWakeLock('screen');
var deviceSpecs
if(navigator.userAgent.indexOf("LG-D300")>=0){
deviceSpecs = '#lgSpecs';
} else if(navigator.userAgent.indexOf("ALCATEL ONE TOUCH 4012")>=0) {
deviceSpecs = '#alcatelSpecs';
} else if(navigator.userAgent.indexOf("ZTEOPEN")>=0) {
deviceSpecs = '#zteSpecs';
} else {
deviceSpecs = '#unsupported';
}
showFox(deviceSpecs);
setInterval(function(){internalChange(deviceSpecs);}, 50000);
}
function internalChange(deviceSpecs){
showFox(deviceSpecs);
setTimeout(function(){showSpecs(deviceSpecs);}, 15000);
}
function showFox(deviceSpecs){
var foxy = $("#foxy");
var specs = $("#specs");
var deviceSpecs = $(deviceSpecs);
foxy.css("left", "50px");
specs.css("left", "-500px");
deviceSpecs.css("display", "none");
}
function showSpecs(deviceSpecs){
var foxy = $("#foxy");
var specs = $("#specs");
var deviceSpecs = $(deviceSpecs);
foxy.css("left", "-500px");
specs.css("left", "0px");
deviceSpecs.css("display", "block");
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import chai, { expect } from "chai";
import PropTypes from "prop-types";
import React from "react";
import Modal from "react-modal";
import { Provider } from "react-redux";
import configureStore from "redux-mock-store";
import thunk from "redux-thunk";
import sinon from "sinon";
import sinonChai from "sinon-chai";
import mountWithL10n from "test/mocks/l10n";
import { initialState } from "../mock-redux-state";
import ModalRootWidget from "src/webextension/widgets/modal-root";
import ModalRoot, { LocalResetModal } from
"src/webextension/settings/containers/modals";
import * as actions from "src/webextension/settings/actions";
chai.use(sinonChai);
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe("settings > containers > modals", () => {
describe("<ModalRoot/>", () => {
beforeEach(() => {
// Enzyme doesn't support React Portals yet; see
// <https://github.com/airbnb/enzyme/issues/1150>.
ModalRootWidget.__Rewire__(
"Modal", class FakeModal extends React.Component {
static get propTypes() {
return {
children: PropTypes.node,
};
}
render() {
return <div>{this.props.children}</div>;
}
}
);
});
afterEach(() => {
ModalRootWidget.__ResetDependency__("Modal");
});
const MODAL_STATE = {
id: "local-reset",
props: {},
};
const MODAL_COMPONENT = LocalResetModal;
it("no modal", () => {
const store = mockStore(initialState);
const wrapper = mountWithL10n(
<Provider store={store}>
<ModalRoot/>
</Provider>
);
expect(wrapper.find(Modal)).to.have.length(0);
});
it("with modal", () => {
const store = mockStore({
...initialState,
modal: MODAL_STATE,
});
const wrapper = mountWithL10n(
<Provider store={store}>
<ModalRoot/>
</Provider>
);
expect(wrapper.find(MODAL_COMPONENT)).to.have.length(1);
});
it("hideModal() dispatched when closing modal", () => {
const store = mockStore({
...initialState,
modal: MODAL_STATE,
});
const wrapper = mountWithL10n(
<Provider store={store}>
<ModalRoot/>
</Provider>
);
wrapper.find("button").last().simulate("click");
expect(store.getActions()).to.deep.equal([
{ type: actions.HIDE_MODAL },
]);
});
});
describe("<LocalResetModal/>", () => {
let store, wrapper, onClose;
beforeEach(() => {
onClose = sinon.spy();
store = mockStore(initialState);
wrapper = mountWithL10n(
<Provider store={store}>
<LocalResetModal onClose={onClose}/>
</Provider>
);
});
it("localRest() dispatched and onClose() called", () => {
wrapper.find("button").first().simulate("click");
const dispatched = store.getActions();
expect(dispatched[0]).to.deep.equal({
type: actions.LOCAL_RESET_STARTING,
actionId: dispatched[0].actionId,
});
expect(onClose).to.have.been.calledWith();
});
it("onClose() called", () => {
wrapper.find("button").last().simulate("click");
expect(store.getActions()).to.deep.equal([]);
expect(onClose).to.have.been.calledWith();
});
});
});
|
(function () {
'use strict';
/**
* POPINS
*/
define(function () {
function Popin() {
this.create = function () {
console.info('popin créé');
};
this.open = function () {
alert('popin ouvert');
};
this.close = function () {
alert('popin fermé');
};
}
return Popin;
});
}());
|
'use strict';
var main = require('../lib/main');
exports['test main'] = function(assert) {
assert.pass('Unit test running!');
};
exports['test main async'] = function(assert, done) {
assert.pass('async Unit test running!');
done();
};
require('sdk/test').run(exports);
|
suite('ICAL.helpers', function() {
suite('#clone', function() {
var subject = ICAL.helpers.clone;
test('some primatives', function() {
assert.equal(subject(null, false), null);
assert.equal(subject(123, false), 123);
assert.equal(subject(null, true), null);
assert.equal(subject(123, true), 123);
});
test('a date', function() {
var date = new Date(2015, 1, 1);
var time = date.getTime();
var copy = subject(date, false);
copy.setYear(2016);
assert.notEqual(time, copy.getTime());
});
test('clonable', function() {
var obj = { clone: function() { return "test"; } };
assert.equal(subject(obj, false), "test");
});
test('shallow array', function() {
var obj = { v: 2 }
var arr = [obj, 2, 3];
var result = subject(arr, false);
assert.deepEqual(result, [{ v: 2 }, 2, 3]);
obj.v = 3;
assert.deepEqual(result, [{ v: 3 }, 2, 3]);
});
test('deep array', function() {
var obj = { v: 2 }
var arr = [obj, 2, 3];
var result = subject(arr, true);
assert.deepEqual(result, [{ v: 2 }, 2, 3]);
obj.v = 3;
assert.deepEqual(result, [{ v: 2 }, 2, 3]);
});
test('shallow object', function() {
var deepobj = { v: 2 };
var obj = { a: deepobj, b: 2 };
var result = subject(obj, false);
assert.deepEqual(result, { a: { v: 2 }, b: 2 });
deepobj.v = 3;
assert.deepEqual(result, { a: { v: 3 }, b: 2 });
});
test('deep object', function() {
var deepobj = { v: 2 };
var obj = { a: deepobj, b: 2 };
var result = subject(obj, true);
assert.deepEqual(result, { a: { v: 2 }, b: 2 });
deepobj.v = 3;
assert.deepEqual(result, { a: { v: 2 }, b: 2 });
});
});
suite('#pad2', function() {
var subject = ICAL.helpers.pad2;
test('with string', function() {
assert.equal(subject(""), "00");
assert.equal(subject("1"), "01");
assert.equal(subject("12"), "12");
assert.equal(subject("123"), "123");
});
test('with number', function() {
assert.equal(subject(0), "00");
assert.equal(subject(1), "01");
assert.equal(subject(12), "12");
assert.equal(subject(123), "123");
});
test('with boolean', function() {
assert.equal(subject(true), "true");
});
});
suite('#foldline', function() {
var subject = ICAL.helpers.foldline;
test('empty values', function() {
assert.strictEqual(subject(null), "");
assert.strictEqual(subject(""), "");
});
// Most other cases are covered by other tests
});
suite('#updateTimezones', function() {
var subject = ICAL.helpers.updateTimezones;
var cal;
testSupport.defineSample('minimal.ics', function(data) {
cal = new ICAL.Component(ICAL.parse(data));
});
testSupport.defineSample('timezones/America/Atikokan.ics', function(data) {
ICAL.TimezoneService.register(
(new ICAL.Component(ICAL.parse(data))).getFirstSubcomponent("vtimezone")
);
});
suiteTeardown(function() {
ICAL.TimezoneService.reset();
});
test('timezones already correct', function() {
var vtimezones;
vtimezones = cal.getAllSubcomponents("vtimezone");
assert.strictEqual(vtimezones.length, 1);
assert.strictEqual(
vtimezones[0].getFirstProperty("tzid").getFirstValue(),
"America/Los_Angeles"
);
});
test('remove extra timezones', function() {
var vtimezones, atikokan;
cal.addSubcomponent(
ICAL.TimezoneService.get("America/Atikokan").component
);
vtimezones = cal.getAllSubcomponents("vtimezone");
assert.strictEqual(vtimezones.length, 2);
vtimezones = subject(cal).getAllSubcomponents("vtimezone");
assert.strictEqual(vtimezones.length, 1);
assert.strictEqual(
vtimezones[0].getFirstProperty("tzid").getFirstValue(),
"America/Los_Angeles"
);
});
test('add missing timezones', function() {
cal.getFirstSubcomponent("vevent").
getFirstProperty("dtend").setParameter("tzid", "America/Atikokan");
vtimezones = cal.getAllSubcomponents("vtimezone");
assert(vtimezones.length, 1);
vtimezones = subject(cal).getAllSubcomponents("vtimezone");
assert.strictEqual(vtimezones.length, 2);
});
test('return non-vcalendar components unchanged', function() {
var vevent = cal.getFirstSubcomponent("vevent");
assert.deepEqual(subject(vevent), vevent);
});
});
});
|
import ULinkORDialogContent from './ULinkORDialogContent'
export default ULinkORDialogContent
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { merge } from 'lodash'
import { makeExecutableSchema } from 'graphql-tools';
const rootDefs = `
type Query {
ingredient(name: String!): Ingredient
user(handler: String!): User
}
schema {
query: Query
}
`
const rootResolvers = {
Query: {
user(_, args, context) {
return context.User.get(args.handler)
},
ingredient(_, args, context) {
return context.Ingredient.get(args.name)
}
}
}
import {userSchema, userResolvers} from './users/schema'
import {ingredientSchema, ingredientResolvers} from './ingredients/schema'
export default makeExecutableSchema({
typeDefs: [rootDefs, userSchema, ingredientSchema],
resolvers: merge(rootResolvers, userResolvers, ingredientResolvers)
})
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const auth = require('../../auth_client_management');
const db = require('../../db');
const hex = require('buf').to.hex;
function developerResponse(developer) {
return {
developerId: hex(developer.developerId),
email: developer.email,
createdAt: developer.createdAt
};
}
module.exports = {
auth: {
strategy: auth.AUTH_STRATEGY,
scope: auth.SCOPE_CLIENT_MANAGEMENT.getImplicantValues()
},
handler: async function activateRegistration(req) {
const email = req.auth.credentials.email;
return db.getDeveloper(email)
.then(function(developer) {
if (developer) {
return developer;
} else {
return db.activateDeveloper(email);
}
})
.then(developerResponse);
}
};
|
var dir_757026fe4db55b4646908144287a0f4d =
[
[ "pa_gnss.h", "pa__gnss_8h.html", "pa__gnss_8h" ]
];
|
/* global dropdownSelector I18n */
var DataTableHelpers = (function() {
return {
initLengthApearance: function(dataTableWraper) {
var tableLengthSelect = $(dataTableWraper).find('.dataTables_length select');
if (tableLengthSelect.val() == null) {
tableLengthSelect.val(10).change();
}
$.each(tableLengthSelect.find('option'), (i, option) => {
option.innerHTML = I18n.t('repositories.index.show_per_page', { number: option.value });
});
$(dataTableWraper).find('.dataTables_length')
.append(tableLengthSelect).find('label')
.remove();
dropdownSelector.init(tableLengthSelect, {
noEmptyOption: true,
singleSelect: true,
closeOnSelect: true,
disableSearch: true,
selectAppearance: 'simple'
});
},
initSearchField: function(dataTableWraper, searchText) {
var tableFilterInput = $(dataTableWraper).find('.dataTables_filter input');
tableFilterInput.attr('placeholder', searchText)
.addClass('sci-input-field')
.css('margin', 0);
$('.dataTables_filter').append(`
<div class="sci-input-container left-icon">
<i class="fas fa-search"></i>
</div>`).find('.sci-input-container').prepend(tableFilterInput);
$('.dataTables_filter').find('label').remove();
}
};
}());
function DataTableCheckboxes(tableWrapper, config) {
/* config = {
checkboxSelector: selector for checkboxes,
selectAllSelector: selector for select all checkbox
}*/
this.selectedRows = [];
this.tableWrapper = $(tableWrapper);
this.config = config;
this.initCheckboxes();
this.initSelectAllCheckbox();
}
DataTableCheckboxes.prototype.checkRowStatus = function(row) {
var checkbox = $(row).find(this.config.checkboxSelector);
if (this.selectedRows.includes(row.id)) {
$(row).addClass('selected');
checkbox.attr('checked', true);
} else {
$(row).removeClass('selected');
checkbox.attr('checked', false);
}
};
DataTableCheckboxes.prototype.checkSelectAllStatus = function() {
var checkboxes = this.tableWrapper.find(this.config.checkboxSelector + ':not(:disabled)');
var selectedCheckboxes = this.tableWrapper.find(this.config.checkboxSelector + ':checked');
var selectAllCheckbox = this.tableWrapper.find(this.config.selectAllSelector);
selectAllCheckbox.prop('indeterminate', false);
if (selectedCheckboxes.length === 0) {
selectAllCheckbox.prop('checked', false);
} else if (selectedCheckboxes.length === checkboxes.length) {
selectAllCheckbox.prop('checked', true);
} else {
selectAllCheckbox.prop('indeterminate', true);
}
};
DataTableCheckboxes.prototype.clearSelection = function() {
var rows = this.tableWrapper.find('tbody tr');
this.selectedRows = [];
$.each(rows, (i, row) => {
$(row).removeClass('selected');
$(row).find(this.config.checkboxSelector).attr('checked', false);
});
this.checkSelectAllStatus();
};
// private methods
DataTableCheckboxes.prototype.initCheckboxes = function() {
this.tableWrapper.on('click', '.table tbody tr', (e) => {
var checkbox = $(e.currentTarget).find(this.config.checkboxSelector);
if (checkbox.attr('disabled')) return;
checkbox.prop('checked', !checkbox.prop('checked'));
this.selectRow(e.currentTarget);
}).on('click', this.config.checkboxSelector, (e) => {
this.selectRow($(e.currentTarget).closest('tr')[0]);
e.stopPropagation();
});
};
DataTableCheckboxes.prototype.selectRow = function(row) {
var id = row.id;
if (this.selectedRows.includes(id)) {
this.selectedRows.splice(this.selectedRows.indexOf(id), 1);
} else {
this.selectedRows.push(id);
}
$(row).toggleClass('selected');
this.checkSelectAllStatus();
if (this.config.onChanged) this.config.onChanged();
};
DataTableCheckboxes.prototype.initSelectAllCheckbox = function() {
this.tableWrapper.on('click', this.config.selectAllSelector, (e) => {
var selectAllCheckbox = $(e.currentTarget);
var rows = this.tableWrapper.find('tbody tr');
$.each(rows, (i, row) => {
var checkbox = $(row).find(this.config.checkboxSelector);
if (checkbox.prop('checked') === selectAllCheckbox.prop('checked') || checkbox.attr('disabled')) return;
checkbox.prop('checked', !checkbox.prop('checked'));
this.selectRow(row);
});
});
};
|
'use strict';
const By = require('selenium-webdriver').By;
const Accessors = require('../accessors');
function NewRecipeAccessors() {
Accessors.apply(this, arguments);
}
NewRecipeAccessors.prototype = Object.assign({
get doneButton() {
return this.waitForElement(By.css('button.app-view__action'));
},
}, Accessors.prototype);
module.exports = NewRecipeAccessors;
|
var formatter = require('./formatter');
var Response = function (socket, id) {
this.socket = socket;
this.id = id;
this.sent = false;
};
Response.prototype._respond = function (responseData) {
if (this.sent) {
throw new Error('Response ' + this.id + ' has already been sent');
} else {
this.sent = true;
this.socket.send(formatter.stringify(responseData));
}
};
Response.prototype.end = function (data) {
if (this.id) {
var responseData = {
rid: this.id
};
if (data !== undefined) {
responseData.data = data;
}
this._respond(responseData);
}
};
Response.prototype.error = function (error, data) {
if (this.id) {
var err;
if (error instanceof Error) {
err = {name: error.name, message: error.message, stack: error.stack};
} else {
err = error;
}
var responseData = {
rid: this.id,
error: err
};
if (data !== undefined) {
responseData.data = data;
}
this._respond(responseData);
}
};
Response.prototype.callback = function (error, data) {
if (error) {
this.error(error, data);
} else {
this.end(data);
}
};
module.exports.Response = Response;
|
var Cu = Components.utils;
const PREF_UTTERANCE_ORDER = "accessibility.accessfu.utterance";
Cu.import('resource://gre/modules/accessibility/Utils.jsm');
Cu.import("resource://gre/modules/accessibility/OutputGenerator.jsm", this);
/**
* Test context output generation.
*
* @param expected {Array} expected output.
* @param aAccOrElmOrID identifier to get an accessible to test.
* @param aOldAccOrElmOrID optional identifier to get an accessible relative to
* the |aAccOrElmOrID|.
* @param aGenerator the output generator to use when generating accessible
* output
*
* Note: if |aOldAccOrElmOrID| is not provided, the |aAccOrElmOrID| must be
* scoped to the "root" element in markup.
*/
function testContextOutput(expected, aAccOrElmOrID, aOldAccOrElmOrID, aGenerator) {
var accessible = getAccessible(aAccOrElmOrID);
var oldAccessible = aOldAccOrElmOrID !== null ?
getAccessible(aOldAccOrElmOrID || 'root') : null;
var context = new PivotContext(accessible, oldAccessible);
var output = aGenerator.genForContext(context);
// Create a version of the output that has null members where we have
// null members in the expected output. Those are indexes that are not testable
// because of the changing nature of the test (different window names), or strings
// that are inaccessible to us, like the title of parent documents.
var masked_output = [];
for (var i=0; i < output.length; i++) {
if (expected[i] === null) {
masked_output.push(null);
} else {
masked_output[i] = typeof output[i] === "string" ? output[i].trim() :
output[i];
}
}
isDeeply(masked_output, expected,
"Context output is correct for " + aAccOrElmOrID +
" (output: " + JSON.stringify(output) + ") ==" +
" (expected: " + JSON.stringify(expected) + ")");
}
/**
* Test object output generated array that includes names.
* Note: test ignores outputs without the name.
*
* @param aAccOrElmOrID identifier to get an accessible to test.
* @param aGenerator the output generator to use when generating accessible
* output
*/
function testObjectOutput(aAccOrElmOrID, aGenerator) {
var accessible = getAccessible(aAccOrElmOrID);
if (!accessible.name || !accessible.name.trim()) {
return;
}
var context = new PivotContext(accessible);
var output = aGenerator.genForObject(accessible, context);
var outputOrder;
try {
outputOrder = SpecialPowers.getIntPref(PREF_UTTERANCE_ORDER);
} catch (ex) {
// PREF_UTTERANCE_ORDER not set.
outputOrder = 0;
}
var expectedNameIndex = outputOrder === 0 ? output.length - 1 : 0;
var nameIndex = output.indexOf(accessible.name);
if (nameIndex > -1) {
ok(output.indexOf(accessible.name) === expectedNameIndex,
"Object output is correct for " + aAccOrElmOrID);
}
}
/**
* Test object and context output for an accessible.
*
* @param expected {Array} expected output.
* @param aAccOrElmOrID identifier to get an accessible to test.
* @param aOldAccOrElmOrID optional identifier to get an accessible relative to
* the |aAccOrElmOrID|.
* @param aOutputKind the type of output
*/
function testOutput(expected, aAccOrElmOrID, aOldAccOrElmOrID, aOutputKind) {
var generator;
if (aOutputKind === 1) {
generator = UtteranceGenerator;
} else {
generator = BrailleGenerator;
}
testContextOutput(expected, aAccOrElmOrID, aOldAccOrElmOrID, generator);
// Just need to test object output for individual
// accOrElmOrID.
if (aOldAccOrElmOrID) {
return;
}
testObjectOutput(aAccOrElmOrID, generator);
}
function testHints(expected, aAccOrElmOrID, aOldAccOrElmOrID) {
var accessible = getAccessible(aAccOrElmOrID);
var oldAccessible = aOldAccOrElmOrID !== null ?
getAccessible(aOldAccOrElmOrID || 'root') : null;
var context = new PivotContext(accessible, oldAccessible);
var hints = context.interactionHints;
isDeeply(hints, expected,
"Context hitns are correct for " + aAccOrElmOrID +
" (hints: " + JSON.stringify(hints) + ") ==" +
" (expected: " + JSON.stringify(expected) + ")");
}
|
import { Point, SVG } from "../utils";
import { hole } from "./utils";
const block = (config, groupedPoints, index, previousArm) => (x, y) => {
const { angle, points } = groupedPoints;
const { inner, outer } = points;
const isExtendedPoint =
index === Math.ceil(groupedPoints.finPoints.length / 2);
const rotate = Point.rotateAroundPoint([x, y], angle);
const halfHoleWidth = config.fin.grip.holeWidth / 2;
const halfFinWidth = config.fin.width / 2;
const halfGripWidth = config.fin.grip.width / 2;
const label = config.layers.labels
? SVG.label(
"POINT " + index,
`translate(${x} ${y}) rotate(${Point.rad2deg(angle)})`
)
: "";
const holeOffset = halfFinWidth;
if (index === 0) {
// if (y === 0) {
// // const p = Point.rotateAroundPoint([x,y], previousArm.angle - Math.PI)([x + config.fin.pointDistance/2,y])
// // return SVG.path([
// // [x,y],
// // [x,y - (150 * Math.cos(angle)) ]
// // ])
// // return SVG.path([
// // [x,y],
// // Point.rotateAroundPoint([x,y], angle)([x + config.fin.pointDistance/2,y])
// // ])
// }
if (y === config.dimensions.height && x > 0) {
return (
"<g>" +
SVG.path([
[x - halfFinWidth - 25, y + halfFinWidth],
[x - 50, y + halfFinWidth],
// cutout for rail
[x - 50, y + 70],
[x + 50, y + 70],
[x + 50, y + halfFinWidth + 20],
[x + 90, y + halfFinWidth + 20],
[x + 90, y + halfFinWidth],
[x + halfFinWidth, y + halfFinWidth],
[x + halfFinWidth, y - halfFinWidth - 25]
]) +
"</g>"
);
} else {
return (
SVG.path([
Point.rotateAroundPoint([x, y], previousArm.angle)([
x - config.fin.pointDistance / 2,
y - halfFinWidth
]),
outer,
rotate([x + config.fin.pointDistance / 2, y - halfFinWidth])
]) +
SVG.path([
Point.rotateAroundPoint([x, y], previousArm.angle)([
x - config.fin.pointDistance / 2,
y + halfFinWidth
]),
inner,
rotate([x + config.fin.pointDistance / 2, y + halfFinWidth])
])
);
}
} else {
const holes =
SVG.path(
hole(x, y, halfHoleWidth, holeOffset, config.material).map(rotate)
) +
SVG.path(
[
[x - halfHoleWidth, y - holeOffset],
[x + halfHoleWidth, y - holeOffset],
[x + halfHoleWidth, y - holeOffset + config.material.thickness],
[x - halfHoleWidth, y - holeOffset + config.material.thickness],
[x - halfHoleWidth, y - holeOffset]
].map(rotate)
);
const rabbitEars =
index === 2 || index === groupedPoints.finPoints.length - 3
? [
[
x + config.fin.frameWidth,
y + 100 + config.material.thickness + 10
],
[x + config.fin.frameWidth, y + 75],
[x + config.fin.frameWidth - 85, y + 75],
[x + config.fin.frameWidth - 85, y + 25],
[x + config.fin.frameWidth, y + 25],
//
[x + config.fin.frameWidth, y - 25],
[x + config.fin.frameWidth - 85, y - 25],
[x + config.fin.frameWidth - 85, y - 75],
[x + config.fin.frameWidth, y - 75]
]
: [];
groupedPoints.points.end = [x - config.fin.frameWidth, y + halfFinWidth];
const distance = isExtendedPoint
? x +
config.fin.frameWidth -
Point.length(
groupedPoints.finPoints[index],
groupedPoints.finPoints[index - 1]
)
: x - config.fin.frameWidth;
return (
"<g>" +
SVG.path(
[
[distance, y + halfFinWidth],
// [x-90, y+150],
// dogbone
[x - 100, y + halfFinWidth],
[x - 100, y + halfFinWidth - 10],
[x - halfGripWidth, y + halfFinWidth - 10],
// grip
[x - halfGripWidth, y + halfFinWidth + config.material.thickness],
[x + halfGripWidth, y + halfFinWidth + config.material.thickness],
// [x+90, y+150],
// dogbone
[x + halfGripWidth, y + halfFinWidth - 10],
[x + 100, y + halfFinWidth - 10],
[x + 100, y + halfFinWidth],
[x + config.fin.frameWidth, y + halfFinWidth]
].map(rotate)
) +
SVG.path(
[
...rabbitEars,
[x + config.fin.frameWidth, y - halfFinWidth],
[x + halfGripWidth, y - halfFinWidth],
[x + halfGripWidth, y - halfFinWidth - config.material.thickness],
[x - halfGripWidth, y - halfFinWidth - config.material.thickness],
[x - halfGripWidth, y - halfFinWidth],
[distance, y - halfFinWidth]
].map(rotate)
) +
holes +
label +
"</g>"
);
}
};
module.exports = {
block
};
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*
* Copyright (c) 2014, Joyent, Inc.
*/
/*
* DTrace metric for TCP accepts, using the syscall provider.
*/
var mod_ca = require('../../../../lib/ca/ca-common');
var desc = {
module: 'tcp',
stat: 'accepts',
fields: [ 'hostname', 'zonename', 'pid', 'execname', 'psargs', 'ppid',
'pexecname', 'ppsargs', 'rport', 'raddr' ],
fields_internal: [ 'sockaddr' ],
metad: {
locals: [
{ addrtype: 'uint16_t' }
],
probedesc: [
{
probes: [ 'syscall::accept:entry' ],
alwaysgather: {
sockaddr: {
gather: 'arg1',
store: 'thread'
}
}
},
{
probes: [ 'syscall::accept:return' ],
local: [ {
addrtype: '*(uint16_t *)copyin(self->sockaddr0, \n' +
'sizeof (uint16_t))'
} ],
predicate: 'arg1 >= 0 && (this->addrtype == AF_INET || ' +
'this->addrtype == AF_INET6)',
aggregate: {
default: 'count()',
hostname: 'count()',
zonename: 'count()',
pid: 'count()',
execname: 'count()',
psargs: 'count()',
ppid: 'count()',
pexecname: 'count()',
ppsargs: 'count()',
rport: 'count()',
raddr: 'count()'
},
transforms: {
hostname:
'"' + mod_ca.caSysinfo().ca_hostname + '"',
zonename: 'zonename',
pid: 'lltostr(pid)',
execname: 'execname',
psargs: 'curpsinfo->pr_psargs',
ppid: 'lltostr(ppid)',
pexecname: 'curthread->t_procp->p_parent->' +
'p_user.u_comm',
ppsargs:
'curthread->t_procp->p_parent->p_user.u_psargs',
rport: [
'ntohs((this->addrtype == AF_INET) ? ',
'((struct sockaddr_in *)copyin(self->sockaddr0, ',
' sizeof (struct sockaddr_in *)))->sin_port : ',
'((struct sockaddr_in6 *)copyin(self->sockaddr0, ',
' sizeof (struct sockaddr_in6 *)))->sin6_port)'
].join('\n'),
raddr: [
'(this->addrtype == AF_INET) ? ',
'inet_ntoa((ipaddr_t *)',
' &(((struct sockaddr_in *)copyin(',
' self->sockaddr0, ',
' sizeof (struct sockaddr_in *)))->sin_addr)) :',
' inet_ntoa6((in6_addr_t *)',
' &(((struct sockaddr_in6 *)copyin(',
'self->sockaddr0, ',
' sizeof (struct sockaddr_in6 *)))->sin6_addr))'
].join('\n')
},
verify: {
sockaddr: '$0'
}
},
{
probes: [ 'syscall::accept:return' ],
clean: {
sockaddr: '$0'
}
}
]
}
};
exports.cadMetricDesc = desc;
|
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test that a newProperty editor is only created if no other editor was
// previously displayed.
const TEST_URI = `
<style type='text/css'>
#testid {
background-color: blue;
}
</style>
<div id='testid'>Styled Node</div>
`;
add_task(function* () {
yield addTab("data:text/html;charset=utf-8," + encodeURIComponent(TEST_URI));
let {inspector, view} = yield openRuleView();
yield selectNode("#testid", inspector);
yield testClickOnEmptyAreaToCloseEditor(inspector, view);
});
function synthesizeMouseOnEmptyArea(ruleEditor, view) {
// any text property editor will do
let propEditor = ruleEditor.rule.textProps[0].editor;
let valueContainer = propEditor.valueContainer;
let valueRect = valueContainer.getBoundingClientRect();
// click right next to the ";" at the end of valueContainer
EventUtils.synthesizeMouse(valueContainer, valueRect.width + 1, 1, {},
view.styleWindow);
}
function* testClickOnEmptyAreaToCloseEditor(inspector, view) {
// Start at the beginning: start to add a rule to the element's style
// declaration, add some text, then press escape.
let ruleEditor = getRuleViewRuleEditor(view, 1);
let propEditor = ruleEditor.rule.textProps[0].editor;
info("Create a property value editor");
let editor = yield focusEditableField(view, propEditor.valueSpan);
ok(editor.input, "The inplace-editor field is ready");
info("Close the property value editor by clicking on an empty area " +
"in the rule editor");
let onRuleViewChanged = view.once("ruleview-changed");
let onBlur = once(editor.input, "blur");
synthesizeMouseOnEmptyArea(ruleEditor, view);
yield onBlur;
yield onRuleViewChanged;
ok(!view.isEditing, "No inplace editor should be displayed in the ruleview");
info("Create new newProperty editor by clicking again on the empty area");
let onFocus = once(ruleEditor.element, "focus", true);
synthesizeMouseOnEmptyArea(ruleEditor, view);
yield onFocus;
editor = inplaceEditor(ruleEditor.element.ownerDocument.activeElement);
is(inplaceEditor(ruleEditor.newPropSpan), editor,
"New property editor was created");
info("Close the newProperty editor by clicking again on the empty area");
onBlur = once(editor.input, "blur");
synthesizeMouseOnEmptyArea(ruleEditor, view);
yield onBlur;
ok(!view.isEditing, "No inplace editor should be displayed in the ruleview");
}
|
// DO NOT EDIT! This test has been generated by tools/gentest.py.
// OffscreenCanvas test in a worker:2d.text.draw.baseline.middle
// Description:textBaseline middle is the middle of the em square (not the bounding box)
// Note:
importScripts("/resources/testharness.js");
importScripts("/2dcontext/resources/canvas-tests.js");
var t = async_test("textBaseline middle is the middle of the em square (not the bounding box)");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
throw reason;
});
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
ctx.font = '50px CanvasTest';
new Promise(function(resolve) { step_timeout(resolve, 500); })
.then(function() {
ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50);
ctx.fillStyle = '#0f0';
ctx.textBaseline = 'middle';
ctx.fillText('CC', 0, 25);
_assertPixelApprox(offscreenCanvas, 5,5, 0,255,0,255, "5,5", "0,255,0,255", 2);
_assertPixelApprox(offscreenCanvas, 95,5, 0,255,0,255, "95,5", "0,255,0,255", 2);
_assertPixelApprox(offscreenCanvas, 25,25, 0,255,0,255, "25,25", "0,255,0,255", 2);
_assertPixelApprox(offscreenCanvas, 75,25, 0,255,0,255, "75,25", "0,255,0,255", 2);
_assertPixelApprox(offscreenCanvas, 5,45, 0,255,0,255, "5,45", "0,255,0,255", 2);
_assertPixelApprox(offscreenCanvas, 95,45, 0,255,0,255, "95,45", "0,255,0,255", 2);
}).then(t_pass, t_fail);
});
done();
|
var VisioLink = {
candidates: [],
reset: function() {
VisioLink.window = null;
},
openVisio: function(from) {
VisioLink.window = window.open('?visio/' + from, '', 'width=600,height=400,status=0,titlebar=0,toolbar=0,menubar=0');
},
setFrom: function(from) {
VisioLink.from = from;
}
}
|
'use strict';
import {Router} from 'express';
import {index} from './prestation.controller';
var router = new Router();
router.get('/', index);
module.exports = router;
|
/*!
* bootswatch v3.2.0
* Homepage: http://bootswatch.com
* Copyright 2012-2014 Thomas Park
* Licensed under MIT
* Based on Bootstrap
*/
(function(){
$(window).scroll(function () {
var top = $(document).scrollTop();
$('.splash').css({
'background-position': '0px -'+(top/3).toFixed(2)+'px'
});
if(top > 50)
$('#home > .navbar').removeClass('navbar-transparent');
else
$('#home > .navbar').addClass('navbar-transparent');
});
$("a[href='#']").click(function(e) {
e.preventDefault();
});
var $button = $("<div id='source-button' class='btn btn-primary btn-xs'>< ></div>").click(function(){
var html = $(this).parent().html();
html = cleanSource(html);
$("#source-modal pre").text(html);
$("#source-modal").modal();
});
$('.bs-component [data-toggle="popover"]').popover();
$('.bs-component [data-toggle="tooltip"]').tooltip();
$(".bs-component").hover(function(){
$(this).append($button);
$button.show();
}, function(){
$button.hide();
});
function cleanSource(html) {
var lines = html.split(/\n/);
lines.shift();
lines.splice(-1, 1);
var indentSize = lines[0].length - lines[0].trim().length,
re = new RegExp(" {" + indentSize + "}");
lines = lines.map(function(line){
if (line.match(re)) {
line = line.substring(indentSize);
}
return line;
});
lines = lines.join("\n");
return lines;
}
})();
|
import axios from 'axios';
import { browserHistory } from 'react-router';
import { AUTH_USER, UNAUTH_USER, AUTH_ERROR, FETCH_MESSAGE } from './types';
import {API_URL} from '../utils/apiCaller';
import config from '../../config/config.js';
var domain = config.domain;
export function signinUser({username, password}) {
return function(dispatch) {
// send username/password
// .then - success, .catch - fail.
console.log(">>>> src/actions/auth.js:");
console.log("Sending POST request from signinUser.");
/* console.log("Username: " + username);
console.log("Password: " + password); */
var credentials = {
"email": username,
"password": password
}
axios.post(`${API_URL}/auth/login`, credentials)
.then(response => {
console.log("Successfully signed in!");
// if request is good
// - update state to indicate that I'm signed in
dispatch({ type: 'AUTH_USER'});
console.log("Auth action dispatched(to flip auth state to true)");
// - save JWT token
localStorage.setItem('authtoken', response.data.token);
console.log("Token saved! " + response.data.token);
// - redirect to /feature
browserHistory.push(domain);
console.log("Redirected to /");
})
.catch(() => {
// if request is bad
dispatch(authError('Bad Login Info'));
})
};
}
export function signupUser({username, password}) {
return function(dispatch) {
// send username/password
// .then - success, .catch - fail.
axios.post(`${API_URL}/signup`, {username, password})
.then(response => {
// if request is good
// - update state to indicate that I'm signed up
dispatch({ type: AUTH_USER});
// - save JWT token
localStorage.setItem('authtoken', response.data.token);
// - redirect to /feature
browserHistory.push(domain);
})
.catch(() => {
// if request is bad - add error to the state.
dispatch(authError('User with this username already exists'));
})
};
}
export function signoutUser() {
// delete token and signout
console.log(">>>> src/actions/auth.js:");
console.log("Signing out user, deleting token from localStorage.");
localStorage.removeItem('authtoken');
console.log("Redirecting to /, and dispatching action UNAUTH_USER.");
browserHistory.push(domain);
return {
type: 'UNAUTH_USER'
};
}
export function authError(error) {
return {
type: AUTH_ERROR,
payload: error
};
}
export function fetchMessage() {
const config = {
headers: { authorization: localStorage.getItem('authtoken')}
};
return function(dispatch) {
axios.get('http://localhost:3000/api/v1/auth-test', config)
.then(response => {
console.log("Auth test " + JSON.stringify(response));
dispatch({
type: FETCH_MESSAGE,
payload: response.data.message
});
});
}
}
|
import React from 'react';
import { PropTypes } from 'prop-types';
import faker from 'faker';
import _ from 'underscore';
import uid from 'node-uuid';
const pad = (num, size) => {
var s = '000000000' + num;
return s.substr(s.length - size);
};
faker.date.day = () => {
return pad(1 + Math.floor(Math.random() * 31), 2);
};
faker.date.monthDigit = () => {
return pad(1 + Math.floor(Math.random() * 12), 2);
};
faker.date.time = () => {
var hours = pad(1 + Math.floor(Math.random() * 12), 2),
minutes = pad(1 + Math.floor(Math.random() * 60), 2);
return hours + ':' + minutes;
};
faker.date.year = () => {
return (2011 + Math.floor(Math.random() * 6)).toString();
};
faker.date.monthShort = () => {
return faker.date.month().substr(0, 3);
};
faker.date.weekdayShort = () => {
return faker.date.weekday().substr(0, 3);
};
const executeFakerCommand = command => {
const fakerCommand = command.replace(/\[/g, '{{').replace(/\]/g, '}}');
const fakerData = faker.fake(fakerCommand);
return fakerData;
};
class Faker extends React.Component {
static propTypes = {
children: PropTypes.string.isRequired,
};
constructor() {
super();
this.prevValue = null;
}
fake(command) {
if (!this.prevValue) {
this.prevValue = executeFakerCommand(command);
}
return this.prevValue;
}
render() {
const propsNoChild = _.omit(this.props, 'children');
return <span {...propsNoChild}>{this.fake(this.props.children)}</span>;
}
}
class FakerImage extends React.Component {
static propTypes = {
imageType: PropTypes.string.isRequired,
};
constructor() {
super();
this.lastImageUrl = null;
}
fake(imageType) {
if (!this.lastImageUrl) {
this.lastImageUrl = faker.image[imageType]();
}
return this.lastImageUrl;
}
render() {
const imageProps = _.omit(this.props, 'imageType');
return <img {...imageProps} src={this.fake(this.props.imageType)} />;
}
}
export { Faker, FakerImage };
|
/*
* This file is part of huborcid.
*
* huborcid is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* huborcid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with huborcid. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"ap.",
"ip."
],
"DAY": [
"sunnuntaina",
"maanantaina",
"tiistaina",
"keskiviikkona",
"torstaina",
"perjantaina",
"lauantaina"
],
"ERANAMES": [
"ennen Kristuksen syntym\u00e4\u00e4",
"j\u00e4lkeen Kristuksen syntym\u00e4n"
],
"ERAS": [
"eKr.",
"jKr."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"tammikuuta",
"helmikuuta",
"maaliskuuta",
"huhtikuuta",
"toukokuuta",
"kes\u00e4kuuta",
"hein\u00e4kuuta",
"elokuuta",
"syyskuuta",
"lokakuuta",
"marraskuuta",
"joulukuuta"
],
"SHORTDAY": [
"su",
"ma",
"ti",
"ke",
"to",
"pe",
"la"
],
"SHORTMONTH": [
"tammikuuta",
"helmikuuta",
"maaliskuuta",
"huhtikuuta",
"toukokuuta",
"kes\u00e4kuuta",
"hein\u00e4kuuta",
"elokuuta",
"syyskuuta",
"lokakuuta",
"marraskuuta",
"joulukuuta"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "cccc d. MMMM y",
"longDate": "d. MMMM y",
"medium": "d.M.y H.mm.ss",
"mediumDate": "d.M.y",
"mediumTime": "H.mm.ss",
"short": "d.M.y H.mm",
"shortDate": "d.M.y",
"shortTime": "H.mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fi",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
// Copyright (c) 2016 Fabio Soldati, www.peakfinder.org
// License MIT: http://www.opensource.org/licenses/MIT
/**
* Compare numbers taking in account an error
*
* @param {Float} number
* @param {Float} expected
* @param {Float} error Optional
* @param {String} message Optional
*/
QUnit.assert.close = function(number, expected, error, message) {
if (error === void 0 || error === null) {
error = 0.00001 // default error
}
var result = number == expected || (number < expected + error && number > expected - error) || false
QUnit.push(result, number, expected, message);
}
|
odoo.define('mail/static/src/components/chat_window_manager/chat_window_manager.js', function (require) {
'use strict';
const components = {
ChatWindow: require('mail/static/src/components/chat_window/chat_window.js'),
ChatWindowHiddenMenu: require('mail/static/src/components/chat_window_hidden_menu/chat_window_hidden_menu.js'),
};
const useStore = require('mail/static/src/component_hooks/use_store/use_store.js');
const { Component } = owl;
class ChatWindowManager extends Component {
/**
* @override
*/
constructor(...args) {
super(...args);
useStore(props => {
return {
chatWindowManagerVisual: this.env.messaging.chatWindowManager.visual,
device: this.env.messaging.device,
};
});
}
}
Object.assign(ChatWindowManager, {
components,
props: {},
template: 'mail.ChatWindowManager',
});
return ChatWindowManager;
});
|
'use strict';
var MCS = require('../MCS');
var dashboardCache = require('../pages/dashboard');
var daemonsCache = require('../pages/daemons');
var pluginsCache = require('../pages/plugins');
var worldsCache = require('../pages/worlds');
var servertypesCache = require('../pages/servertypes');
var settingsCache = require('../pages/settings');
module.exports = class Cache {
/**
* Gets the Dashboard-Page as JSON-String
* @returns {*}
* */
getDashboardPage() {
return dashboardCache;
}
/**
* Gets the Daemons-Page as JSON-String
* @returns {*}
* */
getDaemonsPage() {
return daemonsCache;
}
/**
* Gets the Plugins-Page as JSON-String
* @returns {*}
* */
getPluginsPage() {
return pluginsCache;
}
/**
* Gets the Worlds-Page as JSON-String
* @returns {*}
* */
getWorldsPage() {
return worldsCache;
}
/**
* Gets the Servertypes-Page as JSON-String
* @returns {*}
* */
getServertypesPage() {
return servertypesCache;
}
/**
* Gets the Settings-Page as JSON-String
* @returns {*}
* */
getSettingsPage() {
return settingsCache;
}
};
|
module.exports = function(app, argv, logger) {
if (argv.debug) {
logger.debug("Skip error module for debug");
return;
}
app.use(
function errorHandler(err, req, res, next) {
if (res.headersSent) {
return next(err);
}
logger.error('error');
res.status(500);
res.json('error', {
error: err
});
});
}
|
'use strict'
const panel = require('../modules/panel')
const Helper = require('../utilities/helper')
var autocomplete
exports.init = function() {
var missionJoin = document.querySelector('a[data-mission-join]')
if (missionJoin) {
missionJoin.addEventListener('click', joinMission)
}
var missionLeave = document.querySelector('a[data-mission-leave]')
if (missionLeave) {
missionLeave.addEventListener('click', leaveMission)
}
var missionTitle = document.getElementById('mission_title')
if (missionTitle) {
missionTitle.focus()
missionTitle.select()
}
var missionCreateSendLink = document.querySelector('a[data-mission-create-send]')
if (missionCreateSendLink) {
missionCreateSendLink.addEventListener('click', saveMission)
}
var missionCreateSendLink = document.querySelector('a[data-mission-create-send]')
if (missionCreateSendLink) {
missionCreateSendLink.addEventListener('click', saveMission)
}
var missionUpdateSendLink = document.querySelector('a[data-mission-update-send]')
if (missionUpdateSendLink) {
missionUpdateSendLink.addEventListener('click', saveMission)
}
var input = document.getElementById('mission_location')
if (input && window.google) {
autocomplete = new google.maps.places.Autocomplete(input)
}
}
function joinMission(e) {
e.preventDefault()
var href = e.currentTarget.href
var missionDiv = e.currentTarget.closest('.mission')
Helper.addClass(missionDiv, '--joining')
setTimeout(function() {
Helper.removeClass(missionDiv, '--joining')
Turbolinks.visit(href)
}, 1500)
}
function leaveMission(e) {
e.preventDefault()
var href = e.currentTarget.href
var missionDiv = e.currentTarget.closest('.mission')
Helper.addClass(missionDiv, '--leaving')
setTimeout(function() {
Helper.removeClass(missionDiv, '--leaving')
Turbolinks.visit(href)
}, 1500)
}
// For both new missions and updating missions.
function saveMission(e) {
e.preventDefault()
// Check that all form elements have been properly entered
var missionTitle = document.getElementById('mission_title')
if (missionTitle.value === '') {
return
}
var missionDescription = document.getElementById('mission_description')
if (missionDescription.value === '') {
return
}
var missionLocation = document.getElementById('mission_location')
if (missionLocation.value === '') {
return
}
var missionDate = document.getElementById('mission_date')
if (missionDate.value === '') {
return
}
var missionTime = document.getElementById('mission_time')
if (missionTime.selectedIndex === 0) {
return
}
new Promise(function(resolve, reject) {
// Get the place info.
var place = autocomplete.getPlace()
if (place) {
// User selected a place.
resolve(place)
} else {
if (window.missionData) {
// An existing location has already been chosen previously, set 'place' to that one.
autocomplete.set('place', window.missionData.place)
resolve(window.missionData.place)
} else {
reject('need to select a location')
}
}
}).then(
function(place) {
// Successful promise.
// Send AJAX request.
Helper.addClass(e.currentTarget, '--loading')
var mission = {}
mission.title = missionTitle.value.trim()
mission.description = missionDescription.value.trim()
mission.place = place
mission.date = missionDate.value.trim() + 'T' + missionTime.value + ':00.000Z'
var request = new XMLHttpRequest()
if (e.currentTarget.getAttribute('data-mission-create-send')) {
request.open('POST', '/mission/new', true)
}
if (e.currentTarget.getAttribute('data-mission-update-send')) {
mission.missionId = window.missionData.missionId
request.open('POST', '/mission/' + mission.missionId + '/update', true)
}
request.setRequestHeader('Content-type', 'application/json')
request.onload = function() {
var returnedMission = JSON.parse(request.responseText)
// Done
if (request.readyState == 4 && request.status == 200) {
debugger
window.location = '/mission/' + returnedMission.missionId
}
}
request.onerror = function() {
// There was a connection error of some sort
console.log('connection error')
}
request.send(JSON.stringify(mission))
},
function(reason) {
// Rejected promise.
console.log(reason)
}
)
.catch(function(error) {
console.log(error)
})
}
|
const nest = require('depnest')
const { onceTrue } = require('mutant')
exports.needs = nest({
'sbot.obs.connection': 'first'
})
exports.gives = nest('about.async.latestValues')
exports.create = function (api) {
return nest('about.async.latestValues', function (dest, keys, cb) {
onceTrue(api.sbot.obs.connection, sbot => {
sbot.about.latestValues({ dest, keys }, cb)
})
})
}
|
import values from 'lodash/values';
import PropTypes from 'prop-types';
import { MediaTargets } from '../consts/media';
export const MediaTarget = PropTypes.oneOf(values(MediaTargets));
|
import { JSDOM } from "jsdom";
import sinon from "sinon";
import EnvironmentFileLoader from "../../../common/src/environment/EnvironmentFileLoader";
import EnvironmentReader from "../../../common/src/environment/EnvironmentReader";
const { window } = new JSDOM("<!doctype html><html><body></body></html>");
global.window = window;
global.document = global.window.document;
global.navigator = global.window.navigator;
Object.defineProperty(window, "scrollTo", { "value": () => {}, "writable": true });
global.sessionStorage = {
"item": {},
"getItem": function(key) {
return this.item[key] || null;
},
"setItem": function(key, value) {
this.item[key] = value;
},
"removeItem": function(key) {
delete this.item[key];
}
};
const testConfig = {
"default": {
"serverIpAddress": "127.0.0.1",
"serverPort": 5000,
"couchDbUrl": "http://127.0.0.1:5984",
"searchEngineUrl": "http://127.0.0.1:5985/local",
"userDbPrefix": "db_",
"adminDetails": {
"username": "admin",
"password": "admin",
"db": "common"
},
"facebook": {
"url": "http://localhost:3000/https://www.facebook.com",
"appSecretKey": "asdf",
"appId": "asdf",
"timeOut": 4000,
"limit": 500
},
"twitter": {
"url": "https://api.twitter.com/1.1",
"authenticateUrl": "https://api.twitter.com/oauth/authenticate",
"consumerKey": "",
"consumerSecret": ""
}
}
};
sinon.stub(EnvironmentFileLoader, "instance").returns(new EnvironmentReader(testConfig, "default"));
global.XMLHttpRequest = window.XMLHttpRequest;
|
(function () {
"use strict";
var closeMenus = function () {
var openLaunchers = document.querySelectorAll('.dropdown [aria-expanded="true"]'),
openMenus = document.querySelectorAll('.dropdown [aria-expanded="true"] + .links'),
len = openLaunchers.length;
for (i=0; i<len; i++) {
openLaunchers[i].setAttribute("aria-expanded", "");
openLaunchers[i].parentElement.focus();
openLaunchers[i].setAttribute("aria-expanded", "false");
hideMenu(openMenus[i]);
}
document.removeEventListener('click', closeMenus);
},
hideMenu = function(thisMenu) {
setTimeout(function(){thisMenu.setAttribute("hidden", "hidden");}, 300);
},
launcherClick = function(e) {
var launcher = e.target,
container = launcher.parentElement,
menu = launcher.parentElement.querySelector('.dropdown .links');
launcher.blur();
closeMenus();
menu.removeAttribute("hidden");
setTimeout(function() {
launcher.setAttribute("aria-expanded", "true");
}, 50);
document.addEventListener('click', closeMenus);
e.stopPropagation();
e.preventDefault();
menu.focus();
},
launchers = document.querySelectorAll('.dropdown .launcher'),
len = launchers.length,
i = 0;
for (i=0; i<len; i++) {
launchers[i].addEventListener('click', launcherClick);
}
})();
|
/*
* This file is part of huborcid.
*
* huborcid is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* huborcid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with huborcid. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"ERANAMES": [
"avant J\u00e9sus-Christ",
"apr\u00e8s J\u00e9sus-Christ"
],
"ERAS": [
"av. J.-C.",
"ap. J.-C."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/y HH:mm",
"shortDate": "dd/MM/y",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-yt",
"pluralCat": function(n, opt_precision) { var i = n | 0; if (i == 0 || i == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
window.setTimeout(function () {
jQuery('#sidePlaceholder${uuidValidForJs}').draggable(
{
handle: '#handleImage${uuidValidForJs}',
helper: 'original',
stop: function (event, ui) {
Wicket.Ajax.get({'u': '${dragUrl}&posX=' + (ui.offset.left) + '&posY=' + (ui.offset.top) });
}
});
}, 250);
|
"use strict";
//Load dependencies
var applicationStorage = process.require("core/applicationStorage.js");
var params = process.require("core/utilities/params.js");
/**
* Get the sort to guild
* @param query
* @returns {{}}
*/
module.exports.get = function (query) {
var sort = {};
var paramLastArray = params.parseQueryParam(query.last, 3);
var type = "";
if (paramLastArray.length > 0) {
type = paramLastArray[0][0];
}
if (query.sort == "ranking") {
if (type == "max") {
sort["rank.world"] = -1;
} else {
sort["rank.world"] = 1;
}
} else {
if (type == "max") {
sort["ad.updated"] = 1;
} else {
sort["ad.updated"] = -1;
}
}
if (type == "max") {
sort._id = 1;
} else {
sort._id = -1;
}
return sort;
};
|
/**
* Created by sergiomarcial on 8/1/16.
*/
'use strict';
module.exports = {
'server': 'http://localhost:9000/'
};
|
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Adapter | saml2 idp metadata', function(hooks) {
setupTest(hooks);
// Replace this with your real tests.
test('it exists', function(assert) {
let adapter = this.owner.lookup('adapter:saml2-idp-metadata');
assert.ok(adapter);
});
});
|
window.qd.plotScatterPlot = function(divId, correlateEvents) {
var s = $(divId).empty();
s = d3.select(divId);
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = $(divId).width() - margin.left - margin.right,
height = (width / 1.61) - margin.top - margin.bottom;
var _groupCorrelateEvents = function(events) {
return _.map(events, function(event) {
return {
x: event.activeTimeInMinutes,
y: event.githubPushEventCount,
date: event.date
};
});
};
var heightnew = height - 10;
var xValue = function(d) {
return d.x;
},
xScale = d3.scale.linear().range([0, width]),
xMap = function(d) {
return xScale(xValue(d));
},
xAxis = d3.svg.axis().scale(xScale).orient("bottom");
var yValue = function(d) {
return d.y;
},
yScale = d3.scale.linear().range([heightnew, 0]),
yMap = function(d) {
return yScale(yValue(d));
},
yAxis = d3.svg.axis().scale(yScale).orient("left").ticks(5);
var svg = d3.select(divId).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "<strong>Active programming duration of " + xValue(d) + " mins with " + yValue(d) +" github"+ (yValue(d)===1?" push":" pushes")+"</strong> <span style='color:lightgrey'> on " + moment(d.date).format("ddd MMM DD") + "</span>";
});
svg.call(tip);
var _plotGraph = function() {
var data = _groupCorrelateEvents(correlateEvents);
// don't want dots overlapping axis, so add in buffer to data domain
xScale.domain([d3.min(data, xValue) - 1, d3.max(data, xValue) + 1]);
yScale.domain([d3.min(data, yValue) - 1, d3.max(data, yValue) + 1]);
// draw dots
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", xMap)
.attr("cy", yMap)
.style("fill", function(d) {
return (d.x === 0 || d.y === 0) ? "lightgrey" : "blue";
})
.on("mouseover", tip.show)
.on("mouseout", tip.hide);
// x-axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("x", width)
.attr("y", -6)
.style("text-anchor", "end")
.text("IDE Activity In Minutes");
// y-axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("class", "label")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Push Count");
};
_plotGraph();
};
|
/*jshint esversion: 6 */
/* global __dirname */
(function() {
'use strict';
const clearRequire = require('clear-require');
const Promise = require('bluebird');
const http = require('http');
const path = require('path');
const express = require('express');
const webdriver = require('selenium-webdriver');
const NockController = require(__dirname + '/../mock/nock.js');
class TestUtils {
static startServer(configFile) {
const config = require('nconf');
config.file({ file: __dirname + '/../config/config.json' });
const app = require('../../node_modules/kunta-api-www/index')(config);
return new Promise((resolve, reject) => {
const server = app.listen(3000, () => {
resolve(server);
});
});
}
static createDriver(browser) {
let driver;
if (browser === 'chrome') {
let capabilities = webdriver.Capabilities.chrome();
let chromeOptions = {
'args': [
'--disable-gpu',
'--disable-impl-side-painting',
'--disable-gpu-sandbox',
'--disable-accelerated-2d-canvas',
'--disable-accelerated-jpeg-decoding',
'--no-sandbox',
'--test-type=ui'
]
};
capabilities.set('chromeOptions', chromeOptions);
driver = new webdriver.Builder()
.forBrowser(browser)
.withCapabilities(capabilities)
.build();
} else {
driver = new webdriver.Builder()
.forBrowser(browser)
.build();
}
return driver;
}
static getElementSizes(driver, selector) {
return new Promise((resolve, reject) => {
driver.executeScript(
function (selector) {
var elements = document.querySelectorAll(selector);
var allSizes = findElements(elements);
function findElements(elements) {
var elementSizes = [];
for (var i = 0; i < elements.length; i++) {
elementSizes.push({
'width': elements[i].offsetWidth,
'height': elements[i].offsetHeight
});
};
return elementSizes;
};
return allSizes;
},
selector
).then(function (obj) {
resolve(obj);
});
});
}
static scrollToElement(driver, selector) {
return new Promise((resolve, reject) => {
driver.executeScript(
function (selector) {
var elements = document.getElementsByClassName(selector);
elements[0].scrollIntoView();
return true;
},
selector
).then(function (done) {
resolve(done);
});
});
}
static waitAnimation(duration) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, duration);
});
}
}
module.exports = TestUtils;
}).call(this);
|
(function (Q, $, window, undefined) {
/**
* @module Streams-tools
*/
/**
* Renders a preview for a Streams/category stream
* Requires Streams/preview tool to be activated on the same element.
* @class Streams category preview
* @constructor
* @param {Object} [options] this object contains function parameters
* @param {Object} [options.dialog] Any additional options to pass to Q.Dialogs.push
* @param {Object} [options.subcategory] Any options to pass to Streams/category tool in the dialogs
* @uses Q inplace
* @param {Object} [options.inplace] Any options to pass to the Q/inplace tool -- see its options.
* @uses Q inplace
* @param {Object} [options.templates] Under the keys "views", "edit" and "create" you can override options for Q.Template.render .
* @param {Object} [options.templates.view]
* @param {String} [options.templates.view.name='Streams/image/preview/view']
* @param {Object} [options.templates.view.fields]
* @param {String} [options.templates.view.fields.alt]
* @param {String} [options.templates.view.fields.titleClass]
* @param {String} [options.templates.view.fields.titleTag]
* @param {Object} [options.templates.edit]
* @param {String} [options.templates.edit.name='Streams/image/preview/edit']
* @param {Object} [options.templates.edit.fields]
* @param {String} [options.templates.edit.fields.alt]
* @param {String} [options.templates.edit.fields.titleClass]
* @param {String} [options.templates.edit.fields.titleTag]
*/
Q.Tool.define("Streams/category/preview", "Streams/preview",
function _Streams_category_preview(options, preview) {
var tool = this;
tool.preview = preview;
preview.state.onRefresh.add(tool.refresh.bind(tool));
},
{
inplace: {},
templates: {
view: {
name: 'Streams/category/preview/view',
fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
},
edit: {
name: 'Streams/category/preview/edit',
fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
}
},
dialog: {},
subcategory: {}
},
{
refresh: function (stream, onLoad) {
var tool = this;
var state = tool.state;
var ps = tool.preview.state;
// set up a pipe to know when the icon has loaded
var p = Q.pipe(['inplace', 'icon'], function () {
Q.handle(onLoad, tool);
});
// set up the inplace options
var inplace = null;
if (state.inplace) {
var inplaceOptions = Q.extend({
publisherId: ps.publisherId,
streamName: ps.streamName,
field: 'title',
inplaceType: 'text'
}, state.inplace);
var se = ps.editable;
if (!se || (se !== true && se.indexOf('title') < 0)) {
inplaceOptions.editable = false;
}
inplace = tool.setUpElementHTML('div', 'Streams/inplace', inplaceOptions);
}
// render a template
var f = state.template && state.template.fields;
var editable = stream.testWriteLevel('suggest');
var mode = editable ? 'edit' : 'view';
var fields = Q.extend({}, state.templates[mode].fields, f, {
alt: stream.fields.title,
title: stream.fields.title,
inplace: inplace
});
var tpl = (ps.editable !== false && editable) ? 'edit' : 'view';
Q.Template.render(
'Streams/category/preview/'+tpl,
fields,
function (err, html) {
if (err) return;
tool.element.innerHTML = html;
Q.activate(tool, function () {
// load the icon
var jq = tool.$('img.Streams_preview_icon');
tool.preview.icon(jq[0], p.fill('icon'));
var $pc = tool.$('.Streams_preview_contents');
$pc.width(0).width($pc[0].remainingWidth());
Q.onLayout(tool.element).set(function () {
var $pc = tool.$('.Streams_preview_contents');
$pc.width($pc[0].remainingWidth());
}, tool);
$(tool.element).on(Q.Pointer.fastclick, tool, function () {
var parent = tool.parent();
var relatedState = {};
if (parent.name === 'streams_related') {
relatedState = parent.state;
}
Q.Dialogs.push(Q.extend(state.dialog, {
title: stream.fields.title,
content: Q.Tool.setUpElement(
'div',
'Streams/category',
Q.extend(
{related: relatedState},
state.subcategory,
{
publisherId: stream.fields.publisherId,
streamName: stream.fields.name
}
)
),
className: 'Streams_category_dialog'
}));
});
var inplace = tool.child('Streams_inplace');
if (!inplace) {
return p.fill('inplace').apply(this, arguments);
}
inplace.state.onLoad.add(function () {
p.fill('inplace').apply(this, arguments);
});
});
},
state.templates[tpl]
);
}
}
);
Q.Template.set('Streams/category/preview/view',
'<div class="Streams_preview_container Streams_preview_view Q_clearfix">'
+ '<img alt="{{alt}}" class="Streams_preview_icon">'
+ '<div class="Streams_preview_contents {{titleClass}}">'
+ '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
+ '</div></div>'
);
Q.Template.set('Streams/category/preview/edit',
'<div class="Streams_preview_container Streams_preview_edit Q_clearfix">'
+ '<img alt="{{alt}}" class="Streams_preview_icon">'
+ '<div class="Streams_preview_contents {{titleClass}}">'
+ '<{{titleTag}} class="Streams_preview_title">{{& inplace}}</{{titleTag}}>'
+ '</div></div>'
);
})(Q, jQuery, window);
|
import {NameFieldForm} from "./name"
import {noSpaceTmp} from "../../../common"
export class NameListForm {
constructor(dom, initialValue = [[]]) {
this.currentValue = initialValue
this.dom = dom
}
init() {
this.drawForm()
}
drawForm() {
this.fields = []
this.dom.innerHTML = '<table class="input-list-wrapper"><tbody></tbody></table>'
this.currentValue.forEach((fieldValue, index) => {
this.addField(fieldValue, index)
})
}
addField(fieldValue, index) {
this.dom.firstChild.firstChild.insertAdjacentHTML(
'beforeend',
noSpaceTmp`
<tr>
<td></td>
<td class="input-field-list-ctrl">
<span class="fa fa-minus-circle"></span>
<span class="fa fa-plus-circle"></span>
</td>
</tr>`
)
const fieldDOM = this.dom.firstChild.firstChild.lastChild
const fieldHandler = new NameFieldForm(fieldDOM.firstChild, fieldValue)
fieldHandler.init()
this.fields.push(fieldHandler)
// click on plus
const addItemEl = fieldDOM.querySelector('.fa-plus-circle')
addItemEl.addEventListener('click', () => {
if (!this.value) {
return
}
this.currentValue = this.value
this.currentValue.splice(index + 1, 0, [])
this.drawForm()
})
// Click on minus
const removeItemEl = fieldDOM.querySelector('.fa-minus-circle')
removeItemEl.addEventListener('click', () => {
if (!this.value) {
return
}
this.currentValue = this.value
this.currentValue.splice(index, 1)
if (this.currentValue.length === 0) {
this.currentValue = [[]]
}
this.drawForm()
})
}
get value() {
const formValue = this.fields.map(field => {
return field.value
}).filter(
value => {
return value !== false
}
)
if (formValue.length === 0) {
return false
}
return formValue
}
check() {
return true
}
}
|
module.exports = {
printWidth: 80,
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: false,
trailingComma: "es5",
bracketSpacing: true,
jsxBracketSameLine: false,
arrowParens: "always",
proseWrap: "never",
htmlWhitespaceSensitivity: "strict",
endOfLine: "lf",
};
|
// Dependencies
var winston = require('winston');
// Local vars
var mainSocket = require('winston-nssocket').Nssocket; // Creation of a socket to communicate with the server and send the data
// Main Winston logger instance
var logger = new winston.Logger({
exitOnError: false,
transports: [ // Displaying in the console the log info in json format
new winston.transports.Console(),
],
});
logger.add(mainSocket, {
host : '192.168.1.64',
port : 9000
});
var TIME = 1000;
var NAME = 'Put your name here, please';
function sendData() {
//var random = Math.abs(Math.random() * 10);
//for (var i=0; i<random; i++) {
for (var i=0; i < 20000; i++) {
logger.info('Testing logging', { name : NAME, iteration : i });
}
logger.warn('Testing finished during this ' + TIME + 'miliseconds', { name : NAME });
}
setInterval(sendData, TIME);
|
/* */
'use strict';
exports.Parser = require('./lib/tree_construction/parser');
exports.SimpleApiParser = require('./lib/simple_api/simple_api_parser');
exports.TreeSerializer = exports.Serializer = require('./lib/serialization/serializer');
exports.JsDomParser = require('./lib/jsdom/jsdom_parser');
exports.TreeAdapters = {
default: require('./lib/tree_adapters/default'),
htmlparser2: require('./lib/tree_adapters/htmlparser2')
};
|
require('./layout.js');
|
/**
* This file is part of agora-gui-booth.
* Copyright (C) 2021 Sequent Tech Inc <legal@sequentech.io>
* agora-gui-booth is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License.
* agora-gui-booth is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with agora-gui-booth. If not, see <http://www.gnu.org/licenses/>.
**/
angular.module('avUi')
.controller('ConfirmModal',
function($scope, $modalInstance, data) {
$scope.data = data;
$scope.ok = function () {
$modalInstance.close(data.closingData);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
|
import i18n from '../../../../src/lib/i18n'
import { shallowMount, createLocalVue } from '@vue/test-utils'
import AssetBlock from '../../../../src/components/pages/breakdown/AssetBlock'
import VueLazyLoad from 'vue-lazyload'
const localVue = createLocalVue()
localVue.use(VueLazyLoad)
localVue.prototype.$locale = {
change (locale) {
i18n.locale = locale
},
current () {
return i18n.locale
}
}
describe('AssetBlock', () => {
const wrapper = shallowMount(AssetBlock, {
propsData: {
asset: {
preview_file_id: 1337,
label: 'fixed'
},
nbOccurences: 2,
active: true
},
localVue,
i18n
})
describe('Mount', () => {
it('should be mounted', () => {
const block = wrapper.findAll('.asset')
expect(block).toHaveLength(1)
})
it('should display how many props there is', () => {
const nb = wrapper.findAll('.nb-occurences')
expect(nb.at(0).text()).toMatch('2')
})
it('should display a picture of the asset', () => {
const picture = wrapper.findAll('.asset-picture > img')
expect(picture.exists()).toBe(true)
})
it('should display the label of the asset', () => {
const label = wrapper.findAll('.asset-label')
expect(label.at(0).text()).toMatch('fixed')
})
})
})
|
/**
* BINARY not APPLIED ON a
*/
|
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]}
clover.pageData = {"classes":[{"el":105,"id":45996,"methods":[{"el":63,"sc":2,"sl":52},{"el":73,"sc":2,"sl":69},{"el":85,"sc":2,"sl":79},{"el":104,"sc":2,"sl":94}],"name":"CustomRepositoryRegistry","sl":36}]}
// JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...};
clover.testTargets = {}
// JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]};
clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
|
'use strict';
define(function () {
return {
/**
* @callback tabPageInfoCallback
* @param {Object} pageInfo - page information for tab where extension was initiated
*/
/**
* Send message to the extension
* @param {tabPageInfoCallback} callback - The callback that handles the response.
*/
onExtensionTriggered: function (callback) {
chrome.browserAction.onClicked.addListener(function (tab) {
var pageInfo = {
url: tab.url,
title: tab.title,
nativeWidth: tab.width,
nativeHeight: tab.height
};
callback(pageInfo);
});
},
saveLocal: function (data, callback) {
chrome.storage.local.set(data, callback);
},
notify: function (notification, callback) {
var options = {
type: 'basic',
title: notification.title,
message: notification.message,
iconUrl: notification.iconUrl
};
chrome.notifications.create('', options, function(id) {
console.log('notification ' + id);
callback();
});
},
screenshot: function (callback) {
chrome.tabs.captureVisibleTab(null, {}, function (dataUrl) {
callback(dataUrl);
});
},
getURL: function (path) {
return chrome.extension.getURL(path);
},
sendMessageToDom: function (message, tabId) {
if (tabId) {
chrome.tabs.sendMessage(tabId, message);
} else {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, message);
});
}
},
sendMessageToBackground: function (message) {
chrome.extension.sendMessage(message);
},
currentTab: function (callback) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
callback(tabs[0]);
});
},
onBackgroundConnection: function(callback) {
chrome.extension.onConnect.addListener(function(port) {
if (port.name === 'parallels') {
callback({
id: port._portId,
senderId: port.sender.tab.id,
onMessage: function(cb) {
port.onMessage.addListener(cb);
},
onDisconnect: function(cb) {
port.onDisconnect.addListener(cb);
},
removeListener: function(cb) {
port.onMessage.removeListener(cb);
},
postMessage: function(message) {
port.postMessage(message);
}
});
}
});
},
connectToBackground: function() {
var port = chrome.extension.connect({name: 'parallels'});
return {
onBackgroundMessage: function(listener) {
port.onMessage.addListener(listener);
},
postMessage: function(message) {
port.postMessage(message);
}
};
},
initMessageListener: function(listener) {
chrome.extension.onMessage.addListener(listener);
}
};
});
|
function openRegistration() {
$('#registrationModal').modal('show');
};
function register() {
var name = $('#addNameInput').val();
var mail = $('#addEmailInput').val();
var cake = $('#promiseCake').length > 0 ? $('#promiseCake').checked : false;
var id = name.replace(/\s/,'');
var pass = $('#inputPassword').val();
var pass2 = $('#inputPassword2').val();
if(pass !== pass2) {
alert('Passwörter stimmen nicht überein. Bitte korrigieren.');
return false;
}
pass = Sha256.hash(pass);
new jQuery.get('resources/xql/addSeller.xql',
{name: name,
mail: mail,
id: id,
cake: cake,
pass: pass}, function(data) {
$('#registrationModal').modal('hide');
$('#registrationDetails').html('<div class="hero-unit"><h3>Registrierung erfolgreich</h3><p>' + data + '</p><p><b><a class="btn btn-primary" id="loginLink" href="#">Zur Anmeldung</a></b></p></div>');
$('#loginLink').on('click',function(){
alert('Login funktioniert noch nicht.');
});
});
};
$('#registerBtn').on('click',function() {openRegistration()});
$('#createSeller').on('click',function() {register()});
|
/**
* TTBackboneView is the interface between the TimeTrex BaseViewController and any other classes that need
* to extend from Backbone.View. It allows common logic such as the hierarchical options and required_files
* to work as expected.
*
* When adding functions to this class, make sure they will be compatible with all files that extend from this.
* Do a search to see these, they include the main UI views, as well as the portal etc.
*
* Usage note: When extending this view in a child view instead of from Backbone.View, make sure that your initialize function in the child view
* has the super.initialize( options ); line at the start (before the required_files or any other non-backbone values from the options are used).
*/
export class TTBackboneView extends Backbone.View {
constructor( options = {} ) {
_.defaults( options, {} );
super( options );
}
initialize( options ) {
//Convert options object to this object properties as early as possible.
if ( options && typeof options == 'object' ) {
for ( const property in options ) {
if ( options.hasOwnProperty( property ) ) { // #2808 See Safari bug https://bugs.webkit.org/show_bug.cgi?id=212449 This hasOwnProperty check is essential to prevent problems due to a bug in Safari with an inherited 'render' on the options Object interfering with the Views render() function.
this[property] = options[property];
}
}
}
}
}
|
//
// @route /mobilizations/:mobilization_id/launch
//
import { provideHooks } from 'redial'
import { connect } from 'react-redux'
import MobSelectors from 'mobrender/redux/selectors'
import DNSControlSelectors from 'community/dns-control-selectors'
import * as MobActions from 'mobrender/redux/action-creators'
import Page from './page'
const redial = {
fetch: ({ dispatch, getState, params }) => {
const state = getState()
const promises = []
!MobSelectors(state).hasCurrentMobilization() && promises.push(
dispatch(MobActions.selectMobilization(params.mobilization_id))
)
return Promise.all(promises)
}
}
const mapStateToProps = state => {
const selectors = MobSelectors(state)
const hostedZones = DNSControlSelectors(state).dnsHostedZones().getList()
return {
mobilization: selectors.getMobilization(),
isSaving: selectors.mobilizationIsSaving(),
hostedZones
}
}
export default provideHooks(redial)(
connect(mapStateToProps)(Page)
)
|
angular.module('app.base').config(appConfig);
appConfig.$inject = ['$stateProvider'];
function appConfig($stateProvider) {
$stateProvider.state('base', {
controller: BaseController,
ncyBreadcrumb: {
label: 'Lily',
},
});
}
angular.module('app.base').controller('BaseController', BaseController);
BaseController.$inject = ['$scope', '$state', '$http', '$location', 'AppHash', 'Settings', 'HLShortcuts', 'User'];
function BaseController($scope, $state, $http, $location, AppHash, Settings, HLShortcuts, User) {
// Make sure the settings are available everywhere.
$scope.settings = Settings;
$scope.loadNotifications = loadNotifications;
activate();
//////////
function activate() {
User.me().$promise.then(function(response) {
$scope.settings.currentUser = response;
});
$scope.$on('$stateChangeStart', function() {
new window.Intercom('update', {email: currentUser.email});
});
$scope.$on('$stateChangeSuccess', _setPreviousState);
$scope.$on('$viewContentLoaded', _contentLoadedActions);
$scope.$on('$stateChangeError', _handleResolveErrors);
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
const path = $location.path();
let queryString = '';
let referrer = '';
// Check if there is a query string?
if (path.indexOf('?') !== -1) {
queryString = path.substring(path.indexOf('?'), path.length);
}
// Check if there is a referer?
if (fromState.name) {
referrer = $location.protocol() + '://' + $location.host() + '/#' + fromState.url;
}
// Track a page event in Segment each time you change states.
analytics.page({
path: path,
referrer: referrer,
search: queryString,
url: $location.absUrl(),
});
// Identify a user in Segment when he navigates to a different state.
let currentUser = $scope.settings.currentUser;
if (currentUser) {
analytics.identify(currentUser.id, {
name: currentUser.full_name,
email: currentUser.email,
tenant_id: currentUser.tenant.id,
tenant_name: currentUser.tenant.name,
plan_id: currentUser.tenant.billing.plan ? currentUser.tenant.billing.plan.id : '',
plan_tier: currentUser.tenant.billing.plan ? currentUser.tenant.billing.plan.tier : '',
plan_name: currentUser.tenant.billing.plan ? currentUser.tenant.billing.plan.name : '',
is_free_plan: currentUser.tenant.billing ? currentUser.tenant.billing.is_free_plan : '',
});
}
});
}
function loadNotifications() {
$http.get('/api/utils/notifications/').then(function(notifications) { // On success
angular.forEach(notifications.data, function(message) {
toastr[message.level](message.message);
});
}, function(error) { // On error
if (error.status === 403) {
toastr.error(error, 'You\'ve been logged out, please reload the page.');
} else {
toastr.error(error, 'Couldn\'t load notifications');
}
});
}
function _setPreviousState(event, toState, toParams, fromState, fromParams) {
var previousInbox;
$scope.previousState = $state.href(fromState, fromParams);
Settings.page.previousState = {state: fromState, params: fromParams};
if (['base.email.list', 'base.email.accountList', 'base.email.accountAllList'].includes(fromState.name)) {
previousInbox = {
state: fromState.name,
params: fromParams,
};
Settings.email.setPreviousInbox(previousInbox);
}
if (Settings.email.sidebar && fromState && fromState.name === 'base.email.detail') {
Settings.email.resetEmailSettings();
$scope.$$phase || $scope.apply();
}
Settings.page.toolbar.data = null;
// For some reason we need to do two update calls to display messages
// when they should.
new window.Intercom('update', {email: currentUser.email});
}
function _contentLoadedActions() {
AppHash.get().$promise.then(response => {
// App hash is set, so compare with the response.
if (window.appHash && window.appHash !== response.app_hash) {
// Reload the page so we get new static files.
window.location.reload(true);
} else {
window.appHash = response.app_hash;
}
});
Metronic.unblockUI();
Metronic.initComponents(); // init core components
HLSelect2.init();
HLFormsets.init();
autosize($('textarea'));
$scope.loadNotifications();
$scope.toolbar = Settings.page.toolbar.data;
}
function _handleResolveErrors(event, toState, toParams, fromState, fromParams, error) {
switch (error.status) {
case 404:
$state.go('base.404');
break;
case 403:
window.location.href = '/';
break;
default:
// With JS errors, error isn't an object, but still the default case gets called.
$state.go('base.500');
}
}
}
|
class OpenNodesModel extends Observable{
constructor(){
super();
this._openNodes = [];
this._updatedTitles = new Map();
pydio.UI.registerEditorOpener(this);
pydio.observe("repository_list_refreshed", function(){
this._openNodes = [];
}.bind(this));
}
static getInstance(){
if(!OpenNodesModel.__INSTANCE){
OpenNodesModel.__INSTANCE = new OpenNodesModel();
}
return OpenNodesModel.__INSTANCE;
}
openEditorForNode(selectedNode, editorData){
this.pushNode(selectedNode, editorData);
}
updateNodeTitle(object, newTitle){
this._updatedTitles.set(object, newTitle);
this.notify('titlesUpdated');
}
getObjectLabel(object){
if(this._updatedTitles.has(object)){
return this._updatedTitles.get(object);
}else{
return object.node.getLabel();
}
}
pushNode(node, editorData){
let found = false;
let editorClass = editorData ? editorData.editorClass : null;
let object = {node:node, editorData:editorData};
this.notify('willPushNode', object);
this._openNodes.map(function(o){
if(o.node === node && (o.editorData && o.editorData.editorClass == editorClass) || (!o.editorData && !editorClass)){
found = true;
object = o;
}
});
if(!found){
this._openNodes.push(object);
}
this.notify('nodePushed', object);
this.notify('update', this._openNodes);
}
removeNode(object){
this.notify('willRemoveNode', object);
let index = this._openNodes.indexOf(object);
if(this._updatedTitles.has(object)){
this._updatedTitles.delete(object);
}
this._openNodes = LangUtils.arrayWithout(this._openNodes, index);
this.notify('nodeRemovedAtIndex', index);
this.notify('update', this._openNodes);
}
getNodes(){
return this._openNodes;
}
}
export {OpenNodesModel as default}
|
import test from 'ava';
import StatesHistory from '../../src/services/history.js';
/**
* get()
*/
test('should return empty states array on init', t => {
const h = new StatesHistory();
t.deepEqual(h.get(), []);
});
/**
* add()
*/
test('should add single state', t => {
const h = new StatesHistory();
t.true(h.add('300'));
t.deepEqual(h.get(), ['300']);
});
test('should add multiple states', t => {
const h = new StatesHistory();
t.true(h.add('128'));
t.true(h.add('444'));
t.deepEqual(h.get(), ['128', '444']);
});
/*
test('should not add the same state as the last one', t => {
const h = new StatesHistory();
t.true(h.add('128'));
t.true(h.add('444'));
t.true(h.add('444'));
t.deepEqual(h.get(), ['128', '444']);
});
*/
test('should use round-robin algorithm while adding new items', t => {
const h = new StatesHistory();
t.true(h.add('001'));
t.true(h.add('002'));
t.true(h.add('003'));
t.true(h.add('004'));
t.true(h.add('005'));
t.true(h.add('006'));
t.true(h.add('007'));
t.true(h.add('008'));
t.true(h.add('009'));
t.true(h.add('010'));
t.deepEqual(h.get(), ['001', '002', '003', '004', '005', '006', '007', '008', '009', '010']);
t.true(h.add('011'));
t.deepEqual(h.get(), ['002', '003', '004', '005', '006', '007', '008', '009', '010', '011']);
});
test('should create queue with the given size', t => {
const h = new StatesHistory(3);
t.true(h.add('001'));
t.true(h.add('002'));
t.true(h.add('003'));
t.deepEqual(h.get(), ['001', '002', '003']);
t.true(h.add('004'));
t.deepEqual(h.get(), ['002', '003', '004']);
});
|
exports.examples = (expect) => {
describe('.items', () => {
describe('.get(queryParams)', () => {
it('GETs to /v1/items/show with queryParams as the body', function () {
const queryParams = { facility: 'sampleFacility' };
return expect(this.subject.items.get(queryParams)).to.wrap.request({
method: 'get',
path: '/itemsense/data/v1/items/show',
query: queryParams
});
});
});
describe('.getHistory(queryParams)', () => {
it('GETs to /v1/items/show/history with queryParams as the body', function () {
const queryParams = { facility: 'sampleFacility' };
return expect(this.subject.items.getHistory(queryParams)).to.wrap.request({
method: 'get',
path: '/itemsense/data/v1/items/show/history',
query: queryParams
});
});
});
describe('.configureQueue(filterParams)', () => {
it('PUTs to /data/v1/items/queues with messageQueueParams as the body', function () {
const filterParams = { fromZone: 'exitZone', toZone: 'entryZone' };
return expect(this.subject.items.configureQueue(filterParams)).to.wrap.request({
method: 'put',
path: '/itemsense/data/v1/items/queues',
body: filterParams
});
});
});
describe('.configureQueue(filterParams, options)', () => {
it('PUTs to /data/v1/items/queues with messageQueueParams as the body', function () {
const filterParams = { fromZone: 'exitZone', toZone: 'entryZone' };
const optionParams = { deliveryMethod: 'NON_PERSISTENT' };
return expect(this.subject.items.configureQueue(filterParams, optionParams)).to.wrap.request({
method: 'put',
path: '/itemsense/data/v1/items/queues',
body: filterParams,
query: optionParams
});
});
});
it('handles AMQP events', function () {
const AmqpHandler = require('../../dist/services/amqp-handler.service.js');
return expect(this.subject.health instanceof AmqpHandler.constructor).to.be.true;
});
});
};
|
module.exports = function () {
return {
controller: require("./ItemController"),
transclude: true,
scope: {
"item" : "=",
"itemId": "=",
"plain": "="
},
template: require('./item.html')
};
};
|
module.exports = function () {
var express = require('express'),
swagger = require('swagger-node-express'),
cluster = require('cluster'),
routes = require('../routes'),
app = express(),
os = require('os'),
url = require('url'),
winston = require('winston'),
logger = new (winston.Logger)({ transports: [
new (winston.transports.Console)({
"level" : "debug",
"json" : false,
"colorize" : true
})
]}),
meta = {
"module" : "tagger",
"pid" : process.pid,
"id" : cluster.id
};
logger.log('debug', '%s|loading|module="%s"', meta.module, meta.module, meta);
/**
* Start the Web Server to provide both the HTML frontend and the JSON Web
* service.
*
* @param options an object containing two properties :
* options.context: The context (prefix on the URL) for the web
* service (e.g. http://context/resource)
* options.port: The port on which the server will listen to
*/
function start(options) {
var monitor = (options.statsd && options.syslogd) ? require('node-network-monitor')({
"statsd" : {
"host" : options.statsd.host,
"port" : options.statsd.port,
"domain" : options.statsd.domain
},
"syslogd" : {
"host" : options.syslogd.host,
"port" : options.syslogd.port
}
}) : null;
////////////////////////////////////////////////////////////////////////
//
// Express configuration for ALL environment
//
app.configure(function () {
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser()); // to parse the JSON body
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/../../app/')); // HTML UI
app.use(express.errorHandler());
});
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
var isSwaggerApp = (function configureSwagger() {
var swaggerApp = express();
// Set the main handler in swagger to the express app
app.use('/' + options.context, swaggerApp);
logger.log('debug', '%s|swagger|app.use|%s', meta.module, '/' + options.context, meta);
swagger.setAppHandler(swaggerApp);
// Serve up swagger ui at /docs via static route
var docs_handler = express.static(__dirname + '/../../swagger-ui');
app.get(/^\/docs(\/.*)?$/, function(req, res, next) {
if (req.url === '/docs') { // express static barfs on root url w/o trailing slash
res.writeHead(302, { 'Location' : req.url + '/' });
res.end();
return;
}
// take off leading /docs so that connect locates file correctly
req.url = req.url.substr('/docs'.length);
return docs_handler(req, res, next);
});
//routes.init(swaggerApp, '/' + options.context, swagger);
routes.init(swaggerApp, '/pos', swagger);
var baseURL = process.env.BASEURL || os.hostname() + ':' + options.port;
swagger.configure('http://' + baseURL + '/' + options.context , '0.0.1');
// This is a sample validator. It simply says that for _all_ POST, DELETE, PUT
// methods, the header `api_key` OR query param `api_key` must be equal
// to the string literal `special-key`. All other HTTP ops are A-OK
swagger.addValidator(
function validate(req, path, httpMethod) {
// example, only allow POST for api_key="special-key"
if ("POST" == httpMethod || "DELETE" == httpMethod || "PUT" == httpMethod) {
var apiKey = req.headers["x-api-key"];
if (!apiKey) {
apiKey = url.parse(req.url,true).query["api_key"]; }
if ("henri-id" == apiKey) {
return true;
}
logger.log('error', '%s|swagger|X-API-KEY=%s|INVALID', meta.module, apiKey, meta);
logger.log('info', '%s|swagger|headers=%s', meta.module, req.headers, meta);
return false;
}
return true;
}
);
swagger.setHeaders = function setHeaders(res) {
res.header('Access-Control-Allow-Origin', "*");
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.header("Access-Control-Allow-Headers", "Content-Type, X-API-KEY");
res.header("Content-Type", "application/json; charset=utf-8");
};
return true;
})();
if (!isSwaggerApp)
routes.init(app, '/' + options.context); // Add the postagger URIs to Express
if (monitor)
monitor.app(app.listen(options.port));
else
app.listen(options.port);
logger.log('verbose', '%s|Listening|port=%d', meta.module, options.port, meta);
}
logger.log('debug', '%s|loaded|module=%s', meta.module, meta.module, meta);
return {
"start" : start
};
}();
|
var ExDualCQKnP_8h =
[
[ "ExDualCQKnP", "classCQKnPClass__di__unipi__it_1_1ExDualCQKnP.html", null ]
];
|
var site = function() {
this.navLi = $('#nav li').children('ul').hide().end();
this.init();
};
site.prototype = {
init : function() {
this.setMenu();
},
// Enables the slidedown menu, and adds support for IE6
setMenu : function() {
$.each(this.navLi, function() {
if ( $(this).children('ul')[0] ) {
$(this)
.append('<span />')
.children('span')
.addClass('hasChildren')
}
});
this.navLi.hover(function() {
// mouseover
$(this).find('> ul').stop(true, true).slideDown('slow', 'easeOutBounce');
}, function() {
// mouseout
$(this).find('> ul').stop(true, true).hide();
});
}
}
new site();
|
/* global define */
define([], function(){
// It would be better that this module returns an object called "variablename."
// This is just to get things working with minimal changes to the pre-AMD version.
window.andes.variablename={};
// pick out variable name from definition string
// The forms that are matched:
// ?var is ...
// ?var: ... [space optional]
// ?var = ... [spaces optional]
// Let ?var be ...
// Define ?var (as|to be) ...
//
// Variables are any alphanumeric, _ \ and $,
// for LaTeX compatibility
//
// Returns empty string in case of no match. This correctly
// handles the case where a modification to the text removes the symbol.
//
// This routine needs to match function pull-out-quantity
// in Help/Entry-API.cl
//
// To do:
// Test for variable names that begin with a number
//
// Handle variable names containing parentheses or brackets:
// "H(green house) is the height of the house on Green St."
// "A_{t=0} is the initial area"
window.andes.variablename.parse = function(intext){
if(intext){
// canonicalize whitespace
var cantext = intext.replace(/\s+/g," ");
cantext = cantext.replace(/\s*=\s*/," = ");
cantext = cantext.replace(/\s*:\s*/,": ");
cantext = cantext.replace(/^\s/,"");
// Remove leading puctuation (for comments).
cantext = cantext.replace(/^[?!;:,&#%]/,"");
// match for forms like ?var is ...
var equality=/^([\w\\$]+)(:| is| =) /i;
var match = equality.exec(cantext);
// console.log("equality match ",match);
if (match) return match[1];
// match for let ...
var letre=/^let ([\w\\$]+) (=|be) /i;
match = letre.exec(cantext);
// console.log("letre match ",match," for ",cantext);
if(match) return match[1];
// match for define ...
var definere=/^define ([\w\\$]+) (to be|=|as) /i;
match = definere.exec(cantext);
// console.log("definere match ",match);
if (match) return match[1];
}
return "";
};
});
|
'use strict';
var startTimeout = require('./pauseable-timeout'),
chai = require('chai');
chai.should();
describe('pauseable-timeout', function () {
describe('setTimeout', function () {
it('should invoke callback in no less than 500 ms', function (done) {
var startTime = new Date().getTime();
startTimeout(function () {
(new Date().getTime() - startTime).should.be.at.least(500, 'callback invoked too soon');
done();
}, 500)
});
it('should invoke callback in no less than 750 ms when paused for 250 ms', function (done) {
var startTime = new Date().getTime();
var timeout = startTimeout(function () {
(new Date().getTime() - startTime).should.be.at.least(750, 'callback invoked too soon');
done();
}, 500)
timeout.pause();
setTimeout(function () {
timeout.resume();
}, 250);
});
it('should invoke callback in no less than 1000 ms when paused twice for 250 ms', function (done) {
var startTime = new Date().getTime();
var timeout = startTimeout(function () {
(new Date().getTime() - startTime).should.be.at.least(1000, 'callback invoked too soon');
done();
}, 500)
timeout.pause();
setTimeout(function () {
timeout.resume();
setTimeout(function () {
timeout.pause();
setTimeout(function () {
timeout.resume();
}, 250);
}, 250);
}, 250);
});
it('should invoke callback in no less than 500 ms with given arguments', function (done) {
var these = 'these',
are = 'are',
inputs = 'inputs';
var startTime = new Date().getTime();
startTimeout(function (arg1, arg2, arg3) {
(new Date().getTime() - startTime).should.be.at.least(500, 'callback invoked too soon');
arg1.should.equal(these, 'first argument is not "these"');
arg2.should.equal(are), 'second argument is not "are"';
arg3.should.equal(inputs, 'third argument is not "inputs"');
done();
}, 500, these, are, inputs);
});
});
});
|
'use strict';
var SingleSelectMenu = require('../../../../form-builder/form-control.js').SingleSelectMenu;
var SandboxPage = require('../../../../page-object').SandboxPage;
const SANDBOX_PAGE_URL = 'sandbox/search/components/advanced/dynamic-date-range/';
const DEFAULT_FORM = '#default_values .dynamic-date-range';
const PREDEFINED_FORM = '#predefined_values .dynamic-date-range';
const STATE_BUTTON = '#toggle_state';
const DATE_STEP = '.date-step';
const DATE_OFFSET = '.date-offset';
const DATE_OFFSET_TYPE = '.date-offset-type';
/**
* Page object for the sandbox page bootstrapping the dynamic date range form component.
*
* @author Mihail Radkov
*/
class DynamicDateRangeSandboxPage extends SandboxPage {
open() {
super.open(SANDBOX_PAGE_URL);
this.waitUntilOpened();
}
waitUntilOpened() {
browser.wait(EC.visibilityOf($('.dynamic-date-range-stub')), DEFAULT_TIMEOUT);
}
getDefaultForm() {
var defaultForm = $(DEFAULT_FORM);
browser.wait(EC.visibilityOf(defaultForm), DEFAULT_TIMEOUT);
return new DynamicDateRange(defaultForm);
}
getPredefinedForm() {
var predefinedForm = $(PREDEFINED_FORM);
browser.wait(EC.visibilityOf(predefinedForm), DEFAULT_TIMEOUT);
return new DynamicDateRange(predefinedForm);
}
toggleDefaultFormState() {
var toggleButton = $(STATE_BUTTON);
browser.wait(EC.visibilityOf(toggleButton), DEFAULT_TIMEOUT);
return toggleButton.click();
}
}
/**
* Page object for working with the dynamic date range form and its components.
*
* @author Mihail Radkov
*/
class DynamicDateRange {
constructor(element) {
if (!element) {
throw new Error('Cannot instantiate PO without element!');
}
this.element = element;
this.waitUntilOpened();
}
waitUntilOpened() {
browser.wait(EC.visibilityOf(this.element), DEFAULT_TIMEOUT);
browser.wait(EC.visibilityOf(this.dateStepSelectElement), DEFAULT_TIMEOUT);
}
isDisplayed() {
return this.dateStepSelectElement.isDisplayed();
}
isDisabled() {
return Promise.all([
this.dateStepSelectMenu.isDisabled(),
this.dateOffsetInputElement.getAttribute('disabled'),
this.dateOffsetTypeSelectMenu.isDisabled()
]).then((states) => {
return states[0] && !!states[1] && states[2];
});
}
selectDateStep(dateStep) {
return this.dateStepSelectMenu.selectFromMenu(undefined, dateStep, false);
}
getSelectedDateStep() {
return this.dateStepSelectMenu.getSelectedValue();
}
enterDateOffset(offset) {
return this.dateOffsetInputElement.sendKeys(offset);
}
getDateOffsetValue() {
return this.dateOffsetInputElement.getAttribute('value');
}
selectDateOffsetType(dateOffsetType) {
return this.dateOffsetTypeSelectMenu.selectFromMenu(undefined, dateOffsetType, false);
}
getSelectedDateOffsetType() {
return this.dateOffsetTypeSelectMenu.getSelectedValue();
}
get dateStepSelectElement() {
return this.element.$(DATE_STEP);
}
get dateStepSelectMenu() {
return new SingleSelectMenu(this.dateStepSelectElement);
}
get dateOffsetInputElement() {
return this.element.$(DATE_OFFSET);
}
get dateOffsetTypeSelectElement() {
return this.element.$(DATE_OFFSET_TYPE);
}
get dateOffsetTypeSelectMenu() {
return new SingleSelectMenu(this.dateOffsetTypeSelectElement);
}
}
DynamicDateRange.COMPONENT_SELECTOR = '.dynamic-date-range';
module.exports = {
DynamicDateRangeSandboxPage,
DynamicDateRange
};
|
var async = require('async'),
_ = require('underscore');
read.factory('SettingsService', function($rootScope) {
var settings;
function save() {
localStorage.settings = JSON.stringify(settings);
};
function load() {
if (!localStorage.settings) localStorage.settings = '{}'
settings = JSON.parse(localStorage.settings);
if (!settings.files) settings.files = [];
}
function set(a, b) {
var tmp;
try {
tmp = JSON.stringify(b);
} catch (e) {
return false;
}
settings[a] = b;
return true;
};
function get(a) {
return settings[a];
};
load();
return {
get: get,
set: set,
save: save,
load: load
};
});
|
'use strict';
angular.module('myApp.main', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/main', {
templateUrl: 'main/main.html',
controller: 'MainCtrl',
controllerAs: 'vm'
});
}])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', 'dataService'];
function MainCtrl($scope, dataService) {
var vm = this;
vm.softwares = [];
vm.categories = [];
vm.shortcuts = [];
vm.setSoftware = setSoftware;
activate();
init();
function activate() {
return getSoftwares().then(function() {
console.info('Activated Software View');
});
}
function getCategories() {
return dataService.getCategories(vm.currSoftware.id)
.then(function(data) {
vm.categories = data;
vm.categories[0] && (vm.currCategory = vm.categories[0]);
return vm.categories;
});
}
function getShortcuts() {
return dataService.getShortcuts(vm.currSoftware.id)
.then(function(data) {
vm.shortcuts = data;
return vm.shortcuts;
});
}
function getSoftwares() {
return dataService.getSoftwares()
.then(function(data) {
vm.softwares = data;
vm.softwares[0] && setSoftware(vm.softwares[0]);
return vm.softwares;
});
}
function setSoftware(software){
vm.currSoftware = software;
getCategories();
getShortcuts();
}
function init(){
$(function() {
var isXS = false;
var $accordionXSCollapse = $('.accordion-xs-collapse');
// Window resize event (debounced)
var timer;
$(window).resize(function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(function () {
isXS = Modernizr.mq('only screen and (max-width: 767px)');
var $accordionXSCollapse = $('.accordion-xs-collapse');
// Add/remove collapse class as needed
if (isXS) {
$accordionXSCollapse.addClass('collapse');
} else {
$accordionXSCollapse.removeClass('collapse');
}
}, 100);
}).trigger('resize'); //trigger window resize on pageload
// Initialise the Bootstrap Collapse
$accordionXSCollapse.each(function () {
$(this).collapse({ toggle: false });
});
// <a href="http://www.jqueryscript.net/accordion/">Accordion</a> toggle click event (live)
$(document).on('click', '.accordion-xs-toggle', function (e) {
e.preventDefault();
var $thisToggle = $(this),
$targetRow = $thisToggle.parent('.tr'),
$targetCollapse = $targetRow.find('.accordion-xs-collapse');
if (isXS && $targetCollapse.length) {
var $siblingRow = $targetRow.siblings('.tr'),
$siblingToggle = $siblingRow.find('.accordion-xs-toggle'),
$siblingCollapse = $siblingRow.find('.accordion-xs-collapse');
$targetCollapse.collapse('toggle'); //toggle this collapse
$siblingCollapse.collapse('hide'); //close siblings
$thisToggle.toggleClass('collapsed'); //class used for icon marker
$siblingToggle.removeClass('collapsed'); //remove sibling marker class
}
});
});
}
}
|
const test = require('tape');
const { maybe } = require('../../src/functions');
const { Maybe } = require('../../src/data');
const double = x => x * 2;
const doubleOrZero = maybe(0, double);
test('maybe :: b -> (a -> b) -> Maybe a -> b', (t) => {
t.equal(doubleOrZero(Maybe.of(2)), 4);
t.end();
});
test('maybe :: b -> (a -> b) -> Maybe a -> b', (t) => {
t.equal(doubleOrZero(Maybe.Nothing), 0);
t.end();
});
|
chrome.webRequest.onCompleted.addListener(function(details) {
if (details.statusCode == 404 || details.statusCode == 403) {
chrome.tabs.query({'active': true}, function(tabs) {
// Detect if this is the url in the tab. Avoid redirects when
// it's a 404 in the page
var currentUrl = tabs[0].url;
if (details.url == currentUrl) {
// Rewrite URL
var newUrl = new URL(details.url);
newUrl.host = "obamawhitehouse.archives.gov";
// Redirect
chrome.tabs.update(tabs[0].id, {url: newUrl.href});
}
});
}
},
{urls: ["*://*.whitehouse.gov/*"]},
["responseHeaders"]
);
|
/*! Bootstrap integration for DataTables' Responsive
* ©2015-2016 SpryMedia Ltd - datatables.net/license
*/
(function( factory ){
if ( typeof define === 'function' && define.amd ) {
// AMD
define( ['jquery', 'datatables.net-bs', 'datatables.net-responsive'], function ( $ ) {
return factory( $, window, document );
} );
}
else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = function (root, $) {
if ( ! root ) {
root = window;
}
if ( ! $ || ! $.fn.dataTable ) {
$ = require('datatables.net-bs')(root, $).$;
}
if ( ! $.fn.dataTable.Responsive ) {
require('datatables.net-responsive')(root, $);
}
return factory( $, root, root.document );
};
}
else {
// Browser
factory( jQuery, window, document );
}
}(function( $, window, document, undefined ) {
'use strict';
var dataTable = $.fn.dataTable;
var display = dataTable.Responsive.display;
var original = display.modal;
var modal = $(
'<div class="modal fade dtr-bs-modal" role="dialog">'+
'<div class="modal-dialog" role="document">'+
'<div class="modal-content">'+
'<div class="modal-header">'+
'<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'</div>'+
'<div class="modal-body"/>'+
'</div>'+
'</div>'+
'</div>'
);
display.modal = function ( options ) {
return function ( row, update, render ) {
if ( ! $.fn.modal ) {
original( row, update, render );
}
else {
if ( ! update ) {
if ( options && options.header ) {
modal.find('div.modal-header')
.empty()
.append( '<h4 class="modal-title">'+options.header( row )+'</h4>' );
}
modal.find( 'div.modal-body' )
.empty()
.append( render() );
modal
.appendTo( 'body' )
.modal();
}
}
};
};
return dataTable.Responsive;
}));
|
[
{
"key":"_RegistrationLabel_",
"value":"Registration",
"description":"Registration form label"
},
{
"key":"_UsernamePlaceholder_",
"value":"Username",
"description":"Username placeholder"
},
{
"key":"_PasswordPlaceholder_",
"value":"Password",
"description":"Password placeholder"
},
{
"key":"_PasswordConfirmationPlaceholder_",
"value":"Confirm password",
"description":"Password confirmation placeholder"
},
{
"key":"_WelcomeMessage_",
"value":"Hello, {0}!",
"description":"Login welcome message"
}
]
|
(function(){
var filter = document.querySelector('.filter'),
allButton = filter.querySelector('.all'),
flipkartButton = filter.querySelector('.flipkart'),
photographyButton = filter.querySelector('.photography'),
textButton = filter.querySelector('.text'),
audioButton = filter.querySelector('.audio'),
flipkart = document.querySelectorAll('.postExcerpt.flipkart'),
photography = document.querySelectorAll('.postExcerpt.photography'),
text = document.querySelectorAll('.postExcerpt.text'),
audio = document.querySelectorAll('.postExcerpt.audio');
filter.addEventListener('click', function(e){
e.preventDefault();
var hideElements = function(nodeList) {
for(i=0; i<nodeList.length; i++) {
nodeList[i].style.display = 'none';
}
},
showElements = function(nodeList) {
for(i=0; i<nodeList.length; i++) {
nodeList[i].removeAttribute('style');
}
},
addSelectedClass = function(el) {
allButton.className = allButton.className.replace(' selected', '');
flipkartButton.className = flipkartButton.className.replace(' selected', '');
photographyButton.className = photographyButton.className.replace(' selected', '');
textButton.className = textButton.className.replace(' selected', '');
audioButton.className = audioButton.className.replace(' selected', '');
el.className += ' selected';
};
if(e.target === allButton) {
showElements(flipkart);
showElements(photography);
showElements(text);
showElements(audio);
addSelectedClass(allButton);
localStorage['sortByCategory'] = 'allButton';
}
else if(e.target === flipkartButton) {
showElements(flipkart);
hideElements(photography);
hideElements(text);
hideElements(audio);
addSelectedClass(flipkartButton);
localStorage['sortByCategory'] = 'flipkartButton';
}
else if(e.target === photographyButton) {
hideElements(flipkart);
showElements(photography);
hideElements(text);
hideElements(audio);
addSelectedClass(photographyButton);
localStorage['sortByCategory'] = 'photographyButton';
}
else if(e.target === textButton) {
hideElements(flipkart);
hideElements(photography);
showElements(text);
hideElements(audio);
addSelectedClass(textButton);
localStorage['sortByCategory'] = 'textButton';
}
else if(e.target === audioButton) {
hideElements(flipkart);
hideElements(photography);
hideElements(text);
showElements(audio);
addSelectedClass(audioButton);
localStorage['sortByCategory'] = 'audioButton';
}
}, false);
eval(localStorage['sortByCategory']).click();
//yaya, I know eval is evil, but what is the other way to do something like this?
}());
|
var _util = require('util');
var _async = require('async');
var _db = require('./db');
var _logger = require('./logger');
function save(m, d, cb)
{
_logger.err('Found discrepency for media ID #%d: %s', m.id, d.description);
d.media_id = m.id;
_async.series([
function(cb)
{
_db.createOrUpdate(_db.Discrepancy, { hash : d.hash, type : d.type }, d, cb);
},
function(cb)
{
m.state = 'hasdiscrepancy';
m.save().complete(cb);
}
], function(err)
{
if (err)
return cb(err);
return cb();
});
}
function dupe(m, otherabs, fOtherIsDupe, cb)
{
save(m,
{
type : 'duplicate',
hash : m.hash,
description : _util.format('Found duplicate media file "%s". Original at "%s".',
fOtherIsDupe ? otherabs : (m.abspath || ('#' + m.id)),
fOtherIsDupe ? (m.abspath || ('#' + m.id)) : otherabs),
arg1 : otherabs,
arg2 : fOtherIsDupe
}, cb);
}
function noparse(m, cb)
{
save(m, {
type : 'noparse',
hash : m.hash,
description : _util.format('Unable to parse path "%s"', m.abspath),
arg1 : m.abspath}, cb);
}
function notfound(m, title, type, detail, cb)
{
save(m, {
type : 'notfound',
hash : m.hash,
description : _util.format('Could not find "%s" in %s media database (%s)', title, type, detail),
arg1 : title}, cb);
}
function ambiguous(m, title, type, cnt, cb)
{
save(m, {
type : 'ambiguous',
hash : m.hash,
description : _util.format('Too many possibilities for item "%s" (%d) in %s media database', title, cnt, type),
arg1 : title}, cb);
}
module.exports = {
dupe : dupe,
noparse : noparse,
notfound : notfound,
ambiguous : ambiguous
};
|
function __processArg(obj, key) {
var arg = null;
if (obj) {
arg = obj[key] || null;
delete obj[key];
}
return arg;
}
function Controller() {
function doOpen(e) {
var actionBar = e.source.activity.actionBar;
if (actionBar) {
actionBar.displayHomeAsUp = true;
actionBar.onHomeIconItemSelected = function() {
e.source.close();
};
e.source.activity.invalidateOptionsMenu();
}
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "contact";
if (arguments[0]) {
{
__processArg(arguments[0], "__parentSymbol");
}
{
__processArg(arguments[0], "$model");
}
{
__processArg(arguments[0], "__itemTemplate");
}
}
var $ = this;
var exports = {};
var __defers = {};
$.__views.contact = Ti.UI.createWindow({
backgroundColor: "#222",
id: "contact",
title: "Contact Us"
});
$.__views.contact && $.addTopLevelView($.__views.contact);
doOpen ? $.__views.contact.addEventListener("open", doOpen) : __defers["$.__views.contact!open!doOpen"] = true;
$.__views.__alloyId20 = Ti.UI.createLabel({
color: "#fff",
text: "Please feel free to contact us if you are interested or have any questions!",
top: "15",
left: "10",
right: "10",
id: "__alloyId20"
});
$.__views.contact.add($.__views.__alloyId20);
$.__views.lvContainer = Ti.UI.createView({
top: "65",
width: "280dp",
height: Ti.UI.SIZE,
layout: "vertical",
borderColor: "orange",
borderWidth: 0,
id: "lvContainer"
});
$.__views.contact.add($.__views.lvContainer);
$.__views.fname = Ti.UI.createTextField({
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_NONE,
autocorrect: false,
top: "6dp",
left: "4dp",
bottom: "2dp",
right: "4dp",
paddingLeft: "4dp",
backgroundColor: "#fff",
color: "#000",
width: "260dp",
height: "40dp",
border: 1,
borderColor: "#000",
id: "fname",
hintText: "First Name"
});
$.__views.lvContainer.add($.__views.fname);
$.__views.lname = Ti.UI.createTextField({
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_NONE,
autocorrect: false,
top: "6dp",
left: "4dp",
bottom: "2dp",
right: "4dp",
paddingLeft: "4dp",
backgroundColor: "#fff",
color: "#000",
width: "260dp",
height: "40dp",
border: 1,
borderColor: "#000",
id: "lname",
hintText: "Last Name"
});
$.__views.lvContainer.add($.__views.lname);
$.__views.email = Ti.UI.createTextField({
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_NONE,
autocorrect: false,
top: "6dp",
left: "4dp",
bottom: "2dp",
right: "4dp",
paddingLeft: "4dp",
backgroundColor: "#fff",
color: "#000",
width: "260dp",
height: "40dp",
border: 1,
borderColor: "#000",
id: "email",
hintText: "Email Address"
});
$.__views.lvContainer.add($.__views.email);
$.__views.phone = Ti.UI.createTextField({
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_NONE,
autocorrect: false,
top: "6dp",
left: "4dp",
bottom: "2dp",
right: "4dp",
paddingLeft: "4dp",
backgroundColor: "#fff",
color: "#000",
width: "260dp",
height: "40dp",
border: 1,
borderColor: "#000",
id: "phone",
hintText: "Phone Number"
});
$.__views.lvContainer.add($.__views.phone);
$.__views.submit = Ti.UI.createButton({
id: "submit",
title: "Submit",
color: "#fff",
bottom: "150"
});
$.__views.contact.add($.__views.submit);
exports.destroy = function() {};
_.extend($, $.__views);
arguments[0] || {};
Ti.UI.currentWindow;
Titanium.Network.createHTTPClient();
$.submit.addEventListener("click", function() {
var emailDialog = Titanium.UI.createEmailDialog();
emailDialog.setSubject("Please Sign Me Up!");
emailDialog.setToRecipients([ "wtcollegeofbusiness@gmail.com" ]);
emailDialog.setMessageBody("I'm curious about what the College of Business has to offer!\n\nFirst Name: " + $.fname.value + "\nLast Name: " + $.lname.value + "\nEmail: " + $.email.value + "\nPhone number: " + $.phone.value);
emailDialog.addEventListener("complete", function(e) {
e.result == emailDialog.SENT || alert("message was not sent. result = " + e.result);
});
emailDialog.open();
});
$.contact.open();
__defers["$.__views.contact!open!doOpen"] && $.__views.contact.addEventListener("open", doOpen);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;
|
// Name of the global object.
var globalName = 'WebFont';
// Provide an instance of WebFont in the global namespace.
var globalNamespaceObject = window[globalName] = (function() {
var userAgentParser = new webfont.UserAgentParser(navigator.userAgent, document);
var userAgent = userAgentParser.parse();
var domHelper = new webfont.DomHelper(document);
var asyncCall = function(func, timeout) { setTimeout(func, timeout); };
return new webfont.WebFont(domHelper, new webfont.FontModuleLoader(),
document.documentElement, asyncCall, userAgent);
})();
// Export the public API.
globalNamespaceObject['load'] = globalNamespaceObject.load;
globalNamespaceObject['addModule'] = globalNamespaceObject.addModule;
// Export the UserAgent API because we pass this object to external modules.
webfont.UserAgent.prototype['getName'] = webfont.UserAgent.prototype.getName;
webfont.UserAgent.prototype['getVersion'] = webfont.UserAgent.prototype.getVersion;
webfont.UserAgent.prototype['getEngine'] = webfont.UserAgent.prototype.getEngine;
webfont.UserAgent.prototype['getEngineVersion'] = webfont.UserAgent.prototype.getEngineVersion;
webfont.UserAgent.prototype['getPlatform'] = webfont.UserAgent.prototype.getPlatform;
webfont.UserAgent.prototype['getPlatformVersion'] = webfont.UserAgent.prototype.getPlatformVersion;
webfont.UserAgent.prototype['getDocumentMode'] = webfont.UserAgent.prototype.getDocumentMode;
webfont.UserAgent.prototype['isSupportingWebFont'] = webfont.UserAgent.prototype.isSupportingWebFont;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.