text
stringlengths 2
6.14k
|
|---|
// Dependencies
var _ = require('lodash');
/**
* mergeOptions
*
* @param {Object} options User configuration options for Staticly
* @param {Array} requiredProperties Required configuration options for Staticly
* @param {Object} defaultProperties Default configuration options for Staticly
* @return {Object} Complete options for Staticly
*/
var mergeOptions = function (options, requiredProperties, defaultProperties) {
'use strict';
// Make sure `options` contains `template` property
if (options.templates) {
// Make sure `options.templates` is not empty
if (!_.isEmpty(options.templates)) {
// Iterate over `options.templates` as `templateProperties` and 'templateKey'
_.forEach(options.templates, function (templateProperties, templateKey) {
// Iterate over `requiredProperties` as `property`
_.forEach(requiredProperties, function (property) {
// Make sure `templateProperties` contains all properties from `requiredProperties`
if (!templateProperties.hasOwnProperty(property)) {
// If it doesn't throw an error
throw new Error('`' + templateKey + '` does not contain the required property `' + property + '`');
}
});
// All properties exist so merge `templateProperties` with `defaultProperties`
_.defaultsDeep(templateProperties, defaultProperties);
});
// Return the validated properties
return options;
}
// `options.templates` is empty
else {
throw new Error('`options.templates` was empty');
}
}
// `options.templates` was not passed
else {
throw new Error('`options.templates` property was not passed');
}
};
// Export mergeOptions
module.exports = mergeOptions;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class TagMatcher {
constructor(corpus, position) {
let match = TagMatcher.TAG_REGEX.exec(corpus);
const tags = [];
// Gather all the existing tags.
while (match) {
// Node is a self closing tag, skip.
if (match[TagMatcher.CLOSE_FORWARD_SLASH]) {
match = TagMatcher.TAG_REGEX.exec(corpus);
continue;
}
tags.push({
name: match[TagMatcher.TAG_NAME],
type: match[TagMatcher.OPEN_FORWARD_SLASH] ? 'close' : 'open',
startPos: match.index,
endPos: TagMatcher.TAG_REGEX.lastIndex,
});
match = TagMatcher.TAG_REGEX.exec(corpus);
}
const stack = [];
const matchedTags = [];
for (let tag of tags) {
// We have to push on the stack
// if it is an open tag.
if (tag.type === 'open') {
stack.push(tag);
}
else {
// We have an unmatched closing tag,
// so try and match it with any existing tag.
for (let i = stack.length - 1; i >= 0; i--) {
const openNode = stack[i];
if (openNode.type === 'open' && openNode.name === tag.name) {
// A matching tag was found, ignore
// any tags that were in between.
matchedTags.push({
tag: openNode.name,
openingTagStart: openNode.startPos,
openingTagEnd: openNode.endPos,
closingTagStart: tag.startPos,
closingTagEnd: tag.endPos,
});
stack.splice(i);
break;
}
}
}
}
const tagsSurrounding = matchedTags.filter(n => {
return position >= n.openingTagStart && position <= n.closingTagEnd;
});
if (!tagsSurrounding.length) {
return;
}
// The first one should be the most relevant tag.
const nodeSurrounding = tagsSurrounding[0];
this.openStart = nodeSurrounding.openingTagStart;
this.openEnd = nodeSurrounding.openingTagEnd;
this.closeStart = nodeSurrounding.closingTagStart;
this.closeEnd = nodeSurrounding.closingTagEnd;
}
findOpening(inclusive) {
if (inclusive) {
return this.openStart;
}
return this.openEnd;
}
findClosing(inclusive) {
if (inclusive) {
return this.closeEnd;
}
return this.closeStart;
}
}
TagMatcher.TAG_REGEX = /\<(\/)?([^\>\<\s]+)[^\>\<]*?(\/?)\>/g;
TagMatcher.OPEN_FORWARD_SLASH = 1;
TagMatcher.TAG_NAME = 2;
TagMatcher.CLOSE_FORWARD_SLASH = 3;
exports.TagMatcher = TagMatcher;
//# sourceMappingURL=tagMatcher.js.map
|
(function ($) {
Drupal.gardens_wysiwgy = Drupal.gardens_wysiwyg || {};
Drupal.behaviors.gardens_wysiwyg = {
attach: function(context, settings) {
if (typeof CKEDITOR != 'undefined') {
// Bind events to handle enabling and disabling of the WYSIWYG.
CKEDITOR.on('instanceReady', Drupal.behaviors.gardens_wysiwyg.instanceLoaded);
}
$('.wysiwyg', context).closest('.text-format-wrapper').once('wysiwyg-tabs', function() {
var $tabs = $('<div class="wysiwyg-tab-wrapper"></div>').insertBefore($(this).find('.form-textarea-wrapper'));
$('<div class="wysiwyg-tab enable first">' + Drupal.t('WYSIWYG') + '</div>')
.bind('click', this, Drupal.behaviors.gardens_wysiwyg.tabToggle)
.appendTo($tabs);
$('<div class="wysiwyg-tab disable last">' + Drupal.t('HTML') + '</div>')
.bind('click', this, Drupal.behaviors.gardens_wysiwyg.tabToggle)
.appendTo($tabs);
});
},
instanceLoaded: function(event) {
var $wrapper = $(event.editor.container.$).closest('.text-format-wrapper');
var $original = $wrapper.find('.wysiwyg');
var $clone = $original.clone().val($original.val());
$clone.bind('change', function(event) {
$original.val($clone.val()).change();
});
$wrapper.find('.cke_toolbox').removeAttr('onmousedown').prepend($clone);
$wrapper.find('.wysiwyg-tab.enable').addClass('wysiwyg-active');
$wrapper.find('.wysiwyg-tab.disable').removeClass('wysiwyg-active');
},
tabToggle: function (event) {
if (!$(this).hasClass('wysiwyg-active')) {
$(this).closest('.text-format-wrapper').find('.wysiwyg-toggle-wrapper a').click();
}
}
};
/**
* Overides the default attach behavior for text formats without an editor
*/
Drupal.wysiwyg.editor.attach.none = function(context, params, settings) {
var $field = $('#' + params.field);
var $original = $('#' + params.trigger);
var $clone = $original.clone().val($original.val());
var $container = $('<div class="wysiwyg-none-header"></div>');
$container.append($clone).insertBefore($field);
$clone.bind('change', function(event) {
$original.val($clone.val()).change();
});
// @todo: Need to display the allowed tags here
var tags = Drupal.settings.wysiwyg_formats[$original.val()];
$('<span><b>' + Drupal.t('Allowed tags: ') + '</b>' + tags + '</span>').appendTo($container);
// Original behavior
if (params.resizable) {
var $wrapper = $field.closest('.form-textarea-wrapper');
$wrapper.addClass('resizable');
if (Drupal.behaviors.textarea.attach) {
Drupal.behaviors.textarea.attach();
}
}
$field.closest('.text-format-wrapper').find('.wysiwyg-tab.enable').removeClass('wysiwyg-active');
$field.closest('.text-format-wrapper').find('.wysiwyg-tab.disable').addClass('wysiwyg-active');
};
/**
* Overides the default detach behavior for text formats without an editor
*/
Drupal.wysiwyg.editor.detach.none = function(context, params) {
$('#' + params.field).siblings('.wysiwyg-none-header').remove();
// Original behavior
if (typeof params != 'undefined') {
var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first');
$wrapper.removeOnce('textarea').removeClass('.resizable-textarea')
.find('.grippie').remove();
}
};
})(jQuery);
|
var activityAnimComp;
var taskAnimComp;
var btnAnimComp;
function createComponents(){
activityAnimComp = Qt.createComponent("ActivityAnimationMainView.qml");
taskAnimComp = Qt.createComponent("TaskAnimationMainView.qml");
btnAnimComp = Qt.createComponent("BtnIconAnimatMainView.qml");
}
//Dialogs
///////////////Remove Dialog/////////////////
function showRemoveDialog(actId,actName){
var rmvDialog = Qt.createComponent("ui/RemoveDialogTmpl.qml");
uiConnect.removeDialog = rmvDialog.createObject(uiConnect);
uiConnect.removeDialog.activityCode = actId;
uiConnect.removeDialog.activityName = actName;
uiConnect.removeDialog.defColor = theme.textColor;
uiConnect.removeDialog.open();
}
function deleteRemoveDialog(){
uiConnect.removeDialog.destroy();
}
///////////////Clone Dialog/////////////////
function showCloneDialog(actId,actName){
var clnDialog = Qt.createComponent("ui/CloningDialogTmpl.qml");
uiConnect.cloningDialog = clnDialog.createObject(uiConnect);
uiConnect.cloningDialog.activityCode = actId;
uiConnect.cloningDialog.activityName = actName;
uiConnect.cloningDialog.defColor = theme.textColor;
uiConnect.cloningDialog.open();
}
function deleteCloneDialog(){
uiConnect.cloningDialog.destroy();
}
///////////////Calibration Dialog/////////////////
function showCalibrationDialog(){
var clbDialog = Qt.createComponent("ui/CalibrationDialogTmpl.qml");
uiConnect.calibrationDialog = clbDialog.createObject(uiConnect);
uiConnect.calibrationDialog.defColor = theme.textColor;
uiConnect.calibrationDialog.openD();
}
function deleteCalibrationDialog(){
uiConnect.calibrationDialog.destroy();
}
///////////////Desktop Dialog/////////////////
function showDesktopDialog(actId,desk){
var dskDialog = Qt.createComponent("ui/DesktopDialogTmpl.qml");
uiConnect.desktopDialog = dskDialog.createObject(uiConnect);
uiConnect.desktopDialog.disablePreviews = mainView.disablePreviewsWasForcedInDesktopDialog;
uiConnect.desktopDialog.defColor = theme.textColor;
uiConnect.desktopDialog.openD(actId,desk);
}
function deleteDesktopDialog(){
uiConnect.desktopDialog.destroy();
}
///////////////BusyIndicator Dialog/////////////////
function showBusyIndicatorDialog(){
var bsDialog = Qt.createComponent("ui/BusyIndicatorDialogTmpl.qml");
uiConnect.busyIndicatorDialog = bsDialog.createObject(uiConnect);
uiConnect.busyIndicatorDialog.startAnimation();
}
function deleteBusyIndicatorDialog(){
uiConnect.busyIndicatorDialog.destroy();
}
///////////////LiveTour Dialog/////////////////
function showLiveTourDialog(){
var lvDialog = Qt.createComponent("helptour/TourDialog.qml");
uiConnect.liveTourDialog = lvDialog.createObject(uiConnect);
uiConnect.liveTourDialog.defColor = theme.textColor;
uiConnect.liveTourDialog.openD();
allActT.forceState1();
}
function deleteLiveTourDialog(){
uiConnect.liveTourDialog.destroy();
allActT.unForceState1();
}
/////////////About Dialog//////////////////////
function showAboutDialog(){
var abDialog = Qt.createComponent("ui/AboutDialogTmpl.qml");
uiConnect.aboutDialog = abDialog.createObject(uiConnect);
uiConnect.aboutDialog.defColor = theme.textColor;
uiConnect.aboutDialog.openD();
allActT.forceState1();
}
function deleteAboutDialog(){
allActT.unForceState1();
uiConnect.aboutDialog.destroy();
}
/////////////First Run Help Tour Dialog//////////////////////
function showFirstHelpTourDialog(){
var dialog = Qt.createComponent("ui/FirstRunHelpTourTmpl.qml");
uiConnect.firstHelpTourDialog = dialog.createObject(uiConnect);
uiConnect.firstHelpTourDialog.defColor = theme.textColor;
uiConnect.firstHelpTourDialog.open();
}
function deleteFirstHelpTourDialog(){
uiConnect.firstHelpTourDialog.destroy();
}
/////////////First Run Calibration Dialog//////////////////////
function showFirstCalibrationDialog(){
var dialog = Qt.createComponent("ui/FirstRunCalibrationTmpl.qml");
uiConnect.firstCalibrationDialog = dialog.createObject(uiConnect);
uiConnect.firstCalibrationDialog.defColor = theme.textColor;
uiConnect.firstCalibrationDialog.open();
}
function deleteFirstCalibrationDialog(){
uiConnect.firstCalibrationDialog.destroy();
}
////////////////////////////////////
//Activities Animations
function animateStoppedToActive(cod, coord){
var newObject = activityAnimComp.createObject(mainView);
newObject.animateActivity(cod,coord,allWorkareas.getList());
newObject.destroy(2000);
}
function animateActiveToStop(cod, coord){
var newObject = activityAnimComp.createObject(mainView);
newObject.animateActivity(cod,coord,stoppedPanel.getList());
newObject.destroy(2000);
}
function getActivityCoord(cod,lst){
var newObject = activityAnimComp.createObject(mainView);
var res = newObject.getActivityCoord(cod,lst);
newObject.destroy();
return res;
}
//Tasks Animations
function animateDesktopToEverywhere(cid, coord, anim){
var newObject = taskAnimComp.createObject(mainView);
newObject.animateDesktopToEverywhere(cid, coord, anim);
newObject.destroy(2000);
}
function animateEverywhereToActivity(cid, coord, anim){
var newObject = taskAnimComp.createObject(mainView);
newObject.animateEverywhereToActivity(cid, coord, anim);
newObject.destroy(2000);
}
//General Animations
function animateEverywhereToXY(cid, coord1, coord2, anim){
var newObject = taskAnimComp.createObject(mainView);
newObject.animateEverywhereToXY(cid, coord1, coord2, anim);
newObject.destroy(2000);
}
//Button Animations
function animateIcon(pth,rt,wdth,coord){
var newObject = btnAnimComp.createObject(mainView);
newObject.animateIcon(pth,rt,wdth,coord);
newObject.destroy(2000);
}
|
module.exports = require( './lib/argparse' );
|
/**
* skip-link-focus-fix.js
*
* Helps with accessibility for keyboard only users.
*
* Learn more: https://github.com/Automattic/brianzotoole2.0/pull/136
*/
( function() {
var is_webkit = navigator.userAgent.toLowerCase().indexOf( 'webkit' ) > -1,
is_opera = navigator.userAgent.toLowerCase().indexOf( 'opera' ) > -1,
is_ie = navigator.userAgent.toLowerCase().indexOf( 'msie' ) > -1;
if ( ( is_webkit || is_opera || is_ie ) && document.getElementById && window.addEventListener ) {
window.addEventListener( 'hashchange', function() {
var id = location.hash.substring( 1 ),
element;
if ( ! ( /^[A-z0-9_-]+$/.test( id ) ) ) {
return;
}
element = document.getElementById( id );
if ( element ) {
if ( ! ( /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) ) {
element.tabIndex = -1;
}
element.focus();
}
}, false );
}
})();
|
"use strict";
import socket from "socket.io";
import assert from 'underscore.assert';
export default class SocketHandler {
static register(server){
this.socketRef = socket(server);
}
constructor(namespace="/"){
assert(this.socketRef !== undefined, "you must first register the server using SocketHandler.register(server)")
this.props = {
io: this.socketRef().of(namespace)
}
}
socketRef(){
return SocketHandler.socketRef;
}
_io(){ return this.props.io }
}
|
/*
* 人人商城
*
* @author ewei 狸小狐 QQ:22185157
*/
define(['jquery','core'], function($){
var comment = {
currentpage: 0, //当前页
pagesize: 10 //每页记录数
};
//获取评论
comment.get = function(){
}
//发表评论
comment.post = function(){
}
});
|
module.exports = function (config) {
config.set({
basePath: '../',
files: [
'app/lib/jquery.min.js',
'test/api/**/*.js'
],
proxies: {
'/api/': 'http://127.0.0.1/backle/api/',
'/c/': 'http://127.0.0.1/backle/c/',
'/backle/': 'http://127.0.0.1/backle/',
},
frameworks: ['jasmine'],
autoWatch: true,
browsers: ['Chrome'],
junitReporter: {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
import Geom from './base';
import { mix } from '../util/common';
import SizeMixin from './mixin/size';
import './shape/interval';
class Interval extends Geom {
getDefaultCfg() {
const cfg = super.getDefaultCfg();
cfg.type = 'interval';
cfg.shapeType = 'interval';
cfg.generatePoints = true;
return cfg;
}
constructor(cfg) {
super(cfg);
mix(this, SizeMixin);
}
init() {
super.init();
// 绑定事件
this.initEvent();
}
createShapePointsCfg(obj) {
const cfg = super.createShapePointsCfg(obj);
cfg.size = this.getNormalizedSize(obj);
return cfg;
}
clearInner() {
super.clearInner();
this.set('defaultSize', null);
}
}
Geom.Interval = Interval;
export default Interval;
|
function Dialog(config)
{
this.config = config;
this.show = show;
function show()
{
$("#dialog_text").text(config.message);
$("#dialog").dialog(
{
autoOpen : true,
width : 450,
title : config.title || null,
buttons : [
{
text : config.closeText || 'Ok',
click : function()
{
$(this).dialog("close");
}
}]
});
}
}
|
EasySocial
.require()
.library( 'dialog' )
.done(function($){
EasySocial.ajax( 'admin/controllers/languages/getLanguages', {
}).done(function() {
window.location = '<?php echo rtrim( JURI::root() , '/' );?>/administrator/index.php?option=com_easysocial&view=languages';
});
});
|
// Definizione variabile principale per contenere
// le funzioni che verranno richiamate da popup
var SZGoogleDialog =
{
local_ed:'ed',
// Funzione init per le operazioni iniziali del
// componente da eseguire in questo stesso file
init: function(ed) {
SZGoogleDialog.local_ed = ed;
tinyMCEPopup.resizeToInnerSize();
},
// Funzione cancel associata al bottone di fine
// schermata presente in ogni popup di shortcode
cancel: function(ed) {
tinyMCEPopup.close();
},
// Funzione insert per la creazione del codice
// shortcode con tutti le opzioni preimpostate
insert: function(ed) {
tinyMCEPopup.execCommand('mceRemoveNode',false,null);
// Calcolo i valori delle variabili direttamente
// dai campi del form senza sottomissione standard
var output = '';
var url = jQuery('#ID_url' ).val();
var width = jQuery('#ID_width').val();
var align = jQuery('#ID_align').val();
if (jQuery('#ID_method').val() == '1') url = '';
if (jQuery('#ID_width_auto').is(':checked')) width = 'auto';
// Composizione shortcode selezionato con elenco
// delle opzioni disponibili e valore associato
output = '[sz-gplus-comments ';
if (url != '') output += 'url="' + url + '" ';
if (width != '') output += 'width="' + width + '" ';
if (align != '') output += 'align="' + align + '" ';
output += '/]';
// Una volta eseguita la composizione del comando shotcode
// richiamo i metodi di tinyMCE per inserimento in editor
tinyMCEPopup.execCommand('mceReplaceContent',false,output);
tinyMCEPopup.close();
}
};
// Inizializzo il dialogo tinyMCE e richiamo
// anche la routine init per le operazioni iniziali
tinyMCEPopup.onInit.add(SZGoogleDialog.init,SZGoogleDialog);
|
(function() {
/**
* Extends common lists layout and logic hb-list-container with AMENAGEMENT_SPORTIF
* specific view AND logic.
*/
angular.module('hb5').directive('hbAmenagementSportifList', function () {
return {
require: '^hbListContainer',
restrict: 'A',
templateUrl : "/assets/views-compiled/amenagement_sportif/hbAmenagementSportifList.html",
controller: 'HbAmenagementSportifListController'
};
});
})();
|
jQuery(document).on('ready',function(){
jQuery('ul.img-slider>li>a').on('click', function(event){
jQuery('ul.big>li>img').hide();
var slideId = jQuery(this).attr('data-big');
jQuery('#' + slideId).show();
event.preventDefault();
});
});
|
/**
* View for carousel wrapper. Data is category display title and thumbs list
*/
define( 'videohomepage.views.carousel', [
'videopageadmin.collections.categorydata',
'shared.views.carouselthumb',
'shared.views.owlcarousel',
'videopagetool.templates.mustache'
], function(
CategoryDataCollection,
CarouselThumbView,
OwlCarouselBase,
templates
) {
'use strict';
var CarouselView = OwlCarouselBase.extend( {
initialize: function() {
var total = parseInt( this.model.get( 'total' ), 10 );
this.collection = new CategoryDataCollection( this.model.get( 'thumbnails' ).slice( 0, 24 ) );
// if the category doesn't contain more than 24 videos, don't show seemore label
if ( total > 24 ) {
this.collection.add( {
count: total,
label: this.model.get( 'seeMoreLabel' ),
url: this.model.get( 'url' ),
type: 'redirect'
} );
}
this.render();
},
template: Mustache.compile( templates.carousel ),
render: function() {
var self = this;
this.$el.html( this.template( this.model.toJSON() ) );
this.$carousel = this.$el.find( '.category-carousel' );
this.collection.each( function( categoryData ) {
var view = new CarouselThumbView( {
model: categoryData
} );
self.$carousel.append( view.$el );
} );
this.renderCarousel( {
scrollPerPage: true,
pagination: true,
paginationSpeed: 800,
slideSpeed: 800,
lazyLoad: true,
navigation: true,
rewindNav: false,
afterUpdate: function() {
self.$carousel.find( '.title a' ).ellipses( {
wordsHidden: 2
} );
self.resizeLastSlide();
},
beforeUpdate: function() {
self.$( '.ellipses' ).remove();
}
} );
return this;
},
/**
* @description Method to handle repositioning & resizing of elements based on fluid repaints
*/
resizeLastSlide: function() {
var height,
$buttons;
$buttons = this.$( '.owl-buttons div' );
height = this.$( '.owl-item' ).eq( 0 ).find( 'img' ).height();
// set the last slides height ( since it doesn't come with an image )
this.$( '.category-slide' ).height( height ).show();
// position slider arrows in correct position
$buttons.css( {
top: ( height / 2 ),
marginTop: -Math.round( $buttons.eq( 0 ).height() / 2 )
} );
}
} );
return CarouselView;
} );
|
var main = angular.module("main", [
"main.routing",
"main.templates",
"main.controllers",
"main.directives",
"main.services",
"ngCookies",
"ngMaterial",
"ngScrollSpy",
"ngSanitize"
]).config(["$mdThemingProvider",
function ($mdThemingProvider) {
// Extend the blue-grey theme with a few different colors
var lolcomp_primary = $mdThemingProvider.extendPalette('blue-grey', {
'500': '27586B'
});
var lolcomp_accent = $mdThemingProvider.extendPalette('blue-grey', {
'500': 'FFFFFF'
});
// Register the new color palette maps
$mdThemingProvider.definePalette('lolcomp_primary', lolcomp_primary);
$mdThemingProvider.definePalette('lolcomp_accent', lolcomp_accent);
// Use that theme for the primary and accent intentions
$mdThemingProvider.theme('default')
.primaryPalette('lolcomp_primary')
.accentPalette('lolcomp_accent')
}
]).run(['$http', '$cookies',
/*
* https://docs.djangoproject.com/en/1.8/ref/csrf/
*
* For this reason, there is an alternative method:
* on each XMLHttpRequest, set a custom X-CSRFToken header
* to the value of the CSRF token.
*/
function ($http, $cookies) {
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
}]);
angular.module("main.routing", ['ngRoute']);
angular.module("main.controllers", []);
angular.module("main.directives", []);
angular.module("main.services", []);
|
jQuery(document).ready(function($){
$(document).on('click', '.dot-irecommendthis',function() {
var link = $(this);
if(link.hasClass('active')) return false;
var id = $(this).attr('id'),
suffix = link.find('.dot-irecommendthis-suffix').text();
$.post(dot_irecommendthis.ajaxurl, { action:'dot-irecommendthis', recommend_id:id, suffix:suffix }, function(data){
link.html(data).addClass('active').attr('title','You already recommended this');
});
return false;
});
});
|
/*
* Path
* @author Caro.Huang
*/
(function () {
var self = caro;
/*
* get dir-path
* @param {string} path
* @return {string}
*/
self.getDirPath = function (path) {
var filename = caro.getFileName(path);
return caro.replaceLast(path, filename, '');
};
/*
* get file name in path
* @param {string} path
* @param {boolean} [getFull] if return file-name by full (with extend-name)
* @return {string}
*/
self.getFileName = function (path, getFull) {
getFull = getFull !== false;
var lastIndex = path.lastIndexOf('\\');
var lastIndex2 = path.lastIndexOf('/');
path = path.slice(lastIndex + 1);
path = path.slice(lastIndex2 + 1);
if (getFull) {
return path;
}
var extendName = caro.getExtendName(path);
return path.replace(extendName, '');
};
/*
* get extend name of file
* @param {string} path
* @param {boolean} [withDot] if return extend-name with '.'
* @return {string}
*/
self.getExtendName = function (path, withDot) {
withDot = withDot !== false;
var fileName = caro.getFileName(path);
var aFileName = caro.splitStr(fileName, '.');
if (aFileName.length === 1) {
return '';
}
var extendName = aFileName[aFileName.length - 1];
if (withDot) {
extendName = '.' + extendName;
}
return extendName;
};
})();
|
var ServerURL = "/ServerSide/";
function replaceNumbers(node) {
if (node.nodeType==3) //Text nodes only
node.nodeValue = node.nodeValue.replace(/[0-9]/g, getArabicNumber);
}
function getArabicNumber(n) {
return String.fromCharCode(1632 + parseInt(n,10));
}
function walk(node, func) {
func(node);
node = node.firstChild;
while (node) {
walk(node, func);
node = node.nextSibling;
}
};
function PrintElem(elem)
{
Popup($(elem).html());
}
function Popup(data)
{
// var mywindow = window.open('', 'my div', 'height=400,width=600');
// mywindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
// mywindow.document.write('</head><body >');
// mywindow.document.write(data);
// mywindow.document.write('</body></html>');
window.print() ;
// mywindow.print();
// mywindow.close();
// return true;
}
|
Meteor.startup(function () {
//AdventureNodes.remove({});
//AdventureMetaData.remove({});
if(AdventureMetaData.find().count() == 0){
AdventureMetaData.insert(
{
title: "Super Great Adventure",
author: "Maciek Chudek",
version: "1",
location: 'Vancouver, Canada',
published: true,
author_id: 0
}
);
AdventureMetaData.insert(
{
title: "Invisible Adventure",
author: "Maciek Chudek",
version: "1",
location: 'Vancouver, Canada',
published: false,
author_id: 0
}
);
}
});
|
/**
* @list dependencies
**/
var mocha = require('mocha');
var should = require('should');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var findOrCreate = require('../');
mongoose.connect('mongodb://localhost/findOrCreate')
mongoose.connection.on('error', function (err) {
console.error('MongoDB error: ' + err.message);
console.error('Make sure a mongoDB server is running and accessible by this application')
});
var ClickSchema = new Schema({
ip : {type: String, required: true},
hostname : {type: String, required: false}
})
ClickSchema.plugin(findOrCreate);
var Click = mongoose.model('Click', ClickSchema);
after(function(done) {
mongoose.connection.db.dropDatabase()
done();
})
describe('findOrCreate', function() {
it("should create the object if it doesn't exist", function(done) {
Click.findOrCreate({ip: '127.0.0.1'}, function(err, click) {
click.ip.should.eql('127.0.0.1')
Click.count({}, function(err, num) {
num.should.equal(1)
done();
})
})
})
it("returns the object if it already exists", function(done) {
Click.create({ip: '127.0.0.2'}, function(){
Click.findOrCreate({ip: '127.0.0.2'}, function(err, click) {
click.ip.should.eql('127.0.0.2')
Click.count({ip: '127.0.0.2'}, function(err, num) {
num.should.equal(1)
done();
})
})
})
})
it("should pass created as true if the object didn't exist", function(done) {
Click.findOrCreate({ip: '127.1.1.1'}, function(err, click, created) {
created.should.eql(true);
done();
})
})
it("should pass created as false if the object already exists", function(done) {
Click.findOrCreate({ip: '127.1.1.1'}, function(err, click, created) {
created.should.eql(false);
done();
})
})
it("should not add properties with a $ when creating the object", function(done) {
Click.findOrCreate({
ip: '127.2.2.2',
subnet: { $exists: true }
}, function(err, click, created) {
click.should.be.an.Object;
click.ip.should.eql('127.2.2.2');
should.not.exist(click.subnet);
created.should.eql(true);
done();
})
})
it("should not add properties with a $ when creating an object different from the find call", function(done) {
Click.findOrCreate({
ip: '127.3.3.3',
subnet: { $exists: true }
}, {
ip: '127.3.3.3',
subnet: { $exists: true },
hostname: 'noplacelikehome'
}, function(err, click, created) {
click.should.be.an.Object;
click.ip.should.eql('127.3.3.3');
should.not.exist(click.subnet);
click.hostname.should.eql('noplacelikehome');
created.should.eql(true);
done();
})
})
it("should support upsert", function(done) {
// Create something to upsert.
new Click({
ip: '128.0.0.0',
}).save(function (err, click) {
click.should.be.an.Object;
click.ip.should.eql('128.0.0.0');
should.equal(click.hostname, null);
// Upsert to add a hostname.
Click.findOrCreate({
ip: '128.0.0.0',
}, {
hostname: 'example.org',
}, {
upsert: true,
}, function (err, click, created) {
click.should.be.an.Object;
click.ip.should.eql('128.0.0.0');
click.hostname.should.eql('example.org');
created.should.eql(false);
// Verify that it actually was updated in the database.
Click.findOne({
ip: '128.0.0.0',
}, function (err, click) {
click.should.be.an.Object;
click.ip.should.eql('128.0.0.0');
click.hostname.should.eql('example.org');
done();
});
});
});
})
it("should return updated instance after upserting away from the condition", function(done) {
// Create something to upsert.
new Click({
ip: '128.1.1.1',
}).save(function(err, click) {
var _id = click._id;
click.should.be.an.Object;
click.ip.should.eql('128.1.1.1');
// Upsert in such a way that it no longer matches conditions.
Click.findOrCreate({
ip: '128.1.1.1',
}, {
ip: '128.1.1.2',
}, {
upsert: true,
}, function(err, click, created) {
// Should have returned upserted object even though it no
// longer matches the conditions.
click.should.be.an.Object
click.ip.should.eql('128.1.1.2');
created.should.eql(false);
// Verify that it actually was updated in the database.
Click.findById(_id, function (err, click) {
click.should.be.an.Object;
click.ip.should.eql('128.1.1.2');
done();
})
})
})
})
it("should return a Promise when passed conditions", function() {
var ret = Click.findOrCreate({
ip: '127.4.4.4',
});
ret.should.be.a.Promise;
return ret.then(function(click) {
click.should.be.an.Object;
click.doc.should.be.an.Object;
click.doc.ip.should.eql('127.4.4.4');
click.created.should.eql(true);
})
})
it("should return a Promise when passed conditions, doc", function() {
var ret = Click.findOrCreate({
ip: '127.4.4.4',
}, {
ip: '127.5.5.5',
});
ret.should.be.a.Promise;
return ret.then(function(result) {
result.should.be.an.Object;
result.doc.should.be.an.Object;
result.doc.ip.should.eql('127.4.4.4');
result.created.should.eql(false);
})
})
it("should return a Promise when passed conditions, doc, options", function() {
var ret = Click.findOrCreate({
ip: '127.4.4.4',
}, {
ip: '127.5.5.5',
}, {
upsert: true,
});
ret.should.be.a.Promise;
return ret.then(function (result) {
result.should.be.an.Object;
result.doc.should.be.an.Object;
result.doc.ip.should.eql('127.5.5.5');
result.created.should.eql(false);
})
})
})
|
var lPlaySound=1;
function PlaySound(cLink)
{
// alert(cLink);
if(lPlaySound==1)
document.getElementById("sndspan").innerHTML="<embed src='"+cLink+"' hidden=true autostart=true loop=false>";
}
function SoundLink(cLink)
{
if(lPlaySound==1)
return void(0);
else
window.open(cLink);
}
function SoundDownload(cLink)
{
window.open(cLink);
}
var soundEmbed = null;
function IsHtml5SoundSupported() {
var a = document.createElement('audio');
return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
}
function PlaySound2(SoundFile) {
if (IsHtml5SoundSupported())
PlaySoundHtml5(SoundFile);
else {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent))
PlaySoundMobile(SoundFile);
else
PlaySoundWeb(SoundFile);
}
}
function PlaySoundMobile(SoundFile) {
$(".sndaudio").unbind()
$(".sndaudio").remove();
$(".sndembed").unbind()
$(".sndembed").remove();
var sound = $("<audio class='sndaudio' autoplay='autoplay'><source src='" + SoundFile + "' type='audio/mpeg' /><embed class='sndembed' height='50' width='100' src='" + SoundFile + "' hidden='true' autostart='true' display='none'/></audio>");
$('body').append(sound);
}
function PlaySoundWeb(SoundFile) {
if (!soundEmbed) {
soundEmbed = document.createElement("embed");
soundEmbed.setAttribute("src", SoundFile);
soundEmbed.setAttribute("hidden", true);
soundEmbed.setAttribute("autostart", true);
}
else {
document.body.removeChild(soundEmbed);
soundEmbed.removed = true;
soundEmbed = null;
soundEmbed = document.createElement("embed");
soundEmbed.setAttribute("src", SoundFile);
soundEmbed.setAttribute("hidden", true);
soundEmbed.setAttribute("autostart", true);
}
soundEmbed.removed = false;
document.body.appendChild(soundEmbed);
}
function PlaySoundHtml5(SoundFile) {
var snd = new Audio(SoundFile);
snd.load();
snd.play();
}
|
var request = require("request");
var nconf = require('nconf');
nconf.file({ file: 'config/api.json' });
var urlConf = nconf.get('eu');
function apiCall(req, res, url) {
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
res.send(body);
}
res.statusCode = response.statusCode;
res.send();
});
}
exports.id = function(req, res){
urlConf = nconf.get(req.params.zone);
apiCall(req, res, urlConf.url+'/2.0/clan/info/?application_id='+urlConf.apiKey+'&clan_id='+req.params.id);
};
exports.name = function(req, res) {
urlConf = nconf.get(req.params.zone);
apiCall(req, res, urlConf.url + '/2.0/clan/list/?application_id='+urlConf.apiKey+'&search='+req.params.name);
};
|
// Include gulp.
var gulp = require('gulp');
// Include plugins.
var sassLint = require('gulp-sass-lint');
var jshint = require('gulp-jshint');
// SCSS Linting.
gulp.task('scss-lint', function() {
return gulp.src(['./assets/scss/**/*.scss'])
.pipe(sassLint())
.pipe(sassLint.format())
.pipe(sassLint.failOnError());
});
// JS Linting.
gulp.task('js-lint', function() {
return gulp.src('./assets/js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// Default Task
gulp.task('default', ['js-lint', 'scss-lint']);
|
var CacheApp = angular.module('CacheService',[]);
CacheApp.factory('CACHE', function ($cacheFactory) {
return $cacheFactory('myCache');
});
|
Drupal.userpopups = {};
Drupal.behaviors.userpopups = {
attach: function(context, settings) {
jQuery('html').once('popups-initialized').each(function(){
Drupal.userpopups.init();
});
}
};
Drupal.userpopups.init = function init(){
var login_box = jQuery('#block-userlogin');
var pass_box = jQuery('.user-pass');
login_box.append('<div class="close">Închide</div>');
pass_box.append('<div class="close">Închide</div>');
jQuery('.connect').click(function(e){
login_box.addClass('active');
e.preventDefault();
});
jQuery('.item-list li:nth-child(2)').find('a').click(function(e){
login_box.removeClass('active');
pass_box.addClass('active');
e.preventDefault();
});
jQuery('.close').click(function(e){
jQuery(this).parent().removeClass('active');
e.preventDefault();
});
};
|
$(function(){
/*$.ajax({
type: "post",
url: "",
async:false,
data: {
"userName":userName,
"pwd":pwd
},
dataType: "json",
success: function(data){
if(data['success']){
layer.msg(data['msg'], {icon: 1, time: 1000}, function () {
window.location.href = "loginController/loginSuccess"; //加载主页面
});
}else{
layer.msg(data['msg'], {icon: 2, time:1000});
}
},
error: function(data){
layer.msg(data['msg'], {icon: 2, time: 1000});
}
});*/
});
|
({"iframeTitle1":"編輯區","iframeTitle2":"編輯區框"})
|
/* This manages all the active games. Ie, it controlls who can access them and
* it sets up access when someone who is authorized asks for it. It also kills
* games when they have met their ending conditions.
* Of course, this also provides some functions for other pieces of the code to
* create games under our management.
*/
/*
active_games is a map gameid->gamestructure
gameid is simply some integer that identifies the game
gamestructure looks like this:
{
everyone_allowed: true/false
allowed_players: {'player1': true, 'player2': true, ...}
game: <the actual game datastructure>
empty_timeout: <how long the game stays empty until it vanishes in msec>
last_nonempty_time: <a time in msec>
}
*/
var ongameid = 0;
var active_games = {};
var controller_player = require('./controller_player');
var viewer_player = require('./viewer_player');
/* Call me whenever anyone tries to make a connection by emitting a 'role' */
exports.handle_connection = function(username, gameid, socket)
{
/* Make sure the game actually exists */
if(!active_games.hasOwnProperty(gameid))
{
socket.emit('role', { error: 'No game with this gameid' });
return;
}
/* Get the game's structure */
var game_structure = active_games[gameid];
/* Make sure user has permission to connect to game */
if(!game_structure.everyone_allowed &&
!game_structure.allowed_players.hasOwnProperty(username))
{
socket.emit('role', { error: 'You are not allowed in this game' });
return;
}
/* It's all good! Hook everything up! */
var controller = controller_player.controller_player(username);
var viewer = viewer_player.viewer_player(username);
controller.register_socket(socket);
viewer.register_socket(socket);
controller.register_game(game_structure.game);
game_structure.game.register_viewer(viewer);
controller.on_disconnect(function()
{
viewer.unregister_from_game();
});
socket.emit('role', true);
};
/* Call this to pass over a game to my control */
/*
par.game = the game you're passing
par.everyone_allowed = true/false controlls access
par.allowed_players = {'player1': true, ...} controlls access
par.empty_timeout = <msec> says how long until this game dies when there are no
players in it
We return a gameid you can use to access this game.
*/
exports.pass_game = function(par)
{
var gameid = ongameid++;
active_games[gameid] = par;
active_games[gameid].last_nonempty_time = Date.now();
return gameid;
};
/* Returns the game that gameid points to */
exports.get_game = function(gameid)
{
if(!active_games.hasOwnProperty(gameid))
return undefined;
return active_games[gameid].game;
}
/* Handles game timeouting */
function handle_timeouts()
{
for(gid in active_games)
{
if(active_games.hasOwnProperty(gid))
{
if(active_games[gid].game.get_numplayers() > 0)
{
active_games[gid].last_nonempty_time = Date.now();
}
else
if(Date.now()-active_games[gid].last_nonempty_time>active_games[gid].empty_timeout)
{
active_games[gid].game.cleanup();
delete active_games[gid];
}
}
}
}
setInterval(handle_timeouts, 2000);
|
'use strict';
var _ = require('lodash');
var chai = require('chai');
var rewire = require('rewire');
var DepGraph = require('dependency-graph').DepGraph;
var init = rewire('../../../core/lib/init');
var mockSrvs = require('../../mocks/services');
// Setup
chai.should();
var depGraph = new DepGraph();
module.exports = function(){
describe('Init service processing', function(){
before(function(){
mockSrvs.map(function(item){
return item.id;
}).forEach(function(srvId){
depGraph.addNode(srvId);
});
init.__set__('depGraph', depGraph);
});
it('Should return an array', function(){
mockSrvs.map(init.process).should.be.an('array');
});
it('Should return items with active property set to false', function(){
var processed = mockSrvs.map(init.process)
.every(function(item){ return !item.active; })
.should.be.true;
});
it('Should set as inactivable services with unmet dependencies', function(){
var processed = mockSrvs.map(init.process);
processed[2].activable.should.be.false;
processed[1].activable.should.be.true;
});
it('Should remove inactivable services from the dependency graph', function(){
var processed = mockSrvs.map(init.process);
Object.keys(depGraph.nodes).should.not.include(mockSrvs[2].id);
});
it('Should include all dependants of a service in the dependency graph', function(){
var processed = mockSrvs.map(init.process);
var dependants = depGraph.dependantsOf('service00');
dependants.should.include('service01', 'service03');
});
});
};
|
export { default } from 'ember-jsingla-libs/utils/feedback-message';
|
var request = require('request');
var q = require('q');
var _ = require('underscore');
module.exports = {
createOozieClient: function (options) {
var _options = options;
return {
// Get oozie status
// return {systemMode: ''}
getStatus: getStatus,
// Get oozie jobs
// return: {
// total: 0,
// workflows: [
// { status: '', user: '', createdTime: '', endTime: '', actions: [] }
//]
// }
getJobs: getJobs,
// Run oozie job (params json)
// return: {id: ''}
runJob: runJob,
// Get oozie job detailed info
getJobInfo: getJobInfo,
// Get oozie job log
getJobLog: getJobLog
}
function getJobLog(jobId) {
var uri = _options.uri + '/oozie/v1/job/' + jobId + '?show=log';
return _get(uri);
}
function getJobInfo(jobId) {
var uri = _options.uri + '/oozie/v2/job/' + jobId;
return _get(uri)
.then(function (response) {
return JSON.parse(response);
}, function (err) {
return err;
});
}
function runJob(jobParamsJson) {
var uri = _options.uri + '/oozie/v2/jobs?action=start';
var xmlParams = _.reduce(_.keys(jobParamsJson), function (context, key) {
return context + '<property><name>' + key + '</name><value>' + jobParamsJson[key] + '</value></property>';
}, '');
var oozieParamsXml = '<?xml version="1.0" encoding="UTF-8"?><configuration>' + xmlParams + '</configuration>';
return _post(uri, oozieParamsXml, false)
.then(function(response){
return JSON.parse(response);
}, function(err){
return err;
});
}
function getJobs(params) {
var uri = _options.uri + '/oozie/v2/jobs';
return _get(uri)
.then(function (response) {
return JSON.parse(response);
}, function (err) {
return err;
});
}
function getStatus() {
var uri = _options.uri + '/oozie/v2/admin/status';
return _get(uri)
.then(function (body) {
return JSON.parse(body);
}, function (err) {
return err;
});
}
function _get(uri) {
var deferred = q.defer();
request.get(uri, {
'auth': {
'user': _options.user,
'pass': _options.pass,
'sendImmediately': false
}
}, responseFunc);
function responseFunc(error, response, body) {
if (!error && response.statusCode == 200) {
deferred.resolve(body);
} else {
deferred.reject(error);
}
}
return deferred.promise;
}
function _post(uri, data, isJson) {
var deferred = q.defer();
request({
uri: uri,
method: 'POST',
headers: {
"content-type": "application/xml",
"content-length": Buffer.byteLength(data)
},
auth: {
'user': _options.user,
'pass': _options.pass,
'sendImmediately': false
},
json: isJson,
body: data
}, responseFunc);
function responseFunc(error, response, body) {
if (!error && response.statusCode == 201) {
deferred.resolve(body);
} else {
deferred.reject(error);
}
}
return deferred.promise;
}
}
};
|
//QuestBook Scoreboard
//OnDocumentReady
$(document).ready(function(){
//Initialization of global variables
var scoreIndex = 0;
var score = new Array();
//Calculates total score for players, create scoreboard array
$('.BarPlayer').each(function(i, obj) {
var objs = $(this).children();
var totalvalue = 0;
objs.filter(".BarPlayerQuest").each(function(i, obj) {
$(this).children().filter(".BarPlayerQuestScore").each(function(i, obj) {
var text = $(this).text();
totalvalue += parseInt(text.substring(0, text.length - 1));
});
});
scoreIndex++;
objs.filter(".BarPlayerScore").text(totalvalue);
score[scoreIndex] = totalvalue + "p | " + objs.filter(".BarPlayerInfo").children().filter(".BarPlayerInfoName").text();
});
//Sorting function for scoreboard
function SortFunction(a,b) {
var aVal = a.substring(0, a.indexOf("|") - 2);
var bVal = b.substring(0, b.indexOf("|") - 2);
return bVal - aVal;
}
//Sorts and draws scoreboard
score.sort(SortFunction);
for(var i = 0; i < scoreIndex; i++){
$('#ScoreBoard').append("<p class='ScoreBoardLine'>" + score[i] + "</p><br>");
}
//Fast scroll using scoreboard
$(".ScoreBoardLine").click(function() {
var text = $(this).text();
var name = text.substr(text.indexOf('|') + 2);
var playerObjs = $("body").children().filter(".BarPlayer").children().filter(".BarPlayerInfo").children().filter(".BarPlayerInfoName");
playerObjs.each(function(i, obj) {
if($(this).text() == name){
if(i > scroll + 2) {
var offset = 0; if(i >= playerObjs.size() - 3) { offset = 2; }
for(var s = 0; s < i - scroll - offset; s++){
setTimeout(function(){
$('#ArrowRight').click();
},300 + s * 300);
}
}else if(i < scroll) {
for(var s = 0; s < scroll - i; s++){
setTimeout(function(){
$('#ArrowLeft').click();
},300 + s * 300);
}
}
return(false); //break;
}
});
});
});
|
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2020 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
// RRule dependency
// lib is exported as a module, so it must be imported as a module
import { } from 'rrule'
// Fullcalendar library
require('@fullcalendar/core');
require('@fullcalendar/daygrid');
require('@fullcalendar/interaction');
require('@fullcalendar/list');
require('@fullcalendar/timegrid');
require('@fullcalendar/rrule');
require('@fullcalendar/core/main.css');
require('@fullcalendar/daygrid/main.css');
require('@fullcalendar/list/main.css');
require('@fullcalendar/timegrid/main.css');
|
$(function(){ // on dom ready
$('#cy').cytoscape({
layout: {
name: 'cose',
padding: 10
},
style: cytoscape.stylesheet()
.selector('node')
.css({
'shape': 'ellipse',
'width': 32,
'content': 'data(name)',
'text-valign': 'center',
'text-outline-width': 2,
'text-outline-color': 'green',
'background-color': 'white',
'color': '#000000'
})
.selector('edge').css({ content: 'data(name)' })
.selector(':selected')
.css({
'border-width': 3,
'border-color': '#333'
})
.selector('edge')
.css({
'opacity': 0.666,
'width': 8,
'target-arrow-shape': 'triangle',
'source-arrow-shape': 'circle',
'line-color': 'data(faveColor)',
'source-arrow-color': 'data(faveColor)',
'target-arrow-color': 'data(faveColor)'
})
.selector('edge.questionable')
.css({
'line-style': 'dotted',
'target-arrow-shape': 'diamond'
})
.selector('.faded')
.css({
'opacity': 0.25,
'text-opacity': 0
}),
elements: {
nodes: [
{ data: { id: 'j', name: 'Jerry', weight: 65, faveColor: '#6FB1FC', faveShape: 'triangle' } },
{ data: { id: 'e', name: 'Elaine', weight: 45, faveColor: '#EDA1ED', faveShape: 'ellipse' } },
{ data: { id: 'k', name: 'Kramer', weight: 75, faveColor: '#86B342', faveShape: 'octagon' } },
{ data: { id: 'g', name: 'George', weight: 70, faveColor: '#F5A45D', faveShape: 'rectangle' } }
],
edges: [
{ data: { source: 'j', target: 'e', faveColor: '#6FB1FC', strength: 90 , name:'likes'} },
{ data: { source: 'j', target: 'k', faveColor: '#6FB1FC', strength: 70 , name:'likes'} },
{ data: { source: 'j', target: 'g', faveColor: '#6FB1FC', strength: 80 , name:'likes'} },
{ data: { source: 'e', target: 'j', faveColor: '#EDA1ED', strength: 95 , name:'likes'} },
{ data: { source: 'e', target: 'k', faveColor: '#EDA1ED', strength: 60, name:'likes' }, classes: 'questionable' },
{ data: { source: 'k', target: 'j', faveColor: '#86B342', strength: 100, name:'likes' } },
{ data: { source: 'k', target: 'e', faveColor: '#86B342', strength: 100 , name:'likes'} },
{ data: { source: 'k', target: 'g', faveColor: '#86B342', strength: 100 , name:'likes'} },
{ data: { source: 'g', target: 'j', faveColor: '#F5A45D', strength: 90 , name:'likes'} }
]
},
ready: function(){
window.cy = this;
}
});
});
|
/*
* Filter Behavior
*
* Data attributes:
* - data-behavior="filter" - enables the filter plugin
*
* JavaScript API:
* $('a#someLink').filterBehavior()
*
* Dependences:
* - October Popover (october.popover.js)
*/
|
/*
* Copyright (c) 2012 Francisco Salavert (ICM-CIPF)
* Copyright (c) 2012 Ruben Sanchez (ICM-CIPF)
* Copyright (c) 2012 Ignacio Medina (ICM-CIPF)
*
* This file is part of JS Common Libs.
*
* JS Common Libs is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* JS Common Libs is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JS Common Libs. If not, see <http://www.gnu.org/licenses/>.
*/
var CellBaseManager = {
host: 'https://www.ebi.ac.uk/cellbase/webservices/rest',
version: 'v3',
get: function (args) {
var success = args.success;
var error = args.error;
var async = (_.isUndefined(args.async) || _.isNull(args.async) ) ? true : args.async;
var urlConfig = _.omit(args, ['success', 'error', 'async']);
var url = CellBaseManager.url(urlConfig);
if(typeof url === 'undefined'){
return;
}
console.log(url);
var d;
$.ajax({
type: "GET",
url: url,
dataType: 'json',//still firefox 20 does not auto serialize JSON, You can force it to always do the parsing by adding dataType: 'json' to your call.
async: async,
success: function (data, textStatus, jqXHR) {
if($.isPlainObject(data) || $.isArray(data)){
// data.params = args.params;
// data.resource = args.resource;
// data.category = args.category;
// data.subCategory = args.subCategory;
if (_.isFunction(success)) success(data);
d = data;
}else{
console.log('Cellbase returned a non json object or list, please check the url.');
console.log(url);
console.log(data)
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("CellBaseManager: Ajax call returned : " + errorThrown + '\t' + textStatus + '\t' + jqXHR.statusText + " END");
if (_.isFunction(error)) error(jqXHR, textStatus, errorThrown);
}
});
return d;
},
url: function (args) {
if (!$.isPlainObject(args)) args = {};
if (!$.isPlainObject(args.params)) args.params = {};
var version = this.version;
if(typeof args.version !== 'undefined' && args.version != null){
version = args.version
}
var host = this.host;
if (typeof args.host !== 'undefined' && args.host != null) {
host = args.host;
}
delete args.host;
delete args.version;
var config = {
host: host,
version: version
};
var params = {
of: 'json'
};
_.extend(config, args);
_.extend(config.params, params);
var query = '';
if(typeof config.query !== 'undefined' && config.query != null){
if ($.isArray(config.query)) {
config.query = config.query.toString();
}
query = '/' + config.query;
}
//species can be the species code(String) or an object with text attribute
if ($.isPlainObject(config.species)) {
config.species = Utils.getSpeciesCode(config.species.text);
}
var url = config.host + '/' + config.version + '/' + config.species + '/' + config.category + '/' + config.subCategory + query + '/' + config.resource;
url = Utils.addQueryParamtersToUrl(config.params, url);
return url;
}
};
|
import F2 from '@antv/f2';
const Shape = F2.Shape;
Shape.registerShape('point', 'with-text', {
draw: function draw(cfg, container) {
const size = cfg.size;
const x = cfg.x;
const y = cfg.y;
const circle = container.addShape('Circle', {
className: 'point',
attrs: {
x,
y,
r: size,
fill: cfg.color
}
});
const origin = cfg.origin._origin;
const text = container.addShape('Text', {
className: 'text',
attrs: {
x,
y: y - size - 4,
fill: '#000',
text: origin.name + '\n$' + origin.volumes + 'billion',
textBaseline: 'bottom',
textAlign: 'center',
fontSize: 10
}
});
return [ circle, text ];
}
});
const data = [{
name: 'Stripe',
volumes: 1.5,
x: 0.8,
y: 50
}, {
name: 'Swipely',
volumes: 2,
x: 2.5,
y: 50
}, {
name: 'Square',
volumes: 30,
x: 4.2,
y: 50
}, {
name: 'Alipay',
volumes: 150,
x: 6.7,
y: 50
}, {
name: 'Paypal',
volumes: 180,
x: 10.5,
y: 50
}];
const chart = new F2.Chart({
id: 'container',
pixelRatio: window.devicePixelRatio
});
chart.source(data, {
y: {
min: 0,
max: 100
},
x: {
max: 12,
tickInerval: 1
}
});
chart.axis(false);
chart.tooltip(false);
chart.legend(false);
chart.point()
.position('x*y')
.color('volumes', '#BAE7FF-#1890FF-#0050B3')
.size('volumes', [ 10, 50 ])
.shape('with-text');
chart.render();
|
// search box
+function ($) {
$(document).ready(function (){
var submitIcon = $('.searchbox-icon');
var inputBox = $('.searchbox-input');
var searchBox = $('.searchbox');
var isOpen = false;
submitIcon.click(function(){
if(isOpen == false){
searchBox.addClass('searchbox-open');
inputBox.focus();
isOpen = true;
} else {
searchBox.removeClass('searchbox-open');
inputBox.focusout();
isOpen = false;
}
});
submitIcon.mouseup(function(){
return false;
});
searchBox.mouseup(function(){
return false;
});
$(document).mouseup(function(){
if(isOpen == true){
$('.searchbox-icon').css('display','block');
submitIcon.click();
}
});
});
function buttonUp(){
var inputVal = $('.searchbox-input').val();
inputVal = $.trim(inputVal).length;
if( inputVal !== 0){
$('.searchbox-icon').css('display','none');
} else {
$('.searchbox-input').val('');
$('.searchbox-icon').css('display','block');
}
}
}(jQuery);
// skip link fix
+function ($) {
$( document ).ready(function() {
// bind a click event to the 'skip' link
$("#skip-link a").click(function(event){
// strip the leading hash and declare
// the content we're skipping to
var skipTo="#"+this.href.split('#')[1];
// Setting 'tabindex' to -1 takes an element out of normal
// tab flow but allows it to be focused via javascript
$(skipTo).attr('tabindex', -1).on('blur focusout', function () {
// when focus leaves this element,
// remove the tabindex attribute
$(this).removeAttr('tabindex');
}).focus(); // focus on the content container
});
});
}(jQuery);
|
MaybeLater.Data = function() {
var dataRecord = Ext.data.Record.create([
{name: 'name', mapping: 'fields.name'},
{name: 'description', mapping: 'fields.notes'},
{name: 'effort', type: 'int', mapping: 'fields.effort'},
{name: 'priority', type: 'int', mapping: 'fields.priority'},
{name: 'startDate', type: 'date', dateFormat: 'n/j h:ia', mapping:'fields.startDate'},
{name: 'dueDate', type: 'date', dateFormat: 'n/j h:ia', mapping:'fields.dueDate'}
]);
/*var data = [
['Something','raaar',1],
['Thingsome','',2],
['Another Thing','Stuff',5]
];
var reader = new Ext.data.ArrayReader({}, dataRecord);*/
var reader = new Ext.data.JsonReader({
root: 'tasks',
totalProperty: 'total',
//record: 'item' //the XML delimiter tag for each record (row of data)
},
dataRecord
);
var dataStore;
return {
createStore: function() {
dataStore = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: '/v2/tasks',
method: 'GET'
}),
sortInfo:{field: 'priority', direction: "DESC"},
//data: data,
reader: reader
});
dataStore.load();
return dataStore;
}
};
}();
|
import { getCurrentUser } from '@automattic/calypso-analytics';
import { isAdTrackingAllowed, refreshCountryCodeCookieGdpr } from 'calypso/lib/analytics/utils';
import { debug, isWpcomGoogleAdsGtagEnabled, isFloodlightEnabled, TRACKING_IDS } from './constants';
import { recordParamsInFloodlightGtag } from './floodlight';
import { loadTrackingScripts } from './load-tracking-scripts';
// Ensure setup has run.
import './setup';
export async function adTrackSignupStart( flow ) {
await refreshCountryCodeCookieGdpr();
if ( ! isAdTrackingAllowed() ) {
debug( 'adTrackSignupStart: [Skipping] ad tracking is not allowed' );
return;
}
await loadTrackingScripts();
const currentUser = getCurrentUser();
// Floodlight.
if ( isFloodlightEnabled ) {
debug( 'adTrackSignupStart: [Floodlight]' );
recordParamsInFloodlightGtag( {
send_to: 'DC-6355556/wordp0/pre-p0+unique',
} );
}
if ( isFloodlightEnabled && ! currentUser && 'onboarding' === flow ) {
debug( 'adTrackSignupStart: [Floodlight]' );
recordParamsInFloodlightGtag( {
send_to: 'DC-6355556/wordp0/landi00+unique',
} );
}
// Google Ads.
if ( isWpcomGoogleAdsGtagEnabled && ! currentUser && 'onboarding' === flow ) {
const params = [
'event',
'conversion',
{
send_to: TRACKING_IDS.wpcomGoogleAdsGtagSignupStart,
},
];
debug( 'adTrackSignupStart: [Google Ads Gtag]', params );
window.gtag( ...params );
}
}
|
jQuery(document).ready(function($){
element_ui_textarea={
init_ui_textarea:function(){
Joomla_post.list_function_run_befor_submit.push(element_ui_textarea.update_data);
},
update_data:function(data_submit){
$(".block-item.block-item-textarea").each(function(){
textarea=$(this);
name_textarea=textarea.attr('name');
data_submit[name_textarea]=textarea.val();
});
return data_submit;
}
};
element_ui_textarea.init_ui_textarea();
});
|
// EPI: 9.9 sort a stack in descending order
import Stack from "./stack"
var s = new Stack(10)
// populate the stack
s.push(6)
s.push(7)
s.push(3)
s.push(2)
s.push(1)
s.push(9)
function Insert(e) {
if (s.empty() == true || s.peek(0) <= e) {
s.push(e)
} else {
let f = s.pop()
Insert(e)
s.push(f)
}
}
function Sort() {
if (s.empty() != true) {
let e = s.pop()
// pop all the elements of the stack
Sort()
// insert e in the correct order
Insert(e)
}
}
Sort(s)
console.log("stack:", s.toString())
|
http://jsfiddle.net/fusioncharts/jJM7e/
http://jsfiddle.net/gh/get/jquery/1.9.1/sguha-work/fiddletest/tree/master/fiddles/Gauge/Hover-Effects/Configuring-dial-hover-effects-in-angular-gauge_159/
|
$(document).ready(function () {
$('#feedback-container #close-feedback').click(function () {
hideFeedback();
return false;
});
$('textarea[name=comments]').focus(function () {
if ($(this).val() == 'Additional comments') $(this).val('');
});
$('textarea[name=comments]').blur(function () {
if ($(this).val() == '') $(this).val('Additional comments');
});
var informative_content = '';
var well_organized = '';
var performance_speed = '';
var summary = '';
var description = '';
var url = '';
var name = '';
var uid = '';
var email = '';
var form = '';
$("input:radio[name=content-feelings]").click(function () {
informative_content = $(this).val();
});
$("input:radio[name=design-feelings]").click(function () {
well_organized = $(this).val();
});
$("input:radio[name=technical-feelings]").click(function () {
performance_speed = $(this).val();
});
$('#feedback-container .button').click(function () {
form = $('input[name=form]').val();
summary = $('input[name=page_title]').val();
description = $('textarea[name=comments]').val();
if (description == 'Additional comments') description = '';
url = $('input[name=url]').val();
name = $('input[name=name]').val();
uid = $('input[name=uid]').val();
email = $('input[name=email]').val();
var dataString = 'form=' + encodeURI(form) + '&informative_content=' + encodeURI(informative_content) + '&well_organized=' + encodeURI(well_organized) + '&performance_speed=' + encodeURI(performance_speed) + '&summary=' + encodeURI(summary) + '&description=' + encodeURI(description) + "&url=" + encodeURI(url) + "&name=" + encodeURI(name) + "&uid=" + encodeURI(uid) + "&email=" + encodeURI(email);
$.ajax({
type:"POST",
url:"/feedback.php",
data:dataString,
success:function (data) {
$('#feedback-bar .sub-form-element').find('*').fadeOut();
$('#feedback-bar .sub-form-element').append('<p class="thanks">Thanks for your feedback!</p>');
setTimeout(function () {
hideFeedback();
}, 1200);
setTimeout(function () {
$('#feedback-bar .sub-form-element').find('*').delay(3500).show();
reset_form($('#feedback-container'));
}, 2500);
}
});
return false;
});
$('#feedback-container #feedback-button').click(function () {
$('#feedback-bar, #feedback-container #feedback-nav').addClass('bar-active')
return false;
});
function hideFeedback() {
$('#feedback-bar, #feedback-container #feedback-nav').removeClass('bar-active');
}
});
function reset_form(form) {
$('.thanks', form).remove();
$("input:radio[name=content-feelings]", form).attr('checked', false);
$("input:radio[name=design-feelings]", form).attr('checked', false);
$("input:radio[name=technical-feelings]", form).attr('checked', false);
$("div.radio span").removeClass('checked');
$('textarea[name=comments]').val('Additional comments');
}
|
$(document).ready(function() {
//alert("Adding accordion js");
//ACCORDION BUTTON ACTION
$('div.accordionButton').click(function() {
$('div.accordionContent').slideUp('normal');
$(this).next().slideDown('normal');
});
//HIDE THE DIVS ON PAGE LOAD
$("div.accordionContent").hide();
$("#accordionNav").show();
});
|
'use strict';
angular.module('pizzaApp', [])
.factory('shopCartService', function(){
var factoryInstance = {};
var pizzaListCart = [];
factoryInstance.addPizzaToCart = function(pizza) {
pizzaListCart.push({name: pizza.name, price: pizza.price});
};
factoryInstance.getCart = function(){
return pizzaListCart;
};
return factoryInstance;
})
.controller('shopListController', function($scope, $http, shopCartService) {
$scope.buy = function ( pizza ) {
shopCartService.addPizzaToCart(pizza);
};
$http({method: 'GET', url: '/pizzas.json'}).
success(function(data) {
$scope.pizzaList = data;
}
);
$scope.orderValue = 'name';
})
.controller('shopCartController', function($scope, shopCartService){
$scope.shopCartList = shopCartService.getCart();
$scope.totalPrice = function () {
var total = 0;
angular.forEach($scope.shopCartList, function (pizza){
total += pizza.price;
});
return total;
};
$scope.removeFromCart = function (idx){
$scope.shopCartList.splice(idx,1);
};
});
|
define(function() {
return (/^margin/);
});
|
console.log("Inside main.js");
$('#modal1').modal('show');
|
$(document).ready(function(){
//Architect details event listener
$('.view-details').on('click', function(event){
var targetElement = event.target;
var container = targetElement.parentElement.parentElement;
$(container).find('.details').each(function (index, el){
if($(el).is(':visible')) {
$(el).fadeOut();
targetElement.innerHTML = "View Details";
} else {
$(el).fadeIn();
targetElement.innerHTML = "Hide Details";
}
});
});
//Featurette image scroll-triggered fadeIn
//utilizing Waypoints plug-in: http://imakewebthings.com/waypoints/
var waypoints = $('#waypoint-one').waypoint({
handler: function() {
console.log("success!");
$('#featurette-img-one').fadeIn(3000);
},
offset: '25%'
});
var waypoints2 = $('#waypoint-two').waypoint({
handler: function() {
console.log("success!");
$('#featurette-img-two').fadeIn(3000);
},
offset: '25%'
});
var waypoints3 = $('#waypoint-three').waypoint({
handler: function() {
console.log("success!");
$('#featurette-img-three').fadeIn(3000);
},
offset: '10%'
});
});
|
showWord(["a. ","Chalè ki soti nan fon tè.<br>"])
|
var StrathconaIndustrialPark = {
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-113.46642123578165,
53.47412224209839
],
[
-113.46648208645576,
53.46859869549553
],
[
-113.46649569323652,
53.46531601771038
],
[
-113.47014649015357,
53.4652732256213
],
[
-113.47157521723412,
53.46533780195803
],
[
-113.47289021960485,
53.46545012280132
],
[
-113.47402660364719,
53.46564067459655
],
[
-113.47500943119933,
53.46587960672406
],
[
-113.47855707870495,
53.466986863381706
],
[
-113.47958076440827,
53.4672324158772
],
[
-113.48120525509398,
53.467513764807755
],
[
-113.48221985352005,
53.46763943005361
],
[
-113.48334968731102,
53.46768979451687
],
[
-113.48604203384217,
53.467695644915615
],
[
-113.49206420934239,
53.46773852921333
],
[
-113.49204227670712,
53.47356430546532
],
[
-113.49173480012578,
53.47356448851294
],
[
-113.49114992991672,
53.473563838501605
],
[
-113.49087603254064,
53.480412979933035
],
[
-113.4904211705587,
53.48041358688539
],
[
-113.48609982925977,
53.48040967387228
],
[
-113.48473422538143,
53.480438269938325
],
[
-113.48303397314643,
53.480525529911
],
[
-113.4794009276228,
53.480784255412644
],
[
-113.47588067627781,
53.48121341787963
],
[
-113.4732332439051,
53.48157516909652
],
[
-113.47061937922555,
53.48203035806713
],
[
-113.46646668984822,
53.48283958626473
],
[
-113.4663297713554,
53.48103245350947
],
[
-113.46626675900859,
53.478885849804726
],
[
-113.46642123578165,
53.47412224209839
]
]
]
},
"type": "Feature",
"properties": {
"name": "Strathcona Industrial Park",
"number": "6700",
"coordinate": "-1.13478e+002",
"coords": "53.4738 , -113.478",
"otherCoord": "5.34738e+001",
"area_km2": "2.67695602958339"
}
}
]
};
|
<script type="text/javascript" src=".../Style%20Library/Scripts/jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//After adding our webparts to the page, we hide all webparts, in this example I have
//added 4 image libs to the page with promoted links on the top. This is to avoid using
//folders in our libraries and now allows users to easily navigate between the 4 on the page.
document.getElementById('MSOZoneCell_WebPartWPQ5').style.display = 'none'; //Lib 1 - Pongo
document.getElementById('MSOZoneCell_WebPartWPQ4').style.display = 'none'; //Lib 2 - Gango
document.getElementById('MSOZoneCell_WebPartWPQ7').style.display = 'none'; //Lib 3 - Gango
document.getElementById('MSOZoneCell_WebPartWPQ3').style.display = 'none'; //Lib 4 - Bravo
//Page Name That The Promoted Links Are Found On, Only Enter The Page Name
var SitePageName = "Gallery.aspx" + "#";
//Remove The Properties For The Promoted Links Tile Click Events
//Could relace with "id^=Tile_WPQ2" to impact all tiles and then just repeat
//the last line to hide each individual webpart with its ID but I prefered to
//do them individually myself (was easier during debugging), dont forget to
//replace the WebPart div ID that you want hidden in the clickaction of the
//below code, each function has a click action in the last line where we
//get the ID of the webpart element to show/hide.
//Gango - ID of Promoted Links Tile (Inspect Element)
$('a[id^=Tile_WPQ2_1_3]').each(function(){
$(this).removeAttr('onclick');
$(this).removeAttr("href");
$(this).removeAttr("hrefAction");
$(this).attr('href', SitePageName);
//Add WebPart ID Below/Replace "MSOZoneCell_WebPartWP..."
$(this).attr("clickaction", "PreventDefaultNavigation(); STSNavigate(document.getElementById('MSOZoneCell_WebPartWPQ4').style.display = 'block';); return false;");
});
//Figo - ID of Promoted Links Tile (Inspect Element)
$('a[id^=Tile_WPQ2_2_3]').each(function(){
$(this).removeAttr('onclick');
$(this).removeAttr("href");
$(this).removeAttr("hrefAction");
$(this).attr('href', SitePageName);
//Add WebPart ID Below/Replace "MSOZoneCell_WebPartWP..."
$(this).attr("clickaction", "PreventDefaultNavigation(); STSNavigate(document.getElementById('MSOZoneCell_WebPartWPQ7').style.display = 'block';); return false;");
});
//Pongo - ID of Promoted Links Tile (Inspect Element)
$('a[id^=Tile_WPQ2_3_3]').each(function(){
$(this).removeAttr('onclick');
$(this).removeAttr("href");
$(this).removeAttr("hrefAction");
$(this).attr('href', SitePageName);
//Add WebPart ID Below/Replace "MSOZoneCell_WebPartWP..."
$(this).attr("clickaction", "PreventDefaultNavigation(); STSNavigate(document.getElementById('MSOZoneCell_WebPartWPQ5').style.display = 'block';); return false;");
});
//Bravo - ID of Promoted Links Tile (Inspect Element)
$('a[id^=Tile_WPQ2_4_3]').each(function(){
$(this).removeAttr('onclick');
$(this).removeAttr("href");
$(this).removeAttr("hrefAction");
$(this).attr('href', SitePageName);
//Add WebPart ID Below/Replace "MSOZoneCell_WebPartWP..."
$(this).attr("clickaction", "PreventDefaultNavigation(); STSNavigate(document.getElementById('MSOZoneCell_WebPartWPQ3').style.display = 'block';); return false;");
});
});
</script>
<script type="text/javascript">
$(function () {
//Use The Title Of The Promoted Links Tile To Target Our Code/Action A Event
$("a[id^=Tile_WPQ]").each(function () {
$(this).click(function () {
var linkTitle = $(this).find('li[title]').attr('title');
switch (linkTitle)
{
//Replace Title With Your Approproprite Title (Spaces can be included)
//Replace ElementID With your Appropriate WebPart Element ID
case "Gango":
{
HideAllWebParts();
document.getElementById('MSOZoneCell_WebPartWPQ4').style.display = 'block';
break;
}
//Replace Title With Your Approproprite Title (Spaces can be included)
//Replace ElementID With your Appropriate WebPart Element ID
case "Figo":
{
HideAllWebParts();
document.getElementById('MSOZoneCell_WebPartWPQ7').style.display = 'block';
break;
}
//Replace Title With Your Approproprite Title (Spaces can be included)
//Replace ElementID With your Appropriate WebPart Element ID
case "Pongo":
{
HideAllWebParts();
document.getElementById('MSOZoneCell_WebPartWPQ5').style.display = 'block';
break;
}
//Replace Title With Your Approproprite Title (Spaces can be included)
//Replace ElementID With your Appropriate WebPart Element ID
case "Bravo":
{
HideAllWebParts();
document.getElementById('MSOZoneCell_WebPartWPQ3').style.display = 'block';
break;
}
//Error Handling If Nothing Was Found
default: alert('No Corresponding Option Selected...Contact Your Administrator');
}
});
});
});
function HideAllWebParts(){
//Replace ElementID With your Appropriate WebPart Element ID to Hide Elements when Changing your Option
document.getElementById('MSOZoneCell_WebPartWPQ5').style.display = 'none'; //Pongo Promoted Links Tile
document.getElementById('MSOZoneCell_WebPartWPQ4').style.display = 'none'; //Gango Promoted Links Tile
document.getElementById('MSOZoneCell_WebPartWPQ7').style.display = 'none'; //Figo Promoted Links Tile
document.getElementById('MSOZoneCell_WebPartWPQ3').style.display = 'none'; //Bravo Promoted Links Tile
};
</script>
|
jQuery(function($){
/*-----------------------------------------------------------------------------------*/
/* Sortable
/*-----------------------------------------------------------------------------------*/
$('.wolf-repeatable-add').click(function() {
field = $(this).closest('td').find('.wolf-custom-repeatable li:last').clone(true);
fieldLocation = $(this).closest('td').find('.wolf-custom-repeatable li:last');
$('input', field).val('').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
})
field.insertAfter(fieldLocation, $(this).closest('td'))
return false;
});
$('.wolf-repeatable-remove').click(function(){
field = $('.wolf-custom-repeatable li');
if(field.length>1){
$(this).parent().remove();
}
return false;
});
$('.wolf-custom-repeatable').sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.sort'
});
});
|
/**
* @challenge SHORTEST REPETITION
* @see https://www.codeeval.com/open_challenges/107/
* @author dominic england
*/
var fs = require("fs"),
regex = /(.+?)(\1|$)/;
fs.readFileSync(process.argv[2]).toString().split('\n')
// Node on codeeval doesn't seem to support arrow functions?
//
//.forEach((statement) => statement !== "" ? console.log(statement.match(regex)[1].length) : false);
.forEach((statement) => statement !== "" ? console.log(statement.match(regex)[1].length) : false);
|
jQuery(document).ready(function($) {
// Code here will be executed on document ready. Use $ as normal.
$('.archive .post').hover(function(){
$(this).find('h1').slideToggle();
})
});
|
$(document).ready(function() {
$('#feedbackForm input')
.not('.optional,.no-asterisk')
.after('<span class="glyphicon glyphicon-asterisk form-control-feedback"></span>');
$("#feedbackSubmit").click(function() {
var $btn = $(this);
$btn.button('loading');
contactForm.clearErrors();
//do a little client-side validation -- check that each field has a value and e-mail field is in proper format
var hasErrors = false;
$('#feedbackForm input,textarea').not('.optional').each(function() {
var $this = $(this);
if (($this.is(':checkbox') && !$this.is(':checked')) || !$this.val()) {
hasErrors = true;
contactForm.addError($(this));
}
});
var $email = $('#email');
if (!contactForm.isValidEmail($email.val())) {
hasErrors = true;
contactForm.addError($email);
}
//if there are any errors return without sending e-mail
if (hasErrors) {
$btn.button('reset');
return false;
}
//send the feedback e-mail
$.ajax({
type: "POST",
url: "library/sendmail.php",
data: $("#feedbackForm").serialize(),
success: function(data) {
contactForm.addAjaxMessage(data.message, false);
contactForm.clearForm();
//get new Captcha on success
$('#captcha').attr('src', 'library/vender/securimage/securimage_show.php?' + Math.random());
},
error: function(response) {
contactForm.addAjaxMessage(response.responseJSON.message, true);
},
complete: function() {
$btn.button('reset');
}
});
return false;
});
$('#feedbackForm input').change(function () {
var asteriskSpan = $(this).siblings('.glyphicon-asterisk');
if ($(this).val()) {
asteriskSpan.css('color', '#00FF00');
} else {
asteriskSpan.css('color', 'black');
}
});
});
//namespace as not to pollute global namespace
var contactForm = {
isValidEmail: function (email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
},
clearErrors: function () {
$('#emailAlert').remove();
$('#feedbackForm .help-block').hide();
$('#feedbackForm .form-group').removeClass('has-error');
},
clearForm: function () {
$('.glyphicon-asterisk').css('color', 'black');
$('#feedbackForm input,textarea').val("");
},
addError: function ($input) {
$input.siblings('.help-block').show();
$input.parent('.form-group').addClass('has-error');
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
|
var HtmlWebpackPlugin = require("html-webpack-plugin"),
autoprefixer = require("autoprefixer"),
path = require("path");
module.exports = {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
},{
test: /\.png$/,
loader: "url-loader?limit=100000"
},{
test: /\.jpg$/,
loader: "file-loader"
},{
test: /\.css$/,
loader: "style!css!postcss-loader"
},{
test: /\.less$/,
loader: "css!less"
}],
postcss: [
autoprefixer({browsers: ['last 4 versions', 'iOS 6', 'Android 2.1']})
],
indexPagePlugin: new HtmlWebpackPlugin({
inject: true,
title: 'himynameisdave',
filename: 'index.html',
template: './src/index_template.html'
})
};
|
/*
* Copyright (c) 2009, 2010 and 2011 Frank G. Bennett, Jr. All Rights
* Reserved.
*
* The contents of this file are subject to the Common Public
* Attribution License Version 1.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://bitbucket.org/fbennett/citeproc-js/src/tip/LICENSE.
*
* The License is based on the Mozilla Public License Version 1.1 but
* Sections 14 and 15 have been added to cover use of software over a
* computer network and provide for limited attribution for the
* Original Developer. In addition, Exhibit A has been modified to be
* consistent with Exhibit B.
*
* Software distributed under the License is distributed on an “AS IS”
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is the citation formatting software known as
* "citeproc-js" (an implementation of the Citation Style Language
* [CSL]), including the original test fixtures and software located
* under the ./std subdirectory of the distribution archive.
*
* The Original Developer is not the Initial Developer and is
* __________. If left blank, the Original Developer is the Initial
* Developer.
*
* The Initial Developer of the Original Code is Frank G. Bennett,
* Jr. All portions of the code written by Frank G. Bennett, Jr. are
* Copyright (c) 2009, 2010 and 2011 Frank G. Bennett, Jr. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Affero General Public License (the [AGPLv3]
* License), in which case the provisions of [AGPLv3] License are
* applicable instead of those above. If you wish to allow use of your
* version of this file only under the terms of the [AGPLv3] License
* and not to allow others to use your version of this file under the
* CPAL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the
* [AGPLv3] License. If you do not delete the provisions above, a
* recipient may use your version of this file under either the CPAL
* or the [AGPLv3] License.”
*/
dojo.provide("citeproc_js.sys_stdrhino_locale");
doh.register("citeproc_js.sys_stdrhino_locale", [
function testMakeXmlFromPlainXml(){
var sys = new StdRhinoTest();
var obj = new CSL.Engine(sys,'<style></style>');
var alreadyxml = new XML('<style><citation><text/></citation></style>');
var res = obj.sys.xml.makeXml(alreadyxml);
default xml namespace = "http://purl.org/net/xbiblio/csl"; with({});
doh.assertEqual("text", res..text.localName());
},
function testMakeXml(){
var sys = new StdRhinoTest();
var obj = new CSL.Engine(sys,'<style></style>');
var res = obj.sys.xml.makeXml('<style><citation><text/></citation></style>');
default xml namespace = "http://purl.org/net/xbiblio/csl"; with({});
doh.assertEqual("text", res..text.localName());
},
function testSetAccess(){
var sys = new StdRhinoTest();
var obj = new CSL.Engine(sys,"<style></style>");
var myxml = sys.xml.makeXml( sys.retrieveLocale("af-ZA") );
obj.localeSet(myxml,"af-ZA","af-ZA");
var myxml = sys.xml.makeXml( sys.retrieveLocale("de-DE") );
obj.localeSet(myxml,"de-DE","de-DE");
doh.assertEqual("und", obj.locale["de-DE"].terms["and"]["long"]);
},
function testSetLocaleStringValue(){
var sys = new StdRhinoTest();
var obj = new CSL.Engine(sys,"<style></style>");
var myxml = sys.xml.makeXml( sys.retrieveLocale("de-DE") );
obj.localeSet(myxml,"de-DE","de-DE");
doh.assertEqual("und", obj.locale["de-DE"].terms["and"]["long"]);
},
function testSetLocaleEmptyValue(){
var sys = new StdRhinoTest();
var obj = new CSL.Engine(sys,"<style></style>");
doh.assertEqual("and", obj.locale["en-US"].terms["and"]["long"]);
},
function testLocaleGlobalWorksAtAll(){
try {
var sys = new RhinoTest();
var obj = new CSL.Engine(sys,"<style></style>");
var myxml = sys.xml.makeXml( sys.retrieveLocale("de-DE") );
obj.localeSet(myxml,"de-DE","de-DE");
var res = "Success";
} catch (e){
var res = e;
}
doh.assertEqual("Success", res);
doh.assertNotEqual("undefined", typeof obj.locale["de-DE"].terms);
},
]);
|
function _QueryPainter(drawingPanel_ID){
if(drawingPanel_ID == undefined || drawingPanel_ID.length == 0){
console.error("drawing_panel: [" + drawingPanel_ID + "] is inappropriate!");
}
const STATEMENT_MARGIN = 10;
var offset_x = 0;
var offset_y = 0;
var drawingPanel = $("#" + drawingPanel_ID);
var selectPainter = new _SelectPainter(drawingPanel);
var fromPainter = new _FromPainter(drawingPanel);
var wherePainter = new _WherePainter(drawingPanel);
this.paint = function(queryInfo){
if(queryInfo == undefined){
console.error("queryInfo: [" + queryInfo + "] is inappropriate!");
}
selectPainter.paint(queryInfo.select_info_list);
fromPainter.paint(queryInfo.from_info_list);
if(queryInfo.where_info != undefined){
wherePainter.paint(queryInfo.where_info);
}
}
}
|
jQuery(document).ready(function(){
jQuery('.ksm-reviews-add').on('click', function(e){
e.preventDefault();
if (jQuery('.ksm-reviews-add-form').is(':visible'))
{
jQuery('.ksm-reviews-add-form').slideUp(500);
}
else
{
jQuery('.ksm-reviews-add-form').slideDown(500);
}
});
jQuery('.ksm-reviews-add-form-row-rate img').on('click', function() {
var review = jQuery(this).parents('.ksm-reviews-add-form');
var rate = jQuery(this).data().rate;
review.find('input[name="rate"]').val(rate);
review.find('.ksm-reviews-add-form-row-rate img').attr('src', URI_ROOT + 'components/com_ksenmart/images/star2-small.png');
for (var k = 1; k <= rate; k++)
{
review.find('.ksm-reviews-add-form-row-rate img[data-rate="' + k + '"]').attr('src', URI_ROOT + 'components/com_ksenmart/images/star-small.png');
}
});
});
|
showWord(["","refè menm erè, menm krim, repete yon aksyon."
])
|
showWord(["a. ","ki lwen.<br>"])
|
Meteor.publish("learnings", function(limit) {
return Learnings.find({},
{sort: {created_at: -1}, limit: limit});
});
Meteor.publish("learningsByUserId", function(limit, userId) {
check(userId, String);
if(this.userId){
return Learnings.find({userId: userId},
{sort: {created_at: -1}, limit: limit});
}else{
this.ready();
}
});
Meteor.publish("learningsByHangoutId", function(limit, hangoutId) {
check(hangoutId, String);
check(limit, Number);
return Learnings.find({hangout_id: { $exists: true, $not: {$ne: hangoutId } }},
{sort: {created_at: -1}, limit: limit});
});
Meteor.publish("learningsByStudyGroupId", function(limit, studyGroupId) {
check(studyGroupId, String);
check(limit, Number);
return Learnings.find({study_group_id: { $exists: true, $not: {$ne: studyGroupId } }},
{sort: {created_at: -1}, limit: limit});
});
|
// Globals
// FCEs for current graph
var currentFCEs = 0;
var currentFCEs100 = 0;
var currentFCEs200 = 0;
var currentFCEs300 = 0;
var currentFCEs400 = 0;
var currentFCEsMAT = 0;
// Combined FCEs selected for all graphs
var totalFCEs = 0;
var activeFocus = ''; // The active focus from the 'Focuses' tab.
var timeouts = []; // All timeouts. Used to remove timeouts later on
var nodes = []; // List of all nodes
var graphs = []; // List of graphs (jsons) that are parsed in the database
$(document).ready(function () {
'use strict';
var urlSpecifiedGraph = getURLParameter('dept');
// HACK: Temporary workaround for giving the statistics department a link to our graph.
// Should be replaced with a more general solution.
var active;
if (urlSpecifiedGraph === 'sta') {
active = '2';
} else if (urlSpecifiedGraph !== null) {
active = '1';
} else {
active = getCookie('active-graph');
}
if (active !== '') {
loadGraph(active);
} else {
loadGraph('1');
}
$('#fcecount').hide();
});
/**
* Retrieves an SVG file.
* @param {string} filepath The relative filepath of the graph
* @returns {string} An SVG string representing a graph.
*/
function getRemote(filepath) {
'use strict';
var SVG = $.ajax({
type: 'GET',
url: filepath,
async: false
}).responseText;
$('#graph').append(SVG);
}
|
Ext.define('Surveyportal.view.querybuildernewmodel.queryentitiesjoins.QueryEntitiesModel', {
extend: 'Ext.data.Model',
fields: [{
name: 'entId',
type: 'string'
},{
name: 'entName',
type: 'string'
},{
name: 'tableName',
type: 'string'
},{
name: 'entAlias',
type: 'string'
},
{
name: 'joins',
type:'auto'
},
{
name: 'selectAll',
type:'boolean'
},
{
name:'entFields',
type:'auto'
},
{
name:'entFieldsConfig',
type:'auto'
}
]
});
|
/////////////////////////////////////////////////////////////////////////////////
//
// Jobbox WebGUI
// Copyright (C) 2014-2015 Komatsu Yuji(Zheng Chuyu)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
Ext.define('Jobbox.view.common.Condition', {
alias: 'widget.commonCondition',
extend: 'Ext.grid.Panel',
title: 'Condition',
columns: {
items: [{
text: I18n.t('views.column.kind'),
dataIndex: 'kind',
width: 100,
editable: false,
editor: {
xtype: 'combobox',
editable: false,
store: CONDITION_KIND_DATA,
},
renderer: function(value) {
return JobboxFindRecord(CONDITION_KIND_DATA, value);
}
}, {
text: I18n.t('views.condition.cond'),
dataIndex: 'cond',
width: 200,
editor: {
xtype: 'textfield',
allowBlank: false,
},
}, {
xtype: 'checkcolumn',
text: I18n.t('views.condition.negative'),
dataIndex: 'negative',
editable: false,
width: 70,
}]
},
plugins: [{
ptype: 'cellediting',
clicksToEdit: 1,
pluginId: 'cellediting_condition'
}],
bbar: [{
text: I18n.t('views.button.add'),
icon: location.pathname + '/images/icons/add.png',
disabled: true,
action: 'add_condition'
}, '-', {
text: I18n.t('views.button.delete'),
icon: location.pathname + '/images/icons/delete.png',
disabled: true,
action: 'delete_condition'
}, '->', {
text: I18n.t('views.button.clear'),
icon: location.pathname + '/images/icons/bin_closed.png',
disabled: true,
action: 'clear_condition'
}],
initComponent: function() {
this.callParent();
}
});
|
var searchData=
[
['bmzs',['BMZS',['../namespaceSpecific.html#adf764cbdea00d65edcd07bb9953ad2b7a924065a2d0165fe2d439a98d5170ccf0',1,'Specific']]],
['bmzu',['BMZU',['../namespaceSpecific.html#adf764cbdea00d65edcd07bb9953ad2b7a3eb23b9a9f4f17e2384b00c30ef95715',1,'Specific']]]
];
|
// ChatWebAPIUtils.js
var ChatServerActionCreators = require('../actions/ChatServerActionCreators');
// !!! Please Note !!!
// We are using localStorage as an example, but in a real-world scenario, this
// would involve XMLHttpRequest, or perhaps a newer client-server protocol.
// The function signatures below might be similar to what you would build, but
// the contents of the functions are just trying to simulate client-server
// communication and server-side processing.
module.exports = {
getAllMessages: function() {
// simulate retrieving data from a database
var rawMessages = JSON.parse(localStorage.getItem('messages'));
// simulate success callback
ChatServerActionCreators.receiveAll(rawMessages);
},
createMessage: function(message, threadName) {
// simulate writing to a database
var rawMessages = JSON.parse(localStorage.getItem('messages'));
var timestamp = Date.now();
var id = 'm_' + timestamp;
var threadID = message.threadID || ('t_' + Date.now());
var createdMessage = {
id: id,
threadID: threadID,
threadName: threadName,
authorName: message.authorName,
text: message.text,
timestamp: timestamp
};
rawMessages.push(createdMessage);
localStorage.setItem('messages', JSON.stringify(rawMessages));
// simulate success callback
setTimeout(function() {
ChatServerActionCreators.receiveCreatedMessage(createdMessage);
}, 0);
}
};
|
var obj = null;
function checkHover() {
if (obj) {
obj.find('ul').fadeOut('fast');
} //if
} //checkHover
$(document).ready(function() {
$('#Nav > li').click(function() {
if (obj) {
obj.find('ul').fadeOut('fast');
obj = null;
} //if
$(this).find('ul').fadeIn('fast');
$(this).hover(function(){},function() {
obj = $(this);
setTimeout(
"checkHover()",
0); // si vous souhaitez retarder la disparition, c'est ici
})
});
$('#Nav2 > li').click(function() {
if (obj) {
obj.find('ul').fadeOut('fast');
obj = null;
} //if
$(this).find('ul').fadeIn('fast');
$(this).hover(function(){},function() {
obj = $(this);
setTimeout(
"checkHover()",
0); // si vous souhaitez retarder la disparition, c'est ici
})
});
});
|
const util = require('util');
let inherits = util.inherits;
function Animal(name){
this.name = name;
}
Animal.prototype.walk = function(destination){
console.log(this.name, 'is walking to', destination);
};
let animal = new Animal('elephant');
animal.walk('Melbourne');
//
function Bird(name){
Animal.call(this, name); //Call the super constructor
//
}
//Bird.prototype.__proto__ = Animal.prototype; //extend class
Object.setPrototypeOf(Bird.prototype, Animal.prototype);
Bird.prototype.fly = function(destination){
console.log(this.name, 'is flying to ', destination);
}
let bird = new Bird('Bird');
bird.walk('London');
bird.fly('Melbourne');
function Foo(){}
let foo = new Foo();
console.log(foo.constructor.name);
console.log(foo.constructor === Foo);
//---------------------
function Bird2(name){
Animal.call(this, name);
}
inherits(Bird2, Animal); //Discouraged by Node
//----------------------
function Bird3(name){
Animal.call(this, name);
}
//Object.setPrototypeOf(Bird.prototype, Animal.prototype);
Bird3.prototype = Object.create(Animal.prototype, {
constructor: {
value: Bird,
enumerable: false,
writable: false,
configurable: true
}
});
console.log('is Bird3 instance of Animal? ', new Bird3() instanceof Animal);
//
|
addon.port.on("show", function(myTabs) {
var items = document.getElementById("items");
items.innerHTML = '';
for (var i = 0; i < myTabs.length; i++) {
var p = items.appendChild(document.createElement("p"));
p.id = 'check'+String(i);
var li = p.appendChild(document.createElement("input"));
li.type = "checkbox";
li.checked = true;
li.name = 'check'+String(i);
var url = p.appendChild(document.createElement("a"));
url.href = myTabs[i].url;
var title = url.appendChild(document.createTextNode(myTabs[i].title));
items.appendChild(li);
li.onchange = function() {
items.removeChild(document.getElementById(li.name));
items.removeChild(li);
};
}
})
|
import { Component } from 'preact'
import { route } from 'preact-router'
export default class Redirect extends Component {
componentWillMount () {
route(this.props.to)
}
render () {
return null
}
}
|
import React from 'react';
import TruncateMarkup from 'react-truncate-markup';
import ProfileImage from '../../general/ProfileImage.component';
import SkeletonText from '../../base/Skeleton/Text';
import SkeletonUser from '../../base/Skeleton/User';
import Link from '../../general/Link.component';
import toColor from '../../../utils/toColor';
import Text from '../../base/Text';
import Icon from '../../base/Icon';
import Divider from '../../base/Divider';
import './ListCard.css';
class ListCard extends React.Component {
hasOwner = () => {
const list = this.props.list;
return !!(list && list.owner && list.owner.name);
};
renderBookCover(id, img) {
const POSITIONS = [
'align-self-start',
'align-self-center',
'align-self-end'
];
const SIZES = [
'list-card-brick-sm',
'list-card-brick-md',
'list-card-brick-lg'
];
return img ? (
<img alt="" src={'/v1/image/' + img + '/250/200'} />
) : (
<div
className="list-card-coverTemplate"
style={{background: toColor(id), height: '100%'}}
>
<div
className={`list-card-brick ${toColor(
id + 'size-0',
SIZES
)} ${toColor(id + 'pos-0', POSITIONS)}`}
/>
<div
className={`list-card-brick ${toColor(
id + 'size-1',
SIZES
)} ${toColor(id + 'pos-1', POSITIONS)}`}
/>
<div
className={`list-card-brick ${toColor(
id + 'size-2',
SIZES
)} ${toColor(id + 'pos-2', POSITIONS)}`}
/>
</div>
);
}
render() {
const {
list,
cardRef,
isVisible,
style,
className = '',
onClick
} = this.props;
// if not visible, show skeletons
if (!isVisible) {
return (
<div
className={'ListCard__skeleton p-0 mr-4 ' + className}
ref={cardRef}
>
<div className="ListCard__skeleton__cover" />
<div className="p-3">
<SkeletonText lines={3} color="#e9eaeb" />
<SkeletonUser
name={true}
pulse={false}
styles={{marginTop: '20px'}}
/>
</div>
</div>
);
}
return (
<div
className={'list-card mr-4 align-top ' + className}
style={style}
data-cy={`list-card-${list.title}`}
>
<Link href={`/lister/${list._id}`} onClick={onClick}>
<div className="list-card-wrap">
<div className="list-card-cover">
{this.renderBookCover(list._id, list.image)}
</div>
<div className="p-3">
<div className="list-card-summary">
<TruncateMarkup lines={3}>
<span>
<p className="list-card-about mb-1 Text Text__large">
{list.title}
</p>
<p className="list-card-about Text Text__body">
{list.description}
</p>
</span>
</TruncateMarkup>
</div>
{this.hasOwner() && <Divider variant="thin" />}
<div className="list-card-bottom">
{this.hasOwner() && (
<React.Fragment>
<ProfileImage
key={'profile-img-' + list._id}
user={list.owner}
namePosition={'right'}
type="list"
/>
<div className="d-flex align-self-center">
<Divider
type="vertical"
variant="thick"
className="align-self-center mx-2"
style={{height: 30}}
/>
<div className="list-card-interactions align-self-center">
<Icon
className="md-small"
name="chat_bubble_outline"
style={{paddingTop: 3}}
/>
<Text className="ml-2" type="body">
<strong>{list.num_comments}</strong>
</Text>
</div>
</div>
</React.Fragment>
)}
</div>
</div>
</div>
</Link>
</div>
);
}
}
export default ListCard;
|
// Suluvir streaming server
// Copyright (C) 2018 Jannis Fink
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import Immutable from 'immutable';
import * as defaultStates from './defaultStates';
import * as actionNames from '../actions/actionNames';
import * as notificationActionNames from '../actions/names/notifications';
import * as uploadErrorNames from '../actions/names/upload';
export function mySongs(state = defaultStates.MY_SONGS, action) {
switch (action.type) {
case actionNames.SET_MY_SONGS:
return action.payload;
case actionNames.ADD_TO_MY_SONGS:
return state.push(Immutable.fromJS(action.payload.song));
default:
return state;
}
}
export function myArtists(state = defaultStates.MY_ARTISTS, action) {
switch (action.type) {
case actionNames.SET_MY_ARTISTS:
return action.payload;
default:
return state;
}
}
export function myAlbums(state = defaultStates.MY_ALBUMS, action) {
switch (action.type) {
case actionNames.SET_MY_ALBUMS:
return action.payload;
default:
return state;
}
}
export function myPlaylists(state = defaultStates.MY_PLAYLISTS, action) {
switch (action.type) {
case actionNames.SET_MY_PLAYLISTS:
return action.payload;
default:
return state;
}
}
export function play(state = defaultStates.PLAY, action) {
switch (action.type) {
case actionNames.PLAY_SONG:
return state.set('list', Immutable.List.of(Immutable.fromJS(action.payload))).set('current', 0);
case actionNames.ADD_TO_PLAY_QUERE:
return state.set('list', state.get('list').push(action.payload));
case actionNames.SET_PLAY_QUEUE:
return state.set('list', action.payload).set('current', 0);
case actionNames.NEXT_SONG:
return state.set('current', state.get('current') + 1);
case actionNames.PREVIOUS_SONG:
return state.set('current', state.get('current') - 1);
case actionNames.SET_VOLUME:
return state.set('volume', action.payload);
default:
return state;
}
}
export function playlistsOfSong(state = defaultStates.PLAYLIST_OF_SONG, action) {
switch (action.type) {
case actionNames.SET_PLAYLISTS_FOR_SONG:
return state.set(action.payload.song.get('@id'), action.payload.playlists);
default:
return state;
}
}
export function user(state = defaultStates.USER, action) {
switch (action.type) {
case actionNames.FETCH_USER:
return action.payload;
default:
return state;
}
}
let notificationIdCounter = 0;
export function notifications(state = defaultStates.NOTIFICATIONS, action) {
switch (action.type) {
case notificationActionNames.ADD_NOTIFICATION:
notificationIdCounter++;
return state.push(Immutable.fromJS(action.payload).set('id', notificationIdCounter));
case notificationActionNames.CLOSE_NOTIFICATION:
return state.filter(notification => notification.get('id') !== action.payload);
default:
return state;
}
}
export function upload(state = defaultStates.UPLOAD, action) {
switch (action.type) {
case uploadErrorNames.ADD_TO_UPLOAD_PENDING:
return state.set('pending', state.get('pending').push(Immutable.fromJS({
'name': action.payload.file.name,
'size': action.payload.file.size,
'type': action.payload.file.type
})));
case uploadErrorNames.UPLOAD_DONE:
return state.set('pending', state.get('pending').filter(p =>
p.get('size') !== action.payload.song.get('size'))
).set('uploaded', state.get('uploaded').push(action.payload.song));
default:
return state;
}
}
export function urlCache(state = defaultStates.URL_CACHE, action) {
switch (action.type) {
case actionNames.ADD_TO_URL_CACHE:
return state.set(action.payload.url, action.payload.response);
default:
return state;
}
}
export function newContent(state = defaultStates.NEW_CONTENT, action) {
switch (action.type) {
case actionNames.FETCH_NEW_CONTENT:
return action.payload;
default:
return state;
}
}
|
/**
* This file specifies any system Action permission keys that are used by the
* apps in this Module.
*
* Action Keys are assigned to a user in the system by the Roles & Permission
* system. An Action Key is a unique string usually specified in the following
* format: "[application].[subapp].[verb]" which represents permission to
* perform [verb] for the [subapp] portion of the [application].
*
* [verbs] can be anything, but CRUD terms are preferred [ create, read, update, destroy]
*
* eg
* "adcore.permissions.admin" : does the user have permission to administrate
* permissions on the system?
*
* or perhaps you want more fine grain control:
* "adcore.permissions.user.create" : can user add permissions to a user?
* "adcore.permissions.user.destroy" : can user remove permissions from a user
* "adcore.permissions.roles.create" : can a user create roles in the system
* "adcore.permissions.roles.destroy" : can user remove a role?
* ...
*
*
*/
module.exports = {
language_code: "en",
actions: [
{
action_key: "opsportal.view",
action_description: "Allows the user to access the opsportal."
},
{
action_key: "opsportal.rbac.view",
action_description:
"Allows the user to access the Roles And Permissions Tool."
},
{
action_key: "opsportal.opnavedit.view",
action_description:
"Allows the user to edit the Ops Portal Navigation."
}
]
};
|
import operators from "/imports/utils/operators";
import propertyTypes from "/imports/utils/propertyTypes";
/**
* @summary Filter surcharges based on surcharge restriction data
* @param {Object} surcharge - surcharge to check attributes and destination against
* @param {Object} extendCommonOrder - details about the purchase a user wants to make.
* @returns {Bool} true / false as to whether method is still valid after this check
*/
export async function surchargeCheck(surcharge, extendCommonOrder) {
const { items, shippingAddress } = extendCommonOrder;
const { attributes, destination } = surcharge;
const validSurcharge = items.some((item) => { // eslint-disable-line
if (Array.isArray(attributes) && attributes.length) {
// Item must meet all attributes to be restricted
return attributes.every((attribute) => {
let attributeFound = operators[attribute.operator](item[attribute.property], propertyTypes[attribute.propertyType](attribute.value));
// If attribute is an array on the item, use `includes` instead of checking for ===
// This works for tags, tagIds, and any future attribute that might be an array
if (Array.isArray(item[attribute.property])) {
attributeFound = item[attribute.property].includes(attribute.value);
}
if (attributeFound && shippingAddress) {
// If there is no destination restriction, destination restriction is global
// Return true to restrict this method
if (!destination || Object.getOwnPropertyNames(destination).length === 0) return attributeFound;
const { country, postal, region } = destination;
if (postal && postal.includes(shippingAddress.postal)) {
return true;
}
// Check for an allow list of regions
if (region && region.includes(shippingAddress.region)) {
return true;
}
// Check for an allow list of countries
if (country && country.includes(shippingAddress.country)) {
return true;
}
}
// If shipping location does not match restricted location && attribute, method is not restricted
return false;
});
}
// If there are no attributes on the surcharge, and destination doesn't exist, don't apply surcharge
if (!destination) return false;
const { country, postal, region } = destination;
// If destination exists, make sure we have a shipping address, and check against it
if (shippingAddress) {
if (postal && postal.includes(shippingAddress.postal)) {
return true;
}
// Check for an allow list of regions
if (region && region.includes(shippingAddress.region)) {
return true;
}
// Check for an allow list of countries
if (country && country.includes(shippingAddress.country)) {
return true;
}
}
return false;
});
return validSurcharge;
}
|
import dude from 'debug-dude'
const { /*debug,*/ log, info /*, warn, error*/ } = dude('bot')
import { version } from '../package.json'
info(`jdnet bot v${version} starting`)
import config from '../config.json'
import { connect, message } from 'coffea'
const networks = connect(config)
import fs from 'fs'
import path from 'path'
networks.on('command', (evt, reply) => {
log('Received command event: %o', evt)
switch (evt.cmd) {
case 'say':
reply(message(evt.channel, evt.args.join('')))
break
case 'maxi':
let maxi = Math.floor((Math.random() * 12) + 1)
reply({
type: 'sendPhoto',
action: 'upload_photo',
id: evt.channel,
photo: fs.createReadStream(path.join(__dirname, `pic/${maxi}.jpg`))
})
break
}
})
networks.on('message', (evt, reply) => {
log('Received message event: %o', evt)
let hashtags = evt.text.match(/#([a-zA-Z]+)/)
if (hashtags && hashtags.length > 1) {
reply({
type: 'sendVoice',
action: 'record_audio',
id: evt.channel,
voice: fs.createReadStream(path.join(__dirname, `voice/${hashtags[1]}.mp3`))
})}
})
networks.on('message', (evt, reply) => {
let video = evt.text.match(/#([a-zA-Z]+)/)
if (video && video.length > 1) {
reply({
type: 'sendVideo',
action: 'record_video',
id: evt.channel,
video: fs.createReadStream(path.join(__dirname, `video/${video[1]}.mp4`))
})}
})
networks.on('message', (evt, reply) => {
let pic = evt.text.match(/#([a-zA-Z]+)/)
if (pic && pic.length > 1) {
reply({
type: 'sendPhoto',
action: 'upload_photo',
id: evt.channel,
photo: fs.createReadStream(path.join(__dirname, `pic/etc/${pic[1]}.jpg`))
})}
})
|
/**
* @file Controller for the metadata creation UIs
* @author Joseph Ferraro <@joeferraro>
*/
'use strict';
var Promise = require('bluebird');
var jobQueue = require('../../job-queue');
var TemplateService = require('../../template');
var MetadataController = function(req) {
this.client = req.app.get('client');
this.swig = req.app.get('swig');
this.templateService = new TemplateService();
};
MetadataController.prototype._getTemplates = function(typeXmlName) {
var self = this;
return new Promise(function(resolve, reject) {
self.templateService.getTemplatesForType(typeXmlName)
.then(function(templates) {
resolve(templates);
})
.catch(function(e) {
reject(new Error('Could not retrieve templates: '+e.message));
})
.done();
});
};
/**
* GET (sync)
*/
MetadataController.prototype.new = function(req, res) {
var self = this;
if (!req.project) {
res.status(500).send('Error: No project configured for this MavensMate client.');
} else {
self._getTemplates(req.query.type)
.then(function(templates) {
var locals = {
templates : templates,
metadataType: req.query.type
};
res.render('metadata/new.html', locals);
})
.catch(function(e) {
res.render('metadata/new.html', {});
})
.done();
}
};
/**
* GET (sync)
*/
MetadataController.prototype.template = function(req, res) {
this.templateService.getTemplateBody(req.query.type, req.query.fileName)
.then(function(body) {
res.send(body);
})
.catch(function(e) {
res.status(500).send('Error: '+e.message);
})
.done();
};
/**
* POST (async)
*/
MetadataController.prototype.create = function(req, res) {
var jobId = jobQueue.addJob();
this.client.executeCommandForProject(req.project, 'new-metadata', req.body)
.then(function(response) {
jobQueue.finish(jobId, null, response);
})
.catch(function(err) {
jobQueue.finish(jobId, err, null);
});
return res.send({
status: 'pending',
id: jobId
});
};
module.exports = MetadataController;
|
'use strict';
require('es6-promise').polyfill();
import fetch from 'isomorphic-fetch';
import {
ALERT_ADD,
ALERT_REMOVE
} from './action-types';
import * as messages from './message-types';
export function addAlert(message, resultType){
return {
type: ALERT_ADD,
message,
resultType
}
}
export function removeAlert(data){
return {
type: ALERT_REMOVE
}
}
|
var dir_6e3735f50398b4ebf5f2b8e6ac22d046 =
[
[ "EchelleTest.java", "d8/dcb/_echelle_test_8java.html", [
[ "EchelleTest", "d9/d0d/classfr_1_1iessa_1_1vue_1_1_echelle_test.html", "d9/d0d/classfr_1_1iessa_1_1vue_1_1_echelle_test" ]
] ]
];
|
const https = require('https');
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var multer = require('multer');
var exec = require('child_process').exec;
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
next();
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var baseDir = __dirname.replace(/server\/?/, "");
var uploadDir = baseDir.replace(/\/?$/, "/upload/");
var seriesIdWrite = 0;
fs.readdirSync("data/series").forEach(function(file){seriesIdWrite = Math.max(seriesIdWrite, parseInt(file.slice(0, -5)))});
console.log('Next series id '+seriesIdWrite);
var seriesIdRead = seriesIdWrite;
app.post('/newSeries', function (req, res) {
seriesIdWrite = 0;
fs.readdirSync("data/series").forEach(function(file){seriesIdWrite = Math.max(seriesIdWrite, parseInt(file.slice(0, -5)))});
seriesIdRead = seriesIdWrite;
seriesIdWrite++;
res.send("<p>"+seriesIdWrite+"</p>");
console.log('Next series id '+seriesIdWrite);
})
app.get('/resetSeriesRead', function (req, res) {
seriesIdRead = seriesIdWrite;
res.send("<p>"+seriesIdRead+"</p>");
console.log(seriesIdRead);
})
app.post('/sendSeries', function (req, res) {
// console.log('params');
// console.log(req.params);
// console.log('body');
// console.log(req.body);
// console.log('query');
// console.log(req.query);
// console.log(req);
var fileName = 'data/series/'+seriesIdWrite.toString()+'.json';
console.log("storing Series "+seriesIdWrite);
res.send(JSON.stringify(req.body));
fs.writeFile(fileName, JSON.stringify(req.body), (error) => { console.log('Attempt to write file '+fileName); });
seriesIdRead = seriesIdWrite;
})
app.get('/getSeriesMinus', function (req, res) {
var seriesIdReadCurrent = seriesIdRead;
if (seriesIdRead>1) {
seriesIdRead--;
}
while (seriesIdRead>0 && !fs.existsSync('data/series/'+seriesIdRead.toString()+'.json')) {
seriesIdRead--;
}
var fileName = 'data/series/'+seriesIdRead.toString()+'.json';
if (!fs.existsSync(fileName)) {
seriesIdRead = seriesIdReadCurrent;
fileName = 'data/series/'+seriesIdRead.toString()+'.json';
}
console.log("sending series "+fileName);
res.send(fs.readFileSync(fileName, req.body));
})
app.get('/getSeriesPlus', function (req, res) {
var seriesIdReadCurrent = seriesIdRead;
if (seriesIdRead<seriesIdWrite) {
seriesIdRead++;
}
while (seriesIdRead<seriesIdWrite && !fs.existsSync('data/series/'+seriesIdRead.toString()+'.json')) {
seriesIdRead++;
}
var fileName = 'data/series/'+seriesIdRead.toString()+'.json';
if (!fs.existsSync(fileName)) {
seriesIdRead = seriesIdReadCurrent;
fileName = 'data/series/'+seriesIdRead.toString()+'.json';
}
console.log("sending series "+fileName);
res.send(fs.readFileSync(fileName, req.body));
})
app.get('/removeSeries', function (req, res) { // , checkOrigin
var fileName = 'data/series/'+seriesIdRead.toString()+'.json';
if (fs.existsSync(fileName)) {
var seriesIdReadCurrent = seriesIdRead;
console.log("removing series "+fileName);
fs.unlink(fileName);
if (seriesIdRead<seriesIdWrite) {
seriesIdRead++;
}
while (seriesIdRead>seriesIdWrite && !fs.existsSync('data/series/'+seriesIdRead.toString()+'.json')) {
seriesIdRead++;
}
if (seriesIdReadCurrent == seriesIdRead) {
if (seriesIdRead>1) {
seriesIdRead--;
}
while (seriesIdRead>0 && !fs.existsSync('data/series/'+seriesIdRead.toString()+'.json')) {
seriesIdRead--;
}
}
}
})
app.get('/gitPull', function (req, res) {
var exec = require('child_process').exec;
var child;
child = exec('git pull',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
res.send("pulling from git repo: "+ stdout);
})
app.get('/toto', function (req, res) {
res.send("<p>Bonjour Toto</p>");
})
var privateKey = fs.readFileSync( '/home/lagrange/soundthings.org.key' );
var certificate = fs.readFileSync( '/home/lagrange/soundthings.org.crt' );
var server = https.createServer({
key: privateKey,
cert: certificate
}, app).listen(4000
// var server = app.listen(4000
, function ()
{
var host = server.address().address
var port = server.address().port
console.log("Iom node app listening at https://%s:%s", host, port)
})
// function checkOrigin (req, res, next) {
// let origin = req.headers.origin;
// if (!origin) {
// origin = req.headers.referer.replace(/^(https?:\/\/[^/:]+).*$/, '$1');
// }
// if (origin.match(/(mathieulagrange\.github\.io|localhost)$/)) {
// // Set CORS for the reply
// res.header('Access-Control-Allow-Origin', origin);
// res.header('Access-Control-Allow-Methods', 'POST, OPTIONS');
// res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
// } else {
// return res.send({success: false});
// }
// next();
// }
|
/*
* Copyright (C) 2015 Telosys-tools-saas project org. ( http://telosys-tools-saas.github.io/ )
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.gnu.org/licenses/lgpl.html
*
* 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.
*/
/* globals $ */
'use strict';
angular.module('telosys-tools-saasApp')
.directive('showValidation', function() {
return {
restrict: 'A',
require: 'form',
link: function (scope, element) {
element.find('.form-group').each(function() {
var $formGroup = $(this);
var $inputs = $formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');
if ($inputs.length > 0) {
$inputs.each(function() {
var $input = $(this);
scope.$watch(function() {
return $input.hasClass('ng-invalid') && $input.hasClass('ng-dirty');
}, function(isInvalid) {
$formGroup.toggleClass('has-error', isInvalid);
});
});
}
});
}
};
});
|
{
"Enable": false,
"Minute": 60,
"Items": null
}
|
"use strict";
var async = require('async');
var winston = require('winston');
var nconf = require('nconf');
var templates = require('templates.js');
var nodemailer = require('nodemailer');
var sendmailTransport = require('nodemailer-sendmail-transport');
var smtpTransport = require('nodemailer-smtp-transport');
var htmlToText = require('html-to-text');
var url = require('url');
var User = require('./user');
var Plugins = require('./plugins');
var meta = require('./meta');
var translator = require('../public/src/modules/translator');
var transports = {
sendmail: nodemailer.createTransport(sendmailTransport()),
QQex: undefined
};
var app;
var fallbackTransport;
(function(Emailer) {
Emailer.registerApp = function(expressApp) {
app = expressApp;
// Enable QQex transport if enabled in ACP
if (parseInt(meta.config['email:QQexTransport:enabled'], 10) === 1) {
fallbackTransport = transports.QQex = nodemailer.createTransport(smtpTransport({
// host: 'smtp.exmail.qq.com',
// port: 465,
// secure: true,
service: 'QQex',
auth: {
user: meta.config['email:QQexTransport:user'],
pass: meta.config['email:QQexTransport:pass']
}
}));
} else {
fallbackTransport = transports.sendmail;
}
return Emailer;
};
Emailer.send = function(template, uid, params, callback) {
callback = callback || function() {};
if (!app) {
winston.warn('[emailer] App not ready!');
return callback();
}
async.waterfall([
function(next) {
async.parallel({
email: async.apply(User.getUserField, uid, 'email'),
settings: async.apply(User.getSettings, uid)
}, next);
},
function(results, next) {
if (!results.email) {
winston.warn('uid : ' + uid + ' has no email, not sending.');
return next();
}
params.uid = uid;
Emailer.sendToEmail(template, results.email, results.settings.userLang, params, next);
}
], callback);
};
Emailer.sendToEmail = function(template, email, language, params, callback) {
callback = callback || function() {};
var lang = language || meta.config.defaultLang || 'en_GB';
async.waterfall([
function (next) {
async.parallel({
html: function(next) {
renderAndTranslate('emails/' + template, params, lang, next);
},
subject: function(next) {
translator.translate(params.subject, lang, function(translated) {
next(null, translated);
});
}
}, next);
},
function (results, next) {
var data = {
to: email,
from: meta.config['email:from'] || 'no-reply@' + getHostname(),
from_name: meta.config['email:from_name'] || 'NodeBB',
subject: results.subject,
html: results.html,
plaintext: htmlToText.fromString(results.html, {
ignoreImage: true
}),
template: template,
uid: params.uid,
pid: params.pid,
fromUid: params.fromUid
};
Plugins.fireHook('filter:email.modify', data, next);
},
function (data, next) {
if (Plugins.hasListeners('filter:email.send')) {
Plugins.fireHook('filter:email.send', data, next);
} else {
Emailer.sendViaFallback(data, next);
}
}
], function (err) {
callback(err);
});
};
Emailer.sendViaFallback = function(data, callback) {
// Some minor alterations to the data to conform to nodemailer standard
data.text = data.plaintext;
delete data.plaintext;
// NodeMailer uses a combined "from"
data.from = data.from_name + '<' + data.from + '>';
delete data.from_name;
winston.verbose('[emailer] Sending email to uid ' + data.uid);
fallbackTransport.sendMail(data, callback);
};
function render(tpl, params, next) {
if (meta.config['email:custom:' + tpl.replace('emails/', '')]) {
var text = templates.parse(meta.config['email:custom:' + tpl.replace('emails/', '')], params);
next(null, text);
} else {
app.render(tpl, params, next);
}
}
function renderAndTranslate(tpl, params, lang, callback) {
render(tpl, params, function(err, html) {
translator.translate(html, lang, function(translated) {
callback(err, translated);
});
});
}
function getHostname() {
var configUrl = nconf.get('url');
var parsed = url.parse(configUrl);
return parsed.hostname;
}
}(module.exports));
|
module.exports = {
usage:
`Send a **feature request** to the bot developer, or in other words, sends a \
message to a secret channel somewhere in the abyss. Requests can have a max \
length of **1950 characters**.
\`[command prefix]featurerequest [feature to request]\``,
aliases: ['suggest'],
dm: false,
cooldown: 60,
process: obj => {
var msg = obj.msg,
args = obj.args,
bot = obj.bot;
return new Promise(resolve => {
//If nothing is requested yell at the user for not doing so
if (!args) resolve({
message:
'You must enter something to be requested, ' +
`**${msg.author.username}**.`,
delete: true
})
//If the request is potentially to large tell the user so
else if (args.length > 1950) resolve({
message:
'Requests cannot be over 1950 characters, ' +
`**${msg.author.username}**.`,
delete: true
})
else {
// Create a embed message to a channel at the user’s request
// Note that Chrys has changed this to a channel in his own
// server
//
// To whoever wants to run their own instance of this bot:
// Please change this integer to a channel on your own server;
// this command won’t work unless your instance of this bot has
// access to this channel, which it doesn’t.
bot.createMessage('251581749136588802', {
embed: {
author: {
name:
`${msg.author.username} ` +
`(${msg.channel.guild.name})`,
icon_url: msg.author.avatarURL
},
color: 0x743FBF,
description: args,
footer: {
text:
`UserID: ${msg.author.id} GuildID: ` +
`${msg.channel.guild.id}`
}
}
}).then(() => resolve({
// Tell the user that their request was successfully sent
// to the request channel on promise resolve
message:
'Your request was successfully sent, ' +
`**${msg.author.username}**.`
}))
}
});
}
}
|
/**
* Created by MikeRiy on 17/1/3.
*/
var PACKET_HEADER_SIZE = 4;
function SocketPacket()
{
this.buffer = [];
//this.buffSize = 0;
this.readPos = 0;
this.packetSize = 0;
}
SocketPacket.prototype =
{
construct: SocketPacket,
reset:function()
{
this.buffer = [];
this.readPos = 0;
this.packetSize = 0;
},
loadBytes:function(data, size)
{
var bytes = new DataView(data);
for(var i = 0; i < size; i++)
{
this.writeByte(bytes.getUint8(i));
}
//--
this.packet();
},
subLength:function()
{
return this.buffer.length - this.readPos;
},
empty:function()
{
return this.subLength() == 0;
},
setHeader:function()
{
var v1 = this.buffer[this.readPos] & 0xff;
var v2 = this.buffer[this.readPos + 1] & 0xff;
var v3 = this.buffer[this.readPos + 2] & 0xff;
var v4 = this.buffer[this.readPos + 3] & 0xff;
this.readPos += 4;
//获取长度
this.packetSize = (v1<<0)|(v2<<8)|(v3<<16)|(v4<<24);
},
writeByte:function(val)
{
this.buffer.push(val);
},
readByte:function()
{
var val = this.buffer[this.readPos];
this.readPos++;
return val;
},
packet:function()
{
if(this.packetSize == 0){
if(this.subLength() >= PACKET_HEADER_SIZE)
{
this.setHeader();
//--
if(this.subLength() >= this.packetSize)
{
this.packet();
}
}
}else{
if(this.subLength() >= this.packetSize)
{
//读取一个包
var bytes = new ByteArray(this.packetSize);
for(var i = 0; i < this.packetSize; i++)
{
bytes.writeByte(this.readByte());
}
this.flush();
//---发送消息
LOG_DEBUG("收到包:size=", bytes.length());
appNotice.send("socket_packet", bytes);
//发送消息后是否还有消息
this.packet();
}
}
},
flush:function()
{
this.packetSize = 0;
if(this.empty()) this.reset();
}
}
|
var async = require('async');
var helpers = require('../../../helpers/aws');
module.exports = {
title: 'Empty Groups',
category: 'IAM',
description: 'Ensures all groups have at least one member',
more_info: 'While having empty groups does not present a direct security risk, it does broaden the management landscape which could potentially introduce risks in the future.',
link: 'http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_WorkingWithGroupsAndUsers.html',
recommended_action: 'Remove unused groups without users',
apis: ['IAM:listGroups', 'IAM:getGroup'],
asl: {
conditions: [
{
service: 'iam',
api: 'getGroup',
property: 'Users',
transform: 'COUNT',
op: 'GT',
value: 0
}
]
},
run: function(cache, settings, callback) {
var results = [];
var source = {};
var region = helpers.defaultRegion(settings);
var listGroups = helpers.addSource(cache, source,
['iam', 'listGroups', region]);
if (!listGroups) return callback(null, results, source);
if (listGroups.err || !listGroups.data) {
helpers.addResult(results, 3,
'Unable to query for groups: ' + helpers.addError(listGroups));
return callback(null, results, source);
}
if (!listGroups.data.length) {
helpers.addResult(results, 0, 'No groups found');
return callback(null, results, source);
}
async.each(listGroups.data, function(group, cb){
if (!group.GroupName) return cb();
var getGroup = helpers.addSource(cache, source,
['iam', 'getGroup', region, group.GroupName]);
if (!getGroup || getGroup.err || !getGroup.data) {
helpers.addResult(results, 3, 'Unable to query for group: ' + group.GroupName + ': ' + helpers.addError(getGroup), 'global', group.Arn);
} else if (!getGroup.data.Users) {
helpers.addResult(results, 3, 'Unable to query for group: ' + group.GroupName + ': No users returned attached', 'global', group.Arn);
} else if (!getGroup.data.Users.length) {
helpers.addResult(results, 1, 'Group: ' + group.GroupName + ' does not contain any users', 'global', group.Arn);
return cb();
} else {
helpers.addResult(results, 0, 'Group: ' + group.GroupName + ' contains ' + getGroup.data.Users.length + ' user(s)', 'global', group.Arn);
}
cb();
}, function(){
callback(null, results, source);
});
}
};
|
/*
Nodics - Enterprice Micro-Services Management Framework
Copyright (c) 2017 Nodics All rights reserved.
This software is the confidential and proprietary information of Nodics ("Confidential Information").
You shall not disclose such Confidential Information and shall use it only in accordance with the
terms of the license agreement you entered into with Nodics.
*/
module.exports = {
/**
* This function is used to initiate entity loader process. If there is any functionalities, required to be executed on entity loading.
* defined it that with Promise way
* @param {*} options
*/
init: function (options) {
return new Promise((resolve, reject) => {
resolve(true);
});
},
/**
* This function is used to finalize entity loader process. If there is any functionalities, required to be executed after entity loading.
* defined it that with Promise way
* @param {*} options
*/
postInit: function (options) {
return new Promise((resolve, reject) => {
resolve(true);
});
},
handleExternalDataPushEvent: function (request, callback) {
let event = request.event;
if (event && !UTILS.isBlank(event)) {
SERVICE.DefaultPipelineService.start('processExternalDataPushEventPipeline', {
tenant: request.tenant,
moduleName: event.target,
header: event.header,
data: event.data,
event: event
}, {}).then(success => {
callback(null, {
success: true,
code: 'SUC_EVNT_00000',
message: 'Event processed successfuly',
result: {
event: event.event,
_id: event._id
}
});
}).catch(error => {
callback({
success: false,
code: 'ERR_EVNT_00000',
error: error,
result: {
event: event.event,
_id: event._id
}
});
});
} else {
callback({
success: false,
code: 'ERR_EVNT_00000',
error: 'Event object can not be null or empty'
});
}
}
};
|
/*
Count down until any date script-
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free scripts here!
Modified by Robert M. Kuhnhenn, D.O.
on 5/30/2006 to count down to a specific date AND time,
on 10/20/2007 to a new format, and 1/10/2010 to include
time zone offset.
*/
/* Change the items below to create your countdown target date and announcement once the target date and time are reached. */
var current = "It's Pony Time!"; //-->enter what you want the script to display when the target date and time are reached, limit to 20 characters
var year = 2015; //-->Enter the count down target date YEAR
var month = 10; //-->Enter the count down target date MONTH
var day = 3; //-->Enter the count down target date DAY
var hour = 11; //-->Enter the count down target date HOUR (24 hour clock)
var minute = 30; //-->Enter the count down target date MINUTE
var tz = -4; //-->Offset for your timezone in hours from UTC (see http://wwp.greenwichmeantime.com/index.htm to find the timezone offset for your location)
//--> DO NOT CHANGE THE CODE BELOW! <--
var montharray = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
function countdown(yr,m,d,hr,min){
theyear = yr;themonth = m;theday = d;thehour = hr;theminute = min;
var today = new Date();
var todayy = today.getYear();
if (todayy < 1000) { todayy += 1900; }
var todaym = today.getMonth();
var todayd = today.getDate();
var todayh = today.getHours();
var todaymin = today.getMinutes();
var todaysec = today.getSeconds();
var todaystring1 = montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec;
var todaystring = Date.parse(todaystring1)+(tz*1000*60*60);
var futurestring1 = (montharray[m-1]+" "+d+", "+yr+" "+hr+":"+min);
var futurestring = Date.parse(futurestring1)-(today.getTimezoneOffset()*(1000*60));
var dd = futurestring-todaystring;
var dday = Math.floor(dd/(60*60*1000*24)*1);
var dhour = Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1);
var dmin = Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
var dsec = Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
if(dday <= 0 && dhour <= 0 && dmin<= 0 && dsec <= 0){
document.getElementById('count2').innerHTML = current;
document.getElementById('count2').style.display = "block";
document.getElementById('count2').style.width = "390px";
document.getElementById('dday').style.display = "none";
document.getElementById('dhour').style.display = "none";
document.getElementById('dmin').style.display = "none";
document.getElementById('dsec').style.display = "none";
document.getElementById('days').style.display = "none";
document.getElementById('hours').style.display = "none";
document.getElementById('minutes').style.display = "none";
document.getElementById('seconds').style.display = "none";
return;
}
else {
document.getElementById('count2').style.display = "none";
document.getElementById('dday').innerHTML = dday;
document.getElementById('dhour').innerHTML = dhour;
document.getElementById('dmin').innerHTML = dmin;
document.getElementById('dsec').innerHTML = dsec;
setTimeout("countdown(theyear,themonth,theday,thehour,theminute)",1000);
}
}
|
// Librivox Search Angular Module
'use strict';
var librivoxSearch = angular.module('librivoxSearch', []);
librivoxSearch.controller('librivoxSearchController', function ($scope, $http) {
// book data:
baseURL = 'https://librivox.org/api/feed/audiobooks/'; // base URL
$scope.hideDesc = 'true'; // a value causes description to HIDE -- a little confusing
$scope.showDesc = false;
// button method
$scope.processSearch = function () { // there is nothing to pass to the function
// First time empty search term submission is undefined, second is ''
// Default maximum records return is 50 -- which seems to be about as many
// books as one might expect any author to have written -- or at least is probably
// more than have been audio recorded; but the number CAN be changed, if needed.
// We want to be able to suppress display of description with a checkbox option. use ng-hide
$scope.data = ''; // needed for ng-repeat display
$scope.records = ''; // number of records returned
$scope.searchURL = baseURL; // base URL
if ($scope.filterText == undefined) {
$scope.filterText = ''; // otherwise data does not display on first search
}
// hideDesc = "" = false = show the element; hideDesc = "true" = hide the element
$scope.showDesc == true ? $scope.hideDesc = '' : $scope.hideDesc = "true";
// Assemble the JSONP URL
jsonp = '?format=jsonp&callback=JSON_CALLBACK';
if ($scope.searchTerm != undefined && $scope.searchTerm != '') {
$scope.searchURL += "author/" + $scope.searchTerm;
}
$scope.searchURL += jsonp;
$http.jsonp($scope.searchURL).success(function (data, status) {
$scope.data = data;
$scope.status = status;
// $scope.records += data.books.length;
$scope.records += 'Number of Author Records: ' + data.books.length;
// + ' showDesc: ' + $scope.showDesc; = undefined ???
// We need a no records found message. See error()
}).error(function (data, status) {
$scope.status = status;
switch(status) {
case 404:
$scope.records = 'No such author was found in the database. Error: ' + status;
break;
case 500:
$scope.records = 'Server error. Please try again later. Error: ' + status;
break;
default:
$scope.records = 'Unknown error. Please report to email@domain.com.'
}
}); // end of jsonp(), success() and error()
}
});
// filter to strip out HTML
librivoxSearch.filter('htmlToPlaintext', function () {
return function (text) {
// regex removes all HTML tags: str.replace(/<\/?[^>]+>/gi, '')
// "gi" modifier is global and case insensitive
return String(text).replace(/<\/?[^>]+>/gi, '');
}
});
|
exports.main = function(options)
{
var deferred = require.API.Q.defer();
// NOTE: You can also use `require.resolve()` instead of `require.id()`.
// We use the latter so we can load this module in the browser as well.
// (The browser loader only supports `require.id()` out of the box)
var uri = require.sandbox.id + require.id("./hello.txt");
require.API.JQUERY(function($)
{
$.get(uri, function(data)
{
require.API.Q.call(function()
{
if (data !== "Hello")
{
throw new Error("Loaded resource does not have correct content!");
}
module.log(data + " from 08-ResourceURI!");
}).then(deferred.resolve, deferred.reject);
});
});
return deferred.promise;
}
|
/*
Questioning is a kind of BB system completely written using MeteorJS that
implements Ann Kerwin's Ignorance Map and a rewarding system to involve users.
Copyright (c) 2015, Author: Marco Scordino, Advisor: Paolo Ceravolo http://www.di.unimi.it/ceravolo/
This file is part of Questioning.
Questioning is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Questioning is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Questioning. If not, see <http://www.gnu.org/licenses/>.
*/
Template.answerForm.events({
'submit form': function(e) {
e.preventDefault();
var replyProperties = {
question_id: $(e.target).find('[name=question_id]').val(),
text: $(e.target).find('[name=replyText]').val()
}
Meteor.call("addReply", replyProperties, function(error, id) {
if (error)
return alert(error.reason);
});
e.target.replyText.value = "";
},
});
Template.answerForm.rendered = function() {
//CKEDITOR.replace( 'questionText' );
$('#replyText').ckeditor();
};
|
$(function() {
// Configures Flickity Carousel
$('.carousel-main').flickity({
wrapAround: true,
draggable: true,
adaptiveHeight: true,
prevNextButtons: false,
pageDots: false
});
// 2nd carousel, navigation
$('.carousel-nav').flickity({
asNavFor: '.carousel-main',
contain: true,
prevNextButtons: false,
pageDots: false
});
});
|
/**
* ShippingMethod Schema
*/
/**
* @summary EFrameworkCore.Schemas.ShippingMethod
* @description
* @todo DOCUMENTACION y DESCRIPCION
*/
EFrameworkCore.Schemas.ShippingMethod = new SimpleSchema({
_id: {
type: String,
label: "Shipment Method Id",
autoValue: EFrameworkCore.schemaIdAutoValue
},
name: {
type: String,
label: "Method Name"
},
label: {
type: String,
label: "Public Label"
},
group: {
type: String,
label: "Group"
},
cost: {
type: Number,
label: "Cost",
decimal: true,
optional: true,
//Se agrego valor mínimo 0
min: 0
},
handling: {
type: Number,
label: "Handling",
optional: true,
decimal: true,
defaultValue: 0,
min: 0
},
rate: {
type: Number,
label: "Rate",
decimal: true,
min: 0
},
enabled: {
type: Boolean,
label: "Enabled",
defaultValue: true
},
validRanges: {
type: Array,
optional: true,
label: "Matching Cart Ranges"
},
"validRanges.$": {
type: Object,
optional: true
},
"validRanges.$.begin": {
type: Number,
decimal: true,
label: "Begin",
optional: true
},
"validRanges.$.end": {
type: Number,
decimal: true,
label: "End",
optional: true
},
validLocales: {
type: Array,
optional: true,
label: "Matching Locales"
},
"validLocales.$": {
type: Object,
optional: true
},
"validLocales.$.origination": {
type: String,
label: "From",
optional: true
},
"validLocales.$.destination": {
type: String,
label: "To",
optional: true
},
"validLocales.$.deliveryBegin": {
type: Number,
label: "Shipping Est.",
optional: true
},
"validLocales.$.deliveryEnd": {
type: Number,
label: "Delivery Est.",
optional: true
}
});
/**
* @summary EFrameworkCore.Schemas.ShipmentQuote
* @description
* @todo DOCUMENTACION y DESCRIPCION
*/
EFrameworkCore.Schemas.ShipmentQuote = new SimpleSchema({
carrier: {
type: String
},
method: {
type: EFrameworkCore.Schemas.ShippingMethod
},
rate: {
type: Number,
decimal: true,
defaultValue: "0.00"
}
});
/**
* @summary EFrameworkCore.Schemas.ShipmentItem
* @description
* @todo DOCUMENTACION y DESCRIPCION
*/
// populate with order.items that are added to a shipment
EFrameworkCore.Schemas.ShipmentItem = new SimpleSchema({
_id: {
type: String,
label: "Shipment Line Item",
optional: true,
autoValue: EFrameworkCore.schemaIdAutoValue
},
productId: {
type: String,
index: 1
},
shopId: {
type: String,
index: 1,
label: "Shipment Item ShopId",
optional: true
},
quantity: {
label: "Quantity",
type: Number,
min: 0
},
variantId: {
type: String
}
});
/**
* @summary EFrameworkCore.Schemas.ShippingParcel
* @description
* @todo DOCUMENTACION y DESCRIPCION
*/
/**
* ShippingParcel Schema
*/
EFrameworkCore.Schemas.ShippingParcel = new SimpleSchema({
containers: {
type: String,
optional: true
},
length: {
type: Number,
optional: true
},
width: {
type: Number,
optional: true
},
height: {
type: Number,
optional: true
},
weight: {
type: Number,
optional: true
}
});
/**
* @summary EFrameworkCore.Schemas.Shipment
* @description
* @todo DOCUMENTACION y DESCRIPCION
*/
/**
* Shipment Schema
* used for cart/order shipment tracking
*/
EFrameworkCore.Schemas.Shipment = new SimpleSchema({
_id: {
type: String,
label: "Shipment Id",
autoValue: EFrameworkCore.schemaIdAutoValue
},
address: {
type: EFrameworkCore.Schemas.Address,
optional: true
},
shipmentMethod: {
type: EFrameworkCore.Schemas.ShippingMethod,
optional: true
},
shipmentQuotes: {
type: [EFrameworkCore.Schemas.ShipmentQuote],
optional: true
},
tracking: {
type: String,
optional: true
},
parcel: {
type: EFrameworkCore.Schemas.ShippingParcel,
optional: true
},
items: {
type: [EFrameworkCore.Schemas.ShipmentItem],
optional: true
},
workflow: {
type: EFrameworkCore.Schemas.Workflow,
optional: true
},
invoice: {
type: EFrameworkCore.Schemas.Invoice,
optional: true
},
transactions: {
type: [Object],
optional: true,
blackbox: true
}
});
/**
* @summary EFrameworkCore.Schemas.ShippingProvider
* @description
* @todo DOCUMENTACION y DESCRIPCION
*/
/**
* ShippingProvider Schema
*/
EFrameworkCore.Schemas.ShippingProvider = new SimpleSchema({
name: {
type: String,
label: "Service Code"
},
label: {
type: String,
label: "Public Label"
},
enabled: {
type: Boolean,
defaultValue: true
},
serviceAuth: {
type: String,
label: "Auth",
optional: true
},
serviceSecret: {
type: String,
label: "Secret",
optional: true
},
serviceUrl: {
type: String,
label: "Service URL",
optional: true
}
});
/**
* @summary EFrameworkCore.Schemas.Shipping
* @description
* @todo DOCUMENTACION y DESCRIPCION
*/
/**
* Shipping Schema
*/
EFrameworkCore.Schemas.Shipping = new SimpleSchema({
shopId: {
type: String,
index: 1,
autoValue: EFrameworkCore.shopIdAutoValue,
label: "Shipping ShopId"
},
provider: {
type: EFrameworkCore.Schemas.ShippingProvider,
label: "Shipping Provider"
},
methods: {
type: [EFrameworkCore.Schemas.ShippingMethod],
optional: true,
label: "Shipping Methods"
},
shipmentQuotes: {
type: [EFrameworkCore.Schemas.ShipmentQuote],
optional: true,
label: "Quoted Methods"
}
});
|
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import routing from './main.routes';
import OrientacionesComponent from './orientaciones.component';
import TransversalesComponent from './transversales.component';
export class MainController {
/*@ngInject*/
constructor($http, $rootScope) {
this.$http = $http;
}
$onInit() {
//this.$http.get('/api/things')
// .then(response => {
// this.awesomeThings = response.data;
// });
}
}
export default angular.module('padApp.main', [uiRouter])
.config(routing)
.component('main', {
template: require('./main.html'),
controller: MainController,
controllerAs: 'vm'
})
.component('orientacion', {
template: require('./orientacion.html'),
controller: OrientacionesComponent,
controllerAs: 'vm'
})
.component('transversales', {
template: require('./transversales.html'),
controller: TransversalesComponent,
controllerAs: 'vm'
})
.name;
|
import { Form } from 'form/Form';
describe("Checks the Form object", function() {
let obj = null;
beforeEach(function() {
obj = new Form();
obj.init('name', document.body);
});
afterEach(function() {
obj.destroy();
});
it("checking if the object is defined", function() {
expect(obj).toBeDefined();
});
});
|
(function () {
'use strict';
angular
.module('smartmarket-web')
.controller('UserController', UserController);
UserController.$inject = ['$scope', '$rootScope', 'API', '$state'];
/**
* TodoController
* @param $scope
* @param $rootScope
* @param API
* @param $state
* @constructor
*/
function UserController($scope, $rootScope, API, $state) {
}
})();
|
/*
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function(root) {
var result = [];
if(!root){
return [];
}
traverseTree(root,"");
return result;
function traverseTree(node,str){
if( node.left === null && node.right === null ){
result.push( str+node.val );
}
else{
if( node.left !== null ){
traverseTree( node.left, str + node.val + '->' );
}
if( node.right !== null ){
traverseTree( node.right, str + node.val + '->' );
}
}
}
};
//tag: Google Facebook Apple
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.