text
stringlengths 2
6.14k
|
|---|
export default {
standard: {
credits: { enabled: false },
chart: {
spacingBottom: 20,
style: {
fontFamily: "'proxima', 'Helvetica', sans-serif' ",
paddingTop: '20px' // Make room for buttons
}
},
exporting: {
buttons: {
contextButton: {
onclick: function () {
this.exportChart({type: 'jpeg'})
},
symbol: null,
text: 'Export',
x: -20,
y: -30,
theme: {
style: {
color: '#039',
textDecoration: 'underline'
}
}
}
}
},
title: ''
}
}
|
/*
* Copyright (c) 2014
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
(function() {
OC.Update = {
_started : false,
/**
* Start the upgrade process.
*
* @param $el progress list element
*/
start: function($el, options) {
if (this._started) {
return;
}
var hasWarnings = false;
this.$el = $el;
this._started = true;
this.addMessage(t(
'core',
'Updating {productName} to version {version}, this may take a while.', {
productName: options.productName || 'ownCloud',
version: options.version
}),
'bold'
).append('<br />'); // FIXME: these should be ul/li with CSS paddings!
var updateEventSource = new OC.EventSource(OC.webroot+'/core/ajax/update.php');
updateEventSource.listen('success', function(message) {
$('<span>').append(message).append('<br />').appendTo($el);
});
updateEventSource.listen('notice', function(message) {
$('<span>').addClass('error').append(message).append('<br />').appendTo($el);
hasWarnings = true;
});
updateEventSource.listen('error', function(message) {
$('<span>').addClass('error').append(message).append('<br />').appendTo($el);
message = t('core', 'Please reload the page.');
$('<span>').addClass('error').append(message).append('<br />').appendTo($el);
updateEventSource.close();
});
updateEventSource.listen('failure', function(message) {
$('<span>').addClass('error').append(message).append('<br />').appendTo($el);
$('<span>')
.addClass('bold')
.append(t('core', 'The update was unsuccessful. ' +
'Please report this issue to the ' +
'<a href="https://github.com/owncloud/core/issues" target="_blank">ownCloud community</a>.'))
.appendTo($el);
});
updateEventSource.listen('done', function() {
if (hasWarnings) {
$('<span>').addClass('bold')
.append('<br />')
.append(t('core', 'The update was successful. There were warnings.'))
.appendTo($el);
var message = t('core', 'Please reload the page.');
$('<span>').append('<br />').append(message).append('<br />').appendTo($el);
} else {
// FIXME: use product name
$('<span>').addClass('bold')
.append('<br />')
.append(t('core', 'The update was successful. Redirecting you to ownCloud now.'))
.appendTo($el);
setTimeout(function () {
OC.redirect(OC.webroot);
}, 3000);
}
});
},
addMessage: function(message, className) {
var $span = $('<span>');
$span.addClass(className).append(message).append('<br />').appendTo(this.$el);
return $span;
}
};
})();
$(document).ready(function() {
$('.updateButton').on('click', function() {
var $updateEl = $('.update');
var $progressEl = $('.updateProgress');
$progressEl.removeClass('hidden');
$('.updateOverview').addClass('hidden');
OC.Update.start($progressEl, {
productName: $updateEl.attr('data-productname'),
version: $updateEl.attr('data-version'),
});
return false;
});
});
|
var status = 0;
var minlvl = 100;
var maxlvl = 255;
var minplayers = 1;
var maxplayers = 6;
var time = 15;
var open = true;
function start() {
status = -1; // and when they click lets fight make it turn to a really cool ifght song :D LOL ok like the Zakum battle song? kk and btw uhm can you add a message like after they click OK to say "Matt: Meet me near the top of the map." ? o-o in other words, a
action(1, 0, 0);
}
function action(mode, type, selection) {
if (mode == -1) {
cm.dispose();
} else if (mode == 0) {
cm.sendOk("I spy a chicken :O"); // lLOL
cm.dispose();
} else {
if (mode == 1)
status++;
else
status--;
if (status == 0) {
cm.sendYesNo("Hello #b #h ##k! Would you like to fight #rSuper Horntail?#k He is waiting :)");
} else if (status == 1) {
if (cm.getPlayer().warning[1] == false && cm.isLeader()) {
cm.getPlayer().warning[1] = true;
cm.mapMessage("On behalf of MapleZtory, please defeat Big Puff Daddy! rawrawrawr");
var mf = cm.getPlayer().getMap().getMapFactory();
var bossmap = mf.getMap(240030103);
bossmap.removePortals();
var mob = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810018);
var mob1 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810002);
var mob2 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810003);
var mob3 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810004);
var mob4 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810005);
var mob5 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810006);
var mob6 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810007);
var mob7 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810008);
var mob8 = net.sf.odinms.server.life.MapleLifeFactory.getMonster(8810009);
var overrideStats = new net.sf.odinms.server.life.MapleMonsterStats();
overrideStats.setHp(2147000000);
overrideStats.setExp(2147000000);
overrideStats.setMp(mob.getMaxMp());
// mob.setOverrideStats(overrideStats);
mob1.setOverrideStats(overrideStats);
mob2.setOverrideStats(overrideStats);
mob3.setOverrideStats(overrideStats);
mob4.setOverrideStats(overrideStats);
mob5.setOverrideStats(overrideStats);
mob6.setOverrideStats(overrideStats);
mob7.setOverrideStats(overrideStats);
mob8.setOverrideStats(overrideStats);
mob.setHp(overrideStats.getHp());
//eim.registerMonster(mob);
bossmap.spawnMonsterOnGroudBelow(mob, new java.awt.Point(-182, -178));
bossmap.spawnMonsterOnGroudBelow(mob1, new java.awt.Point(-182, -178));
bossmap.spawnMonsterOnGroudBelow(mob2, new java.awt.Point(-182, -178));
bossmap.spawnMonsterOnGroudBelow(mob3, new java.awt.Point(-182, -178));
bossmap.spawnMonsterOnGroudBelow(mob4, new java.awt.Point(-182, -178));
bossmap.spawnMonsterOnGroudBelow(mob5, new java.awt.Point(-182, -178));
bossmap.spawnMonsterOnGroudBelow(mob6, new java.awt.Point(-182, -178));
bossmap.spawnMonsterOnGroudBelow(mob7, new java.awt.Point(-182, -178));
bossmap.spawnMonsterOnGroudBelow(mob8, new java.awt.Point(-182, -178));
// bossmap.killAllMonsters(false);
// bossmap.killMonster(8810018); // i like that funkshun :( // this one looks pro though :Dlol ur right XD
// spawnMonster(int mobid, int HP, int MP, int level, int EXP, int boss, int undead, int amount, int x, int y);
cm.dispose();
} else {
cm.sendOk("Super Horntail has already been spawned or you are not leader!");
cm.dispose();
}
}
}
}
|
/**
* @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'uploadwidget', 'ja', {
abort: 'アップロードを中止しました。',
doneOne: 'ファイルのアップロードに成功しました。',
doneMany: '%1個のファイルのアップロードに成功しました。',
uploadOne: 'ファイルのアップロード中 ({percentage}%)...',
uploadMany: '{max} 個中 {current} 個のファイルをアップロードしました。 ({percentage}%)...'
} );
|
'use strict';
const async = require('async');
const mongoose = require('mongoose');
const UserNotification = mongoose.model('Usernotification');
const DEFAULT_LIMIT = 50;
const DEFAULT_OFFSET = 0;
module.exports = {
countForUser,
create,
get,
getAll,
getForUser,
remove,
setAcknowledged,
setAllRead,
setRead
};
function countForUser(user, query, callback) {
const id = user._id || user;
const q = {target: id, acknowledged: false};
query = query || {};
if (query.read !== undefined) {
q.read = query.read;
}
return UserNotification.count(q).exec(callback);
}
function create(usernotification, callback) {
if (!usernotification) {
return callback(new Error('usernotification is required'));
}
new UserNotification(usernotification).save(callback);
}
function get(id, callback) {
if (!id) {
return callback(new Error('id is not defined'));
}
return UserNotification.findById(id).exec(callback);
}
function getAll(ids, callback) {
if (!ids) {
return callback(new Error('id is not defined'));
}
const formattedIds = ids.map(id => mongoose.Types.ObjectId(id));
const query = { _id: { $in: formattedIds } };
return UserNotification.find(query).exec(callback);
}
function getForUser(user, query, callback) {
const id = user._id || user;
const q = {target: id, acknowledged: false};
query = query || {};
if (query.read !== undefined) {
q.read = query.read;
}
const mq = UserNotification.find(q);
mq.limit(+query.limit || DEFAULT_LIMIT);
mq.skip(+query.offset || DEFAULT_OFFSET);
mq.sort('-timestamps.creation');
mq.exec(callback);
}
function remove(query, callback) {
UserNotification.remove(query, callback);
}
function setAcknowledged(usernotification, acknowledged, callback) {
if (!usernotification) {
return callback(new Error('usernotification is required'));
}
usernotification.acknowledged = acknowledged;
usernotification.save(callback);
}
function setAllRead(usernotifications, read, callback) {
if (!usernotifications) {
return callback(new Error('usernotification is required'));
}
async.each(usernotifications, setRead, callback);
function setRead(usernotification, cb) {
usernotification.read = read;
usernotification.save(cb);
}
}
function setRead(usernotification, read, callback) {
if (!usernotification) {
return callback(new Error('usernotification is required'));
}
usernotification.read = read;
usernotification.save(callback);
}
|
Meteor.publish('card-vocoder-vocoders',function(simulatorId){
return Flint.collection('vocoders').find({simulatorId:simulatorId});
});
|
import React from "react";
import basicComponent from "core/basicComponent";
import Radium from "radium";
import ReactAplayer from "react-aplayer";
import mergeAdvanced from "object-merge-advanced";
class audioPlayer extends basicComponent {
constructor(props) {
super(props);
if (!this.isRestored) {
this.state = { ...this.state, audios: [] };
}
this.myRef = React.createRef();
}
onInit = ap => {
this.ap = ap;
};
play = () => this.ap.play();
pause = () => this.ap.pause();
seek = timePos => this.ap.seek(timePos);
addAudio(audioProps) {
this.setState(prevState => {
const prevAudios = prevState.audios;
const nextAudios = prevAudios.concat([audioProps]);
const nextState = mergeAdvanced(prevState, { audios: nextAudios });
return nextState;
});
}
thisComponent = () => {
const state = this.getState();
const styles = this.getStyles();
return (
<ReactAplayer
ref={this.myRef}
theme="#F57F17"
lrcType={3}
audio={state.audios || []}
onInit={this.onInit}
style={styles}
{...this.getEvents()}
/>
);
};
}
export default Radium(audioPlayer);
|
describe('Service: can', function () {
var api
beforeEach(angular.mock.inject(function (can) {
api = can
}))
describe('.can()', function () {
it('returns true when the resource includes a method', function () {
var project = {
'_links': {
repositories: {
update: 'PUT'
}
}
}
expect(api.can('update-repositories', project)).toBeTruthy()
})
it('returns false when resource excludes method', function () {
var project = {
'_links': {
repositories: {}
}
}
expect(api.can('update-repositories', project)).toBeFalsy()
})
it('returns false otherwise', function () {
expect(api.can('update-repositories', {})).toBeFalsy()
})
})
})
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'link', 'cs', {
acccessKey: 'Přístupový klíč',
advanced: 'Rozšířené',
advisoryContentType: 'Pomocný typ obsahu',
advisoryTitle: 'Pomocný titulek',
anchor: {
toolbar: 'Záložka',
menu: 'Vlastnosti záložky',
title: 'Vlastnosti záložky',
name: 'Název záložky',
errorName: 'Zadejte prosím název záložky',
remove: 'Odstranit záložku'
},
anchorId: 'Podle Id objektu',
anchorName: 'Podle jména kotvy',
charset: 'Přiřazená znaková sada',
cssClasses: 'Třída stylu',
download: 'Force Download', // MISSING
displayText: 'Zobrazit text',
emailAddress: 'E-mailová adresa',
emailBody: 'Tělo zprávy',
emailSubject: 'Předmět zprávy',
id: 'Id',
info: 'Informace o odkazu',
langCode: 'Kód jazyka',
langDir: 'Směr jazyka',
langDirLTR: 'Zleva doprava (LTR)',
langDirRTL: 'Zprava doleva (RTL)',
menu: 'Změnit odkaz',
name: 'Jméno',
noAnchors: '(Ve stránce není definována žádná kotva!)',
noEmail: 'Zadejte prosím e-mailovou adresu',
noUrl: 'Zadejte prosím URL odkazu',
other: '<jiný>',
popupDependent: 'Závislost (Netscape)',
popupFeatures: 'Vlastnosti vyskakovacího okna',
popupFullScreen: 'Celá obrazovka (IE)',
popupLeft: 'Levý okraj',
popupLocationBar: 'Panel umístění',
popupMenuBar: 'Panel nabídky',
popupResizable: 'Umožňující měnit velikost',
popupScrollBars: 'Posuvníky',
popupStatusBar: 'Stavový řádek',
popupToolbar: 'Panel nástrojů',
popupTop: 'Horní okraj',
rel: 'Vztah',
selectAnchor: 'Vybrat kotvu',
styles: 'Styl',
tabIndex: 'Pořadí prvku',
target: 'Cíl',
targetFrame: '<rámec>',
targetFrameName: 'Název cílového rámu',
targetPopup: '<vyskakovací okno>',
targetPopupName: 'Název vyskakovacího okna',
title: 'Odkaz',
toAnchor: 'Kotva v této stránce',
toEmail: 'E-mail',
toUrl: 'URL',
toolbar: 'Odkaz',
type: 'Typ odkazu',
unlink: 'Odstranit odkaz',
upload: 'Odeslat'
} );
|
app.controller('LeadStatusEditCtrl', ['$scope', 'Auth', 'Leadstatus', function ($scope, Auth, Leadstatus) {
$("ul.page-sidebar-menu li").removeClass("active");
$("#id_LeadStatus").addClass("active");
$scope.isSignedIn = false;
$scope.immediateFailed = false;
$scope.nbLoads = 0;
$scope.isLoading = false;
$scope.isSelectedAll = false;
$scope.nbrSelected = 0;
$scope.selectStatus = function (status) {
status.isSelected = !status.isSelected;
if (status.isSelected) $scope.nbrSelected++;
else $scope.nbrSelected--;
};
$scope.$watch('isSelectedAll', function (newValue, oldValue) {
if (newValue) $scope.nbrSelected = $scope.leadstatuses.length;
else $scope.nbrSelected = 0;
angular.forEach($scope.leadstatuses, function (value, key) {
$scope.leadstatuses[key].isSelected = newValue;
});
});
$scope.deleteSelected = function () {
angular.forEach($scope.leadstatuses, function (value, index) {
if (value.isSelected) {
$scope.deletleadstatus(value);
}
});
};
$scope.inProcess = function (varBool, message) {
if (varBool) {
$scope.nbLoads += 1;
if ($scope.nbLoads == 1) {
$scope.isLoading = true;
}
;
} else {
$scope.nbLoads -= 1;
if ($scope.nbLoads == 0) {
$scope.isLoading = false;
}
;
}
;
};
$scope.apply = function () {
if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
$scope.$apply();
}
return false;
};
// What to do after authentication
$scope.runTheProcess = function () {
Leadstatus.list($scope, {});
ga('send', 'pageview', '/admin/lead_status');
};
// We need to call this to refresh token when user credentials are invalid
$scope.refreshToken = function () {
Auth.refreshToken();
};
$scope.addLeadsStatusModal = function () {
$("#addLeadsStatusModal").modal('show')
};
$scope.saveLeadStatus = function (lead) {
var params = {
'status': lead.status
};
Leadstatus.insert($scope, params);
$('#addLeadsStatusModal').modal('hide');
$scope.lead.status = '';
};
$scope.editleadstatus = function (leadStatus) {
$scope.leadstat = $scope.leadstat || {};
$scope.leadstat.status = leadStatus.status;
$scope.leadstat.id = leadStatus.id;
$('#EditLeadStatus').modal('show');
};
$scope.updateLeadstatus = function (stat) {
var params = {
'id': $scope.leadstat.id,
'status': stat.status
};
Leadstatus.update($scope, params)
$('#EditLeadStatus').modal('hide');
};
//HKA 22.12.2013 Delete Lead status
$scope.deletleadstatus = function (leadstat) {
var params = {'entityKey': leadstat.entityKey};
Leadstatus.delete($scope, params);
};
$scope.listleadstatus = function () {
Leadstatus.list($scope, {});
};
Auth.init($scope);
}]);
|
import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemDamageDone from 'parser/ui/ItemDamageDone';
import DemoPets from '../pets/DemoPets';
const BONUS_DAMAGE_PER_PET = 0.04;
const MAX_TRAVEL_TIME = 3000; // Shadow Bolt is the slowest, takes around 2 seconds to land from max distance, add a little more to account for target movement
const debug = false;
/*
Sacrificed Souls:
Shadow Bolt and Demonbolt deal 5% additional damage per demon you have summoned.
*/
class SacrificedSouls extends Analyzer {
get totalBonusDamage() {
return this._shadowBoltDamage + this._demonboltDamage;
}
static dependencies = {
demoPets: DemoPets,
};
_shadowBoltDamage = 0;
_demonboltDamage = 0;
_queue = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SACRIFICED_SOULS_TALENT.id);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleCast);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleDamage);
}
// essentially same snapshotting mechanic as in Destruction's Eradication
handleCast(event) {
const bonus = this.demoPets.getPetCount() * BONUS_DAMAGE_PER_PET;
this._queue.push({
timestamp: event.timestamp,
spellId: event.ability.guid,
targetID: event.targetID,
targetInstance: event.targetInstance,
bonus,
});
debug && this.log('Pushed a cast into queue', JSON.parse(JSON.stringify(this._queue)));
}
handleDamage(event) {
// filter out old casts if there are any
this._queue = this._queue.filter(cast => cast.timestamp > (event.timestamp - MAX_TRAVEL_TIME));
const castIndex = this._queue
.findIndex(cast => cast.targetID === event.targetID
&& cast.targetInstance === event.targetInstance
&& cast.spellId === event.ability.guid);
if (castIndex === -1) {
debug && this.error('Encountered damage event with no cast associated. Queue', JSON.parse(JSON.stringify(this._queue)), 'event', event);
return;
}
debug && this.log('Paired damage event', event, 'with queued cast', JSON.parse(JSON.stringify(this._queue[castIndex])));
const bonusDamage = calculateEffectiveDamage(event, this._queue[castIndex].bonus);
this._queue.splice(castIndex, 1);
if (event.ability.guid === SPELLS.SHADOW_BOLT_DEMO.id) {
this._shadowBoltDamage += bonusDamage;
} else {
this._demonboltDamage += bonusDamage;
}
}
statistic() {
const hasPS = this.selectedCombatant.hasTalent(SPELLS.POWER_SIPHON_TALENT.id);
return (
<Statistic
category={STATISTIC_CATEGORY.TALENTS}
size="flexible"
tooltip={(
<>
{formatThousands(this.totalBonusDamage)} bonus damage<br />
Bonus Shadow Bolt damage: {formatThousands(this._shadowBoltDamage)} ({this.owner.formatItemDamageDone(this._shadowBoltDamage)})<br />
Bonus Demonbolt damage: {formatThousands(this._demonboltDamage)} ({this.owner.formatItemDamageDone(this._demonboltDamage)})
{hasPS && (
<>
<br /><br />* Since you have Power Siphon talent, it's highly likely that it messes up getting current pets at certain time because sometimes
the number of Imps we sacrifice in code doesn't agree with what happens in logs. Therefore, this value is most likely a little wrong.
</>
)}
</>
)}
>
<BoringSpellValueText spell={SPELLS.SACRIFICED_SOULS_TALENT}>
<ItemDamageDone amount={this.totalBonusDamage} />
</BoringSpellValueText>
</Statistic>
);
}
}
export default SacrificedSouls;
|
import * as Actions from './actions'
import * as Controls from './controls'
import Editor from './editor'
import Panel from './panel'
export {Actions}
export {Editor}
export {Panel}
export {Controls}
|
/*
* Give a file path uuid, or full path, render a html for the file display.
*
* ../unit/u-rvp.js will be the test file.
*/
var fs = require('fs');
var path = require('path');
var handlebars = require('handlebars');
var folder_module = require("../aws/folder-v5.js");
var vpt = require("./video-player-tpl.js");
var tpl = require("../myutils/tpl.js");
var p = console.log;
// Constants
var Html_template = path.join(__dirname, "video.html");
/*
*
*/
function render_video_page_pu(path_uuid, callback){
folder_module.retrieve_file_meta_pu(path_uuid, function(err, meta){
var s3key = meta.storage.key;
var vid_src = path.join('/ss/', s3key);
console.log('console.log vid src: ', vid_src);
var video_html = vpt.render_video_element(meta);
var context = {
video_element : video_html,
};
tpl.render_template(Html_template, context, callback);
//callback(null, video_html);
});
}
var get_file = require("../aws/get-file.js");
/*
* Given video file full path, give an html render of the video player.
*/
function render_video_page(video_full_path, callback){
get_file.get_1st_file_obj_with_auxpath_by_path(video_full_path, function(err, file){
if(err) return callback(err);
var meta = file.get_meta();
render_video_meta_to_web_page(meta, callback);
});
}
function render_video_meta_to_web_page(meta, callback){
var video_html = vpt.render_video_element(meta);
var context = {
video_element : video_html,
};
tpl.render_template(Html_template, context, callback);
}
module.exports.render_video_meta_to_web_page = render_video_meta_to_web_page;
module.exports.render_video_page_pu = render_video_page_pu;
module.exports.render_video_page = render_video_page;
//todo
function render_html (context, callback) {
tpl.render_template(Html_template, context, callback);
//return fs.readFile(Html_template, 'utf-8', function(err, str){
// if(err) return callback(err);
// p(str.slice(0, 300));
// callback(null,null);
//});
};
// -- checkings -- //
function c_render_html(){
render_html({}, function(err, what){
p(err, what);
process.exit();
});
}
/*
* to give video element <video...> </video>
*/
function c_v_element(fpath){
fpath = fpath || {};
}
if(require.main === module){
//p(Html_template);
c_render_html();
}
|
/**
* EditorUpload.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* Handles image uploads, updates undo stack and patches over various internal functions.
*
* @private
* @class tinymce.EditorUpload
*/
define("tinymce/EditorUpload", [
"tinymce/util/Arr",
"tinymce/file/Uploader",
"tinymce/file/ImageScanner",
"tinymce/file/BlobCache"
], function(Arr, Uploader, ImageScanner, BlobCache) {
return function(editor) {
var blobCache = new BlobCache();
// Replaces strings without regexps to avoid FF regexp to big issue
function replaceString(content, search, replace) {
var index = 0;
do {
index = content.indexOf(search, index);
if (index !== -1) {
content = content.substring(0, index) + replace + content.substr(index + search.length);
index += replace.length - search.length + 1;
}
} while (index !== -1);
return content;
}
function replaceImageUrl(content, targetUrl, replacementUrl) {
content = replaceString(content, 'src="' + targetUrl + '"', 'src="' + replacementUrl + '"');
content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
return content;
}
function replaceUrlInUndoStack(targetUrl, replacementUrl) {
Arr.each(editor.undoManager.data, function(level) {
level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
});
}
function uploadImages(callback) {
var uploader = new Uploader({
url: editor.settings.images_upload_url,
basePath: editor.settings.images_upload_base_path,
credentials: editor.settings.images_upload_credentials,
handler: editor.settings.images_upload_handler
});
function imageInfosToBlobInfos(imageInfos) {
return Arr.map(imageInfos, function(imageInfo) {
return imageInfo.blobInfo;
});
}
return scanForImages().then(imageInfosToBlobInfos).then(uploader.upload).then(function(result) {
result = Arr.map(result, function(uploadInfo) {
var image;
image = editor.dom.select('img[src="' + uploadInfo.blobInfo.blobUri() + '"]')[0];
if (image) {
replaceUrlInUndoStack(image.src, uploadInfo.url);
editor.$(image).attr({
src: uploadInfo.url,
'data-mce-src': editor.convertURL(uploadInfo.url, 'src')
});
}
return {
element: image,
status: uploadInfo.status
};
});
if (callback) {
callback(result);
}
return result;
}, function() {
// Silent
// TODO: Maybe execute some failure callback here?
});
}
function scanForImages() {
return ImageScanner.findAll(editor.getBody(), blobCache).then(function(result) {
Arr.each(result, function(resultItem) {
replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
resultItem.image.src = resultItem.blobInfo.blobUri();
});
return result;
});
}
function destroy() {
blobCache.destroy();
}
function replaceBlobWithBase64(content) {
return content.replace(/src="(blob:[^"]+)"/g, function(match, blobUri) {
var blobInfo = blobCache.getByUri(blobUri);
if (!blobInfo) {
blobInfo = Arr.reduce(editor.editorManager.editors, function(result, editor) {
return result || editor.editorUpload.blobCache.getByUri(blobUri);
}, null);
}
if (blobInfo) {
return 'src="data:' + blobInfo.blob().type + ';base64,' + blobInfo.base64() + '"';
}
return match[0];
});
}
editor.on('setContent paste', scanForImages);
editor.on('RawSaveContent', function(e) {
e.content = replaceBlobWithBase64(e.content);
});
editor.on('getContent', function(e) {
if (e.source_view || e.format == 'raw') {
return;
}
e.content = replaceBlobWithBase64(e.content);
});
return {
blobCache: blobCache,
uploadImages: uploadImages,
scanForImages: scanForImages,
destroy: destroy
};
};
});
|
var searchData=
[
['fan2para',['Fan2Para',['../classrisa_1_1cuda_1_1_fan2_para.html',1,'risa::cuda']]],
['filter',['Filter',['../classrisa_1_1cuda_1_1_filter.html',1,'risa::cuda']]]
];
|
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
url = require('url'),
config = require('../../config'),
GitHubStrategy = require('passport-github').Strategy;
module.exports = function() {
// Use github strategy
passport.use(new GitHubStrategy({
clientID: config.github.clientID,
clientSecret: config.github.clientSecret,
callbackURL: config.github.callbackURL,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
req.session.gitToken = accessToken;
process.nextTick(function () {
return done(null, profile);
});
}
));
};
|
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import _ from 'underscore';
import Backbone from 'backbone';
export default Backbone.Model.extend({
defaults: function () {
return {
page: 1,
maxResultsReached: false,
query: {},
facets: []
};
},
nextPage: function () {
var page = this.get('page');
this.set({ page: page + 1 });
},
clearQuery: function (query) {
var q = {};
Object.keys(query).forEach(function (key) {
if (query[key]) {
q[key] = query[key];
}
});
return q;
},
_areQueriesEqual: function (a, b) {
var equal = Object.keys(a).length === Object.keys(b).length;
Object.keys(a).forEach(function (key) {
equal = equal && a[key] === b[key];
});
return equal;
},
updateFilter: function (obj, options) {
var oldQuery = this.get('query'),
query = _.extend({}, oldQuery, obj),
opts = _.defaults(options || {}, { force: false });
query = this.clearQuery(query);
if (opts.force || !this._areQueriesEqual(oldQuery, query)) {
this.setQuery(query);
}
},
setQuery: function (query) {
this.set({ query: query }, { silent: true });
this.set({ changed: true });
this.trigger('change:query');
}
});
|
angular.module('dnsControllers', ['dnsServices', 'dnsModels'])
.controller('dnsCtrl', function($scope, $location, socket, Hosts, Zone) {
$scope.dns = {
zone : Zone.get(),
hosts : Hosts.list()
};
socket.on('new:host', function (host) {
var found = false;
if ($scope.dns.hosts.records) {
for (var i = 0 ; i < $scope.dns.hosts.records.length ; ++i) {
if ($scope.dns.hosts.records[i].name === host.name) {
found = true;
$scope.dns.hosts.records[i].record = host.record;
break;
}
}
}
if (!found) {
if (!$scope.dns.hosts.records)
$scope.dns.hosts.records = [];
$scope.dns.hosts.records.push(host);
}
});
socket.on('delete:host', function (host) {
if ($scope.dns.hosts.records) {
for (var i = 0 ; i < $scope.dns.hosts.records.length ; ++i) {
if ($scope.dns.hosts.records[i].name === host.name) {
$scope.dns.hosts.records.splice(i, 1);
break;
}
}
}
});
})
;
|
const fs = require("fs");
const assert = require("assert");
const testMngr = require("test/testManager");
const FormData = require("form-data");
describe("Document No Auth", function () {
let client;
before(async function () {
if (!testMngr.app.config.document) {
this.skip();
}
client = testMngr.client("bob");
});
after(async () => {});
it("should get a 401 when getting all documents", async () => {
try {
let tickets = await client.get("v1/document");
assert(tickets);
} catch (error) {
console.log("error ", error);
assert.equal(error.response.status, 401);
assert.equal(error.response.data, "Unauthorized");
}
});
});
describe("Document", function () {
let client;
before(async function () {
if (!testMngr.app.config.document) {
this.skip();
}
client = testMngr.client("alice");
await client.login();
});
after(async () => {});
it("should upload a document", async () => {
const formData = new FormData();
formData.append("name", "IMG_20180316_153034.jpg");
formData.append("file_type", "image/jpeg");
formData.append(
"photo",
fs.createReadStream(__dirname + "/testDocument.js")
);
await client.upload("v1/document", formData);
const formData2 = new FormData();
formData2.append("name", "IMG_20180316_153035.jpg");
formData2.append("file_type", "image/jpeg");
formData2.append(
"photo",
fs.createReadStream(__dirname + "/testDocument.js")
);
await client.upload("v1/document", formData2);
//assert(document);
});
it("should upload a specific document", async () => {
const formData = new FormData();
formData.append("name", "IMG_20180316_153034.jpg");
formData.append("file_type", "image/jpeg");
formData.append(
"photo",
fs.createReadStream(__dirname + "/testDocument.js")
);
const type = "profile_picture";
await client.upload(`v1/document/${type}`, formData);
const picture = await client.get(`v1/document/${type}`);
assert.equal(picture.type, type);
assert(picture.content);
});
it("should return an error when no file is present", async () => {
const formData = new FormData();
formData.append("name", "IMG_20180316_153034.jpg");
formData.append("file_type", "image/jpeg");
try {
await client.upload("v1/document", formData);
assert(false);
} catch (error) {
assert.equal(error.response.status, 400);
}
});
});
|
import _ from 'lodash';
import React from 'react';
import Reflux from 'reflux';
import { Navigation } from 'react-router';
import recipeActions from 'actions/recipe';
import recipeStore from 'stores/recipe';
import SapCalculator from 'components/sapCalculator';
import FormSaveRecipe from 'components/formSaveRecipe';
import Imageable from 'components/imageable';
import ImageableEdit from 'components/imageableEdit';
export default React.createClass( {
statics: {
willTransitionTo: function ( transition, params ) {
recipeActions.getRecipeById( params.id );
}
},
mixins: [
Navigation,
Reflux.connect( recipeStore, 'recipe' )
],
render() {
document.title = 'Soapee - Edit';
return (
<div id="recipe-edit">
<SapCalculator
recipe={ this.state.recipe }
/>
{ _.get(this.state, 'recipe.recipe.images.length' ) > 0 &&
<div className="row">
<div className="col-md-12">
<legend>Delete Photos?</legend>
<ImageableEdit
images={ this.state.recipe.recipe.images }
/>
</div>
</div>
}
{ this.state.recipe.countWeights() > 0 &&
<div className="row">
<FormSaveRecipe
recipe={ this.state.recipe }
buttonCancel={ true }
buttonCaptionSave={ this.saveCaption() }
buttonDisabledSave={ this.state.saving }
onSave={ this.saveRecipe }
onSaveAs={ this.saveAsRecipe }
onCancel={ this.goBackToView }
/>
</div>
}
</div>
);
},
startImageUploadHookFn( fnToStartUploads ) {
this.startUploads = fnToStartUploads;
},
saveCaption() {
return this.state.saving ? 'Saving Recipe' : 'Save Recipe';
},
saveRecipe() {
return this.doSaveAction( recipeActions.updateRecipe );
},
saveAsRecipe() {
return this.doSaveAction( recipeActions.createRecipe );
},
doSaveAction( action ) {
this.setState( {
saving: true
} );
recipeStore.calculate();
return action( this.state.recipe )
.then( this.toRecipeView.bind( this ) )
.finally(() => this.setState({
saving: false
}));
function uploadImages() {
this.startUploads( this.state.recipe.getModelValue( 'id' ) );
}
},
printRecipe() {
this.replaceWith( 'printRecipe', { id: this.state.recipe.getModelValue( 'id' ) } );
},
goBackToView() {
this.toRecipeView( this.state.recipe.recipe );
},
toRecipeView(recipe) {
this.transitionTo( 'recipe', { id: recipe.id} );
}
} );
|
var AppGlobal = {
exposePrivateVariablesForTesting: true
};
var testableObject = function (exposePrivateVariablesForTesting) {
var _privateVar = "can't see this";
var _publicVar = "we see this fine";
function _privateFunction() {
console.log("Executed Private");
}
function _exposedFunction() {
console.log("Exposed Function");
}
var returnValue = {
ExposedFunction: _exposedFunction,
ExposedVariable: _publicVar
};
if (exposePrivateVariablesForTesting) {
$.extend(returnValue, {
PrivateVar: _privateVar,
PrivateFunction: _privateFunction
});
}
return returnValue;
}(AppGlobal.exposePrivateVariablesForTesting);
testableObject.ExposedFunction();
console.log(testableObject.ExposedVariable);
testableObject.PrivateFunction();
console.log(testableObject.PrivateVar);
|
import when from 'when';
import { post } from 'utils/http';
import baseUrl from 'utils/baseUrl';
export function requestPasswordReset( email ) {
return when(
post( baseUrl( 'auth/reset_password' ), {
params: {
email
}
} )
);
}
export function verifyResetPasswordToken( token, password) {
return when(
post( baseUrl( 'auth/verify_reset_password_token' ), {
params: {
token,
password
}
} )
);
}
|
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('gftApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
// place here mocked dependencies
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(MainCtrl.awesomeThings.length).toBe(3);
});
});
|
(function(synth, lang, langIndex) {
var voice = synth.getVoices().filter(voice => voice.lang === lang)[langIndex],
text = window.getSelection().toString();
function speak(text, voice) {
var utterance = new SpeechSynthesisUtterance(text);
utterance.voice = voice;
utterance.lang = lang;
utterance.rate = .4;
synth.speak(utterance);
}
speak(text, voice);
})(window.speechSynthesis, 'pt-PT', 0);
|
(function (parent, $, element) {
function loadEvents() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
return [
{
title: 'Appointment 1',
start: new Date(y, m, d, 10),
end: new Date(y, m, d, 11),
allDay: false,
editable: true,
startEditable: true,
durationEditable: true,
plantpot: 'coffeetable'
},
{
title: 'Appointment 2',
start: new Date(y, m, d, 11, 30),
end: new Date(y, m, d, 12),
allDay: false
}
];
}
function onEventClick(event) {
alert(event.plantpot);
alert($(element).fullCalendar('clientEvents').length);
}
function render() {
$(document).ready(function() {
$(element).fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: loadEvents(),
eventClick: onEventClick
});
});
}
parent.schedule = {
load: render
};
})(window, $, '#calendar');
window.schedule.load();
|
#!/usr/bin/env node
/**
* Copyright IBM Corp. 2019, 2019
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable no-console */
'use strict';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', (error) => {
console.error(error);
});
var chalk = require('chalk');
var currentNodeVersion = process.versions.node;
var semver = currentNodeVersion.split('.');
var major = semver[0];
if (major < 14) {
console.error(
chalk.red(
`You are running Node ${currentNodeVersion}.\n` +
`carbon-upgrade requires Node 14 or higher, please update your ` +
`version of Node.`
)
);
process.exit(1);
}
var main = require('../src/cli');
main(process).catch((error) => {
console.error(error);
process.exit(1);
});
|
var gulp = require('gulp');
var g = require('gulp-load-plugins')({lazy: false});
var config = require('../config');
gulp.task('webpack', function () {
g.webpack(config.webpack)
.pipe(gulp.dest(config.js.dest));
});
gulp.task('webpack-dev', function () {
g.webpack(config.webpackDev)
.pipe(gulp.dest(config.js.dest));
});
|
(function(){
id = Ti.App.Properties.getString("tisink", "");
var param, xhr;
file = Ti.Filesystem.getFile("examples/label.js");
xhr = Ti.Network.createHTTPClient();
xhr.open("POST", "http://tisink.nodester.com/");
xhr.setRequestHeader("content-type", "application/json");
param = {
data: "" + file.read(),
file: "label.js",
id: id
};
xhr.send(JSON.stringify(param));
})();
//TISINK----------------
// create label view data object
var data = [
{title:'Basic', hasChild:true, test:'../examples/label_basic.js'}
];
// add android specific tests
if (Ti.Platform.name == 'android')
{
data.push({title:'Auto Link', hasChild:true, test:'../examples/label_linkify.js'});
}
// create table view
var tableview = Ti.UI.createTableView({
data:data
});
// create table view event listener
tableview.addEventListener('click', function(e)
{
if (e.rowData.test)
{
var win = Ti.UI.createWindow({
url:e.rowData.test,
title:e.rowData.title
});
Ti.UI.currentTab.open(win,{animated:true});
}
});
// add table view to the window
Ti.UI.currentWindow.add(tableview);
|
//
"use strict";
var AppDispatcher = require('../dispatcher/AppDispatcher');
var StationEquipmentAlarmConstants = require('../constants/StationEquipmentAlarmConstants');
var StationEquipmentAlarmsWebApiUtils = require('../webapiutils/StationEquipmentAlarmsWebApiUtils')
var Station = require('../domain/Station');
var StationEquipmentAlarmActionCreators = {
loadDefectData: function(station){
console.assert(station instanceof Station);
AppDispatcher.dispatch({
action: StationEquipmentAlarmConstants.ActionTypes.GET_EQUIPMENT_ALARMS,
payload: station
});
StationEquipmentAlarmsWebApiUtils.getEquipmentAlarms(station);
}
};
module.exports = StationEquipmentAlarmActionCreators;
|
var expect = require('chai').expect
describe('Pane', function () {
describe('# Show pane', function () {
it('should show a lateral pane when requested (click on data feature)', function () {
const pane = require('../src/pane')
expect(pane.show).to.be.a('function')
pane.show()
expect(document.getElementById('pane')).not.to.be.null
})
})
describe('# Close pane', function () {
it('should empty lateral pane when requested (click on map or click on close button)', function () {
const pane = require('../src/pane')
expect(pane.close).to.be.a('function')
pane.close()
expect(document.getElementById('pane').hasChildNodes()).to.be.false
})
})
describe('# Show feature in pane', function () {
const pane = require('../src/pane')
const parcelFeature = require('./fixtures').getGoogleMapsParcelFeature()
it('should have a hero header section with an image button', function () {
pane.show(parcelFeature)
var sectionsHeroHeader = document.getElementById('pane').getElementsByClassName('section-hero-header')
expect(sectionsHeroHeader).to.not.be.null
expect(sectionsHeroHeader.length).to.be.equal(1, '1 and only 1 section hero header')
var sectionHeroHeader = sectionsHeroHeader[0]
expect(sectionHeroHeader.getElementsByTagName('button')).to.not.be.null
expect(sectionHeroHeader.getElementsByTagName('button').length).to.be.least(1, 'Almost a button in section-hero-header')
var imageButton = sectionHeroHeader.getElementsByTagName('button')[0]
expect(imageButton.getElementsByTagName('img')).to.not.be.null
expect(imageButton.getElementsByTagName('img').length).to.be.least(1, 'Almost an image in the button of section-hero-header')
})
it('and with a description in the hero header section', function () {
pane.show(parcelFeature)
var sectionHeroHeader = document.getElementById('pane').getElementsByClassName('section-hero-header')[0]
expect(sectionHeroHeader.getElementsByClassName('section-hero-header-description')).to.not.be.null
expect(sectionHeroHeader.getElementsByClassName('section-hero-header-description').length).to.be.least(1, 'Almost a description in section-hero-header')
var description = sectionHeroHeader.getElementsByClassName('section-hero-header-description')[0]
expect(description.getElementsByClassName('section-hero-header-title')).to.not.be.null
expect(description.getElementsByClassName('section-hero-header-title').length).to.be.least(1, 'Almost a title in section-hero-header')
expect(description.getElementsByTagName('h1').length).to.be.least(1, 'Almost a title in section-hero-header')
expect(description.getElementsByTagName('h1')[0].textContent).to.be.equal(parcelFeature.properties.nationalCadastralReference, 'Title with the national cadastral reference of the selected parcel')
expect(description.getElementsByClassName('section-hero-header-container')).to.not.be.null
expect(description.getElementsByClassName('section-hero-header-description-container').length).to.be.least(1, 'Almost a description container in section-hero-header')
})
it('should have an action section', function () {
pane.show(parcelFeature)
var sectionsAction = document.getElementById('pane').getElementsByClassName('section-action')
expect(sectionsAction).to.not.be.null
expect(sectionsAction.length).to.be.equal(1, '1 and only 1 action section')
var sectionAction = sectionsAction[0]
var buttons = sectionAction.getElementsByTagName('button')
expect(buttons).to.not.be.null
expect(buttons.length).to.be.equal(4, 'Four action buttons in the action section')
})
})
})
|
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
export default {
'People Finder': 'Localizador de Pessoas',
'Groups Finder': 'Localizador de Grupos',
'Locations Finder': 'Localizador de Locais',
'People': 'Pessoas',
'Groups': 'Grupos',
'Locations': 'Locais',
'Organization': 'Organização',
'Details': 'Detalhes',
'Owners': 'Proprietários',
'Search': 'Buscar',
'No matching people': 'Nenhuma pessoa encontrada',
'No matching groups': 'Nenhum grupo encontrado',
'No matching locations': 'Nenhuma localização encontrada',
'People matching': 'Pessoas correspondentes {search}',
'Groups matching': 'Grupos correspondentes {search}',
'Locations matching': 'Locais correspondentes {search}',
'Refine search to find more': 'Refinar a pesquisa para encontrar mais.',
};
|
module.exports = LocalTransport;
function LocalTransport(incoming, options) {
options = options || {};
this.name = "local";
this.outgoing = function(destination, message, sender, callback) {
setImmediate(incoming(destination, message, callback)); //to make function async, just like other transports?
//incoming(destination, message, callback)
}
}
|
export const GET = 'GET';
export const PUT = 'PUT';
export const POST = 'POST';
export const DELETE = 'DELETE';
|
/*
------
IOS
------
*/
if(OS_IOS){
// NappSlideMenu
var NappSlideMenu = require('dk.napp.slidemenu');
var drawerIphone = NappSlideMenu.createSlideMenuWindow({
centerWindow: $.navWindow,
leftWindow: Alloy.createController('menu').getView(),
leftLedge: 50
});
// Configure navigation and init app
Alloy.Globals.nav.setIphoneDrawer(drawerIphone);
Alloy.Globals.nav.setParentWindow($.firstWindow);
Alloy.Globals.nav.openCenter('Feed', 'feed', false);
Alloy.Globals.nav.init();
function openMenu(){
drawerIphone.toggleLeftView();
}
}
/*
------
ANDROID
------
*/
else if(OS_ANDROID){
// Ti.DrawerLayout
var TiDrawerLayout = require('com.tripvi.drawerlayout');
var drawer = TiDrawerLayout.createDrawer({
leftView: Alloy.createController('menu').getView(),
leftDrawerWidth: "280dp",
width: Ti.UI.FILL,
height: Ti.UI.FILL
});
// Configure navigation and init app
Alloy.Globals.nav.setAppName('My App Name');
Alloy.Globals.nav.setAndroidDrawer(drawer);
Alloy.Globals.nav.setParentWindow($.index);
Alloy.Globals.nav.openCenter('Feed', 'feed', false);
Alloy.Globals.nav.init();
}
|
module.exports = function (process, manifest, actionCallback) {
var program = require('commander');
program
.version(manifest.version)
.option('-v, --verbose', 'Enable verbose output')
.command('*')
.action(function (args) {
actionCallback(process, args);
});
program.parse(process.argv);
};
|
define(['socket.io'], function() {
var socket = io.connect('//' + window.document.location.host);
return socket;
})
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* Lévy distribution median.
*
* @module @stdlib/stats/base/dists/levy/median
*
* @example
* var median = require( '@stdlib/stats/base/dists/levy/median' );
*
* var y = median( 0.0, 1.0 );
* // returns ~2.198
*
* y = median( 4.0, 2.0 );
* // returns ~8.396
*/
// MODULES //
var median = require( './median.js' );
// EXPORTS //
module.exports = median;
|
/**
* This looks at static needs parameter in components and waits for the promise to be fullfilled
* It is used to make sure server side rendered pages wait for APIs to resolve before
* returning res.end()
*
* As seen in: https://github.com/caljrimmer/isomorphic-redux-app
*/
export function fetchComponentDataBeforeRender(dispatch, components, params) {
const needs = components.reduce((prev, current) => {
if (!current) {
return prev;
}
return (current.need || [])
.concat((current.WrappedComponent ? current.WrappedComponent.need : []) || [])
.concat(prev);
}, []);
const promises = needs.map(need => dispatch(need(params)));
return Promise.all(promises);
}
|
//Funcion para insertar un trozo de codigo HTML
function loadXMLDoc(url)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("principal").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
define("joynr/messaging/inprocess/InProcessMessagingSkeleton", [], function() {
/**
* @name InProcessMessagingSkeleton
* @constructor
*/
function InProcessMessagingSkeleton() {
var onReceive;
/**
* @name InProcessMessagingSkeleton#receiveMessage
* @function
*
* @param {JoynrMessage} joynrMessage
* @returns {Object} A+ promise object
*/
this.receiveMessage = function receiveMessage(joynrMessage) {
return onReceive(joynrMessage);
};
/**
* A setter for the callback function that will receive the incoming messages
*
* @name InProcessMessagingSkeleton#registerListener
* @function
*
* @param {Function} newOnReceive the function that is called with the incoming JoynrMessage
*/
this.registerListener = function registerListener(newOnReceive) {
onReceive = newOnReceive;
};
}
return InProcessMessagingSkeleton;
});
|
var http=require('http');
var url = require('url')
var httpget = function ( url ) {
return new Promise(( resolve,reject)=>{
http.get( url ,function(req,res){
var html='';
req.on('data',function(data){
html+=data;
});
req.on('end',function(){
resolve(html);
});
req.on('error',function(err){
reject(err);
});
});
})
}
var httppostsimple = function (posturl,port,postData,username,passwd) {
var postDatastr=JSON.stringify(postData);
var urlObj = url.parse(posturl)
var p = username + ":" + passwd;
var b = new Buffer( p );
var cred = b.toString('base64');
var options={
hostname:urlObj.hostname,
port:port,
path: urlObj.pathname,
method:'POST',
headers:{
'Content-Type':'text/plain',
'Content-Length':Buffer.byteLength(postDatastr),
'Authorization': `Basic ${cred}`
}
}
return httppost(options,postDatastr);
}
var httppost = function (options,postData) {
/* var options={
hostname:'www.gongjuji.net',
port:80,
path:'/',
method:'POST',
headers:{
//'Content-Type':'application/x-www-form-urlencoded',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length':Buffer.byteLength(postData)
}
}*/
return new Promise(( resolve,reject)=>{
var buffers = [];
var req=http.request(options, function(res) {
res.on('data',function(reposebuffer){
buffers.push(reposebuffer);
});
res.on('end',function(){
//console.log('No more data in response.********');
var wholeData = Buffer.concat(buffers);
var dataStr = wholeData.toString('utf8');
resolve(dataStr)
});
res.on('error',function(err){
reject(err);
});
});
req.write(postData);
req.end();
})
}
exports.httpget = httpget;
exports.httppost =httppost;
exports.httppostsimple = httppostsimple;
|
import {rnaPlot} from './rnaplot.js';
export function rnaTreemapChart() {
var width = 550;
var height = 400;
function rnaTreemapNode(selection) {
// create a background rectangle for each RNA structure
selection.each(function(d) {
d3.select(this)
.attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')' })
.append('rect')
.classed('structure-background-rect', true)
.attr('width', function(d) { return Math.max(0, d.dx); })
.attr('height', function(d) { return Math.max(0, d.dy); })
// draw the actual RNA structure
var chart = rnaPlot()
.width( Math.max(0, d.dx))
.height( Math.max(0, d.dy))
.labelInterval(0)
.rnaEdgePadding(10)
.showNucleotideLabels(false);
if ('structure' in d) d3.select(this).call(chart)
});
}
var chart = function(selection) {
selection.each(function(data) {
console.log('data:', data)
// initialize the treemap structure
// sample input
// { 'name': 'blah',
// 'children: [{'structure': '..((..))',
// 'sequence': 'ACCGGCC',
// 'size': 50}]
// }
var treemap = d3.layout.treemap()
.size([width, height])
.sticky(false)
.value(function(d) { return d.size; });
// create a new <g> for each node in the treemap
// this may be a little redundant, since we expect the calling
// selection to contain their own g elements
var gEnter = d3.select(this).append('g');
var treemapGnodes = gEnter.datum(data).selectAll('.treemapNode')
.data(treemap.nodes)
.enter()
.append('g')
.attr('class', 'treemapNode')
.call(rnaTreemapNode);
});
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
}
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
}
return chart;
}
function rnaTreemapGridChart() {
var chart = function(selection) {
console.log('selection:', selection);
selection.each(function(data) {
console.log('data:', data);
});
}
return chart;
}
|
'use strict';
/**
* Configuration options for Ember CLI App used to manage broccoli build tree for DataHub web.
* Returns a method to import build dependencies and an options
* object with configuration attributes
*
* @param {string} env current build application environment
* @returns { options: object }
*/
module.exports = function(env) {
const isTesting = env === 'test';
const isProduction = env === 'production';
return {
options: {
// Configuration options for ember-auto-import library
autoImport: {
// Note: restliparams has an outDir of lib, but autoImport looks for dist
alias: {
restliparams: 'restliparams/lib'
},
webpack: {
node: {
// this will add support for 'require('path')' in browsers
// this is needed by minimatch dependency
path: true
}
},
exclude: ['@glimmer/tracking']
},
// Configurations options for ember-ace editor library
ace: isTesting
? {}
: {
modes: ['json', 'graphqlschema', 'text'],
workers: ['json', 'graphqlschema', 'text'],
exts: ['searchbox']
},
babel: {
sourceMaps: env === 'development' ? 'inline' : false,
targets: {
browsers: ['last 3 versions']
}
},
'ember-cli-babel': {
includePolyfill: !isTesting
},
storeConfigInMeta: false,
SRI: {
enabled: false
},
fingerprint: {
enabled: isProduction
},
'ember-cli-uglify': {
enabled: isProduction,
// Improve build times by using the Fast Minify Mode
// For our internal use case, app load times are not a significant bottleneck currently
// https://github.com/mishoo/UglifyJS2#uglify-fast-minify-mode
uglify: {
compress: false,
mangle: true
}
},
outputPaths: {
app: {
html: 'index.html',
css: {
app: '/assets/datahub-web.css'
},
js: '/assets/datahub-web.js'
},
vendor: {
css: '/assets/vendor.css',
js: '/assets/vendor.js'
}
},
svgJar: {
sourceDirs: ['public/assets/images/svgs']
},
// Configuration options specifying inclusion of Mirage addon files in the application tree
'mirage-from-addon': {
includeAll: true,
exclude: [/scenarios\/default/, /config/]
}
}
};
};
|
var Canvas = require('canvas');
function generateCode() {
return ('' + Math.random()).substr(3, 6);
}
function generateImage(req, res, params) {
params.color = params.color || 'rgb(0, 0, 0)';
params.background = params.background || 'rgb(255, 255, 255)';
params.width = params.width || 250;
params.height = params.height || 150;
params.innerWidth = params.width * 0.6;
params.fontHeight = params.height * 0.6;
params.offset = params.width * 0.08;
params.fontWidth = Math.ceil(params.fontHeight / 2);
var offset = params.width * 0.4 * Math.random();
var canvas = new Canvas(params.width, params.height);
var ctx = canvas.getContext('2d');
ctx.antialias = 'gray';
ctx.fillStyle = params.background;
ctx.fillRect(0, 0, params.width, params.height);
ctx.fillStyle = params.color;
ctx.lineWidth = params.fontHeight / 10;
ctx.strokeStyle = params.color;
ctx.font = params.fontHeight + 'px sans';
for (var i = 0; i < 2; i++) {
ctx.moveTo(offset, Math.random() * params.innerWidth);
ctx.bezierCurveTo(
params.width * 0.32,
Math.random() * params.height,
params.width * 0.64,
Math.random() * params.height,
params.width * 0.92,
Math.random() * params.height);
ctx.stroke();
}
var text = params.text || generateCode();
for (i = 0; i < text.length; i++) {
ctx.setTransform(Math.random() * 0.5 + 1, Math.random() * 0.4, Math.random() * 0.4, Math.random() * 0.5 + 1, params.fontWidth * i + offset, params.height * 2 / 3);
ctx.fillText(text.charAt(i), 0, 0);
}
canvas.toBuffer(function(err, buf) {
if(req.session)
req.session.captcha = text;
res.end(buf);
});
}
module.exports = function(params){
if (params.hasOwnProperty('text'))
delete params.text;
return function(req, res, next){
generateImage(req, res, params);
};
};
module.exports.generateImage = generateImage;
module.exports.generateCode = generateCode;
|
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var path = require('path'),
fs = require('fs'),
url = require('url'),
shell = require('shelljs');
// Map of project_root -> JSON
var configCache = {};
var autoPersist = true;
/**
* 将opts中的属性值以json格式添加到<proj_root>/.xface/config.json中
* config.json包含的属性主要有id, name, lib, dev_type。id和name分别为工程的id和名称,
* dev_type用于标识是内部项目开发还是外部开发者使用('internal'表示内部项目开发,不存在或者为空时为外部使用)
* @param {String} project_root
* @param {Object} opts
*/
function config(project_root, opts) {
var json = config.read(project_root);
for (var p in opts) {
json[p] = opts[p];
}
if (autoPersist) {
config.write(project_root, json);
} else {
configCache[project_root] = JSON.stringify(json);
}
return json;
};
config.setAutoPersist = function(value) {
autoPersist = value;
};
config.read = function get_config(project_root) {
var data = configCache[project_root];
if (data === undefined) {
var configPath = path.join(project_root, '.xface', 'config.json');
if (!fs.existsSync(configPath)) {
data = '{}';
} else {
data = fs.readFileSync(configPath, 'utf-8');
}
}
configCache[project_root] = data;
return JSON.parse(data);
};
config.write = function set_config(project_root, json) {
var configPath = path.join(project_root, '.xface', 'config.json');
var contents = JSON.stringify(json, null, 4);
configCache[project_root] = contents;
// Don't write the file for an empty config.
if (contents != '{}' || !fs.existsSync(configPath)) {
shell.mkdir('-p', path.join(project_root, '.xface'));
fs.writeFileSync(configPath, contents, 'utf-8');
}
return json;
};
config.has_custom_path = function(project_root, platform) {
var json = config.read(project_root);
if (json.lib && json.lib[platform]) {
var uri = url.parse(json.lib[platform].uri);
if (!(uri.protocol)) return uri.path;
else if (uri.protocol && uri.protocol[1] ==':') return uri.href;
}
return false;
};
/**
* 判断指定工程是否为内部开发使用的工程
* @param {String} project_root 工程根路径
*/
config.internalDev = function(project_root) {
var json = config.read(project_root);
return json.dev_type === 'internal';
};
module.exports = config;
|
/*
* ../../../..//localization/fr/HelpDialog.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*************************************************************
*
* MathJax/localization/fr/HelpDialog.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("fr", "HelpDialog", {
version: "2.7.5",
isLoaded: true,
strings: {
Help: "Aide MathJax",
MathJax:
"*MathJax* est une biblioth\u00E8que JavaScript qui permet aux auteurs de pages d\u2019inclure des math\u00E9matiques dans leurs pages web. En tant que lecteur, vous n\u2019avez rien besoin de faire pour que cela fonctionne.",
Browsers:
"*Navigateurs*: MathJax fonctionne avec tous les navigateurs modernes y compris Internet Explorer 6, Firefox 3, Chrome 0.2, Safari 2, Opera 9.6 et leurs versions sup\u00E9rieures ainsi que la plupart des navigateurs pour mobiles et tablettes.",
Menu:
"*Menu math*: MathJax ajoute un menu contextuel aux \u00E9quations. Cliquez-droit ou Ctrl-cliquez sur n\u2019importe quelle formule math\u00E9matique pour acc\u00E9der au menu.",
ShowMath:
"*Afficher les maths comme* vous permet d\u2019afficher le balisage source de la formule pour copier-coller (comme MathML ou dans son format d\u2019origine).",
Settings:
"*Param\u00E8tres* vous donne le contr\u00F4le sur les fonctionnalit\u00E9s de MathJax, comme la taille des math\u00E9matiques, et le m\u00E9canisme utilis\u00E9 pour afficher les \u00E9quations.",
Language:
"*Langue* vous laisse s\u00E9lectionner la langue utilis\u00E9e par MathJax pour ses menus et ses messages d\u2019avertissement.",
Zoom:
"*Zoom des maths*: Si vous avez des difficult\u00E9s \u00E0 lire une \u00E9quation, MathJax peut l\u2019agrandir pour vous aider \u00E0 mieux la voir.",
Accessibilty:
"*Accessibilit\u00E9*: MathJax travaillera automatiquement avec les lecteurs d\u2019\u00E9cran pour rendre les math\u00E9matiques accessibles aux malvoyants.",
Fonts:
"*Polices*: MathJax utilisera certaines polices math\u00E9matiques si elles sont install\u00E9es sur votre ordinateur\u202F; sinon, il utilisera les polices trouv\u00E9es sur le web. Bien que ce ne soit pas obligatoire, des polices install\u00E9es localement acc\u00E9l\u00E9reront la composition. Nous vous sugg\u00E9rons d\u2019installer les [polices STIX](%1).",
CloseDialog: "Fermer la bo\u00EEte de dialogue d\u2019aide"
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/fr/HelpDialog.js");
|
function Vec2(_x, _y) {
var self = this;
self.x = _x;
self.y = _y;
self.Distance = function (OtherPoint) {
try {
return Math.sqrt(Math.pow(OtherPoint.x - self.x, 2) + Math.pow(OtherPoint.y - self.y, 2));
} catch (e) {
console.error(e);
return false;
}
}
}
function getMCC(c, e) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
} else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
x -= c.offsetLeft + c.clientLeft;
y -= c.offsetTop + c.clientTop;
return new Vec2(x, y);
}
|
MotorTemperatures = new Mongo.Collection('MotorTemperatures');
// fields : value, timestamp
MotorTemperatures.allow({
insert: function(userid, temp){return true;} //for now
});
Meteor.methods({
motorTemperatureInsert: function(temp) {
check(temp,Match.Integer);
var tempObject = {
value: temp,
timestamp: Date.now()
};
MotorTemperatures.insert(tempObject);
}
});
if(Meteor.isClient){
Session.set("actualMotorTemp",MotorTemperatures.find({}, {sort: {timestamp: -1}, limit:1}).fetch()[0]);
motorTemps = [];
Session.set("motorTemps", motorTemps);
MotorTemperatures.find().observe({
added: function(temp){
Session.set("actualMotorTemp",temp);
var localMotorTemps = Session.get("motorTemps");
localMotorTemps.push({x:temp.timestamp, y:temp.value});
if(localMotorTemps.length > 50){
localMotorTemps.shift();
}
Session.set("motorTemps", localMotorTemps);
}
});
}
|
/*!
* Start Bootstrap - Agency Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top'
})
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
$('.timeline-image').css('background-color', '#fed136').each(function(){
var element = $(this);
if(element.offset().top > y_scroll_pos + $(window).height()/3 && element.offset().top < y_scroll_pos + 2* $(window).height()/3){
element.css('background-color', '#9a0000');
}
});
});
|
// 热门推荐
module.exports = function recommend() {
var t = t || {
};
t = {
init: function () {
this.tap()
},
tap: function () {
$('.hot-lesson ul li').tooltip('tag', {
type: 'mouseover',
selected: 'on',
contentClass: '#hot-lessonbox .one-classfiy-lesson'
})
}
},
t.init();
}();
|
/* eslint-disable */
// not run locally - here for reference
function pageFunction(context) {
// called on every page the crawler visits, use it to extract data from it
var $ = context.jQuery;
var result = {
constituency: $('#commons-constituency').text(),
fullName: $('#commons-biography-header h1').text(),
party: $('#commons-party').text(),
email: $('#ctl00_ctl00_FormContent_SiteSpecificPlaceholder_PageContent_addParliamentaryAddress_rptAddresses_ctl00_hypEmailAddress').text(),
parlTel: $('#ctl00_ctl00_FormContent_SiteSpecificPlaceholder_PageContent_addParliamentaryAddress_rptAddresses_ctl00_pnlTelephone').text(),
conAddress: $('#ctl00_ctl00_FormContent_SiteSpecificPlaceholder_PageContent_addConstituencyAddress_rptAddresses_ctl00_pnlAddress').text(),
conTel: $('#ctl00_ctl00_FormContent_SiteSpecificPlaceholder_PageContent_addConstituencyAddress_rptAddresses_ctl00_pnlTelephone').text().slice(5)
};
$('.social-media li').each(function() {
const type = $(this).find('span').text().slice(0,-1).toLowerCase();
console.log(type);
const link = $(this).find('a').attr('href');
console.log(link);
result[type] = link;
});
return result;
}
|
// Sanity test for removing documents with adjacent index keys. SERVER-2008
t = db.jstests_removec;
t.drop();
t.ensureIndex({a: 1});
/** @return an array containing a sequence of numbers from i to i + 10. */
function runStartingWith(i) {
ret = [];
for (j = 0; j < 11; ++j) {
ret.push(i + j);
}
return ret;
}
// Insert some documents with adjacent index keys.
for (i = 0; i < 1100; i += 11) {
t.save({a: runStartingWith(i)});
}
// Remove and then reinsert random documents in the background.
s = startParallelShell('t = db.jstests_removec;' +
'Random.setRandomSeed();' +
'for( j = 0; j < 1000; ++j ) {' +
' o = t.findOne( { a:Random.randInt( 1100 ) } );' +
' t.remove( { _id:o._id } );' +
' t.insert( o );' +
'}');
// Find operations are error free. Note that the cursor throws if it detects the $err
// field in the returned document.
for (i = 0; i < 200; ++i) {
t.find({a: {$gte: 0}}).hint({a: 1}).itcount();
}
s();
t.drop();
|
"use strict";
var cases = module.exports = [];
cases[0] = {};
cases[0].resources = [{
"resource": {
"id": "Condition/c-0-0",
"resourceType": "Condition",
"status": "confirmed",
"onsetDateTime": "2012-08-05",
"dateAsserted": "2012-08-05",
"abatementBoolean": true,
"code": {
"coding": [{
"code": "233604007",
"system": "http://snomed.info/sct",
"display": "Pneumonia"
}]
}
}
}];
cases[0].input = cases[0].resources[0];
cases[0].result = {
"problem": {
"code": {
"name": "Pneumonia",
"code": "233604007",
"code_system_name": "SNOMED CT"
},
"date_time": {
"low": {
"date": "2012-08-05T00:00:00.000Z",
"precision": "day"
}
}
},
"status": {
"name": "Resolved"
}
};
cases[1] = {};
cases[1].resources = [{
"resource": {
"id": "Condition/c-1-0",
"resourceType": "Condition",
"status": "confirmed",
"onsetDateTime": "2007-01-03",
"dateAsserted": "2007-01-03",
"code": {
"coding": [{
"code": "195967001",
"system": "http://snomed.info/sct",
"display": "Asthma"
}]
}
}
}];
cases[1].input = cases[1].resources[0];
cases[1].result = {
"problem": {
"code": {
"name": "Asthma",
"code": "195967001",
"code_system_name": "SNOMED CT"
},
"date_time": {
"low": {
"date": "2007-01-03T00:00:00.000Z",
"precision": "day"
}
}
}
};
cases[2] = {};
cases[2].resources = [{
"resource": {
"id": "Condition/c-2-0",
"resourceType": "Condition",
"status": "confirmed",
"onsetDateTime": "2007-01-03",
"dateAsserted": "2007-01-03",
"abatementDate": "2012-09-05",
"code": {
"coding": [{
"code": "195967001",
"system": "http://snomed.info/sct",
"display": "Asthma"
}]
}
}
}];
cases[2].input = cases[2].resources[0];
cases[2].result = {
"problem": {
"code": {
"name": "Asthma",
"code": "195967001",
"code_system_name": "SNOMED CT"
},
"date_time": {
"low": {
"date": "2007-01-03T00:00:00.000Z",
"precision": "day"
},
"high": {
"date": "2012-09-05T00:00:00.000Z",
"precision": "day"
}
}
}
};
|
app.controller('submissions', ['$scope', '$http', '$rootScope', 'globalHelpers', function ($scope, $http, $rootScope, globalHelpers) {
$scope.stats = {};
$scope.getUrlLanguages = function(gitUrlId){
globalHelpers.getUrlLanguagesPromise(gitUrlId).then( function (response){
$scope.stats[gitUrlId] = response.data.languages;
});
}
$scope.addForReview = function () {
$scope.showWarning = false;
$scope.showGithubWarning = false;
if (!$scope.newName || !$scope.newUrl) {
$scope.showWarning = true;
return;
}
var _new_name = $scope.newName.trim();
var _new = $scope.newUrl.trim();
if (!_new || !_new_name) {
$scope.showWarning = true;
return;
}
if (!_new || !_new_name) {
$scope.showWarning = true;
return;
}
var _newUrl = globalHelpers.getLocation(_new);
var pathArray = _newUrl.pathname.split('/');
isCommit = pathArray.indexOf('commit') > -1;
isPR = pathArray.indexOf('pull') > -1;
if (_newUrl.hostname != "github.com" || (!isCommit && !isPR)){
$scope.showGithubWarning = true;
return;
}
var obj = JSON.parse('{"github_user": "' + $scope.github_user + '", "name": "' + _new_name + '", "url": "' + _new + '"}');
for (var i=0; i < $scope.existing.length; i++){
if (Object.keys($scope.existing[i])[0] == _new){
return;
}
}
$scope.existing.push(obj);
$http({
method: "post",
url: "/add_for_review",
headers: {'Content-Type': "application/json"},
data: obj
}).success(function () {
// console.log("success!");
});
$scope.showUWarning = false;
$scope.showGithubWarning = false;
$scope._new = '';
$rootScope.$broadcast('urlEntryChange', 'args');
};
$scope.removeUrl = function (url) {
if(confirm("Are you sure you want to delete entry \"" + url["name"] + "\"?")){
for (var i=0; i < $scope.existing.length; i++){
if ($scope.existing[i]["url"] == url['url']){
$scope.existing.splice(i, 1)
$http({
method: "post",
url: "/remove_from_list",
headers: {'Content-Type': "application/json"},
data: url
}).success(function () {
console.log("success!");
});
$rootScope.$broadcast('urlEntryChange', 'args');
}
}
}
};
}]);
|
function loadText()
{
var txtLang = document.getElementsByName("txtLang");
txtLang[0].innerHTML = "St\u00F8rrelse";
txtLang[1].innerHTML = "Egenskaber";
txtLang[2].innerHTML = "Typografi";
txtLang[3].innerHTML = "Bredde";
txtLang[4].innerHTML = "Bredde styret af indhold";
txtLang[5].innerHTML = "Tabelbredde";
txtLang[6].innerHTML = "Tilpas til vindue";
txtLang[7].innerHTML = "H\u00F8jde";
txtLang[8].innerHTML = "Bredde styret af indhold";
txtLang[9].innerHTML = "Tabelbredde";
txtLang[10].innerHTML = "Tilpas til vindue";
txtLang[11].innerHTML = "Justering";
txtLang[12].innerHTML = "Margen";
txtLang[13].innerHTML = "Venstre";
txtLang[14].innerHTML = "H\u00F8jre";
txtLang[15].innerHTML = "Top";
txtLang[16].innerHTML = "Nederst";
txtLang[17].innerHTML = "Ramme";
txtLang[18].innerHTML = "Collapse";
txtLang[19].innerHTML = "Baggrund";
txtLang[20].innerHTML = "Celle afstand";
txtLang[21].innerHTML = "Celle margen";
txtLang[22].innerHTML = "Typografi";
var optLang = document.getElementsByName("optLang");
optLang[0].text = "pixels"
optLang[1].text = "procent"
optLang[2].text = "pixels"
optLang[3].text = "procent"
optLang[4].text = "Venstre"
optLang[5].text = "Centrer"
optLang[6].text = "H\u00F8jre"
optLang[7].text = "Ingen"
optLang[8].text = "Ja"
optLang[9].text = "Nej"
document.getElementById("btnPick").value="V\u00E6lg";
document.getElementById("btnImage").value="Billede";
document.getElementById("btnCancel").value = "Annuller";
document.getElementById("btnApply").value = "Opdater";
document.getElementById("btnOk").value = " Ok ";
}
function getText(s)
{
switch(s)
{
case "Custom Colors": return "Egne farver";
case "More Colors...": return "Flere farver...";
default:return "";
}
}
function writeTitle()
{
document.write("<title>Tabel egenskaber</title>")
}
|
db = connect(mserver);
db = db.getSiblingDB('kynetx');
db.schedev.ensureIndex({cron_id : 1});
db.schedev.ensureIndex({ken : 1});
db.schedev.ensureIndex({expired : 1},{expireAfterSeconds : 120});
|
class TabList {
constructor (tabs, parentTaskList) {
this.tabs = tabs || []
this.parentTaskList = parentTaskList
}
//tab properties that shouldn't be saved to disk
static temporaryProperties = ['hasAudio', 'previewImage', 'loaded']
add (tab = {}, options = {}) {
var tabId = String(tab.id || Math.round(Math.random() * 100000000000000000)) // you can pass an id that will be used, or a random one will be generated.
var newTab = {
url: tab.url || '',
title: tab.title || '',
id: tabId,
lastActivity: tab.lastActivity || Date.now(),
secure: tab.secure,
private: tab.private || false,
readerable: tab.readerable || false,
themeColor: tab.themeColor,
backgroundColor: tab.backgroundColor,
scrollPosition: tab.scrollPosition || 0,
selected: tab.selected || false,
muted: tab.muted || false,
loaded: tab.loaded || false,
hasAudio: false,
previewImage: '',
isFileView: false,
}
if (options.atEnd) {
this.tabs.push(newTab)
} else {
this.tabs.splice(this.getSelectedIndex() + 1, 0, newTab)
}
this.parentTaskList.emit('tab-added', tabId)
return tabId
}
update (id, data) {
if (!this.has(id)) {
throw new ReferenceError('Attempted to update a tab that does not exist.')
}
const index = this.getIndex(id)
for (var key in data) {
if (data[key] === undefined) {
throw new ReferenceError('Key ' + key + ' is undefined.')
}
this.tabs[index][key] = data[key]
this.parentTaskList.emit('tab-updated', id, key)
// changing URL erases scroll position
if (key === 'url') {
this.tabs[index].scrollPosition = 0
this.parentTaskList.emit('tab-updated', id, 'scrollPosition')
}
}
}
destroy (id) {
const index = this.getIndex(id)
if (index < 0) return false
tasks.getTaskContainingTab(id).tabHistory.push(this.toPermanentState(this.tabs[index]))
this.tabs.splice(index, 1)
this.parentTaskList.emit('tab-destroyed', id)
return index
}
destroyAll () {
// this = [] doesn't work, so set the length of the array to 0 to remove all of the itemss
this.tabs.length = 0
}
get (id) {
if (!id) { // no id provided, return an array of all tabs
// it is important to copy the tab objects when returning them. Otherwise, the original tab objects get modified when the returned tabs are modified (such as when processing a url).
var tabsToReturn = []
for (var i = 0; i < this.tabs.length; i++) {
tabsToReturn.push(Object.assign({}, this.tabs[i]))
}
return tabsToReturn
}
for (var i = 0; i < this.tabs.length; i++) {
if (this.tabs[i].id === id) {
return Object.assign({}, this.tabs[i])
}
}
return undefined
}
has (id) {
return this.getIndex(id) > -1
}
getIndex (id) {
for (var i = 0; i < this.tabs.length; i++) {
if (this.tabs[i].id === id) {
return i
}
}
return -1
}
getSelected () {
for (var i = 0; i < this.tabs.length; i++) {
if (this.tabs[i].selected) {
return this.tabs[i].id
}
}
return null
}
getSelectedIndex () {
for (var i = 0; i < this.tabs.length; i++) {
if (this.tabs[i].selected) {
return i
}
}
return null
}
getAtIndex (index) {
return this.tabs[index] || undefined
}
setSelected (id) {
if (!this.has(id)) {
throw new ReferenceError('Attempted to select a tab that does not exist.')
}
for (var i = 0; i < this.tabs.length; i++) {
if (this.tabs[i].id === id) {
this.tabs[i].selected = true
this.tabs[i].lastActivity = Date.now()
} else if (this.tabs[i].selected) {
this.tabs[i].selected = false
this.tabs[i].lastActivity = Date.now()
}
}
this.parentTaskList.emit('tab-selected', id)
}
moveBy (id, offset) {
var currentIndex = this.getIndex(id)
var newIndex = currentIndex + offset
var newIndexTab = this.getAtIndex(newIndex)
if (newIndexTab) {
var currentTab = this.getAtIndex(currentIndex)
this.splice(currentIndex, 1, newIndexTab)
this.splice(newIndex, 1, currentTab)
}
}
count () {
return this.tabs.length
}
isEmpty () {
if (!this.tabs || this.tabs.length === 0) {
return true
}
if (this.tabs.length === 1 && !this.tabs[0].url) {
return true
}
return false
}
forEach (fun) {
return this.tabs.forEach(fun)
}
splice (...args) {
return this.tabs.splice.apply(this.tabs, args)
}
toPermanentState (tab) {
//removes temporary properties of the tab that are lost on page reload
let result = {}
Object.keys(tab)
.filter(key => !TabList.temporaryProperties.includes(key))
.forEach(key => result[key] = tab[key])
return result
}
getStringifyableState () {
return this.tabs.map(tab => this.toPermanentState(tab))
}
}
module.exports = TabList
|
/*
* ! JSRT JavaScript Library 0.1.1 lico.atom@gmail.com
*
* Copyright 2008, 2014 Atom Union, Inc. Released under the MIT license
*
* Date: Feb 11, 2014
*/
Class.forName({
name: "class js.util.Iterator extends Object",
"private _element": null,
"private _cursor": 0,
"private _lastRet": -1,
Iterator: function(element) {
this._element = element || [];
},
hasNext: function() {
return this._cursor < this._element.size();
},
next: function() {
try {
var next = this._element.get(this._cursor);
this._lastRet = this._cursor++;
return next;
} catch (e) {
throw new js.lang.IndexOutOfBoundsException("Index: " + this._cursor + ", Size: " + this._element.size() + ",Message:" + e.getMessage());
}
},
remove: function() {
if (this._lastRet === -1)
throw new js.lang.IllegalStateException();
try {
this._element.removeAt(this._lastRet);
if (this._lastRet < this._cursor)
this._cursor--;
this._lastRet = -1;
} catch (e) {
throw new js.lang.IndexOutOfBoundsException();
}
}
});
|
/*
* ../../../..//localization/cy/FontWarnings.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*************************************************************
*
* MathJax/localization/cy/FontWarnings.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("cy", "FontWarnings", {
version: "2.7.5",
isLoaded: true,
strings: {}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/cy/FontWarnings.js");
|
var parentchild = require('../'),
assert = require('assert');
assert.deepEqual(parentchild('foo'), []);
assert.deepEqual(parentchild({}), []);
assert.deepEqual(parentchild([1, 2, 3]), [['inarray', undefined, 1],
['inarray', undefined, 2],
['inarray', undefined, 3]]);
assert.deepEqual(parentchild({
a: {
b: 'foo'
},
c: ['a', 'b']
}), [['child', undefined, 'a'],
['child', 'a', 'b'],
['value', 'b', 'foo'],
['child', undefined, 'c'],
['inarray', 'c', 'a'],
['inarray', 'c', 'b']]);
assert.deepEqual(parentchild({
a: {
b: 'foo'
},
c: {
f: 'baz',
d: {
e: 'bar'
},
g: 'darp',
h: {
i: 'derp',
o: {
p: {
q: 'qak'
},
r: 'rez'
}
},
j: 'gar'
},
k: {
l: 'one',
m: 'two',
n: 'three',
s: [1, 2, 3]
}
}), [['child', undefined, 'a'],
['child', 'a', 'b'],
['value', 'b', 'foo'],
['child', undefined, 'c'],
['child', 'c', 'f'],
['value', 'f', 'baz'],
['child', 'c', 'd'],
['child', 'd', 'e'],
['value', 'e', 'bar'],
['child', 'c', 'g'],
['value', 'g', 'darp'],
['child', 'c', 'h'],
['child', 'h', 'i'],
['value', 'i', 'derp'],
['child', 'h', 'o'],
['child', 'o', 'p'],
['child', 'p', 'q'],
['value', 'q', 'qak'],
['child', 'o', 'r'],
['value', 'r', 'rez'],
['child', 'c', 'j'],
['value', 'j', 'gar'],
['child', undefined, 'k'],
['child', 'k', 'l'],
['value', 'l', 'one'],
['child', 'k', 'm'],
['value', 'm', 'two'],
['child', 'k', 'n'],
['value', 'n', 'three'],
['child', 'k', 's'],
['inarray', 's', 1],
['inarray', 's', 2],
['inarray', 's', 3]]);
console.log('ok');
|
$('#confirmacaoExclusaoModal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var codigoVinho = button.data('codigo');
var nomeVinho = button.data('nome');
var modal = $(this);
var form = modal.find('form');
var action = form.data('url-base');
if (!action.endsWith('/')) {
action += '/';
}
form.attr('action', action + codigoVinho);
modal.find('.modal-body span').html('Tem certeza que deseja excluir o vinho <strong>' + nomeVinho + '</strong>?');
});
|
import { IconPathDetails } from '../config';
class ReactIcon {
constructor(name, component) {
this.name = name;
this.file = `${IconPathDetails.iconDir}${name}.jsx`;
this.component = component;
}
}
export default ReactIcon;
|
const crypto = require('crypto')
module.exports = function (doc) {
doc._source.bar = crypto
.createHash('md5')
.update(String(doc._source.foo))
.digest('hex')
}
|
$(function() {
var search = $("#search");
var submissions = $("#submissions tbody tr");
search.on('keyup', function(event) {
var filter = search.val();
submissions.each(function(index, elem) {
var $elem = $(elem);
$elem.toggle($elem.data("student").indexOf(filter) !== -1);
});
})
});
|
/*******************************************************************************
* Copyright [2017] [Quirino Brizi (quirino.brizi@gmail.com)]
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
'use strict'
module.exports = {
handleError: function(eventEmitter, err, req, res) {
console.error("received error %j", err);
var statusCode = (!err.statusCode || err.statusCode == 0) ? 500 : err.statusCode,
message = !err.error ? !err.body ? { message: "Internal Server Error" } : err.body : err.error;
eventEmitter.emit('event', {message: message, payload: err});
res.status(statusCode).send(message);
},
handleSuccess: function(eventEmitter, res, message, payload) {
eventEmitter.emit('event', {message: message, payload: payload});
res.status(200).json(payload);
},
handleApiError: function(err, req, res) {
console.error("received error: ", err.stack);
var statusCode = (!err.statusCode || err.statusCode == 0) ? 500 : err.statusCode,
message = !err.error ? !err.body ? { message: "Internal Server Error" } : err.body : err.error;
res.status(statusCode).send(message);
},
};
|
/* eslint-disable */
var webpack = require('webpack');
var path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './index.js',
output: {
path: path.join(__dirname, '..', '..', 'build'),
filename: 'app.js'
},
resolve: {
modulesDirectories: ['shared', 'node_modules'],
extensions: ['', '.js', '.jsx', '.json']
},
externals: [nodeExternals()],
plugins: [
new webpack.BannerPlugin('require("source-map-support").install();', {
raw: true,
entryOnly: false
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
],
target: 'node',
node: { // webpack strangely doesn't do this when you set `target: 'node'`
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false,
setImmediate: false
},
devtool: 'sourcemap',
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['react', 'es2015', 'stage-0'],
plugins: ['transform-decorators-legacy', ['react-transform', {
transforms: [
{
transform: 'react-transform-catch-errors',
imports: ['react', 'redbox-react']
}
]
}]]
}
},
{
test: /\.(css|less)$/,
loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!less'
},
{
test: /\.(woff|woff2|ttf|eot|svg|png|jpg|jpeg|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url'
}
]
}
};
|
var searchData=
[
['checksyscall_2eh',['CheckSysCall.h',['../db/d19/_check_sys_call_8h.html',1,'']]],
['classid_2eh',['ClassID.h',['../dc/d14/_class_i_d_8h.html',1,'']]],
['comparator_2eh',['Comparator.h',['../d7/d0c/_comparator_8h.html',1,'']]]
];
|
sap.ui.define(['exports', './asset-registries/i18n', './asset-registries/LocaleData', './asset-registries/Themes', './asset-registries/Icons'], function (exports, i18n, LocaleData, Themes, Icons) { 'use strict';
exports.registerI18nLoader = i18n.registerI18nLoader;
exports.registerLocaleDataLoader = LocaleData.registerLocaleDataLoader;
exports.registerThemePropertiesLoader = Themes.registerThemePropertiesLoader;
exports.registerIconLoader = Icons.registerIconLoader;
Object.defineProperty(exports, '__esModule', { value: true });
});
|
import { connect } from 'react-redux'
import { increment, doubleAsync,callApiAsync } from '../modules/Login'
/* This is a container component. Notice it does not contain any JSX,
nor does it import React. This component is **only** responsible for
wiring in the actions and state necessary to render a presentational
component - in this case, the counter: */
import Login from '../views/LoginView'
/* Object of action creators (can also be function that returns object).
Keys will be passed as props to presentational components. Here we are
implementing our wrapper around increment; the component doesn't care */
const mapDispatchToProps = {
increment : () => increment(1),
doubleAsync,
callApiAsync
}
const mapStateToProps = (state) => ({
counter : state.counter,
jsonResult: state.jsonResult
})
/* Note: mapStateToProps is where you should use `reselect` to create selectors, ie:
import { createSelector } from 'reselect'
const counter = (state) => state.counter
const tripleCount = createSelector(counter, (count) => count * 3)
const mapStateToProps = (state) => ({
counter: tripleCount(state)
})
Selectors can compute derived data, allowing Redux to store the minimal possible state.
Selectors are efficient. A selector is not recomputed unless one of its arguments change.
Selectors are composable. They can be used as input to other selectors.
https://github.com/reactjs/reselect */
export default connect(mapStateToProps, mapDispatchToProps)(Login)
|
function getFunction(f,b){
return function myNextTick(){
console.log(f + " " + b);
};
}
process.nextTick(getFunction("foo", "bar"));
|
var CLIENT_ID = '';
var CLIENT_SECRET = '';
var OWNER = "";
var REPO = "";
/**
* Manage Form Answer
* Create a trigger by going to Resources > Current projet's triggers
* Select function manageAnswer() and create a trigger at form submission
*/
function manageAnswer(e) {
var form = e.source;
var rep = {
"Title":"",
"Message":"",
"Email":""
};
var itemResponses = e.response.getItemResponses();
for (var i = 0; i < itemResponses.length; i++) {
var itemTitle = itemResponses[i].getItem().getTitle();
var itemResponse = itemResponses[i].getResponse();
rep[itemTitle] = itemResponse;
Logger.log(itemTitle + ': ' + itemResponse );
}
try{
var issue = submitIssue(rep);
var body = "<p>Hi,</p>"
+"<p>Thank you for submitting your issue, you can follow it on this page : <a href='"+issue.html_url+"'>link</a>.</p>"
+"<p>Title : "+rep.Title+"<br>"
+"Message : "+rep.Message+"</p>"
+"Regards";
GmailApp.sendEmail(rep.Email, 'Issue posted on GitHub', '', {
htmlBody:body,
});
}catch(e){
GmailApp.sendEmail(Session.getEffectiveUser().getEmail(), 'Error issue submission', '', {
htmlBody:JSON.stringify(rep),
});
}
}
/**
* Function to send issue to GitHub
*/
function submitIssue(data){
var service = getService();
if (service.hasAccess()) {
var url = 'https://api.github.com/repos/'+OWNER+'/'+REPO+'/issues';
var bodyRequest = {
"title":data.Title,
"body":"_## Issue created anonymously for a user ##_\n"+data.Message
};
var response = UrlFetchApp.fetch(url, {
method : "post",
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
payload : JSON.stringify(bodyRequest)
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
return result;
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
/**
* Authorizes and makes a request to the GitHub API.
*/
function run() {
var service = getService();
if (service.hasAccess()) {
var url = 'https://api.github.com/user/repos';
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
/**
* Configures the service.
*/
function getService() {
return OAuth2.createService('GitHub')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://github.com/login/oauth/authorize')
.setTokenUrl('https://github.com/login/oauth/access_token')
// Set the client ID and secret.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function that should be invoked to complete
// the OAuth flow.
.setCallbackFunction('authCallback')
//scope for app
.setScope('repo')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
}
/**
* Handles the OAuth callback.
*/
function authCallback(request) {
var service = getService();
var authorized = service.handleCallback(request);
if (authorized) {
return HtmlService.createHtmlOutput('Success!');
} else {
return HtmlService.createHtmlOutput('Denied');
}
}
|
"use strict";
let User = require("../../../../persistence").models.User;
let debug = require("debug")("app:auth");
module.exports = (findUserEntity, createUserEntity, methodName) => {
return (tokenA, tokenB, profile, done) => {
return User.findOneQ(findUserEntity(profile))
.then((found) => found || User.createQ(createUserEntity(profile)))
.then((user) => done(null, user))
.catch((err) => {
debug(`error authenticating via ${methodName}`, err);
done(err, null);
});
};
};
|
/*
Copyright 2016 ElasticBox All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class InstanceFiltersController {
constructor($scope) {
'ngInject';
this.instancesFilteredByState = [];
this.selectedOwners = [];
this.filteredInstances = [];
$scope.$watch('ctrl.selectedState', () => this.filterInstancesByState());
$scope.$watchCollection('ctrl.instancesToFilter', () => this.filterInstancesByState());
$scope.$watchCollection('ctrl.selectedOwners', () => this.filterInstancesByOwners());
$scope.$watchCollection('ctrl.instancesFilteredByState', () => this.filterInstancesByOwners());
}
filterInstancesByState() {
this.instancesFilteredByState = _.chain(this.instancesToFilter)
.filter((x) => {
return _.isUndefined(this.selectedState) || this.selectedState.state.kind === 'all'
|| this.selectedState.state.kind.toLowerCase() === (x.kind || '').toLowerCase()
&& _.isUndefined(this.selectedState.substate) || !_.isUndefined(this.selectedState.substate)
&& _.get(x, 'status.phase') === this.selectedState.substate.state;
})
.value();
}
filterInstancesByOwners() {
this.filteredInstances = _.isEmpty(this.selectedOwners)
? this.instancesFilteredByState
: _.filter(this.instancesFilteredByState, (x) => _.includes(this.selectedOwners, x.owner));
}
}
export default InstanceFiltersController;
|
var fs = require('fs');
fs.readFile('data/file1.txt', function (err, data) {
console.log('Second');
});
console.log('First');
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
function drawSctDiagram(concept, parentDiv) {
parentDiv.svg({settings: {width: '600px', height: '500px'}});
var svg = parentDiv.svg('get');
loadDefs(svg);
rect1 = drawSctBox(parentDiv, 10, 10, "<span class='sct-box-id'>12676007<br></span>Fracture of radius", "sct-defined-concept");
circle1 = drawEquivalentNode(svg, 120,130);
drawSubsumedByNode(svg, 120,230);
drawSubsumesNode(svg, 120,330);
drawSctBox(parentDiv, 100, 400, "<slot>", "sct-slot");
connectElements(svg, rect1, circle1, 'center', 'left');
circle2 = drawConjunctionNode(svg, 200, 130);
connectElements(svg, circle1, circle2, 'right', 'left');
rect2 = drawSctBox(parentDiv, 250, 100, "<span class='sct-box-id'>65966004<br></span>Fracture of forearm", "sct-defined-concept");
connectElements(svg, circle2, rect2, 'bottom', 'left', 'ClearTriangle');
rect3 = drawSctBox(parentDiv, 250, 200, "<span class='sct-box-id'>429353004<br></span>Injury of radius", "sct-defined-concept");
connectElements(svg, circle2, rect3, 'bottom', 'left', 'ClearTriangle');
circle3 = drawAttributeGroupNode(svg, 250, 330);
connectElements(svg, circle2, circle3, 'bottom', 'left');
circle4 = drawConjunctionNode(svg, 300, 330);
connectElements(svg, circle3, circle4, 'right', 'left');
rect4 = drawSctBox(parentDiv, 350, 300, "<span class='sct-box-id'>116676008<br></span>Associated morphology", "sct-attribute");
connectElements(svg, circle4, rect4, 'right', 'left');
rect5 = drawSctBox(parentDiv, 550, 300, "<span class='sct-box-id'>72704001<br></span>Fracture", "sct-primitive-concept");
connectElements(svg, rect4, rect5, 'right', 'left');
rect6 = drawSctBox(parentDiv, 350, 400, "<span class='sct-box-id'>363698007<br></span>Finding site", "sct-attribute");
connectElements(svg, circle4, rect6, 'bottom', 'left');
rect7 = drawSctBox(parentDiv, 550, 400, "<span class='sct-box-id'>62413002<br></span>Bone structure of radius", "sct-primitive-concept");
connectElements(svg, rect6, rect7, 'right', 'left');
}
function toggleIds() {
$('.sct-box-id').toggle();
}
|
var win = Ti.UI.createWindow({
backgroundColor:'white'
});
win.open();
var GA = require('analytics.google');
//GA.optOut = true;
GA.debug = true;
GA.trackUncaughtExceptions = true;
var tracker = GA.getTracker("UA-XXXXXX-X");
tracker.trackEvent({
category: "category",
action: "test",
label: "label",
value: 1
});
tracker.trackSocial({
network: "facebook",
action: "action",
target: "target"
});
tracker.trackTiming({
category: "",
time: 10,
name: "",
label: ""
});
tracker.trackScreen("Home");
var transaction = GA.makeTransaction({
id: "hi",
tax: 0.6,
shipping: 0,
revenue: 24.99 * 0.7
});
transaction.addItem({
sku: "ABC123",
name: "My Alphabet",
category: "product category",
price: 24.99,
quantity: 1
});
tracker.trackTransaction(transaction);
|
var __window = window;
var destringify = function(date) {
if (date != null && 'string' === typeof(date)) return new Date(date);
return date;
}
var stringify = function(date) {
if (!date) return null;
return dateFormat(date, "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'");
}
var stringreplaceall = function(target, search, replacement) {
return target.split(search).join(replacement);
};
var grabiframecontentdocument = function(id) {
return document.getElementById(id).contentWindow.document;
};
var grabcontentdocument = function(selector, parent) {
return jQuery(selector, parent).get(0).contentWindow.document;
};
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {PostOptions} from '@support/ui/component';
import {isAndroid} from '@support/utils';
class EditPostScreen {
testID = {
editPostScreen: 'edit_post.screen',
closeEditPostButton: 'close.edit_post.button',
messageInput: 'edit_post.message.input',
saveButton: 'edit_post.save.button',
};
editPostScreen = element(by.id(this.testID.editPostScreen));
closeEditPostButton = element(by.id(this.testID.closeEditPostButton));
messageInput = element(by.id(this.testID.messageInput));
saveButton = element(by.id(this.testID.saveButton));
toBeVisible = async () => {
if (isAndroid()) {
await expect(this.editPostScreen).toBeVisible();
} else {
await expect(this.editPostScreen).toExist();
}
return this.editPostScreen;
};
open = async () => {
// # Swipe up panel on Android
if (isAndroid()) {
await PostOptions.slideUpPanel.swipe('up');
}
// # Open edit post screen
await PostOptions.editAction.tap();
return this.toBeVisible();
};
close = async () => {
await this.closeEditPostButton.tap();
await expect(this.editPostScreen).not.toBeVisible();
};
}
const editPostScreen = new EditPostScreen();
export default editPostScreen;
|
/*分页JS*/
var rsss = false;
$(function () {
$(".leftNav_side").css("min-height", $(".leftNav_side").height());
$(window).resize(function () {
$(".leftNav_side").height($(window).height());
}).trigger("resize");//左侧菜单高度自适应,但是保留内容最小高度
//切换左导航一级菜单
$(".Nav_lvl dt").click(function () {
$(this).parent().siblings().find("dd").hide();
$(this).siblings().slideDown(300);
});
//切换左导航二级菜单
$(".Nav_lvl dd").click(function () {
$(".Nav_lvl dd").removeClass();
$(this).addClass("Nav_lvl_dd_on");
});
//切换顶部导航
$(".topNav_ul li").click(function () {
$(this).addClass("topNav_li_on").siblings().removeClass();
});
if(Number($("[name='totalCount']").val()) > 0){
var pages = [],
totalPage = Number($("[name='totalPage']").val()),
totalCount = Number($("[name='totalCount']").val()),
currentPage = Number($("[name='pageNum']").val())==0 ? 1 :Number($("[name='pageNum']").val());
pages[pages.length] = ' <th colspan="100"><i>当前第'+currentPage+'页/共'+totalPage+'页</i><i>共'+totalCount+'条记录</i>';
if (currentPage == 1) {
pages[pages.length] = ' <span>首页</span><span>上一页</span>';
}
else {
pages[pages.length] = ' <a class="first" href="#">首页</a><a class="prev" href="#">上一页</a>';
}
if (currentPage < 5) {
for (var i = 1; i <= (totalPage > 10 ? 10 : totalPage); i++) {
if (currentPage == i)
pages[pages.length] = '<span class="sel">' + i + '</span>';
else
pages[pages.length] = '<a href="#">' + i + '</a>';
}
}
else if (currentPage >= totalPage - 5)
for (var i = totalPage - 9; i <= totalPage; i++) {
if (currentPage == i)
pages[pages.length] = '<span class="sel">' + i + '</span>';
else
pages[pages.length] = '<a href="#">' + i + '</a>';
}
else {
for (var i = currentPage - 5; i <= currentPage + 4; i++) {
if (currentPage == i)
pages[pages.length] = '<span class="sel">' + i + '</span>';
else
pages[pages.length] = '<a href="#">' + i + '</a>';
}
}
if (currentPage < totalPage) {
pages[pages.length] = '<a class="next" href="#">下一页</a><a class="last" href="#">尾页</a>';
}
else {
pages[pages.length] = '<span>下一页</span><span>尾页</span>';
}
pages[pages.length] = '<input type="text" name="page" value="'+currentPage+'"/>';
pages[pages.length] = '<input type="button" value="跳转" class="btn_violet" />';
$(".pager").html(pages.join("")).find("a:not(.next):not(.prev)").click(function(){
$("[name='currentPage']").val($(this).text());
$("#pagerForm").submit();
});
$(".pager").find("a.first").click(function(){
num = 1;
$("[name='currentPage']").val(num);
$("#pagerForm").submit();
});
$(".pager").find("a.prev").click(function(){
num = Number($("[name='currentPage']").val()) - 1 < 0 ? 0 :Number($("[name='currentPage']").val()) - 1;
$("[name='currentPage']").val(num);
$("#pagerForm").submit();
});
$(".pager").find("a.next").click(function(){
$("[name='currentPage']").val(Number($("[name='currentPage']").val()) + 1);
$("#pagerForm").submit();
});
$(".pager").find("a.last").click(function(){
num = Number($("[name='totalPage']").val());
$("[name='currentPage']").val(num);
$("#pagerForm").submit();
});
$(".pager").find("input.btn_violet").click(function(){
num = Number($("[name='page']").val());
if(num > totalPage){
num = totalPage;
} else if(num < 1){
num = 1;
}
$("[name='currentPage']").val(num);
$("#pagerForm").submit();
});
}
});
|
/**
* Copyright 2015 Wouter van Heeswijk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
define(
["geometries/loader", "json!assets/triangle.json"],
function (loader, asset) {
return loader.load(asset);
}
);
|
import React from 'react';
import PropTypes from 'prop-types';
import Preselect from 'material-ui-icons/ThumbUp';
import IconWithTooltipButton from '../../common/iconWithTooltipButton';
import withApplicationStatusChange from '../../common/hoc/withApplicationStatusChange';
import { APPLICATION_STATUSES } from '../../../helpers/constants';
const messages = {
text: 'Preselect',
};
const PreselectButton = (props) => {
const { id, status, changeStatus, ...other } = props;
return (
<IconWithTooltipButton
icon={<Preselect />}
name="preselect"
text={messages.text}
onClick={(event) => {
event.stopPropagation();
changeStatus(id);
}}
{...other}
/>
);
};
PreselectButton.propTypes = {
id: PropTypes.oneOfType([
PropTypes.array,
PropTypes.string,
]),
status: PropTypes.string,
changeStatus: PropTypes.func,
};
export default withApplicationStatusChange(APPLICATION_STATUSES.PRE)(PreselectButton);
|
define([
"less!theme/textmate.less"
], function(cssContent) {
return {
'isDark': false,
'cssClass': "ace-tm",
'cssText': cssContent
}
});
|
function PreferencesAssistant() {
/* this is the creator function for your scene assistant object. It will be passed all the
additional parameters (after the scene name) that were passed to pushScene. The reference
to the scene controller (this.controller) has not be established yet, so any initialization
that needs the scene controller should be done in the setup function below. */
this.cookie = new Mojo.Model.Cookie('prefs');
this.model = this.cookie.get();
if (!this.model) {
this.model = {
useOldInterface: false
};
this.cookie.put(this.model);
}
}
PreferencesAssistant.prototype.setup = function() {
/* this function is for setup tasks that have to happen when the scene is first created */
/* use Mojo.View.render to render view templates and add them to the scene, if needed */
/* setup widgets here */
this.controller.setupWidget(
'oldInterfaceToggle',
{
modelProperty: 'useOldInterface',
disabledProperty: 'oldInterfaceToggleDisabled'
},
this.model
);
/* add event handlers to listen to events from widgets */
Mojo.Event.listen(
this.controller.get('oldInterfaceToggle'),
Mojo.Event.propertyChange,
this.handlePrefsChange.bind(this)
);
};
PreferencesAssistant.prototype.handlePrefsChange = function(event) {
this.cookie.put(this.model);
};
PreferencesAssistant.prototype.activate = function(event) {
/* put in event handlers here that should only be in effect when this scene is active. For
example, key handlers that are observing the document */
};
PreferencesAssistant.prototype.deactivate = function(event) {
/* remove any event handlers you added in activate and do any other cleanup that should happen before
this scene is popped or another scene is pushed on top */
};
PreferencesAssistant.prototype.cleanup = function(event) {
/* this function should do any cleanup needed before the scene is destroyed as
a result of being popped off the scene stack */
Mojo.Event.stopListening(
this.controller.get('oldInterfaceToggle'),
Mojo.Event.propertyChange,
this.handlePrefsChange.bind(this)
);
};
|
'use strict';
import React, {Component, PropTypes} from 'react';
import ReactNative, {Animated, Easing} from 'react-native';
var Animation = require('../Popover/Animation');
class TooltipAnimation extends Animation {
prepareStyle() {
const {
placement,
open,
} = this.props;
const tooltipPlacement = placement.split('-');
const verticalPlacement = tooltipPlacement [0];
const horizontalPlacement = tooltipPlacement[1];
const offset = verticalPlacement === 'bottom' ? 5 : -5;
const {anim} = this.state;
return {
opacity: this.interpolate(1),
transform: [
{translateY: open ? this.interpolate(offset, -offset) : -10000},
],
};
}
}
module.exports = TooltipAnimation;
|
var zz = {
Internal: {
Local: {
FS: {
File: {},
Directory: {}
}
}
}
};
zz.Internal.Local.FS.File.read = function(path, successCallback, errorCallback) {
Ti.API.debug("ZZ.Internal.Local.FS.File.read");
Ti.API.debug("ZZ.Internal.Local.FS.File.read [path : " + path + "]");
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path);
var blob = file.read();
if (null == blob) {
var errorMessage = "ZZ.Internal.Local.FS.File.read unable to read file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]";
_manageError({
errorMessage: errorMessage
}, errorCallback);
return null;
}
Ti.API.debug("ZZ.Internal.Local.FS.File.read readed file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]");
null != successCallback && successCallback(blob);
return blob;
};
zz.Internal.Local.FS.File.write = function(path, content, successCallback, errorCallback) {
Ti.API.debug("ZZ.Internal.Local.FS.File.write");
Ti.API.debug("ZZ.Internal.Local.FS.File.write [path : " + path + "]");
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path);
file.write(content);
var blob = file.read();
if (null == blob) {
var errorMessage = "ZZ.Internal.Local.FS.File.write unable to write file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]";
_manageError({
errorMessage: errorMessage
}, errorCallback);
return null;
}
Ti.API.debug("ZZ.Internal.Local.FS.File.write written file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]");
null != successCallback && successCallback(blob);
return blob;
};
zz.Internal.Local.FS.File.copy = function(from, to, successCallback, errorCallback) {
Ti.API.debug("ZZ.Internal.Local.FS.File.copy");
Ti.API.debug("ZZ.Internal.Local.FS.File.copy [from : " + from + ", to : " + to + "]");
var fromFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, from);
var toFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, to);
toFile.write(fromFile.read());
var blob = toFile.read();
if (null == blob) {
var errorMessage = "ZZ.Internal.Local.FS.File.copy unable to copy file [name : " + toFile.name + ", nativePath : " + toFile.nativePath + ", blob.mimeType : " + blob.mimeType + "]";
_manageError({
errorMessage: errorMessage
}, errorCallback);
return null;
}
Ti.API.debug("ZZ.Internal.Local.FS.File.copy copied to file [name : " + toFile.name + ", nativePath : " + toFile.nativePath + ", blob.mimeType : " + blob.mimeType + "]");
null != successCallback && successCallback(blob);
return blob;
};
zz.Internal.Local.FS.File.delete = function(path, successCallback, errorCallback) {
Ti.API.debug("ZZ.Internal.Local.FS.File.delete");
Ti.API.debug("ZZ.Internal.Local.FS.File.delete [path : " + path + "]");
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path);
var done = file.deleteFile();
if (!done) {
var errorMessage = "ZZ.Internal.Local.FS.File.delete unable to delete file [name : " + file.name + ", nativePath : " + file.nativePath + "]";
_manageError({
errorMessage: errorMessage
}, errorCallback);
return false;
}
Ti.API.debug("ZZ.Internal.Local.FS.File.delete deleted file [name : " + file.name + ", nativePath : " + file.nativePath + "]");
null != successCallback && successCallback();
return true;
};
zz.Internal.Local.FS.Directory.make = function(path, successCallback, errorCallback) {
Ti.API.debug("ZZ.Internal.Local.FS.Directory.make");
Ti.API.debug("ZZ.Internal.Local.FS.Directory.make [path : " + path + "]");
var dir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path);
var done = dir.createDirectory();
if (!done) {
var errorMessage = "ZZ.Internal.Local.FS.Directory.make unable to create directory [name : " + dir.name + "]";
_manageError({
errorMessage: errorMessage
}, errorCallback);
return false;
}
Ti.API.debug("ZZ.Internal.Local.FS.Directory.make created directory [name : " + dir.name + ", nativePath : " + dir.nativePath + "]");
null != successCallback && successCallback();
return true;
};
zz.Internal.Local.FS.Directory.remove = function(path, successCallback, errorCallback) {
Ti.API.debug("ZZ.Internal.Local.FS.Directory.remove");
var dir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path);
var done = dir.deleteDirectory();
if (!done) {
var errorMessage = "ZZ.Internal.Local.FS.Directory.remove unable to remove directory [name : " + dir.name + ", nativePath : " + dir.nativePath + "]";
_manageError({
errorMessage: errorMessage
}, errorCallback);
return false;
}
Ti.API.debug("ZZ.Internal.Local.FS.Directory.remove removed directory [name : " + dir.name + ", nativePath : " + dir.nativePath + "]");
null != successCallback && successCallback();
return true;
};
exports.ZZ = zz;
exports.version = .2;
var _manageError = function(error, errorCallback) {
Ti.API.trace("ZZ.Internal.Local.FS._manageError");
Ti.API.error(error.errorMessage);
null != errorCallback && errorCallback(error);
};
|
/**
Copyright 2011-2013 Here's A Hand Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
$(function() {
$("input.yes").mouseover(function(){
$(this).attr('value','No');
$(this).removeClass('yes')
$(this).addClass('no')
});
$("input.yes").mouseout(function(){
$(this).attr('value','Yes');
$(this).removeClass('no')
$(this).addClass('yes')
});
$("input.no").mouseover(function(){
$(this).attr('value','Yes');
$(this).removeClass('no')
$(this).addClass('yes')
});
$("input.no").mouseout(function(){
$(this).attr('value','No');
$(this).removeClass('yes')
$(this).addClass('no')
});
});
|
/**
* @license Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
const Runner = require('../../../../runner');
const EstimatedInputLatency = require('../../../../gather/computed/metrics/estimated-input-latency'); // eslint-disable-line
const assert = require('assert');
const trace = require('../../../fixtures/traces/progressive-app-m60.json');
const devtoolsLog = require('../../../fixtures/traces/progressive-app-m60.devtools.log.json');
/* eslint-env jest */
describe('Metrics: EIL', () => {
it('should compute a simulated value', async () => {
const artifacts = Runner.instantiateComputedArtifacts();
const settings = {throttlingMethod: 'simulate'};
const result = await artifacts.requestEstimatedInputLatency({trace, devtoolsLog, settings});
expect({
timing: Math.round(result.timing),
optimistic: Math.round(result.optimisticEstimate.timeInMs),
pessimistic: Math.round(result.pessimisticEstimate.timeInMs),
}).toMatchSnapshot();
});
it('should compute an observed value', async () => {
const artifacts = Runner.instantiateComputedArtifacts();
const settings = {throttlingMethod: 'provided'};
const result = await artifacts.requestEstimatedInputLatency({trace, devtoolsLog, settings});
assert.equal(Math.round(result.timing * 10) / 10, 17.1);
});
describe('#calculateRollingWindowEIL', () => {
it('uses a 5s rolling window', async () => {
const events = [
{start: 7500, end: 10000, duration: 2500},
{start: 10000, end: 15000, duration: 5000},
];
assert.equal(EstimatedInputLatency.calculateRollingWindowEIL(events), 4516);
});
it('handles continuous tasks', async () => {
const events = [];
const longTaskDuration = 100;
const longTaskNumber = 1000;
const shortTaskDuration = 1.1;
const shortTaskNumber = 10000;
for (let i = 0; i < longTaskNumber; i++) {
const start = i * longTaskDuration;
events.push({start: start, end: start + longTaskDuration, duration: longTaskDuration});
}
const baseline = events[events.length - 1].end;
for (let i = 0; i < shortTaskNumber; i++) {
const start = i * shortTaskDuration + baseline;
events.push({start: start, end: start + shortTaskDuration, duration: shortTaskDuration});
}
assert.equal(EstimatedInputLatency.calculateRollingWindowEIL(events), 106);
});
});
});
|
/******************************************************************************\
| |
| package-version-file-types-view.js |
| |
|******************************************************************************|
| |
| This defines an dialog that is used to select directories within |
| package versions. |
| |
|******************************************************************************|
| Copyright (c) 2013 SWAMP - Software Assurance Marketplace |
\******************************************************************************/
define([
'jquery',
'underscore',
'backbone',
'marionette',
'text!templates/packages/info/versions/info/source/dialogs/package-version-file-types.tpl',
'scripts/registry',
'scripts/views/dialogs/error-view',
'scripts/views/files/file-types-list/file-types-list-view'
], function($, _, Backbone, Marionette, Template, Registry, ErrorView, FileTypesListView) {
return Backbone.Marionette.LayoutView.extend({
//
// attributes
//
regions: {
fileTypes: '#file-types'
},
events: {
'click #ok': 'onClickOk',
'keypress': 'onKeyPress'
},
//
// rendering methods
//
template: function() {
return _.template(Template, {
title: this.options.title,
packagePath: this.options.packagePath
});
},
onRender: function() {
this.showFileTypes();
},
showFileTypes: function() {
// fetch package version file types
//
var self = this;
this.model.fetchFileTypes({
data: {
'dirname': this.options.packagePath
},
// callbacks
//
success: function(data) {
var collection = new Backbone.Collection();
for (var key in data) {
collection.add(new Backbone.Model({
'extension': key,
'count': data[key]
}));
}
self.fileTypes.show(
new FileTypesListView({
collection: collection
})
);
},
error: function() {
// show error dialog
//
Registry.application.modal.show(
new ErrorView({
message: "Could not fetch file types for this package version."
})
);
}
});
},
//
// event handling methods
//
onClickOk: function() {
// apply callback
//
if (this.options.accept) {
this.options.accept();
}
},
onKeyPress: function(event) {
// respond to enter key press
//
if (event.keyCode === 13) {
this.onClickOk();
this.hide();
}
}
});
});
|
define(function (require) {
var app = angular.module('easyCodeApp', ['ngRoute', 'ui.bootstrap', 'ui.codemirror', 'vtortola.ng-terminal', 'flow']);
// controller for header actions
app.controller('headerController', function($scope){
// add header properties for phone support
$scope.header = {
isCollapsed : true
};
});
/**
* lazy loading configuration
*/
var config = require('routes');
var dependencyResolverFor = require('appDir/services/dependencyResolverFor');
/**
* lazy routing configuration
*/
app.config(
[
'$routeProvider',
'$locationProvider',
'$controllerProvider',
'$compileProvider',
'$filterProvider',
'$provide',
function($routeProvider, $locationProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, terminalConfigurationProvider)
{
// allow blob link
$compileProvider.aHrefSanitizationWhitelist(/^\s*(blob):/);
app.controller = function(name, constructor) {
$controllerProvider.register(name, constructor);
return this;
}
app.directive = function(name, constructor) {
$compileProvider.directive(name, constructor);
return this;
}
app.filter = function(name, constructor) {
$filterProvider.register(name, constructor);
return this;
}
app.factory = function(name, constructor) {
$provide.factory(name, constructor);
return this;
}
app.service = function (name, constructor) {
$provide.service(name, constructor);
return this;
}
// $locationProvider.html5Mode(true);
if(config.routes !== undefined)
{
angular.forEach(config.routes, function(route, path)
{
// default template has the same name as the controller
route.templateUrl = route.templateUrl || route.controller+'.html';
$routeProvider.when(
path,
{
templateUrl:route.templateUrl,
resolve:dependencyResolverFor(route.dependencies),
controller : route.controller
}
);
});
}
if(config.defaultRoutePaths !== undefined)
{
$routeProvider.otherwise({redirectTo:config.defaultRoutePaths});
}
}
]);
/**
* configuration for terminal emlator
*/
app.config([
'terminalConfigurationProvider',
function(terminalConfigurationProvider){
terminalConfigurationProvider.config('vintage').outputDelay = 10;
terminalConfigurationProvider.config('vintage').allowTypingWriteDisplaying = false;
}
]);
app.init = function(){
// lancement de l'application
angular.bootstrap(document, ['easyCodeApp']);
}
return app;
});
|
(function() {
var port = 8080;
if (window.location.search) {
var params = window.location.search.match(/port=(\d+)/);
if (params) {
port = params[1];
}
// How often to poll
params = window.location.search.match(/pollInterval=(\d+)/);
if (params) {
window.JOLOKIA_POLL_INTERVAL = parseInt(params[1]);
}
}
window.JOLOKIA_URL = "http://localhost:" + port + "/jolokia";
})();
|
/**
* Symbol Art Editor
*
* @author malulleybovo (since 2021)
* @license GNU General Public License v3.0
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (C) 2021 Arthur Malulley B. de O.
*
*
* The JavaScript code in this page is free software: you can
* redistribute it and/or modify it under the terms of the GNU
* General Public License (GNU GPL) as published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. The code is distributed WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
*
* As additional permission under GNU GPL version 3 section 7, you
* may distribute non-source (e.g., minimized or compacted) forms of
* that code without the copy of the GNU GPL normally required by
* section 4, provided you include this license notice and a URL
* through which recipients can access the Corresponding Source.
*
* @licend The above is the entire license notice
* for the JavaScript code in this page.
*
*/
class UIAsset extends UIView {
get viewPath() { return 'res/templates/asset.html' }
_onTap = null;
get onTap() { return this._onTap }
set onTap(value) {
if (typeof value !== 'function' && value !== null) return;
this._onTap = value;
}
get assetFilePath() {
return this.view.attr('src');
}
_resourceLoaded = false;
get loaded() {
return this.view instanceof jQuery
&& this.view[0] instanceof HTMLElement
&& this._resourceLoaded;
}
constructor({ filePath = null } = {}) {
super();
let path = filePath;
this.didLoad(_ => {
this.view.on('load', _ => {
this._resourceLoaded = true;
});
this.view.attr('src', path);
this.gestureRecognizer = new UITapGestureRecognizer({
targetHtmlElement: this.view[0], onTap: () => {
if (this._onTap) {
this._onTap(this);
}
}
});
});
}
}
|
// @flow
/* eslint-env node */
/* global Restivus */
// Import Meteor :3 and Mongo :3
import { Meteor } from 'meteor/meteor'
// Import fs and path to access the filesystem. And mime to get MIMETypes.
import { readdirSync, lstatSync, readFileSync } from 'fs'
import { join, sep, basename } from 'path'
import { lookup } from 'mime'
// Create the Meteor methods.
Meteor.methods({
// This method enables the client to get the contents of any folder.
getFolderContents (folder: string): Array<{ name: string, type: string }> {
// Get folder contents and create initial variables the loop will write to.
const folderContents: Array<string> = readdirSync(folder)
const folderContentsWithTypes = []
let i
// Define the function to get the type of a directory item.
const getType = () => {
if (lstatSync(`${folder}/${folderContents[i]}`).isDirectory()) {
return 'folder'
}
return 'file'
}
// Start the loop to push folderContents.
for (i = 0; i < folderContents.length; i += 1) {
// Push objects to folderContentsWithTypes.
folderContentsWithTypes.push({ name: folderContents[i], type: getType() })
}
// Return folderContentsWithTypes.
return folderContentsWithTypes
},
// Pass it some paths and get a combination of those paths.
joinPaths (...paths): string {
return join(...paths)
},
goUpOneDirectory (pathy: string): string {
const pathyArray: Array<string> = pathy.split(sep)
if (pathyArray[0] === '') {
pathyArray[0] = '/'
}
const newArray = []
for (let x = 0; x < pathyArray.length - 1; x += 1) {
newArray.push(pathyArray[x])
}
return join(...newArray)
}
})
// Create a Restivus API.
// flow-disable-next-line
const Api = new Restivus({
prettyJson: true
})
Api.addRoute('/file/:_filePath', {
get () {
// Get basename.
const filename = basename(this.urlParams._filePath)
const mimetype = lookup(this.urlParams._filePath)
// Set em' headers.
this.response.writeHead({
// Filename.
'Content-disposition': `attachment; filename=${filename}`,
// Type of file.
'Content-type': mimetype
})
// Read the file and write data to response to client.
const file = readFileSync(this.urlParams._filePath)
this.response.write(file)
// this.done() is quite self-explanatory.
this.done()
}
})
|
/*
* Copyright 2017-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
ONOS GUI -- Widget -- Table Detail Panel Service
*/
(function () {
'use strict';
// injected refs
var $log, $interval, $timeout, fs, wss;
// constants
// var refreshInterval = 2000;
function noop() {}
// TODO: describe the input object for the main function
// example params to (functionX):
// {
// ...
// }
function buildBasePanel(opts) {
var popTopF = fs.isF(opts.popTop) || noop,
popMidF = fs.isF(opts.popMid) || noop,
popBotF = fs.isF(opts.popBot) || noop;
$log.debug('options are', opts);
// TODO use panel service to create base panel
// TODO: create divs, and pass into invocations of popTopF(div), etc.
}
// more functions
// TODO: add ref to PanelService
angular.module('onosWidget')
.factory('TableDetailService',
['$log', '$interval', '$timeout', 'FnService', 'WebSocketService',
function (_$log_, _$interval_, _$timeout_, _fs_, _wss_) {
$log = _$log_;
$interval = _$interval_;
$timeout = _$timeout_;
fs = _fs_;
wss = _wss_;
return {
buildBasePanel: buildBasePanel
};
}]);
}());
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _url = require('url');
var _url2 = _interopRequireDefault(_url);
var _qs = require('qs');
var _qs2 = _interopRequireDefault(_qs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Request is generated each time the user navigates.
* @param {string} path
* @param {object} query
* @param {object} params
*
* @property {string} path - The request path.
* @property {object} query - If the hash contains a query part, it is treated as a query string.
* @property {object} params - An object containing properties mapped to the named route “parameters”.
*/
var Request = function () {
function Request(path, query, params) {
_classCallCheck(this, Request);
this.path = path;
this.query = query;
this.params = params;
}
/**
* create a new Request object
* @param {string} path
* @param {string} query
* @param {array} keys
* @param {array} results
*/
_createClass(Request, null, [{
key: 'create',
value: function create(path, query, keys, results) {
var params = Object.create(null);
keys.forEach(function (key, index) {
return params[key.name] = results[index + 1];
});
return new Request(path, _qs2.default.parse(query), params);
}
}]);
return Request;
}();
exports.default = Request;
//# sourceMappingURL=Request.js.map
|
import content from "./content.md"
import image from "./image.png"
export default function() {
return content + image
}
|
setTimeout(function() {
$('.color-box').colpick({
layout:'hex',
submit:0,
colorScheme:'dark',
onChange:function(hsb,hex,rgb,el,bySetColor) {
$(el).css('background','#'+hex);
// Fill the text box just if the color was set using the picker, and not the colpickSetColor function.
if(!bySetColor) $(el).val(hex);
}
});
$("#batch-input").click(function () {
$("#batch").fadeIn("fast");
$(".popup-background").fadeIn("fast");
});
$(".close-popup").click(function () {
$(".popup").fadeOut("fast");
$(".popup-background").fadeOut("fast");
});
$("a.debug").click(function () {
$("#debug").css("visibility", "visible");
});
$("a.save-version").click(function () {
$("#save").fadeIn("fast");
$(".popup-background").fadeIn("fast");
});
$("a.leave").click(function () {
$("#message").fadeIn("fast");
$(".popup-background").fadeIn("fast");
});
$("a.topline").click(function () {
$("#topline").fadeIn("fast");
$("#topline").delay( 5000 ).fadeOut("fast");
});
$("a.win-edit").click(function () {
$("#markdown").fadeIn("fast");
$(".popup-background").fadeIn("fast");
})
$("a.search-button").click(function () {
$("#search").css("visibility", "visible");
})
},1000);
|
(function () {
'use strict';
angular.module('Pedal2Play')
.directive('logoutModal', function ()
{
return {
restrict: 'E',
templateUrl: 'partials/logout.modal.html'
};
});
})();
|
'use strict';
angular.module('angularPHP')
.controller('CreateorganizationCtrl', function ($scope, Session, Organizations, $timeout, $location) {
Session.require();
$scope.name = "";
$scope.msg = "";
$scope.error = "";
$scope.create = function() {
$scope.error = "";
$scope.msg = "";
Organizations.create($scope.name,function(){
$scope.msg = "The organization was created successfully";
$scope.$apply;
$timeout(function(){
$location.path("/organizations");
},2000);
},function(error){
$scope.error = error;
$scope.$apply;
});
};
});
|
//# sourceMappingURL=audio.component.js.map
|
/*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
$(function() {
var obtainFormMeta = function(formId) {
return $(formId).data();
};
$('#form-asset-update').ajaxForm({
beforeSubmit:function(){
PublisherUtils.blockButtons({
container:'updateButtons',
msg:'Updating '+PublisherUtils.resolveCurrentPageAssetType()+' instance'
});
},
success: function() {
alert('Updated the '+PublisherUtils.resolveCurrentPageAssetType()+ ' successfully');
PublisherUtils.unblockButtons({
container:'updateButtons'
});
},
error: function() {
alert('Unable to update the '+PublisherUtils.resolveCurrentPageAssetType());
PublisherUtils.unblockButtons({
container:'updateButtons'
});
}
});
var initDatePicker = function(){
console.info('init date picker');
if($(this).attr('data-render-options') == "date-time"){
var dateField = this;
$(this).DatePicker({
mode: 'single',
position: 'right',
onBeforeShow: function(el){
if($(dateField).val().replace(/^\s+|\s+$/g,"")){
$(dateField).DatePickerSetDate($(dateField).val(), true);
}
},
onChange: function(date, el) {
$(el).val((date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear());
if($('#closeOnSelect input').attr('checked')) {
$(el).DatePickerHide();
}
}
});
}
};
$('#form-asset-update input[type="text"]').each(initDatePicker);
var removeUnboundRow = function(link){
var table = link.closest('table');
if($('tr',table).length == 2){
table.hide();
}
link.closest('tr').remove();
};
$('.js-add-unbounded-row').click(function(){
var tableName = $(this).attr('data-name');
var table = $('#table_'+tableName);
var referenceRow = $('#table_reference_'+tableName);
var newRow = referenceRow.clone().removeAttr('id');
table.show().append(newRow);
$('input[type="text"]',newRow).each(initDatePicker);
});
$('.js-unbounded-table').on('click','a',function(event){
removeUnboundRow($(event.target));
});
$('#tmp_refernceTableForUnbounded').detach().attr('id','refernceTableForUnbounded').appendTo('body');
$('#tmp_refernceTableForUnbounded').remove();
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.