text
stringlengths
2
6.14k
function createGroup(){ $('#createGroup-modal').modal(); } function getUsers(id,token){ $('#userGroup-modal').modal() $.ajax({ url:'/api/get-userlist-group/'+id, dataType:'json', headers:{ 'X-Key':token, } }) .done(function(response) { renderUsers(response); }) } function changeGroup(title,id,token){ $('#changeGroup-modal').modal(); renderGroup(title,id,token); } function deleteGroup(title,id,token){ $('#deleteGroup-modal').modal(); $('#warning').html('Вы действительно хотите удалить группу <span class"text-danger">'+title+'</span>?') $('#sub_delete').click(function(){ $.ajax({ url:'/api/delete-group/'+id, headers:{ 'X-Key':token, } }) .done(function(res) { if(res.result) location.reload(); else{ if(res.error) $('#error').text('Ошибка удаления!'); else $('#error').text('Вы не можете удалить группу, не удалив подгруппы!'); } }) }) } function renderUsers(response){ var html = '<div class="form-group">'; html += '<H3>Пользователи в группе</H3>'; for (var i in response) { html += '<div>'; html += '<a href="/profile/index/'+response[i].user_id+'" class="link-primary">'+response[i].username+'</a>'; html += '<a href="/profile/index/'+response[i].user_id+'" class="link-primary pull-right">'+response[i].rolename+'</a>'; html += '</div>'; } html += '</div>'; html += '<div class="btn-group" role="group">'; html += '<a href="/profile/create" class="btn btn-primary">Создать пользователя</a>'; html += '<button type="button" class="btn btn-primary" data-dismiss="modal">Закрыть</button>'; html += '</div>'; $('#container').html(html); } function renderGroup(title,id,token){ var html = '<div class="form-group">'; html += '<H3>Редактирование группы</H3>'; html += '</div>'; html += '<div class="form-group">'; html += '<label class="control-label" for="input">Название новой группы</label>'; html += '<input type="text" id="changeInput" class="form-control" name="group" value="'+title+'">'; html += '</div>'; html += '<div class="btn-group" role="group">'; html += '<button type="button" id="sub_save" class="btn btn-primary">Сохранить</a>'; html += '<button type="button" class="btn btn-primary" data-dismiss="modal">Отмена</button>'; html += '</div>'; $('#groupContainer').html(html); $('#sub_save').click(function(){ var value = $('#changeInput').val(); if(value.length > 0){ $.ajax({ url:'/api/change-group/'+id, method:'post', headers:{ 'X-Key':token, }, data:{title:value} }) .done(function(res) { if(res.result) location.reload(); $('#changeGroup-modal').modal('hide'); }) } }) }
/** * @author: Daniel Knobe * @copyright: Daniel Knobe * * @file */ /** * @class MenuState * * Used by the StateManager */ var MenuState = function(guiManager, soundManager) { /** * Return the name of the State */ this.getStateName = function() { return "MenuState"; } /** * Mainloop of State */ this.run = function() { /*if (this.HumanVsHuman.pressed()) { this.guiManager.deleteAllGUIElements(); playerHuman = 1; resetKeys(); stateManager.showGame(); }*/ if (this.HumanVsCPU.pressed()) { this.guiManager.deleteAllGUIElements(); playerHuman = 0; resetKeys(); stateManager.showGame(); } /*if (this.MuteSound.pressed()) { if (this.MuteSound.innerHTML == 'Unmute Sound') { this.MuteSound.innerHTML = 'Mute Sound'; this.soundManager.muteSound(false); } else { this.MuteSound.innerHTML = 'Unmute Sound'; this.soundManager.muteSound(true); } }*/ }; /** * @constructor * * Create GUI-Elements and draws the background */ this.soundManager = soundManager; this.guiManager = guiManager; guiManager.createText('Header1', 'Menu:', 40, 380); this.HumanVsHuman = guiManager.createButton('Button1', 'Human vs Human', 40, 410); this.HumanVsCPU = guiManager.createButton('Button2', 'Human vs CPU', 40, 440); guiManager.createText('Header2', 'Options:', 40, 480); var isSoundMutedText = 'Mute Sound'; /* if (soundManager.isSoundMuted() == true) { isSoundMutedText = 'Unmute Sound'; }*/ this.MuteSound = guiManager.createButton('Button3', isSoundMutedText, 40, 510); guiManager.createText('Header3', 'Keys:', 400, 380); guiManager.createText('Text3', 'a, w, d - control left blobby', 400, 410); guiManager.createText('Text4', 'h, u, k - control right blobby', 400, 440); guiManager.createText('Text4', 'Version 1.5 Daniel Knobe &copy;', 520, 550); guiManager.selectFirstSelectable(); drawMenu(); } module.exports = MenuState
var fabrikGraph = new Class( { initialize: function(el, d){ //todo doesnt seem to work with 1 record of data this.el =el; this.options = Object.extend({ legend: false, label: '', aChartKeys: {}, axis_label: '', json: {}, chartType: 'barChart', xticks:[] }, arguments[2] || {}); this.json = d; window.addEvent('domready',function(e){ this.render(); }.bind(this)) }, render: function(){ switch(this.options.chartType){ case 'BarChart': this.graph = new Plotr.BarChart(this.el, this.options); break; case 'PieChart': this.graph = new Plotr.PieChart(this.el, this.options); break; case 'LineChart': this.graph = new Plotr.LineChart(this.el, this.options); break; } this.graph.addDataset(this.json); this.graph.render(); if( this.options.legend == '1' ){ this.graph.addLegend(this.el); } } });
define([ 'ngw/openlayers' ], function (openlayers) { return openlayers.Class(openlayers.Control, { defaultHandlerOptions: { 'single': true, 'double': false, 'pixelTolerance': 0, 'stopSingle': false, 'stopDouble': false }, initialize: function (options) { if (!options) { options = {}; } this.handlerOptions = openlayers.Util.extend(options, this.defaultHandlerOptions); openlayers.Control.prototype.initialize.apply(this, arguments); this.handler = new openlayers.Handler.Click( this, { 'click': this.handlerOptions.callback }, this.handlerOptions ); } }); });
function setActiveStyleSheet(title) { var i, a, main; for(i=0; (a = document.getElementsByTagName("link")[i]); i++) { if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) { a.disabled = true; if(a.getAttribute("title") == title) a.disabled = false; } } }
/* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 3.1.2 build: 56 */ YUI.add("lang/datatype-date-format_es-ES",function(A){A.Intl.add("datatype-date-format","es-ES",{"a":["dom","lun","mar","mié","jue","vie","sáb"],"A":["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],"b":["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],"B":["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],"c":"%a, %d %b %Y %H:%M:%S %Z","p":["A.M.","P.M."],"P":["a.m.","p.m."],"x":"%d/%m/%y","X":"%H:%M:%S"});},"3.1.2");
var fs = require('fs'), path = require('path'), https = require('https'); var localeDir = path.join('src', 'locale'); var args = process.argv.slice(2); function help() { console.log(process.argv[1], '[list|mention|find-commenters] ARGS'); console.log(); console.log(" list show all authors in all locales"); console.log(" mention show all authors in all locales, ready to copy-paste in github issue"); console.log(" find-commenters #ID finds all people that participated in a github conversation"); } function extract() { var authors = {}; fs.readdirSync(localeDir).forEach(function (locale) { var content = fs.readFileSync(path.join(localeDir, locale), {encoding: 'utf-8'}), localeCode = locale.split('.')[0], localeAuthors = []; content.split('\n').forEach(function (line) { var match = line.match(/^\/\/! author.*github[.]com\/(.*)$/); if (match !== null) { // console.log(" ", line); localeAuthors.push(match[1]); } }); if (localeAuthors.length === 0) { // use to debug content.split('\n').forEach(function (line) { var match = line.match(/^\/\/! author(.*)$/); if (match !== null) { // console.log(" ", line); localeAuthors.push('---' + match[1]); } }); console.log(localeCode, localeAuthors); } else { authors[localeCode] = localeAuthors; } }); return authors; } function list() { var authors = extract(); Object.keys(authors).forEach(function (localeCode) { console.log(localeCode, authors[localeCode]); }); } function mention() { var authors = extract(); Object.keys(authors).forEach(function (localeCode) { console.log('- [ ]', localeCode, authors[localeCode].map(function (author) { return "@" + author; }).join(" ")); }); } function findCommenters(postId) { function fetchComments(page, callback) { var options = { hostname: 'api.github.com', port: 443, path: '/repos/moment/moment/issues/' + postId + '/comments?page=' + page, method: 'GET', headers: { 'User-Agent': 'node script' } }, links = {}; console.log('fetching', options.path); https.get(options, function (res) { if ('link' in res.headers) { res.headers.link.split(', ').forEach(function(linkStr) { var pieces = linkStr.split('; '); var key = pieces[1].split('=')[1]; var link = pieces[0]; key = key.substr(1, key.length - 2); link = link.substr(1, link.length - 2); links[key] = link; }); } var bodyChunks = [], body; res.on('data', function (chunk) { bodyChunks.push(chunk); }); res.on('end', function () { body = bodyChunks.join(''); callback(page, JSON.parse(body), links); }); }); } var commenters = {}; var maxPage = 1; fetchComments(1, function (page, body, links) { handleBody(body, page); if ('last' in links) { maxPage = parseInt(links.last.split('=')[1], 10); } var pagesLeft = maxPage - 1; for (var p = 2; p <= maxPage; p += 1) { fetchComments(p, function (page, body, links) { handleBody(body, page); pagesLeft -= 1; if (pagesLeft === 0) { handleCommenters(Object.keys(commenters)); } }); } }); function handleBody(body, page) { body.forEach(function (comment) { console.log(page, comment.user.login); commenters[comment.user.login] = 1; }); } function handleCommenters(commenters) { console.log('len of commenters', commenters.length); console.log(commenters); } } if (args.length === 0) { help(); process.exit(0); } switch (args[0]) { case 'list': list(); break; case 'mention': mention(); break; case 'find-commenters': findCommenters(args[1]); break; default: console.log("unknown argument", args[0]); break; }
jQuery(document).ready( function($) { $('#registration_ticket').focus(); $('#registration_form').on('keyup', '#registration_ticket', function(event){ if($(this).val().length == 9){ $('#registration_form').submit(); } }); });
require.config({ paths:{ vue:'../../../bower_components/vue/dist/vue.min', }, shim: {      } }); requirejs(['vue'],function(Vue){ Vue.component('child',{ template:'<div>{{text}}<slot name="header"></slot><slot></slot></div>' }); new Vue({ el:'#app', data (){ return{ text:'ggg', message : 'nihao' } } }) window.onbeforeunload = function() { return "真的离开?"; } });
/* * Kendo UI v2015.2.805 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["nso"] = { name: "nso", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-%n","%n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$-n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "R" } }, calendars: { standard: { days: { names: ["Lamorena","Mošupologo","Labobedi","Laboraro","Labone","Labohlano","Mokibelo"], namesAbbr: ["Lam","Moš","Lbb","Lbr","Lbn","Lbh","Mok"], namesShort: ["La","Mo","Lb","Lr","Ln","Lh","Mk"] }, months: { names: ["Janaware","Feberware","Matšhe","Aprele","Mei","June","Julae","Agostose","Setemere","Oktoboro","Nofemere","Disemere"], namesAbbr: ["Jan","Feb","Matš","Apr","Mei","June","Julae","Agost","Set","Oky","Nof","Dis"] }, AM: ["MS","ms","MS"], PM: ["TP","tp","TP"], patterns: { d: "dd/MM/yy", D: "dd MMMM yyyy", F: "dd MMMM yyyy hh:mm:ss tt", g: "dd/MM/yy hh:mm tt", G: "dd/MM/yy hh:mm:ss tt", m: "MMMM d", M: "MMMM d", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "hh:mm tt", T: "hh:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
/*global CKEDITOR, dotclear, $ */ 'use strict'; (() => { CKEDITOR.plugins.add('dclink', { icons: 'dclink', init(editor) { editor.addCommand('dcLinkCommand', { exec(editor) { if ( editor.getSelection().getSelectedElement() != null || editor.getSelection().getNative().toString().replace(/\s*/, '') != '' ) { $.toolbarPopup('popup_link.php?plugin_id=dcCKEditor'); } }, }); editor.ui.addButton('dcLink', { label: dotclear.msg.link_title, command: 'dcLinkCommand', toolbar: 'insert', }); editor.on('doubleclick', (e) => { const element = CKEDITOR.plugins.link.getSelectedLink(editor) || e.data.element; if ( !element.isReadOnly() && element.is('a') && !element.hasClass('media-link') && // link to original media @see js/popup_media.js !element.hasClass('ref-post') ) { // link to an entry @see js/popup_posts.js editor.getSelection().selectElement(element); let popup_url = 'popup_link.php?plugin_id=dcCKEditor'; if (element.getAttribute('href')) { popup_url += `&href=${element.getAttribute('href')}`; } if (element.getAttribute('hreflang')) { popup_url += `&hreflang=${element.getAttribute('hreflang')}`; } if (element.getAttribute('title')) { popup_url += `&title=${element.getAttribute('title')}`; } $.toolbarPopup(popup_url); return false; } }); }, }); })();
// Generated by CoffeeScript 1.6.2 (function() { jQuery('document').ready(function($) { $('.gameover').hide(); $('.gameend').hide(); if (localStorage.highscore) { jQuery('.highscore').html(localStorage.highscore); } $('.start').click(function() { $('.menu').hide("drop", { direction: "left" }, "slow", function() { return ig.main('#canvas', GritsEvasion, 60, window.innerWidth, window.innerHeight, 1); }); return $('.hud').show(); }); $('.pause').click(function() { return ig.game.resumeGame(); }); $('.back2menu').click(function() { $('.gameover').hide("drop", { direction: "left" }, "slow"); return $('.menu').show("drop", { direction: "left" }, "slow"); }); return $(window).resize(function() { if (ig.system) { return ig.system.resize(window.innerWidth, window.innerHeight); } }); }); }).call(this);
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ var controllerModule = angular.module('ingsoftblogControllers'); controllerModule.controller('loginController', ['$scope', '$rootScope', '$location', 'authService', function ($scope, $rootScope, $location, authService) { $scope.user = { userName: "", password: "" }; $scope.login = function(user) { authService.login(user).then(function(response) { if (response.success) { $rootScope.loggedIn = true; $location.path('/admin'); } else { $rootScope.loggedIn = false; $scope.error = true; } }, function(response) { $scope.error = true; }); }; }]);
/* * Kendo UI v2015.2.805 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["es-NI"] = { name: "es-NI", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["($n)","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3,0], symbol: "C$" } }, calendars: { standard: { days: { names: ["domingo","lunes","martes","miércoles","jueves","viernes","sábado"], namesAbbr: ["dom","lun","mar","mié","jue","vie","sáb"], namesShort: ["do","lu","ma","mi","ju","vi","sá"] }, months: { names: ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"], namesAbbr: ["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"] }, AM: ["a.m.","a.m.","A.M."], PM: ["p.m.","p.m.","P.M."], patterns: { d: "dd/MM/yyyy", D: "dddd, d' de 'MMMM' de 'yyyy", F: "dddd, d' de 'MMMM' de 'yyyy hh:mm:ss tt", g: "dd/MM/yyyy hh:mm tt", G: "dd/MM/yyyy hh:mm:ss tt", m: "d' de 'MMMM", M: "d' de 'MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "hh:mm tt", T: "hh:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM' del 'yyyy", Y: "MMMM' del 'yyyy" }, "/": "/", ":": ":", firstDay: 0 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
'use strict'; angular.module('allocine-api').factory('AlloCineExposed', [ '$http', 'Config', 'Authentication', function ($http, Config, Authentication) { var allocineExposed = {}; var httpConfig = null; var endpoint = function (path) { var creds = Authentication.credentials ? Authentication.credentials.token : null; httpConfig = { headers: { 'auth-web-token': creds } }; return Config.apiRoute + path; }; allocineExposed.searchByName = function (type, name) { return $http.get(endpoint('/allocine/type/' + type + '/name/' + name), httpConfig); }; allocineExposed.getMovieById = function (type, id) { return $http.get(endpoint('/allocine/type/' + type + '/id/' + id), httpConfig); }; return allocineExposed; } ]);
// Application & Component Prototype /* Application prototype */ var Application = { initState: 0, // 0 - not initialized, 1 - initializing, 2 - initialized configuration: {}, init: function() { Application.initState = 1; Application.util.init(); Application.event.init(); Application.connect.init(); // Load the default configuration Application.connect.ajax({ url: "/configuration/configuration.json", successFunction: function( jsonEl, text ) { Application.configuration = jsonEl; Application.effects.init(); Application.debug.init({ afterInit: function() { // Init Components Component.init(); // Init queued functions Application.loader.init(); } }); } }); }, util: { init: null, connect: { init: null, ajax: null }, browserInformation: { init: null }, serialize: { init: null }, style: { init: null }, selectText: { init: null } }, event: { add: null, remove: null }, debug: { }, loader: { componentsQueue: [], widgetsQueue: [], initializingScripts: 0, init: function() { if( Application.loader.initializingScripts > 0 ) { // Delaying the components and widgets init until the scripts have loaded setTimeout( Application.loader.init, 50 ); return; } for(var i in Application.loader.widgetsQueue) { if( typeof Application.loader.widgetsQueue[ i ] != 'object' ) { continue; } Application.loader.widgetsQueue[i].widgetObject().init( Application.loader.widgetsQueue[ i ].args ); } for(var i in Application.loader.componentsQueue) { if( typeof Application.loader.componentsQueue[ i ] != 'object' ) { continue; } Application.loader.componentsQueue[i].componentObject().init( Application.loader.componentsQueue[ i ].args ); } Application.loader.widgetsQueue = []; Application.loader.componentsQueue = []; Application.initState = 2; // All fully initialized }, addComponent: function( args ) { if( typeof args != "object" || !args.componentObject || !args.componentID ) { return false; } if( typeof Application.loader.componentsQueue[ args.componentID ] == 'undefined' ) { Application.loader.componentsQueue[ args.componentID ] = { componentObject: args.componentObject, args: [] }; } Application.loader.componentsQueue[ args.componentID ].args.push( args.initArgs ); return true; }, addWidget: function( args ) { if( typeof args != "object" || !args.widgetObject || !args.widgetID ) { return false; } if( typeof Application.loader.widgetsQueue[ args.widgetID ] == 'undefined' ) { Application.loader.initializingScripts++; // Load the widget JS file var scriptObject = document.createElement('script'); scriptObject.src = "/widgets/" + args.widgetID + "/application.widget." + args.widgetID + ".js"; scriptObject.type = "text/javascript"; document.getElementsByTagName("head")[0].appendChild( scriptObject ); // FF Specific scriptObject.onload = function() { Application.loader.initializingScripts--; /* if( Application.debug.add ) { Application.debug.add("Widget " + args.widgetID + " loaded"); } */ } // IE Specific scriptObject.onreadystatechange = function() { if( scriptObject.readyState != "loaded" ) { return; } Application.loader.initializingScripts--; /* if( Application.debug.add ) { Application.debug.add("Widget " + args.widgetID + " loaded"); } */ } // Append into the init queue Application.loader.widgetsQueue[ args.widgetID ] = { widgetObject: args.widgetObject, args: [] }; } Application.loader.widgetsQueue[ args.widgetID ].args.push( args.initArgs ); return true; }, remove: function( args ) { } }, widget: { } }; /* Component prototype */ var Component = { init: function() { } };
'use strict'; module.exports = function (grunt) { grunt.registerTask('dev', [ 'ngconstant:dev', 'injector', 'connect', 'watch']); };
module.exports = 0.25;
document.addEventListener('DOMContentLoaded', function(){ Typed.new('#typed', { stringsElement: document.getElementById('typed-strings'), loop: true, typeSpeed: 100, }); }); jQuery(document).ready(function(){ // Select all links with hashes jQuery('a[href*="#"]') // Remove links that don't actually link to anything .not('[href="#"]') .not('[href="#0"]') .click(function(event) { // On-page links if ( location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname ) { // Figure out element to scroll to var target = jQuery(this.hash); target = target.length ? target : jQuery('[name=' + this.hash.slice(1) + ']'); // Does a scroll target exist? if (target.length) { // Only prevent default if animation is actually gonna happen event.preventDefault(); jQuery('html, body').animate({ scrollTop: target.offset().top }, 1000, function() { // Callback after animation // Must change focus! var jQuerytarget = jQuery(target); jQuerytarget.focus(); if (jQuerytarget.is(":focus")) { // Checking if the target was focused return false; } else { jQuerytarget.attr('tabindex','-1'); // Adding tabindex for elements not focusable jQuerytarget.focus(); // Set focus again }; }); } } }); });
// $Id: form.js,v 1.1 2007/09/12 18:29:32 goba Exp $ Drupal.behaviors.multiselectSelector = function() { // Automatically selects the right radio button in a multiselect control. $('.multiselect select:not(.multiselectSelector-processed)') .addClass('multiselectSelector-processed').change(function() { $('.multiselect input:radio[value="'+ this.id.substr(5) +'"]') .attr('checked', true); }); };
jQuery(document).ready(function($) { var formfield = null, formfielddeux = null, num =''; $('.get-image').on( 'click', function() { $('html').addClass('image_spe'); num = $(this).attr('data-num'); formfield = $('.id_img[data-num="'+num+'"]').attr('name'); var id=$("#post_ID").val(); tb_show('', 'media-upload.php?post_id='+id+'&type=image&TB_iframe=true'); return false; }); $('.del-image').on('click', function(){ var cible = $(this).attr('data-num'); $('.img-preview[data-num="'+cible+'"]').empty(); $('.id_img[data-num="'+cible+'"]').val(''); }); $('.upload_pdf_button').live('click',function() { $('html').addClass('pdf'); num = $(this).attr('data-cible'); formfielddeux = $('.url_pdf_input[data-input="'+num+'"]').attr('name'); var id=$("#post_ID").val(); tb_show('', 'media-upload.php?post_id='+id+'&type=file&TB_iframe=true'); return false; }); // user inserts file into post. only run custom if user started process using the above process // window.send_to_editor(html) is how wp would normally handle the received data window.original_send_to_editor = window.send_to_editor; window.send_to_editor = function(html){ var fileurl; if (formfield !== null) { var matches = html.match(/wp-image-([0-9]*)/); $('input[name="' + formfield + '"]').val(matches[1]); var imgfull = $(html).find('img').css({width:"100px", height:"100px"}); $('.img-preview[data-num="'+num+'"]').append($(imgfull)); tb_remove(); $('html').removeClass('image_spe'); formfield = null; num = null; } else { if(formfielddeux !== null) { fileurl = $(html).filter('a').attr('href'); $('.url_pdf_input[data-input="'+num+'"]').val(fileurl); tb_remove(); $('html').removeClass('pdf'); formfielddeux = null; num = null; } else { window.original_send_to_editor(html); } } } });
/************************************************************************************************** * Archivo: FormularioController.js * ------------------------------------------------------------------------------------------------ * Version: 1.0 * Descripcion: * Modificaciones: * - * * Nota: Registrar en este encabezado todas las modificaciones hechas al archivo. **************************************************************************************************/ Ext.define ('Sistema.view.Sistema.Provincia.FormularioController', { extend: 'Ext.app.ViewController', alias: 'controller.sis-prov-FormularioController', init: function () { FormularioControllerBase.InyectarDependencia (this, 'Sistema.view.Sistema.model.Provincia', 'Sistema:Provincia'); this.control ({ "button[name='btnBorrar']": { click: this.onBtnBorrarClick }, "button[name='btnGuardar']": { click: this.onBtnGuardarClick }, "sis-prov-Formulario": { afterrender: this.onRender } }); }, SetearParametrosFormulario: function (ctl) { ctl.params.anchoVentana = 500; ctl.params.altoVentana = 190; }, CargarComponentes: function () { var me = this; this.params.nombreEntidad = 'Provincia'; this.ctl.cbPaisId = this.getView ().down ("combo[name='cbPaisId']"); this.ctl.tbNombre = this.getView ().down ("textfield[name='tbNombre']"); this.ctl.tbAbreviatura = this.getView ().down ("textfield[name='tbAbreviatura']"); }, GetElementoFoco: function () { return "combo[name='cbPaisId']"; }, CargarRegistroEnFormulario: function (rec, esNuevo) { this.params.registro = rec; this.ctl.cbPaisId.store.reload (); this.ctl.cbPaisId.setValue (rec.get ('paisId')); this.ctl.tbNombre.setValue (rec.get ('nombre')); this.ctl.tbAbreviatura.setValue (rec.get ('abreviatura')); }, ObtenerRegistroDeFormulario: function () { this.params.registro.set ('paisId', this.ctl.cbPaisId.value); this.params.registro.set ('nombre', this.ctl.tbNombre.value); this.params.registro.set ('abreviatura', this.ctl.tbAbreviatura.value); return this.params.registro; } });
$(document).ready(function(){ $("input:button").removeAttr("disabled"); $("#resposta").click(function(){ var certo = "../../../../readinweb-tool/content/modulos/exercicios/imagens/certo.gif"; var errado = "../../../../readinweb-tool/content/modulos/exercicios/imagens/errado.gif"; if ($("#opcao1").val() == "4") { $("#resp1").attr({ src: certo}); } else {$("#resp1").attr({ src: errado});}; if ($("#opcao2").val() == "2") { $("#resp2").attr({ src: certo}); } else {$("#resp2").attr({ src: errado});}; if ($("#opcao3").val() == "1") { $("#resp3").attr({ src: certo}); } else {$("#resp3").attr({ src: errado});}; if ($("#opcao4").val() == "3") { $("#resp4").attr({ src: certo}); } else {$("#resp4").attr({ src: errado});}; }); });
jQuery(document).ready(function(){ /*RESPONSIVE NAVIGATION, COMBINES MENUS EXCEPT FOR FOOTER MENU*/ jQuery('.menu').not('#footer .menu, #footer-widgets .menu').wrap('<div id="nav-response" class="nav-responsive">'); jQuery('#nav #nav-response').append('<a href="#" id="pull" class="closed"><strong>MENU</strong></a>'); //move the search box if(jQuery('#pull').css('display') != 'none'){ var mysearch = jQuery('.nav-responsive').find('li.search'); jQuery('#pull').before(mysearch); } //combinate sf_duplicate_menu( jQuery('.nav-responsive>ul').not('#sidebar .nav-responsive>ul'), jQuery('#pull'), 'mobile_menu', 'sf_mobile_menu' ); function sf_duplicate_menu( menu, append_to, menu_id, menu_class ){ var jQuerycloned_nav; menu.clone().attr('id',menu_id).removeClass().attr('class',menu_class).appendTo( append_to ); jQuerycloned_nav = append_to.find('> ul'); jQuerycloned_nav.find('.menu_slide').remove(); jQuerycloned_nav.find('li:first').addClass('sf_first_mobile_item'); append_to.click( function(){ if ( jQuery(this).hasClass('closed') ){ jQuery(this).removeClass( 'closed' ).addClass( 'opened' ); jQuerycloned_nav.slideDown( 500 ); } else { jQuery(this).removeClass( 'opened' ).addClass( 'closed' ); jQuerycloned_nav.slideUp( 500 ); } return false; } ); append_to.find('a').click( function(event){ event.stopPropagation(); } ); } jQuery('#pull li.menu-item-53>a').click( function(){ if ( jQuery(this).parent('li').hasClass('opened') ){ jQuery(this).parent('li').removeClass( 'opened' ).addClass( 'closed' ); jQuery(this).parent('li').find('.sub-menu').slideUp( 500 ); } else { jQuery(this).parent('li').removeClass( 'closed' ).addClass( 'opened' ); jQuery(this).parent('li').find('.sub-menu').slideDown( 500 ); } return false; } ); });
showWord(["n. ","separasyon nan yon espas pou kreye lòt espas endepandan. Klwazon.<br>"])
var valid; (function ( $ ) { "use strict"; $(function () { // form submit action $('#pfSaveSettings').bind('submit', function(e) { valid = true; $('.pfFormReq').each(function(){ if($(this).val()==null || $(this).val()=='' || $(this).val()==' '){ $(this).addClass('pfError'); valid = false; } else { $(this).removeClass('pfError'); } }); if (valid == true) { // continue } else { // scroll to top of error if($('.pfError').length > 0) { var firstErrorTop = $('.pfError').eq(0).offset().top; $("html, body").animate({ scrollTop: firstErrorTop-100 },1000,'swing'); } e.preventDefault(); } }); }); }(jQuery)); function pfValid_payhip_user(elementD,jQ,eee) { var formHtml = elementD.closest('form'); var elementVal = elementD.val(); if(elementVal != '') { valid = false; jQ.ajax({ type: 'POST', url: pf_json_admin_data .ajaxURL, dataType : "json", data: { userNa : encodeURIComponent(elementD.val()), action: 'pfPayhipData' }, success: function(data) { if (data.status == 'success') { // success valid = true; if (data.count == '0') { valid = false; elementD.addClass('pfError'); if(formHtml.length) { formHtml.prepend("<div class='updated'><p>Payhip username is correct but 0 items found on web.</p></div>"); formHtml.find(".updated").delay(5000).fadeOut(500); } } else { valid = true; elementD.off('submit'); } } else if (data.status == 'failure') { valid = false; elementD.addClass('pfError'); if(formHtml.length) { formHtml.prepend("<div class='updated'><p>Payhip username is wrong.</p></div>"); formHtml.find(".updated").delay(5000).fadeOut(500); } } console.log('success ' + valid); }, complete: function(data) { var parsePFDate = JSON.parse(data.responseText); console.log('status : ' + parsePFDate.status + ' & count : ' + parsePFDate.count); if (parsePFDate.status == 'success' && parsePFDate.count != '0') { valid = true; console.log('complete ' + valid); } } }) } }
(function ($) { $(document).ready(function() { $("input#edit-same").click(function() { if ($("input#edit-same").is(':checked')) { // Checked, copy values $("input#edit-shipping-first-name").val($("input#edit-cc-first-name").val()); $("input#edit-shipping-last-name").val($("input#edit-cc-last-name").val()); $("input#edit-shipping-address1").val($("input#edit-billing-address1").val()); $("input#edit-shipping-address2").val($("input#edit-billing-address2").val()); $("input#edit-shipping-city").val($("input#edit-billing-city").val()); $("input#edit-shipping-state").val($("input#edit-billing-state").val()); $("input#edit-shipping-country").val($("input#edit-billing-country").val()); $("input#edit-shipping-phone").val($("input#edit-billing-phone").val()); $("input#edit-shipping-zip").val($("input#edit-billing-zip").val()); } else { // Clear on uncheck $("input#edit-shipping-first-name").val(""); $("input#edit-shipping-last-name").val(""); $("input#edit-shipping-address1").val(""); $("input#edit-shipping-address2").val(""); $("input#edit-shipping-city").val(""); $("input#edit-shipping-state").val(""); $("input#edit-shipping-country").val(""); $("input#edit-shipping-phone").val(""); $("input#edit-shipping-zip").val(""); } }); }); })(jQuery);
/* global Ext */ Ext.define( 'App.model.Download', { extend: 'Ext.data.Model', fields: [ {name: 'id', type: 'int'}, {name: 'name', type: 'string'}, {name: 'filename', type: 'string'}, {name: 'originalName', type: 'string'}, {name: 'mask', type: 'string'}, {name: 'maxAllowed', type: 'int'} ] });
$(document).ready(function(){ var validacion=false; $('#liFecha').hide(); $('.liRangoFecha').hide(); $('#divDetalleOrdenVenta').hide(); msboxTitle = "Guia Pedidos del Vendedor"; var codigoInicial=$('#codigoVendedor').val(); $('#lstLinea').change(function(){ cargaSubLinea(); }); $('#btnConsultar').click(function(e){ e.preventDefault(); cargaTabla(); }); $('input[name="rbFiltro"]').change(function(){ $('#divDetalleOrdenVenta').hide(); $('#txtFecha').val(''); $('#txtFechaInicio').val(''); $('#txtFechaFinal').val(''); if(this.value == "1"){ $('#liFecha').hide(); $('.liRangoFecha').hide(); }else if(this.value == "2"){ $('#liFecha').hide(); $('.liRangoFecha').hide(); }else if(this.value == "3"){ $('#liFecha').hide(); $('.liRangoFecha').hide(); }else if(this.value == "4"){ $('#liFecha').show(); $('.liRangoFecha').hide(); }else{ $('#liFecha').hide(); $('.liRangoFecha').show(); } }); //Mostrar el detalle de la orden de pedido $('.btnDetalleOrdenVenta').click(function(e){ e.preventDefault(); $('#tblOrdenVenta tr').removeClass(); $(this).parents('tr').addClass('active-row'); var ruta = $(this).attr('href'); mostrarDetalleOrdenVenta(ruta); }); /* Lista de busqueda*/ $("#seleccion").change(function(){ var id=$("#seleccion option:selected").text(); var url='/vendedor/lista/'+id; window.location=url; }); /*Cancelar el registro*/ $('#btnCancelar').on('click',function(e){ e.preventDefault(); window.location = '/vendedor/lista/'; }); $('#codigoVendedor').on('keyup',function(e){ e.preventDefault(); if ($(this).val()!=codigoInicial) { codigo=$('#codigoVendedor').attr('value'); $.ajax({ url: '/vendedor/validarCodigo/', type: 'POST', async: false, dataType:'json', data:{'codigo':codigo}, success: function(respuesta){ //console.log(respuesta) $('#error').text(respuesta.error); validacion=respuesta.verificado; if(codigo==""){ validacion=false; $('#error').text(''); $('#error').css({'color':'red'}); $('#error').text("Codigo Vacio"); }else if (validacion==true) { $('#error').css({'color':'green'}); //$('#codigoVendedor').attr('readonly','readonly'); }else{ $('#error').css({'color':'red'}) }; }, error: function(jqXHR, status, error) { //console.log(status) //console.log(error) } }); }else if($(this).val()==""){ $('#error').css({'color':'red'}); $('#error').text("Codigo Vacio"); validacion=false; }else if ($(this).val()==codigoInicial && $(this).val()!="" && $(this).val()!="0") { $('#error').css({'color':'green'}); $('#error').text('Codigo Actual'); validacion=true; } console.log(codigoInicial); console.log(validacion); }); $('#enviar').on('click',function(e){ if (validacion==false) { e.preventDefault(); alert("Codigo Invalido"); }; }); $('#enviarActualiza').on('click',function(e){ if (validacion==false) { e.preventDefault(); alert("Codigo Invalido"); }; }); }); msboxTitle = "Guia Pedidos Vendedor"; /*Carga tabla guia de pedidos*/ function cargaTabla(){ var fecha = $('#txtFecha').val(); var fechaInicio = $('#txtFechaInicio').val(); var fechaFinal = $('#txtFechaFinal').val(); filtro = $('input[name="rbFiltro"]:checked').val(); mensaje = ""; if(filtro == "4"){ if(fecha == ""){ mensaje = "Seleccione correctamente la fecha a buscar."; } }else if(filtro == "5"){ if(fechaInicio == "" || fechaFinal ==""){ mensaje = "Seleccione correctamente el rango de fecha a buscar."; } }else{ mensaje = ""; } if(mensaje!=""){ $.msgbox(msboxTitle, mensaje); }else{ ruta = "/ordenventa/listaxvendedor/"; $.post(ruta, {filtro: filtro, fecha: fecha, fechaInicio: fechaInicio, fechaFinal: fechaFinal}, function(data){ $('#tblOrdenVenta tbody').html(data); $('#tblOrdenVenta').show(); }); } } //Mostrar detalle de la orden de compra function mostrarDetalleOrdenVenta(ruta){ $.post(ruta, function(data){ $('#divDetalleOrdenVenta').show(); $('#tblDetalleOrdenVenta tbody').html(data); if($('#txtObservacionVentas').val().length){ $('#liObservacionVentas').show(); }else{ $('#liObservacionVentas').hide(); } if($('#txtObservacionCobranzas').val().length){ $('#liObservacionCobranzas').show(); }else{ $('#liObservacionCobranzas').hide(); } if($('#txtObservacionCreditos').val().length){ $('#liObservacionCreditos').show(); }else{ $('#liObservacionCreditos').hide(); } }); } /*Messagebox -------------------------------------------------------------- */ function execute(){ var marginTop = "-" + ($("#msgbox").height() / 2) + "px"; var marginLeft = "-" + ($("#msgbox").width() / 2) + "px"; $("#msgbox").css({"margin-top":marginTop, "margin-left":marginLeft}); }
'use strict'; angular.module('person') .factory('Person', function($resource) { return $resource('/persons/:id.json', {id:'@id'}, { query: { method: 'GET', isArray: false , url: '/persons.json'}, put: {method: 'PUT'}, publications: {method: 'GET', url:'/persons/:id/publications.json'}, contacts: {method: 'GET', url: '/persons/:id/contacts.json'}, network: {method: 'GET', url: '/persons/:id/network.json'} }); }) .service('PersonState', function() { this.person = {}; });
define( [ "jquery", "scripts/common_scripts/backend/common_ajax_handlers" ], function( $, ajax_handlers ) { "use strict"; // jshint ;_; var dismiss_plugins_messages_handler = function( e ) { var data = { "action" : 'ai1ec_facebook_cron_dismiss' }; $.post( ajaxurl, data, ajax_handlers.handle_dismiss_plugins, 'json' ); }; var dismiss_notification_handler = function( e ) { var $button = $( this ); // disable the update button $button.attr( 'disabled', true ); // create the data to send var data = { action: 'ai1ec_disable_notification', note : false }; $.post( ajaxurl, data, ajax_handlers.handle_dismiss_notification ) ; }; var dismiss_intro_video_handler = function( e ) { var $button = $( this ); // Disable the update button. $button.attr( 'disabled', true ); // Create the data to send. var data = { action: 'ai1ec_disable_intro_video', note : false }; $.post( ajaxurl, data, ajax_handlers.handle_dismiss_intro_video ) ; }; /** * Dismiss button clicked in invalid license warning. * * @param {Event} e jQuery event object */ var dismiss_license_warning_handler = function( e ) { var $button = $( this ); // Disable the update button. $button.attr( 'disabled', true ); // Create the data to send. var data = { action: 'ai1ec_set_license_warning', value: 'dismissed' }; $.post( ajaxurl, data, ajax_handlers.handle_dismiss_license_warning ) ; }; // Show/hide the multiselect containers when user clicks on "limit by" widget options var handle_multiselect_containers_widget_page = function( e ) { $( this ).parent().next( '.ai1ec-limit-by-options-container' ).toggle(); }; return { dismiss_plugins_messages_handler : dismiss_plugins_messages_handler, dismiss_notification_handler : dismiss_notification_handler, dismiss_intro_video_handler : dismiss_intro_video_handler, dismiss_license_warning_handler : dismiss_license_warning_handler, handle_multiselect_containers_widget_page : handle_multiselect_containers_widget_page }; } );
//输入提示 function autoSearch() { var keywords = document.getElementById("locationkeywords").value; if(keywords == '') { document.getElementById("result1").style.display = "none"; return; } var auto; var autoOptions = { pageIndex:1, pageSize:10, city: curCity //城市,默认全国 }; auto = new AMap.Autocomplete(autoOptions); //查询成功时返回查询结果 AMap.event.addListener(auto, "complete", autocomplete_CallBack); auto.search(keywords); } //输出输入提示结果的回调函数 function autocomplete_CallBack(data) { var resultStr = ""; var tipArr = []; tipArr = data.tips; if (tipArr.length>0) { for (var i = 0; i < tipArr.length; i++) { resultStr += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById(" + (i + 1) + ",this)' onclick='selectResult(" + i + ")' onmouseout='onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 13px;cursor:pointer;padding:5px 5px 5px 5px;\">" + tipArr[i].name + "<span style='color:#C1C1C1;'>"+ tipArr[i].district + "</span></div>"; } } else { resultStr = " π__π 亲,人家找不到结果!<br />要不试试:<br />1.请确保所有字词拼写正确<br />2.尝试不同的关键字<br />3.尝试更宽泛的关键字"; } document.getElementById("result1").innerHTML = resultStr; document.getElementById("result1").style.display = "block"; } //输入提示框鼠标滑过时的样式 function openMarkerTipById(pointid, thiss) { //根据id打开搜索结果点tip thiss.style.background = '#CAE1FF'; } //输入提示框鼠标移出时的样式 function onmouseout_MarkerStyle(pointid, thiss) { //鼠标移开后点样式恢复 thiss.style.background = ""; } //从输入提示框中选择关键字并查询 function selectResult(index) { if (navigator.userAgent.indexOf("MSIE") > 0) { document.getElementById("locationkeywords").onpropertychange = null; document.getElementById("locationkeywords").onfocus = focus_callback; } //截取输入提示的关键字部分 var text = document.getElementById("divid" + (index + 1)).innerHTML.replace(/<[^>].*?>.*<\/[^>].*?>/g,"");; document.getElementById("locationkeywords").value = text; document.getElementById("result1").style.display = "none"; //根据选择的输入提示关键字查询 mapObj.plugin(["AMap.PlaceSearch"], function() { var msearch = new AMap.PlaceSearch(); //构造地点查询类 AMap.event.addListener(msearch, "complete", placeSearch_CallBack); //查询成功时的回调函数 msearch.search(text); //关键字查询查询 }); } //定位选择输入提示关键字 function focus_callback() { if (navigator.userAgent.indexOf("MSIE") > 0) { document.getElementById("locationkeywords").onpropertychange = autoSearch; } } //输出关键字查询结果的回调函数 function placeSearch_CallBack(data) { var poiArr = data.poiList.pois; var resultCount = poiArr.length; if(resultCount > 0) { showLoading("加载中..."); //清空地图上的InfoWindow和Marker windowsArr = []; marker = []; mapObj.clearMap(); addmarker(0, poiArr[0].location); } else { toast("未找到该地址附近活动!"); } mapObj.setFitView(); } //添加查询结果的marker&infowindow function addmarker(i, loc) { var lngX = loc.getLng(); var latY = loc.getLat(); var markerOption = { map:mapObj, icon:"http://webapi.amap.com/images/marker_sprite.png", position:new AMap.LngLat(lngX, latY) }; var mar = new AMap.Marker(markerOption); marker.push(new AMap.LngLat(lngX, latY)); startGetActivitiesFromService(lngX,latY); }
app.controller("leftNavController",function($scope){ $scope.blogNavStatus = true;//close $scope.clickBlogNav = function(){ //console.log("博客菜单") if($scope.blogNavStatus){ $scope.blogNavStatus = false; $("#blog-ul").collapse('show')//.css("display","block") }else{ $scope.blogNavStatus = true; $("#blog-ul").collapse('hide')//.css("display","none") } } })
var LoginController = function(options) {}; // needed for detection LoginController.update = function(vars, data) { if (data['function']) { LoginController[data['function']](data['arguments']); return; } var targetId = '#'+data['targetid']; // render the new html using mustache and the data from the server and show it var rendered = Mustache.render(vars["template"],data); $(targetId).html(rendered); $(targetId+" > form > button").on('click', function() { var obj = {}; obj['user'] = $(targetId +" input[type='text']").val(); obj['pass'] = $(targetId +" input[type='password']").val(); eddie.sendEvent(data['targetid'],"loginSubmitted",obj); }); }; LoginController.redirect = function() { location.reload(); };
'use strict'; /** * links-national.js * Foxtrick add links to national pages * @author convinced, LA-MJ */ Foxtrick.modules.LinksNational = { MODULE_CATEGORY: Foxtrick.moduleCategories.LINKS, PAGES: ['national'], LINK_TYPES: 'nationalteamlink', /** * return HTML for FT prefs * @param {document} doc * @return {HTMLUListElement} */ OPTION_FUNC: function(doc) { // @ts-ignore return Foxtrick.util.links.getPrefs(doc, this); }, /** @param {document} doc */ run: function(doc) { // @ts-ignore Foxtrick.util.links.run(doc, this); }, /** * @param {document} doc * @return {LinkPageDefinition} */ links: function(doc) { let main = doc.getElementById('mainBody'); let header = main.querySelector('h1'); let LeagueOfficeTypeID = -1; if (header) { // eslint-disable-next-line no-magic-numbers LeagueOfficeTypeID = /U21/.test(header.textContent) ? 4 : 2; } let leagueId = Foxtrick.util.id.findLeagueId(main); let ntTeamId = Foxtrick.Pages.All.getId(doc); let info = { leagueId, ntTeamId, LeagueOfficeTypeID, }; /** @type {LinkPageType[]} */ let types = ['nationalteamlink']; if (Foxtrick.Prefs.isModuleEnabled('LinksTracker')) { let tracker = { type: 'trackernationalteamlink', module: 'LinksTracker', }; types.push(tracker); } return { types, info }; }, };
'use strict'; (function($){ $(function(){ if( $('#wp_cf7pdf_pdf').length ) { var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {}; editorSettings.codemirror = _.extend( {}, editorSettings.codemirror, { indentUnit: 2, tabSize: 2, mode: 'text/html', } ); var editor = wp.codeEditor.initialize( $('#wp_cf7pdf_pdf'), editorSettings ); } if( $('#wp_cf7pdf_pdf_css').length ) { var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {}; editorSettings.codemirror = _.extend( {}, editorSettings.codemirror, { indentUnit: 2, tabSize: 2, mode: 'text/css', } ); var editor = wp.codeEditor.initialize( $('#wp_cf7pdf_pdf_css'), editorSettings ); } if( $('#cf7pdf_html_footer').length ) { var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {}; editorSettings.codemirror = _.extend( {}, editorSettings.codemirror, { indentUnit: 2, tabSize: 2, mode: 'text/html', } ); var editor = wp.codeEditor.initialize( $('#cf7pdf_html_footer'), editorSettings ); } }); })(jQuery);
/* Copyright 2010 Arran Schlosberg (http://arranschlosberg.com); This file is part of javascript-genetic-algos (https://github.com/aschlosberg/javascript-genetic-algos). javascript-genetic-algos 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. javascript-genetic-algos 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 javascript-genetic-algos. If not, see <http://www.gnu.org/licenses/>. */ function F(){ if(F.instance){ return F.instance; } var _fns, _max; _fns = new Array( function(a, b){ return a+b; }, function(a, b){ return a-b; }, function(a, b){ return a*b; }, function(a, b){ return a/b; }, Math.pow, Math.max, Math.min, function(a, b){ return (a+b)/2; }, //normal distribution mean 0 sd $b or 1 function(a, b){ var v = typeof b != 'number' || b==0 ? 1 : b*b; if(v==0){ //above check sometimes wasn't working v = 1; } var c = 1/Math.sqrt(2*Math.PI*v); var e = a*a/(2*v); return c*Math.exp(-e); }, function(a, b){ return Math.sqrt(a); }, function(a, b){ return Math.sqrt(b); }, function(a, b){ return Math.abs(a); }, function(a, b){ return Math.abs(b); } ); _max = _fns.length; function _getMax(){ return _max; } F.max = _getMax; function _run(id, a, b){ try { var val = _fns[id](a, b); if( isNaN(val) ){ throw 0; } return val; } catch(e){ return null; } } F.run = _run; F.instance = this; }; new F();
/* This is a TIGRA javascript from SoftComplex. Feel free to use your custom icons for the tree. Make sure they are all of the same size. User icons collections are welcome, we'll publish them giving all regards. */ var tree_tpl = { // Name of the frame links will be opened in // Other possible values are: _blank, _parent, _search, _self and _top 'target' : '_self', 'icon_e' : gJsTreeUrl + '/icons/', // empty image 'icon_l' : gJsTreeUrl + '/icons/line.gif', // vertical line 'icon_32' : gJsTreeUrl + '/icons/', // root leaf icon normal 'icon_36' : gJsTreeUrl + '/icons/', // root leaf icon selected 'icon_48' : gJsTreeUrl + '/icons/', // root icon normal 'icon_52' : gJsTreeUrl + '/icons/', // root icon selected 'icon_56' : gJsTreeUrl + '/icons/', // root icon opened 'icon_60' : gJsTreeUrl + '/icons/', // root icon selected 'icon_16' : gJsTreeUrl + '/icons/', // node icon normal 'icon_20' : gJsTreeUrl + '/icons/', // node icon selected 'icon_24' : gJsTreeUrl + '/icons/', // node icon opened 'icon_28' : gJsTreeUrl + '/icons/', // node icon selected opened 'icon_0' : gJsTreeUrl + '/icons/', // leaf icon normal 'icon_4' : gJsTreeUrl + '/icons/page.gif', // leaf icon selected 'icon_2' : gJsTreeUrl + '/icons/joinbottom.gif', // junction for leaf 'icon_3' : gJsTreeUrl + '/icons/join.gif', // junction for last leaf 'icon_18' : gJsTreeUrl + '/icons/plusbottom.gif', // junction for closed node 'icon_19' : gJsTreeUrl + '/icons/plus.gif', // junction for last closed node 'icon_26' : gJsTreeUrl + '/icons/minusbottom.gif',// junction for opened node 'icon_27' : gJsTreeUrl + '/icons/minus.gif' // junction for last opended node };
(function () { var immodels = {}; window.imsdk = function () { var _url; var socket; var ths = this; this.models = immodels; this.onmessage = function (ev) { }; this.onerror = function (ev) { }; this.onconnected = function () { }; this.onconnectfailed = function () { }; this.ondisconnected = function () { }; function onwsclose(ev) { setTimeout(function () { ths.start(); }, 2000); }; function onwserror(ev) { ths.onerror(JSON.stringify(ev)); }; function onwsmessage(ev) { ths.onmessage(ev); }; function onwsopen(ev) { ths.onconnected(); }; function sendPackage(seq, category, content) { var socketPackage = immodels.SocketPackage.create({ Seq: seq, Category: category, Content: content }); socket.send(immodels.SocketPackage.encode(socketPackage).finish()); } this.init = function (callback) { protobuf.load("ImProto.proto", function (err, root) { immodels.PackageCategory = root.lookupEnum("IM.Protocol.PackageCategory"); immodels.SocketPackage = root.lookupType("IM.Protocol.SocketPackage"); immodels.SocketResult = root.lookupType("IM.Protocol.SocketResult"); immodels.LoginToken = root.lookupType("IM.Protocol.LoginToken"); immodels.SendUserMessage = root.lookupType("IM.Protocol.SendUserMessage"); immodels.ReceivedUserMessage = root.lookupType("IM.Protocol.ReceivedUserMessage"); immodels.SendChannelMessage = root.lookupType("IM.Protocol.SendChannelMessage"); immodels.ReceivedChannelMessage = root.lookupType("IM.Protocol.ReceivedChannelMessage"); immodels.Channel = root.lookupType("IM.Protocol.Channel"); callback(); }); } this.setServerUrl = function (url) { _url = url; } this.login = function (uid) { var loginToken = immodels.LoginToken.create({ UserID: uid }); sendPackage(0, 1, immodels.LoginToken.encode(loginToken).finish()); } this.joinChannel = function (channelId) { var channel = immodels.Channel.create({ ChannelID: "1" }); sendPackage(0, 7, immodels.Channel.encode(channel).finish()); } this.sendToChannel = function (channelId, content) { var sendChannelMsg = immodels.SendChannelMessage.create(); sendChannelMsg.ChannelID = channelId; sendChannelMsg.Content = content; sendPackage(0, 4, immodels.SendChannelMessage.encode(sendChannelMsg).finish()); } this.start = function () { var ws = new WebSocket(_url, "im"); ws.binaryType = "arraybuffer"; ws.onclose = onwsclose; ws.onerror = onwserror; ws.onmessage = onwsmessage; ws.onopen = onwsopen; socket = ws; } } })()
/** This file is part of the Indigo Nameserver. Indigo Nameserver 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. Indigo Nameserver 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 Indigo Nameserver. If not, see <http://www.gnu.org/licenses/>. */ var indigoApp = angular.module('indigoApp', ['ngRoute', 'xeditable']); indigoApp.run(function(editableOptions, editableThemes) { editableOptions.theme = 'bs3'; editableThemes.bs3.inputClass = 'input-sm'; editableThemes.bs3.buttonsClass = 'btn-sm'; }); indigoApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/logs', { templateUrl: 'views/logs.html' }). when('/home', { templateUrl: 'views/records.html' }). when('/settings', { templateUrl: 'views/settings.html' }). otherwise({ redirectTo: 'home' }); }]); indigoApp.factory('recordsBackend', function ($http) { var backend = { get: function () { return $http.get("/api/records"); }, create: function(data) { return $http.post("/api/records", data); }, delete: function(id) { return $http.delete("/api/records/" + id) }, update: function(id, data) { return $http.post("/api/records/" + id, data); } }; return backend; }); indigoApp.factory('logsBackend', function ($http) { var backend = { get: function () { return $http.get("/api/logs"); } }; return backend; }); indigoApp.factory('configBackend', function ($http) { var backend = { get: function () { return $http.get("/api/config"); }, update: function(config) { return $http.post("/api/config/", config); } }; return backend; }); indigoApp.controller("recordsController", function($scope, recordsBackend) { $scope.records = []; $scope.newRecord = {"type": "A"}; $scope.valueLabels = { "A": "IP Address", "AAAA": "IP Address", "CNAME": "DNS Record", "MX": "Mail Server", "TXT": "Value", "SRV": "Service", "SOA": "Nameserver" } $scope.refresh = function() { recordsBackend.get().then(function(results) { $scope.records = results.data; }) } $scope.refresh(); $scope.delete = function(id) { recordsBackend.delete(id).then(function() { $scope.refresh(); }); } $scope.create = function() { recordsBackend.create($scope.newRecord).then(function() { $scope.refresh(); }); } $scope.update = function(record) { recordsBackend.update(record._id, record).then(function() { $scope.refresh(); }); } }); indigoApp.controller("logsController", function($scope, logsBackend) { $scope.logs = []; $scope.refresh = function() { logsBackend.get().then(function(results) { $scope.logs = results.data; }); } $scope.refresh(); }); indigoApp.controller("settingsController", function($scope, configBackend) { $scope.config = {}; $scope.response = {}; $scope.refresh = function() { configBackend.get().then(function(results) { $scope.config = results.data; }); } $scope.refresh(); $scope.update = function() { configBackend.update($scope.config).then(function() { $scope.response = results.data; }); } });
$(window).load(function() { options = $('#options'); }); function optionsPressed(node, event) { options.fadeIn(); } function cancelOptions(node, event) { options.fadeOut(); } function saveOptions(node, event) { // TODO: implemented saving here. options.fadeOut(); }
'use strict'; var nconf = require('nconf'); var url = require('url'); var winston = require('winston'); var cache = require('./cache'); var plugins = require('../plugins'); var translator = require('../../public/src/modules/translator'); var urlRegex = /href="([^"]+)"/g; module.exports = function(Posts) { Posts.parsePost = function(postData, callback) { postData.content = postData.content || ''; if (postData.pid && cache.has(postData.pid)) { postData.content = cache.get(postData.pid); return callback(null, postData); } // Casting post content into a string, just in case if (typeof postData.content !== 'string') { postData.content = postData.content.toString(); } plugins.fireHook('filter:parse.post', {postData: postData}, function(err, data) { if (err) { return callback(err); } data.postData.content = translator.escape(data.postData.content); if (global.env === 'production' && data.postData.pid) { cache.set(data.postData.pid, data.postData.content); } callback(null, data.postData); }); }; Posts.parseSignature = function(userData, uid, callback) { userData.signature = userData.signature || ''; plugins.fireHook('filter:parse.signature', {userData: userData, uid: uid}, callback); }; Posts.relativeToAbsolute = function(content) { // Turns relative links in post body to absolute urls var parsed, current, absolute; while ((current = urlRegex.exec(content)) !== null) { if (current[1]) { try { parsed = url.parse(current[1]); if (!parsed.protocol) { if (current[1].startsWith('/')) { // Internal link absolute = nconf.get('url') + current[1]; } else { // External link absolute = '//' + current[1]; } content = content.slice(0, current.index + 6) + absolute + content.slice(current.index + 6 + current[1].length); } } catch(err) { winston.verbose(err.messsage); } } } return content; }; };
/*! * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ $(document).ready(function () { if (!piwik || !location.protocol) { return; } if (!piwik.hasSuperUserAccess) { // we show a potential notification only to super users return; } if (piwik.hasServerDetectedHttps) { // https was detected, not needed to show a message return; } var isHttpsUsed = 0 === location.protocol.indexOf('https'); if (!isHttpsUsed) { // not using https anyway, we do not show a message return; } var params = [ '"config/config.ini.php"', '"assume_secure_protocol=1"', '"[General]"', '<a href="?module=Proxy&action=redirect&url=https://matomo.org/faq/how-to-install/faq_98/" target="_blank">', '</a>' ]; var message = _pk_translate('CoreAdminHome_ProtocolNotDetectedCorrectly') + " " + _pk_translate('CoreAdminHome_ProtocolNotDetectedCorrectlySolution', params); var UI = require('piwik/UI'); var notification = new UI.Notification(); notification.show(message, {context: 'warning'}); });
var mongoose = require('mongoose'); require('./app/models/user.js'); var User = mongoose.model('User'); process.env.NODE_ENV = process.env.NODE_ENV || 'development'; // Initializing system variables var config = require('./config/config'); // Bootstrap db connection var db = mongoose.connect(config.db, function (err) { //db.connection.db.dropDatabase(function (err) { User.findOne( {email: 'admin@aurea.it'}, function (err, user) { if (user) { db.connection.close(); return; } var admin = new User(); admin.name = 'admin'; admin.email = 'admin@aurea.it'; admin.password = 'admin'; admin.role = 'admin'; admin.save(function () { db.connection.close(); console.log('ATTENZIONE: E\' fortemente consigliato di eliminare questo file dopo averlo eseguito'); }); } ); //}); });
import Logger from "@reactioncommerce/logger"; import appEvents from "/imports/node-app/core/util/appEvents"; import { Job } from "/imports/plugins/core/job-collection/lib"; import { Jobs } from "/lib/collections"; let moment; async function lazyLoadMoment() { if (moment) return; moment = await import("moment").default; } /** * @summary Adds a "jobServerStart" event consumer, which registers * a job to remove stale jobs. * @returns {undefined} */ export function addCleanupJobControlHook() { appEvents.on("jobServerStart", () => { Logger.debug("Adding Job jobControl/removeStaleJobs to JobControl"); new Job(Jobs, "jobControl/removeStaleJobs", {}) .retry({ retries: 5, wait: 60000, backoff: "exponential" }) .repeat({ schedule: Jobs.later.parse.text("every day") }) .save({ cancelRepeats: true }); }); } export function cleanupJob() { const removeStaleJobs = Jobs.processJobs("jobControl/removeStaleJobs", { pollInterval: 60 * 60 * 1000, // backup polling, see observer below workTimeout: 60 * 1000 }, (job, callback) => { Logger.debug("Processing jobControl/removeStaleJobs..."); // TODO: set this interval in the admin UI Promise.await(lazyLoadMoment()); const olderThan = moment().subtract(3, "days")._d; const ids = Jobs.find({ type: { $nin: ["sendEmail"] }, status: { $in: ["cancelled", "completed", "failed"] }, updated: { $lt: olderThan } }, { fields: { _id: 1 } }).map((d) => d._id); let success; if (ids.length > 0) { Jobs.removeJobs(ids); success = `Removed ${ids.length} stale jobs`; Logger.debug(success); } else { success = "No eligible jobs to cleanup"; Logger.debug(success); } job.done(success, { repeatId: true }); return callback(); }); Jobs.find({ type: "jobControl/removeStaleJobs", status: "ready" }).observe({ added() { return removeStaleJobs.trigger(); } }); }
#pragma strict @script RequireComponent( GUITexture ) var cameraGUI: Camera; var ball: Transform; var viewPos : Vector3 ; function Start() { cameraGUI = Camera.main; //if(cameraGUI == null) cameraGUI = Camera.main; } function Update() { //viewPos = cameraGUI.WorldToViewportPoint (Vector3(ball.position.x, ball.position.y, ball.position.z)); if ( Camera.main!=null)viewPos = Camera.main.WorldToViewportPoint (Vector3(ball.position.x, ball.position.y, ball.position.z)); //Camera.main.worldToCameraMatrix transform.position.x = viewPos.x; transform.position.y = viewPos.y; transform.position.z = viewPos.z; }
'use strict'; angular.module('badongApp') .config(function ($stateProvider) { $stateProvider .state('login', { url: '/login', templateUrl: 'app/account/login/login.html', controller: 'LoginCtrl' }) .state('signup', { url: '/signup', templateUrl: 'app/account/signup/signup.html', controller: 'SignupCtrl' }) .state('settings', { url: '/settings', templateUrl: 'app/account/settings/settings.html', controller: 'SettingsCtrl', authenticate: true }); });
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'basicstyles', 'fr', { bold: 'Gras', italic: 'Italique', strike: 'Barré', subscript: 'Indice', superscript: 'Exposant', underline: 'Souligné' } );
/** * snekw.com, * Copyright (C) 2018 Ilkka Kuosmanen * * This file is part of snekw.com. * * snekw.com 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. * * snekw.com 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 snekw.com. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const uploadSchema = new Schema({ name: {type: String, required: true}, uploaded: {type: Date, default: Date.now}, mimeType: {type: String, required: true}, path: {type: String, required: true}, size: {type: Number, required: true}, encoding: {type: String, required: true}, type: {type: String, required: true}, info: { title: {type: String}, alt: {type: String}, description: {type: String} }, articles: [{type: String, ref: 'article', index: true}] }); uploadSchema.methods.attachArticle = function (articleId, save = false) { if (this.articles.indexOf(articleId) === -1) { this.articles.push(articleId); } if (save) { return this.save(); } }; uploadSchema.methods.detachArticle = function (articleId, save = false) { this.articles = this.articles.filter((a) => a !== articleId); if (save) { return this.save(); } }; mongoose.model('upload', uploadSchema);
var system = require("system"); var e2ePort = system.env.E2E_PORT || 8099; casper.test.begin("Weather Widget - Current and 3 Day Forecast - e2e Testing", function (test) { casper.start("http://localhost:"+e2ePort+"/src/current-and-three-day-e2e.html", function () { test.assertTitle("Weather - Current and 3 Day Forecast", "Test page has loaded"); } ); casper.waitForText("Humidity", function() { casper.then(function() { var today = new Date().getDay(), tomorrow = (today + 1) > 6 ? 0 : today + 1, nextDay = (tomorrow + 1 > 6) ? 0 : tomorrow + 1, days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], images = ["img/mostly_sunny.png", "img/mostly_sunny.png", "img/showers.png", "img/mostly_cloudy.png", "img/partly_cloudy.png", "img/mostly_cloudy.png", "img/mostly_sunny.png"], titles = ["More sun than clouds. Cool.", "More sun than clouds. Cool.", "Scattered showers. Mostly cloudy. Cool.", "Mostly cloudy. Cool.", "Morning clouds. Cool.", "Partly sunny. Cool.", "More sun than clouds. Cool."], temps = ["3° / 1°", "5° / 1°", "5° / 3°", "5° / 2°", "3° / 0°", "3° / 0°", "2° / 0°"]; casper.test.comment("Weather Details"); test.assertSelectorHasText(".address", "Glen Eden Ski Area, Ontario", "City is correct"); test.assertSelectorHasText(".humidity", "Humidity 44%", "Humidity is correct"); test.assertSelectorHasText(".wind", "Wind NW at 18 kph", "Wind is correct"); casper.test.comment("Current Weather"); test.assertEquals(this.getElementAttribute(".current-icon", "src"), "img/mostly_cloudy.png", "Image is correct"); test.assertEquals(this.getElementAttribute(".current-icon", "title"), "Partly sunny. Chilly.", "Image title is correct"); test.assertSelectorHasText(".current-temp", "2°C", "Temperature is correct"); casper.test.comment("Forecasted Weather"); casper.test.comment("Today"); test.assertSelectorHasText(".forecast-day:nth-child(1) .day-of-week", this.evaluate( function(today, days) { return days[today]; }, today, days), "Day is correct"); test.assertEquals(this.getElementAttribute(".forecast-day:nth-child(1) .icon", "src"), this.evaluate( function(today, images) { return images[today]; }, today, images), "Image is correct"); test.assertEquals(this.getElementAttribute(".forecast-day:nth-child(1) .icon", "title"), this.evaluate( function(today, titles) { return titles[today]; }, today, titles), "Image title is correct"); test.assertSelectorHasText(".forecast-day:nth-child(1) .forecast-temp", this.evaluate( function(today, temps) { return temps[today]; }, today, temps), "Temperature is correct"); casper.test.comment("Tomorrow"); test.assertSelectorHasText(".forecast-day:nth-child(2) .day-of-week", this.evaluate( function(tomorrow, days) { return days[tomorrow]; }, tomorrow, days), "Day is correct"); test.assertEquals(this.getElementAttribute(".forecast-day:nth-child(2) .icon", "src"), this.evaluate( function(tomorrow, images) { return images[tomorrow]; }, tomorrow, images), "Image is correct"); test.assertEquals(this.getElementAttribute(".forecast-day:nth-child(2) .icon", "title"), this.evaluate( function(tomorrow, titles) { return titles[tomorrow]; }, tomorrow, titles), "Image title is correct"); test.assertSelectorHasText(".forecast-day:nth-child(2) .forecast-temp", this.evaluate( function(tomorrow, temps) { return temps[tomorrow]; }, tomorrow, temps), "Temperature is correct"); casper.test.comment("Two days from now"); test.assertSelectorHasText(".forecast-day:nth-child(3) .day-of-week", this.evaluate( function(nextDay, days) { return days[nextDay]; }, nextDay, days), "Day is correct"); test.assertEquals(this.getElementAttribute(".forecast-day:nth-child(3) .icon", "src"), this.evaluate( function(nextDay, images) { return images[nextDay]; }, nextDay, images), "Image is correct"); test.assertEquals(this.getElementAttribute(".forecast-day:nth-child(3) .icon", "title"), this.evaluate( function(nextDay, titles) { return titles[nextDay]; }, nextDay, titles), "Image title is correct"); test.assertSelectorHasText(".forecast-day:nth-child(3) .forecast-temp", this.evaluate( function(nextDay, temps) { return temps[nextDay]; }, nextDay, temps), "Temperature is correct"); casper.test.comment("Error Message"); test.assertNotVisible(".error", "Error message is not displayed"); }); }); casper.run(function() { test.done(); }); });
/* GCompris - clickanddraw_dataset.js * Copyright (C) 2014 Emmanuel Charruau <echarruau@gmail.com> * * Authors: Emmanuel Charruau <echarruau@gmail.com> (initial set) * Timothée Giet <animtim@gmail.com> (update set ratio) * * 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 <https://www.gnu.org/licenses/>. */ function get() { return [ { "imageName1": "dn_fond1.svg", "imageName2": "dn_fond2.svg", "coordinates": [[267,121],[349,369],[139,216],[397,214],[190,369],[267,121]] }, { "imageName1": "de1.svg", "imageName2": "de2.svg", "coordinates": [[104,275],[106,171],[203,133],[288,178],[288,237],[311,211],[427,220],[428,324],[382,386],[260,374],[260,297],[195,323],[104,275]] }, { "imageName1": "house1.svg", "imageName2": "house2.svg", "coordinates": [[306,360],[412,360],[413,175],[356,120],[355,70],[330,70],[330,96],[272,40],[119,177],[120,361],[253,361],[252,276],[306,276],[306,360]] }, { "imageName1": "sapin1.svg", "imageName2": "sapin2.svg", "coordinates": [[104,463],[201,361],[127,373],[221,238],[160,251],[237,127],[189,146],[259,52],[324,144],[276,128],[352,251],[295,239],[387,371],[318,362],[417,466],[282,453],[282,504],[234,504],[234,453],[104,463]] }, { "imageName1": "epouvantail1.svg", "imageName2": "epouvantail2.svg", "coordinates": [[105,449],[190,340],[190,224],[62,233],[58,168],[245,160],[218,135],[217,77],[190,79],[189,68],[213,65],[209,30],[310,30],[314,56],[338,54],[339,66],[313,68],[312,135],[284,161],[462,163],[457,223],[327,221],[327,337],[411,457],[357,487],[263,377],[159,491],[105,449]] }, { "imageName1": "plane1.svg", "imageName2": "plane2.svg", "coordinates": [[228,296],[106,299],[85,278],[103,253],[142,237],[133,220],[148,213],[103,159],[108,140],[130,138],[247,223],[332,222],[377,214],[351,197],[352,187],[369,188],[395,198],[428,164],[438,216],[470,236],[472,248],[451,247],[428,240],[378,265],[308,280],[394,352],[392,382],[350,370],[266,316],[228,324],[214,310],[228,296]] }, { "imageName1": "fish1.svg", "imageName2": "fish2.svg", "coordinates": [[21,320],[50,256],[100,212],[209,203],[244,156],[276,146],[294,156],[302,175],[292,204],[314,215],[342,195],[360,207],[355,225],[365,242],[408,258],[446,246],[462,222],[480,215],[494,226],[498,278],[481,349],[469,373],[440,366],[424,335],[362,328],[318,339],[325,357],[322,378],[299,392],[268,388],[226,352],[202,352],[210,360],[206,380],[188,382],[172,360],[52,360],[35,350],[32,322],[21,320]] }, { "imageName1": "carnaval1.svg", "imageName2": "carnaval2.svg", "coordinates": [[135,204],[192,143],[224,180],[246,118],[265,188],[269,120],[277,179],[312,154],[364,203],[315,188],[286,224],[286,236],[284,296],[279,315],[320,306],[364,262],[384,184],[404,186],[386,279],[313,366],[304,473],[312,518],[208,518],[220,473],[202,365],[177,402],[200,468],[180,483],[148,407],[180,333],[227,317],[219,295],[214,235],[213,223],[183,189],[135,204]] }, { "imageName1": "bear1.svg", "imageName2": "bear2.svg", "coordinates": [[154,256],[112,240],[66,206],[42,174],[45,159],[66,154],[107,167],[150,188],[184,220],[202,206],[220,200],[192,185],[171,154],[169,117],[187,90],[170,76],[165,55],[185,38],[210,40],[226,52],[227,66],[250,59],[281,60],[300,66],[301,48],[318,37],[340,36],[357,48],[360,70],[351,82],[336,86],[352,110],[356,136],[349,164],[329,189],[308,200],[330,212],[372,180],[428,158],[461,154],[472,164],[468,184],[442,213],[400,236],[365,251],[379,286],[382,329],[376,364],[398,354],[416,360],[426,384],[421,417],[398,455],[370,470],[343,456],[340,419],[311,440],[264,453],[210,441],[180,422],[181,450],[167,471],[134,467],[105,434],[92,402],[98,366],[121,354],[146,364],[138,326],[142,282],[154,256]] } ] }
const StatusCode = require('../../common/status-code'); const ArticleService = require('../lib/article-service'); function tags(opts) { return function* (next) { let ctx = this; let articleService = ArticleService.getInstance(); let tags = yield articleService.getTags(); let total = yield articleService.getArticlesCount(); ctx.body = { status: StatusCode.OK, total: total, tagList: tags }; return; }; } module.exports = tags;
import {module, test} from 'qunit' import {setupTest} from 'ember-qunit' module('Unit | Route | settings/account', function(hooks) { setupTest(hooks) test('it exists', function(assert) { let route = this.owner.lookup('route:settings/account') assert.ok(route) }) })
var searchData= [ ['brick',['Brick',['../class_brick.html',1,'']]] ];
// @flow import axios from "axios"; import type {$AxiosXHR} from "axios"; export function fetchData(path: string): Promise<$AxiosXHR<*,*>> { return axios.get('/' + path) }
/* Copyright (C) 2014 PencilBlue, LLC 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 TableSort(opts) { var self = this; this.pagination = null; this.options = { table: null, rowClass: null, sortFields: [] } for(var key in opts) { this.options[key] = opts[key]; } if(!this.options.table || !this.options.rowClass || this.options.sortFields.length == 0) { return; } this.sortField = function(event) { var header = '#' + event.currentTarget.id; for(var i = 0; i < self.options.sortFields.length; i++) { if(self.options.sortFields[i].header == header) { $('body').append('<table id="temp_sort_table" style="display:none"></table>'); $('#temp_sort_table').append($(self.options.rowClass)); $(self.options.rowClass).show(); self.getNextRow(self.options.sortFields[i]); return; } } } this.getNextRow = function(field) { var nextRow = null; var nextRowText = ''; if($('#temp_sort_table ' + self.options.rowClass).length == 0) { this.switchSortIcon(field); $('#temp_sort_table').remove(); if(this.pagination) { this.pagination.initializeElements(); } return; } var rowIndex = 0; $('#temp_sort_table ' + self.options.rowClass).each(function() { var row = $(this); row.find(field.textContainer).each(function() { if(!nextRow) { nextRow = row; nextRowText = $(this).html(); } else { if((field.sortAsc && $(this).html() < nextRowText) || (!field.sortAsc && $(this).html() > nextRowText)) { nextRow = row; nextRowText = $(this).html(); } } }); rowIndex++; if(rowIndex >= $('#temp_sort_table ' + self.options.rowClass).length) { $(self.options.table).append(nextRow); self.getNextRow(field); } }); } this.switchSortIcon = function(field) { for(var i = 0; i < this.options.sortFields.length; i++) { $(this.options.sortFields[i].header + ' i').remove(); $(this.options.sortFields[i].header).append('<i class="fa fa-sort text-muted"></i>'); } $(field.header + ' i').remove(); if(field.sortAsc) { $(field.header).append('<i class="fa fa-sort-asc"></i>'); field.sortAsc = false; } else { $(field.header).append('<i class="fa fa-sort-desc"></i>'); field.sortAsc = true; } } for(var i = 0; i < this.options.sortFields.length; i++) { if(!this.options.sortFields[i].default) { $(this.options.sortFields[i].header).append('&nbsp;<i class="fa fa-sort text-muted"></i>'); this.options.sortFields[i].sortAsc = true; } else { $(this.options.sortFields[i].header).append('&nbsp;<i class="fa fa-sort-asc"></i>'); this.options.sortFields[i].sortAsc = false; } $(this.options.sortFields[i].header).css({cursor: 'pointer'}); $(this.options.sortFields[i].header).click(this.sortField); } }
/** * Created by sinires on 02.03.17. */ function redrawTable(data) { var table = document.getElementById("table_data"), content = ""; if(!data && !data.length) return; data.forEach( function(field) { if (!field && !field.length) return; content +='<tr>'; field.forEach( function(cell) { content+= '<td class="text-style">'; content+= cell; content+= '</td>'; } ); content +='</tr>' } ); table.innerHTML = content; updateStyle(); } redrawTable(string2array(globalString))
/************************************************ * jQuery iphoneSwitch plugin * * * * Author: Daniel LaBare * * Date: 2/4/2008 * ************************************************/ jQuery.fn.iphoneSwitch = function(start_state, switched_on_callback, switched_off_callback, options) { var state = start_state == 'on' ? start_state : 'off'; // define default settings var settings = { mouse_over: 'pointer', mouse_out: 'default', switch_on_container_path: 'iphone_switch_container_on.png', switch_off_container_path: 'iphone_switch_container_off.png', switch_path: 'iphone_switch.png', switch_height: 27, switch_width: 94 }; if(options) { jQuery.extend(settings, options); } // create the switch return this.each(function() { var container; var image; // make the container container = jQuery('<div class="iphone_switch_container" style="height:'+settings.switch_height+'px; width:'+settings.switch_width+'px; position: relative; overflow: hidden"></div>'); // make the switch image based on starting state image = jQuery('<img class="iphone_switch" style="height:'+settings.switch_height+'px; width:'+settings.switch_width+'px; background-image:url('+settings.switch_path+'); background-repeat:none; background-position:'+(state == 'on' ? 0 : -53)+'px" src="'+(state == 'on' ? settings.switch_on_container_path : settings.switch_off_container_path)+'" /></div>'); // insert into placeholder jQuery(this).html(jQuery(container).html(jQuery(image))); jQuery(this).mouseover(function(){ jQuery(this).css("cursor", settings.mouse_over); }); jQuery(this).mouseout(function(){ jQuery(this).css("background", settings.mouse_out); }); // click handling jQuery(this).click(function() { if(state == 'on') { if (switched_off_callback()) { jQuery(this).find('.iphone_switch').animate({backgroundPosition: -53}, "slow", function() { jQuery(this).attr('src', settings.switch_off_container_path); }); state = 'off'; } } else { if (switched_on_callback()) { jQuery(this).find('.iphone_switch').animate({backgroundPosition: 0}, "slow", function() { ; }); jQuery(this).find('.iphone_switch').attr('src', settings.switch_on_container_path); state = 'on'; } } }); }); };
const Koa=require("koa") // const mount=require("koa-mount") //全部用router中间件实现 const Router=require("koa-router") const createStatic=require("koa-static") //数据库配置 let mongoose=require("mongoose") mongoose.connect("mongodb://localhost/test") //设置为默认Promise mongoose.Promise=Promise global.SiteDB=mongoose //以下进行接口配置 const app=new Koa() const path=require("path") //顶层路由 const top=new Router() //静态文件 top.all("/",createStatic(path.join(__dirname,"./static"))) //配置api路由 const apiRouter=new Router() //加载所有模块 const assert=require("assert") const ModuleList=require("./ModuleList") let InitList=[] for(let item of ModuleList){ const mod=require(`./serverModules/${item.mod}.js`) assert.notEqual(mod.Route,null) apiRouter.use(item.url,mod.Route.routes(),mod.Route.allowedMethods()) //如果有初始化函数就执行初始化 if(mod.Init) InitList.push(mod.Init); } //执行初始化 for(let fun of InitList){ fun(); } //添加api路由 top.use("/api",apiRouter.routes(),apiRouter.allowedMethods()) //使用顶层路由 app.use(top.routes()).use(top.allowedMethods()); app.listen(3000)
function FindNewsCtrl($scope, $http, $templateCache) { "use strict"; var documentUrl = URI(document.location); $scope.searchTerms = "ecs eprints"; $scope.searchText = ''; $scope.user = function(link) { $scope.url = link; }; $scope.search = function() { var search = $scope.searchTerms.replace(/,/g,''); $scope.url = URI("/find").addSearch({kw: search.split(" ")}).toString(); }; $scope.absoluteUrl = function() { if($scope.url === undefined) { $scope.search(); } return URI($scope.url).authority(documentUrl.authority()).scheme(documentUrl.scheme()).toString(); }; $scope.googleReaderUrl = function() { return URI("http://www.google.com/ig/add").addSearch( { feedurl:$scope.absoluteUrl() } ).toString(); }; $scope.feedShowReaderUrl = function() { return URI("http://reader.feedshow.com/subscribe.php").addSearch( { url:$scope.absoluteUrl() } ).toString(); }; $scope.newsAlloyReaderUrl = function() { return URI("http://www.newsalloy.com/").addSearch( { rss:$scope.absoluteUrl() } ).toString(); }; $scope.fetch = function() { $http( { method: "GET", url: '/api/v2/feed/?format=json&limit=0', cache: $templateCache, transformResponse: function(data,headersGetter) { var objects = JSON.parse(data).objects; angular.forEach(objects, function(object) { object["searchOn"] = object.title + object.description; }); return objects } }).success(function(data,status) { $scope.feeds = arrayShuffle(data); }); } /* Modified implementation of Fisher-Yates shuffling algorithm, from: http://www.hardcode.nl/subcategory_1/article_317-array-shuffle-function */ function arrayShuffle(oldArray) { var newArray = oldArray.slice(); var len = newArray.length; var i = len; while (i--) { var p = parseInt(Math.random()*len); var t = newArray[i]; newArray[i] = newArray[p]; newArray[p] = t; } return newArray; } $scope.fetch(); }
define(['underscore', 'objTools', 'xsdval/XmlValidationResult'], function (_, objTools, XmlValidationResult) { /** * @lends NodeValidator.prototype */ var nodeValidator = { /** * @constructor NodeValidator * @classdesc A dummy NodeValidator, always validates. Serves as a base for all other node validators. * @param {Element} node - The XML node validated by this validator. * @param {Element} definition - The XSD node to be used for validation by this validator. * @param {NodeValidatorFactory} [validatorFactory] - The validator factory that can be used to spawn further validators if needed. */ init: function (node, definition, validatorFactory) { this.node = node; this.definition = definition; this.validatorFactory = validatorFactory; this.xsdLibrary = validatorFactory ? validatorFactory.xsdLibrary : null; return this; }, /** * Validates the XML node against the XSD node. * @returns {XmlValidationResult} */ validate: function () { return new XmlValidationResult(); } }; return objTools.makeConstructor(function NodeValidator () {}, nodeValidator); });
// import { moduleForComponent, test } from 'ember-qunit'; // import hbs from 'htmlbars-inline-precompile'; // // moduleForComponent('meeting/share-stream', 'Integration | Component | meeting/share stream', { // integration: true // }); // // test('it renders', function(assert) { // // Set any properties with this.set('myProperty', 'value'); // // Handle any actions with this.on('myAction', function(val) { ... }); // // this.render(hbs`{{meeting/share-stream}}`); // // // assert.notEqual(this.$().text().trim(), ''); // // // Template block usage: // // this.render(hbs` // // {{#meeting/share-stream}} // // template block text // // {{/meeting/share-stream}} // // `); // // // // assert.equal(this.$().text().trim(), 'template block text'); // });
'use strict'; var async = require('async'), plugins = require('../plugins'), db = require('../database'); module.exports = function(User) { User.follow = function(uid, followuid, callback) { toggleFollow('follow', uid, followuid, callback); }; User.unfollow = function(uid, unfollowuid, callback) { toggleFollow('unfollow', uid, unfollowuid, callback); }; function toggleFollow(type, uid, theiruid, callback) { if (!parseInt(uid, 10) || !parseInt(theiruid, 10)) { return callback(new Error('[[error:invalid-uid]]')); } if (parseInt(uid, 10) === parseInt(theiruid, 10)) { return callback(new Error('[[error:you-cant-follow-yourself]]')); } async.waterfall([ function (next) { User.exists(theiruid, next); }, function (exists, next) { if (!exists) { return next(new Error('[[error:no-user]]')); } User.isFollowing(uid, theiruid, next); }, function (isFollowing, next) { if (type === 'follow') { if (isFollowing) { return next(new Error('[[error:already-following]]')); } var now = Date.now(); async.parallel([ async.apply(db.sortedSetAdd, 'following:' + uid, now, theiruid), async.apply(db.sortedSetAdd, 'followers:' + theiruid, now, uid), async.apply(User.incrementUserFieldBy, uid, 'followingCount', 1), async.apply(User.incrementUserFieldBy, theiruid, 'followerCount', 1) ], next); } else { if (!isFollowing) { return next(new Error('[[error:not-following]]')); } async.parallel([ async.apply(db.sortedSetRemove, 'following:' + uid, theiruid), async.apply(db.sortedSetRemove, 'followers:' + theiruid, uid), async.apply(User.decrementUserFieldBy, uid, 'followingCount', 1), async.apply(User.decrementUserFieldBy, theiruid, 'followerCount', 1) ], next); } } ], callback); } User.getFollowing = function(uid, start, stop, callback) { getFollow(uid, 'following', start, stop, callback); }; User.getFollowers = function(uid, start, stop, callback) { getFollow(uid, 'followers', start, stop, callback); }; function getFollow(uid, type, start, stop, callback) { if (!parseInt(uid, 10)) { return callback(null, []); } db.getSortedSetRevRange(type + ':' + uid, start, stop, function(err, uids) { if (err) { return callback(err); } plugins.fireHook('filter:user.' + type, { uids: uids, uid: uid, start: start, stop: stop }, function(err, data) { if (err) { return callback(err); } User.getUsers(data.uids, uid, callback); }); }); } User.isFollowing = function(uid, theirid, callback) { if (!parseInt(uid, 10) || !parseInt(theirid, 10)) { return callback(null, false); } db.isSortedSetMember('following:' + uid, theirid, callback); }; };
// Copyright 2016-2020, University of Colorado Boulder /** * Panel that contains a 100, 10 and 1, which can be clicked/dragged to create draggable paper numbers. * * @author Jonathan Olson <jonathan.olson@colorado.edu> */ import DerivedProperty from '../../../../../axon/js/DerivedProperty.js'; import Vector2 from '../../../../../dot/js/Vector2.js'; import merge from '../../../../../phet-core/js/merge.js'; import HBox from '../../../../../scenery/js/nodes/HBox.js'; import Node from '../../../../../scenery/js/nodes/Node.js'; import Panel from '../../../../../sun/js/Panel.js'; import makeATen from '../../../makeATen.js'; import BaseNumber from '../../common/model/BaseNumber.js'; import PaperNumber from '../../common/model/PaperNumber.js'; import BaseNumberNode from '../../common/view/BaseNumberNode.js'; const MAX_SUM = 9999; class ExplorePanel extends Panel { /** * @param {MakeATenExploreScreenView} screenView * @param {NumberProperty} sumProperty * @param {Object} [options] - Passed to Node */ constructor( screenView, sumProperty, options ) { options = merge( { fill: 'rgb(208,222,239)', stroke: 'black', lineWidth: 1.5, xMargin: 30, yMargin: 5, resize: false }, options ); function createTarget( place ) { const numberValue = Math.pow( 10, place ); const node = new Node( { cursor: 'pointer', // empirically determined stacking children: [ new Vector2( -8, -8 ), new Vector2( 0, 0 ) ].map( offset => { const paperNode = new BaseNumberNode( new BaseNumber( 1, place ), 1 ); paperNode.scale( 0.64, 0.55 ); paperNode.translation = offset; return paperNode; } ) } ); node.touchArea = node.localBounds.dilatedX( 15 ).dilatedY( 5 ); // We need to be disabled if adding this number would increase the sum past the maximum sum. new DerivedProperty( [ sumProperty ], sum => sum + numberValue <= MAX_SUM ).linkAttribute( node, 'visible' ); node.addInputListener( { down: event => { if ( !event.canStartPress() ) { return; } // We want this relative to the screen view, so it is guaranteed to be the proper view coordinates. const viewPosition = screenView.globalToLocalPoint( event.pointer.point ); const paperNumber = new PaperNumber( numberValue, new Vector2( 0, 0 ) ); // Once we have the number's bounds, we set the position so that our pointer is in the middle of the drag target. paperNumber.setDestination( viewPosition.minus( paperNumber.getDragTargetOffset() ), false ); // Create and start dragging the new paper number node screenView.addAndDragNumber( event, paperNumber ); } } ); return node; } const hundredTarget = createTarget( 2 ); const tenTarget = createTarget( 1 ); const oneTarget = createTarget( 0 ); const box = new HBox( { children: [ hundredTarget, tenTarget, oneTarget ], spacing: 30 } ); super( box, options ); // @private {MakeATenExploreScreenView} this.screenView = screenView; this.hundredTarget = hundredTarget; this.tenTarget = tenTarget; this.oneTarget = oneTarget; } /** * Given a specified number of digits for a paper number, return the view coordinates of the closest matching * target, so that it can animate back to this position. * @public * * @param {number} digits * @returns {Vector2} */ getOriginPosition( digits ) { let target; switch( digits ) { case 1: target = this.oneTarget; break; case 2: target = this.tenTarget; break; case 3: target = this.hundredTarget; break; default: // Probably something big, no better place to send it target = this.hundredTarget; } // Trail to screenView, not including the screenView let trail = this.screenView.getUniqueLeafTrailTo( target ); trail = trail.slice( 1, trail.length ); // Transformed to view coordinates return trail.localToGlobalPoint( target.localBounds.center ); } } makeATen.register( 'ExplorePanel', ExplorePanel ); export default ExplorePanel;
const express = require('express') const session = require('express-session') const bodyParser = require('body-parser') const passport = require('passport') const cors = require('cors') const settings = require('./settings') const initPassport = require('./passport/init') const initDB = require('./helpers/initDB') settings.HOST = `${settings.http.scheme}://${settings.http.hostname}:${settings.http.port}` settings.GUI = `${settings.gui.scheme}://${settings.gui.hostname}:${settings.gui.port}/#` // Load app const app = initApp() initDB(settings).then(({ds, rConn}) => { initPassport(app, passport, ds, rConn, settings) assignUserRoutes(app) assignServiceRoutes(app) startApp(app, settings) }) function initApp () { const app = express() app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended: true})) app.use(cors('*')) app.use(session({ secret: settings.http.sessionSecret, resave: false, saveUninitialized: false })) console.log(`App is running in: ${app.settings.env}`) return app } function assignUserRoutes (app) { app.get('/', (req, res) => { res.send(`Please login with email/password, Facebook or Google`) }) app.get('/status', (req, res) => { res.json(`{status: 'success'}`) }) app.get('/logout', (req, res) => { req.logout() res.send('success') }) } function assignServiceRoutes (app) { app.post('/verify', (req, res) => { res.json("{status: 'success'}") }) app.post('/request-token', (req, res) => { res.json("{status: 'success'}") }) } function startApp (app, settings) { app.listen(settings.http.port, () => { console.log(`Ronny started on port ${settings.http.port}`) }) }
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. import scrypt from 'scryptsy'; import Transaction from 'ethereumjs-tx'; import { pbkdf2Sync } from 'crypto'; import { createDecipheriv } from 'browserify-aes'; import { inHex } from '~/api/format/input'; import { sha3 } from '~/api/util/sha3'; // Adapted from https://github.com/kvhnuke/etherwallet/blob/mercury/app/scripts/myetherwallet.js export class Signer { static fromJson (json, password) { return Signer .getSeed(json, password) .then((seed) => { return new Signer(seed); }); } static getSeed (json, password) { try { const seed = Signer.getSyncSeed(json, password); return Promise.resolve(seed); } catch (error) { return Promise.reject(error); } } static getSyncSeed (json, password) { if (json.version !== 3) { throw new Error('Only V3 wallets are supported'); } const { kdf } = json.crypto; const kdfparams = json.crypto.kdfparams || {}; const pwd = Buffer.from(password); const salt = Buffer.from(kdfparams.salt, 'hex'); let derivedKey; if (kdf === 'scrypt') { derivedKey = scrypt(pwd, salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); } else if (kdf === 'pbkdf2') { if (kdfparams.prf !== 'hmac-sha256') { throw new Error('Unsupported parameters to PBKDF2'); } derivedKey = pbkdf2Sync(pwd, salt, kdfparams.c, kdfparams.dklen, 'sha256'); } else { throw new Error('Unsupported key derivation scheme'); } const ciphertext = Buffer.from(json.crypto.ciphertext, 'hex'); const mac = sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext])); if (mac !== inHex(json.crypto.mac)) { throw new Error('Key derivation failed - possibly wrong password'); } const decipher = createDecipheriv( json.crypto.cipher, derivedKey.slice(0, 16), Buffer.from(json.crypto.cipherparams.iv, 'hex') ); let seed = Buffer.concat([decipher.update(ciphertext), decipher.final()]); while (seed.length < 32) { const nullBuff = Buffer.from([0x00]); seed = Buffer.concat([nullBuff, seed]); } return seed; } constructor (seed) { this.seed = seed; } signTransactionObject (tx) { tx.sign(this.seed); return tx; } signTransaction (transaction) { const tx = new Transaction(transaction); return inHex(this.signTransactionObject(tx).serialize().toString('hex')); } }
var searchData= [ ['loging',['Loging',['../class_resa___pro_1_1_formularios_1_1_loging.html',1,'Resa_Pro::Formularios']]] ];
'use strict'; describe('Controllers Tests ', function () { beforeEach(mockApiAccountCall); beforeEach(mockI18nCalls); describe('ActivationController', function () { var $scope, $httpBackend, $q; // actual implementations var MockAuth, MockStateParams; // mocks var createController; // local utility function beforeEach(inject(function ($injector) { $q = $injector.get('$q'); $scope = $injector.get('$rootScope').$new(); $httpBackend = $injector.get('$httpBackend'); MockAuth = jasmine.createSpyObj('MockAuth', ['activateAccount']); MockStateParams = jasmine.createSpy('MockStateParams'); MockStateParams.key = 'ABC123'; var locals = { '$scope': $scope, '$stateParams': MockStateParams, 'Auth': MockAuth }; createController = function () { $injector.get('$controller')('ActivationController as vm', locals); }; })); it('calls Auth.activateAccount with the key from stateParams', function () { // given MockAuth.activateAccount.and.returnValue($q.resolve()); // when $scope.$apply(createController); // then expect(MockAuth.activateAccount).toHaveBeenCalledWith({ key: 'ABC123' }); }); it('should set set success to OK upon successful activation', function () { // given MockAuth.activateAccount.and.returnValue($q.resolve()); // when $scope.$apply(createController); // then expect($scope.vm.error).toBe(null); expect($scope.vm.success).toEqual('OK'); }); it('should set set error to ERROR upon activation failure', function () { // given MockAuth.activateAccount.and.returnValue($q.reject()); // when $scope.$apply(createController); // then expect($scope.vm.error).toBe('ERROR'); expect($scope.vm.success).toEqual(null); }); }); });
/* bender-tags: editor */ var tools = bender.tools; bender.editor = { creator: 'replace', config: { // Start the editor in other mode. on: { loaded: function( evt ) { var editor = evt.editor; editor.addMode( 'source', function( callback ) { callback(); } ); }, instanceReady: function( evt ) { var editor = evt.editor; // Force result data un-formatted. editor.dataProcessor.writer._.rules = {}; } }, autoParagraph: false } }; bender.test( { // Test the wysiwyg mode provider. test_setMode: function() { var editor = this.editor; editor.setMode( 'source', function() { editor.setMode( 'wysiwyg', function() { resume( function() { var editable = editor.editable(); assert.isTrue( editable.hasClass( 'cke_editable' ) ); assert.isTrue( editable.is( 'body' ), 'editable should be the "body" element' ); assert.areSame( editor.document.$, editable.getDocument().$, 'editor.document' ); assert.areSame( editor.window.$, editor.document.getWindow().$, 'editor.window' ); } ); } ); } ); wait(); }, test_focus: function() { var ed = this.editor, bot = this.editorBot; bot.focus( function() { assert.isTrue( ed.focusManager.hasFocus ); } ); }, test_setData: function() { var editor = this.editor; var editable = this.editor.editable(); var data = '<p>foo</p>'; editor.setData( data, function() { resume( function() { assert.isMatching( /^<p>foo(<br \/>)?<\/p>$/, tools.compatHtml( editable.getHtml() ), 'set data' ); assert.areSame( data, editor.getData(), 'retrieve data' ); } ); } ); wait(); }, 'test editable listeners after setData': function() { var editor = this.editor, editable = editor.editable(), obj = {}, fired = false, doc = editable.getDocument(); editor.editable( editable ); CKEDITOR.event.implementOn( obj ); editable.attachListener( obj, 'testEvent', function() { fired = true; } ); editor.setData( 'abc', function() { resume( function() { obj.fire( 'testEvent' ); assert.isFalse( fired, 'Editable-dependent listeners were removed' ); assert.isTrue( doc.$ !== editor.editable().getDocument(), 'Document has changed' ); } ); } ); wait(); }, _testInsertion: function( insertFn, input, result ) { !result && ( result = input ); var editor = this.editor; editor.editable().setHtml( '' ); editor.focus(); if ( insertFn == 'insertElement' ) input = CKEDITOR.dom.element.createFromHtml( input, editor.document ); editor[ insertFn ]( input ); this.wait( function() { assert.areSame( result, editor.getData(), insertFn ); }, 0 ); }, test_detach: function() { this.editor.editable( null ); assert.areSame( 0, this.editor.ui.space( 'contents' ).$.getElementsByTagName( 'iframe' ).length ); } } );
let eris = require('../lib/client'); let fs = require('fs'); let config = JSON.parse(fs.readFileSync('./config.json', 'utf8')); module.exports = { label: 'shard', enabled: true, isSubcommand: false, generator: (message, args) => { try { eris.createMessage(config.starbucks, "[`" + message.channel.guild.name + "`" + "~>" + "`" + message.channel.name + "`]" + "**" + message.author.username + "**:" + message.content); var shardsinfo = ""; eris.shards.forEach(shard => { shardsinfo += `Shard [${shard.id+1}/${eris.shards.size}] | Status: ${shard.status} | Latency: ${shard.latency} ms | Ready: ${shard.ready}\n`; }); return "```css\n" + shardsinfo + "\n```"; } catch (err) { eris.createMessage(config.logChannel, `[${message.channel.guild.name}>>${message.channel.name}]${message.author.username}#${message.author.discriminator}:${this.label}\n\t>> ${err.response}\n\t${err.stack}`); } }, options: { description: 'Veja as shards do bot', deleteCommand: false, caseInsensitive: true, alias: ['si'] } };
/* switch.js (c) 2012 by Christian Mayer [CometVisu at ChristianMayer dot de] * * 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, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ define( ['_common'], function( design ) { var basicdesign = design.basicdesign; design.basicdesign.addCreator('switch', { create: function( element, path, flavour, type ) { var $e = $(element); // create the main structure var ret_val = basicdesign.createDefaultWidget( 'switch', $e, path, flavour, type, this.update ); // and fill in widget specific data var data = templateEngine.widgetDataInsert( path, { 'on_value' : $e.attr('on_value' ) || 1, 'off_value' : $e.attr('off_value') || 0 } ); // create the actor var $actor = $('<div class="actor switchUnpressed"><div class="value"></div></div>'); ret_val.append( $actor ); // bind to user action var bindClickToWidget = templateEngine.bindClickToWidget; if ( data['bind_click_to_widget'] ) bindClickToWidget = data['bind_click_to_widget']==='true'; var clickable = bindClickToWidget ? ret_val : $actor; clickable.bind( 'click', this.action ); // initially setting a value basicdesign.defaultUpdate( undefined, undefined, ret_val, true, path ); return ret_val; }, update: function(e,d) { var element = $(this), data = templateEngine.widgetDataGetByElement( element ), actor = element.find('.actor'), value = basicdesign.defaultUpdate( e, d, element, true, element.parent().attr('id') ), off = templateEngine.map( data['off_value'], data['mapping'] ); actor.removeClass( value == off ? 'switchPressed' : 'switchUnpressed' ); actor.addClass( value == off ? 'switchUnpressed' : 'switchPressed' ); }, action: function() { var widgetData = templateEngine.widgetDataGetByElement( this ); for( var addr in widgetData.address ) { if( !(widgetData.address[addr][1] & 2) ) continue; // skip when write flag not set templateEngine.visu.write( addr.substr(1), templateEngine.transformEncode( widgetData.address[addr][0], widgetData.basicvalue == widgetData.off_value ? widgetData.on_value : widgetData.off_value ) ); } } }); }); // end define
const restify = require("restify"); const config = require("../config"); const log = require("./log"); const utils = module.exports = {}; /** * Get user-friendly error message and log actual error * Defaults to 500 Internal Server Error if unknown status code * @param {error} e HttpError from Requests library, contains statusCode * @return {error} restify error from restify"s errors module */ utils.getErrorMessage = function (e) { const statusCode = e.statusCode || 500; const errorMessage = config.ERROR[statusCode] || config.ERROR[500]; return errorMessage; }; /** * Log and send error * @param {request} req Request object * @param {response} res Response object * @param {string} source Name of error"s origin function * @param {string} route Name of error"s origin route * @param {Error} error Error object, contains "message" */ utils.handleError = function (req, res, source, route, error) { if (!error.body) { error = new restify.InternalServerError(error.message); } error.body.explanation = utils.getErrorMessage(error); res.send(error); };
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'horizontalrule', 'tr', { toolbar: 'Yatay Satır Ekle' } );
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'newpage', 'bg', { toolbar: 'Нова страница' } );
/* PublicLibrary class, with hard-coded catalogs for genre. */ var PublicLibrary = function(books) { // implements Library this.catalog = {}; this.biographyCatalog = new BiographyCatalog(); this.fantasyCatalog = new FantasyCatalog(); this.mysteryCatalog = new MysteryCatalog(); this.nonFictionCatalog = new NonFictionCatalog(); this.sciFiCatalog = new SciFiCatalog(); for(var i = 0, len = books.length; i < len; i++) { this.addBook(books[i]); } }; PublicLibrary.prototype = { findBooks: function(searchString) { //todo }, checkoutBook: function(book) { //todo }, returnBook: function(book) { //todo }, // 这里需要分别对每个图书分类调用handleFilingRequest方法 // 如果想增加更多图书类别那就需要修改构造函数和addBook方法这两处的代码。 addBook: function(newBook) { // Always add the book to the main catalog. this.catalog[newBook.getIsbn()] = { book: newBook, available: true }; // Try to add the book to each genre catalog. this.biographyCatalog.handleFilingRequest(newBook); this.fantasyCatalog.handleFilingRequest(newBook); this.mysteryCatalog.handleFilingRequest(newBook); this.nonFictionCatalog.handleFilingRequest(newBook); this.sciFiCatalog.handleFilingRequest(newBook); } };
const path = require('path'); const gulp = require('gulp'); const replace = require('gulp-replace'); const jeditor = require('gulp-json-editor'); const log = require('fancy-log'); const PluginError = require('plugin-error'); const { series, //顺序 parallel, // 并行 } = gulp; const ROOT_PATH = path.resolve(__dirname, '../'); const CONFIG_PATH = path.resolve(ROOT_PATH, './config'); process.env['NODE_CONFIG_DIR'] = CONFIG_PATH; // 手动设置配置文件目录, 否则会在build文件夹里面找 gulp.task('assets', async function() { gulp.src('../src/assets/**/*').pipe(gulp.dest('../dist/assets/')); gulp.src('./entry.js').pipe(gulp.dest('../dist/')); }); gulp.task('webpack', function(callback) { const webpack = require('webpack'); const webpackConfig = require('./config/webpack.config.js'); webpack(webpackConfig, function(err, stats) { if (err) { throw new PluginError('webpack', err); } log('[webpack]', stats.toString({ modules: false, colors: true })); callback(); }); }); gulp.task( 'redirect', series('webpack', function() { return gulp .src('../dist/app.*.js') .pipe(replace('/src/assets/', './assets/')) .pipe(replace('//at.alicdn.com', 'https://at.alicdn.com')) .pipe(gulp.dest('../dist/')); }) ); gulp.task('default', parallel('assets', 'webpack', 'redirect')); gulp.task( 'package', series('default', function(callback) { const packager = require('electron-packager'); const packagerConfig = require('./config/packager.config.js'); log('[electron-packager]', 'start packing...'); packager(packagerConfig, function(err, appPaths) { if (err) { throw new Error(err); } else { log('[electron-packager]', 'package completed!', appPaths); callback(); } }); }) ); gulp.task( 'package:all', series('default', function(callback) { const packager = require('electron-packager'); const packagerConfig = require('./config/packager.config.js'); packagerConfig.all = true; log('[electron-packager]', 'start packing...'); packager(packagerConfig, function(err, appPaths) { if (err) { throw new Error(err); } else { log('[electron-packager]', 'package completed!', appPaths); callback(); } }); }) ); gulp.task('build:createBuilderPackage', function() { return gulp .src('../package.json') .pipe( jeditor((json) => { json.main = './entry.js'; return json; }) ) .pipe(gulp.dest('../.buildcache/')); }); gulp.task( 'package:builder', series('default', function(callback) { const builder = require('electron-builder'); const Platform = builder.Platform; const builderConfig = require('./config/builder.config.js'); log('[electron-builder]', 'start building...'); builder .build({ targets: Platform.MAC.createTarget(), config: builderConfig, }) .then(() => { log('[electron-builder]', 'building completed!'); callback(); }) .catch((err) => { log('[electron-builder]', 'building error:'); throw new Error(err); }); }) ); // 将字体文件复制到设备对应目录 gulp.task('copyIconfont', function() { return gulp .src('../src/assets/fonts/iconfont.ttf') .pipe(gulp.dest('../android/app/src/main/assets/fonts/')) .pipe(gulp.dest('../ios/trpg/Images.xcassets/iconfont.dataset/')); });
import _ from 'lodash'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { gotoCalendarNextRange, gotoCalendarPreviousRange, gotoCalendarToday, setCalendarView } from 'Store/Actions/calendarActions'; import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector'; import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; import CalendarHeader from './CalendarHeader'; function createMapStateToProps() { return createSelector( (state) => state.calendar, createDimensionsSelector(), createUISettingsSelector(), (calendar, dimensions, uiSettings) => { const result = _.pick(calendar, [ 'isFetching', 'view', 'time', 'start', 'end' ]); result.isSmallScreen = dimensions.isSmallScreen; result.collapseViewButtons = dimensions.isLargeScreen; result.longDateFormat = uiSettings.longDateFormat; return result; } ); } const mapDispatchToProps = { setCalendarView, gotoCalendarToday, gotoCalendarPreviousRange, gotoCalendarNextRange }; class CalendarHeaderConnector extends Component { // // Listeners onViewChange = (view) => { this.props.setCalendarView({ view }); } onTodayPress = () => { this.props.gotoCalendarToday(); } onPreviousPress = () => { this.props.gotoCalendarPreviousRange(); } onNextPress = () => { this.props.gotoCalendarNextRange(); } // // Render render() { return ( <CalendarHeader {...this.props} onViewChange={this.onViewChange} onTodayPress={this.onTodayPress} onPreviousPress={this.onPreviousPress} onNextPress={this.onNextPress} /> ); } } CalendarHeaderConnector.propTypes = { setCalendarView: PropTypes.func.isRequired, gotoCalendarToday: PropTypes.func.isRequired, gotoCalendarPreviousRange: PropTypes.func.isRequired, gotoCalendarNextRange: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(CalendarHeaderConnector);
StartTest(function(t) { t.testExtJS(function (t) { var panel = new Ext.Panel({ html : 'foo', title : 'bar' }); t.firesOk(panel, 'render', 1, 0, function() { panel.render(Ext.getBody()); }, 'firesOk reported correctly'); t.willFireNTimes(panel, 'hide', 1, 'willFireNTimes reported correctly'); t.willFireNTimes(panel, 'show', 1, 'willFireNTimes reported correctly'); panel.hide(); panel.show(); var panel2 = new Ext.Panel({ html : 'foo', title : 'bar' }); t.waitForEvent(panel2, 'render', function () { t.ok(panel2.rendered, 'Panel is rendered') }) panel2.render(Ext.getBody()); }); t.expectPass(function(t2) { var obs = new Ext.util.Observable(); obs.on('foo', function() {}); t.hasListener(obs, 'foo', 'Found "foo" listener'); }) t.expectFail(function(t2) { var obs = new Ext.util.Observable(); t2.hasListener(obs, 'bar', 'Did not find "bar" listener'); }); t.expectFail(function(t2) { var obs2 = new Ext.util.Observable(); t2.wontFire(obs2, 'foo', 'Should not fire'); t2.firesAtLeastNTimes(obs2, 'foo', 3); obs2.fireEvent('foo'); obs2.fireEvent('foo'); }); });
export class Entity { constructor(params) { this.ID = params.ID; this._x = params.x; this._y = params.y; this.spdX = 0; this.spdY = 0; this.updatePack = { ID: this.ID }; } //Entity.constructor() update() { this.updatePosition(); } //Entity.update() updatePosition() { this.x += this.spdX; this.y += this.spdY; } //Entity.updatePosition() //ENTITY GETTERS AND SETTERS get x() { return this._x; } set x(newX) { if( this._x !== newX ) { this._x = newX; this.updatePack.x = this._x; } } get y() { return this._y; } set y(newY) { if( this._y !== newY ) { this._y = newY; this.updatePack.y = this._y; } } //END ENTITY GETTERS AND SETTERS } //class Entity
var utils = require('./utils'); var gets = require('./gets'); var input = ''; var stdin_flag = true; var scanf = module.exports = function(format) { var re = new RegExp('[^%]*%[A-Za-z][^%]*', 'g'); var selector = format.match(re); var result, len = selector.length; var json_flag = false, count = 0, keys = Array.prototype.slice.call(arguments, 1); if (!this.sscanf) { // clear sscanf cache if (!stdin_flag) input = ''; stdin_flag = true; } if (keys.length > 0) { result = {}; json_flag = true; } else if (len > 1) { result = []; } else { return dealType(selector[0]); } selector.forEach(function(val) { if (json_flag) { result[keys.shift() || count++] = dealType(val); } else { result.push(dealType(val)); } }); return result; }; module.exports.sscanf = function(str, format) { if (str.constructor != String || !str.length) { return null; } // clear scanf cache if (stdin_flag) input = ''; input = str; stdin_flag = false; return scanf.apply({ sscanf: true }, Array.prototype.slice.call(arguments, 1)); }; var getInput = function(pre, next, match, type) { var result; if (!input.length || input === '\r') { if (stdin_flag) { input = gets(); } else { return null; } } // match format var replace = '(' + match + ')'; var tmp = input; // while scan string, replace before and after if (type === 'STR' && next.trim().length > 0) { var before_macth = utils.regslashes(pre); var after_match = utils.regslashes(next) + '[\\w\\W]*'; if (before_macth.length) { tmp = tmp.replace(new RegExp(before_macth), ''); } tmp = tmp.replace(new RegExp(after_match), ''); } else { replace = utils.regslashes(pre) + replace; } var m = tmp.match(new RegExp(replace)); if (!m) { // todo strip match return null; } result = m[1]; // strip match content input = input.substr(input.indexOf(result)).replace(result, '').replace(next, ''); return result; }; var getInteger = function(pre, next) { var text = getInput(pre, next, '[-]?[A-Za-z0-9]+'); if (!text) { return null; } else if (text[0] == '0') { if (text[1] == 'x' || text[1] == 'X') { return utils.hex2int(text); } else { return utils.octal2int(text); } } else { return parseInt(text); } }; var getFloat = function(pre, next) { var text = getInput(pre, next, '[-]?[0-9]+[\.]?[0-9]*'); return parseFloat(text); }; var getHex = function(pre, next) { var text = getInput(pre, next, '[A-Za-z0-9]+'); return utils.hex2int(text); }; var getOctal = function(pre, next) { var text = getInput(pre, next, '[A-Za-z0-9]+'); return utils.octal2int(text); }; var getString = function(pre, next) { var text = getInput(pre, next, '([\\w]|\\S[^\\][^\\ ])+(\\\\[\\w\\ ][\\w\\:]*)*', 'STR'); if (/\\/.test(text)) text = utils.stripslashes(text); return text; }; var getLine = function(pre, next) { var text = getInput(pre, next, '[^\n\r]*'); if (/\\/.test(text)) text = utils.stripslashes(text); return text; }; var dealType = function(format) { var ret; var res = format.match(/%[A-Za-z]/); var res2 = format.match(/[^%]*/); if (!res) { return null; } var type = res[0]; var pre = !!res2 ? res2[0] : null; var next = format.substr(format.indexOf(type) + type.length); switch (type) { case '%d': ret = getInteger(pre, next); break; case '%s': ret = getString(pre, next); break; case '%S': ret = getLine(pre, next); break; case '%X': case '%x': ret = getHex(pre, next); break; case '%O': case '%o': ret = getOctal(pre, next); break; case '%f': ret = getFloat(pre, next); break; } return ret; };
Chatters = new Mongo.Collection('chatters'); /* * Add query methods like this: * Chatters.findPublic = function () { * return Chatters.find({is_public: true}); * } */
const HAXCMS = require('../lib/HAXCMS.js'); /** * @OA\Post( * path="/deleteNode", * tags={"cms","authenticated","node"}, * @OA\Parameter( * name="jwt", * description="JSON Web token, obtain by using /login", * in="query", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response="200", * description="Delete a node" * ) * ) */ async function deleteNode(req, res) { let site = await HAXCMS.loadSite(req.body['site']['name']); // update the page's content, using manifest to find it // this ensures that writing is always to what the file system // determines to be the correct page if (page = site.loadNode(req.body['node']['id'])) { if (await site.deleteNode(page) === false) { res.send(500); } else { await site.gitCommit( 'Page deleted: ' + page.title + ' (' + page.id + ')' ); res.send(page); } } else { res.send(500); } } module.exports = deleteNode;
/** * This class used to expand a row in a Grid Panel. It allows to configure which * rows can be expanded: * * @example * me.grid = Ext.create('Ext.dirac.utils.DiracGridPanel', { * store : me.dataStore, * columnLines : true, * enableLocking : true, * width : 600, * height : 300, * oColumns : oColumns, * tbar : pagingToolbar, * contextMenu : me.contextGridMenu, * pagingToolbar : pagingToolbar, * scope : me, * plugins : [{ * ptype : 'diracrowexpander', * checkField : { * 'CE' : 'Multiple' * }, * rowBodyTpl : ['<div id="expanded-Grid-{Site}"> </div>'] * }] * }); */ Ext.define("Ext.dirac.utils.DiracRowExpander", { extend: "Ext.grid.plugin.RowExpander", alias: "plugin.diracrowexpander", checkField: null, containValue: null, selectRowOnExpand: true, getHeaderConfig: function () { var me = this; return { width: 28, lockable: false, sortable: false, resizable: false, draggable: false, hideable: false, menuDisabled: true, tdCls: Ext.baseCSSPrefix + "grid-cell-special", innerCls: Ext.baseCSSPrefix + "grid-cell-inner-row-expander", /*renderer : function(value, metadata) { if (!me.grid.ownerLockable) { metadata.tdAttr += ' rowspan="2"'; } return '<div class="' + Ext.baseCSSPrefix + 'grid-row-expander"></div>'; },*/ renderer: function (value, metadata) { // Only has to span 2 rows if it is not in a lockable grid. if (!me.grid.ownerLockable) { metadata.tdAttr += ' rowspan="2"'; } if (me.checkField) { var html = ""; for (var key in me.checkField) { if (metadata.record.data[key] == me.checkField[key]) { html = '<div class="' + Ext.baseCSSPrefix + 'grid-row-expander" role="presentation"></div>'; } } return html; } else if (me.containValue) { var html = ""; for (var key in me.containValue) { if (~metadata.record.data[key].indexOf(me.containValue[key])) { html = '<div class="' + Ext.baseCSSPrefix + 'grid-row-expander" role="presentation"></div>'; } } return html; } else if (me.boolValue) { for (var key in me.boolValue) { if (metadata.record.data[key] == me.boolValue[key]) { html = '<div class="' + Ext.baseCSSPrefix + 'grid-row-expander" role="presentation"></div>'; } } return html; } else { return '<div class="' + Ext.baseCSSPrefix + 'grid-row-expander" role="presentation"></div>'; } }, processEvent: function (type, view, cell, rowIndex, cellIndex, e, record) { if (type == "mousedown" && e.getTarget("." + Ext.baseCSSPrefix + "grid-row-expander")) { me.toggleRow(rowIndex, record); return me.selectRowOnExpand; } }, }; }, });
import Device from 'core/device'; export default new Device(navigator.userAgent);
import React, { PropTypes } from 'react' import { Router } from 'dva/router' // import pathToRegexp from 'path-to-regexp' import App from './routes/app' const cached = {} const registerModel = (app, model) => { if (!cached[model.namespace]) { app.model(model) cached[model.namespace] = 1 } } const Routers = function ({ history, app }) { const handleChildRoute = ({ location, params, routes }) => { console.log(location, params, routes) } const routes = [ { path: '/', component: App, getIndexRoute (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/dashboard')); cb(null, { component: require('./routes/dashboard/') }) }, 'dashboard') }, childRoutes: [ { path: 'dashboard', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/dashboard')) cb(null, require('./routes/dashboard/')) }, 'dashboard') }, }, { path: 'users', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/users')) cb(null, require('./routes/users/')) }, 'users') }, }, { path: 'request', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/request/')) }, 'request') }, }, { path: 'UIElement/iconfont', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/UIElement/iconfont/')) }, 'UIElement-iconfont') }, }, { path: 'UIElement/search', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/UIElement/search/')) }, 'UIElement-search') }, }, { path: 'UIElement/dropOption', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/UIElement/dropOption/')) }, 'UIElement-dropOption') }, }, { path: 'UIElement/layer', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/UIElement/layer/')) }, 'UIElement-layer') }, }, { path: 'UIElement/dataTable', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/UIElement/dataTable/')) }, 'UIElement-dataTable') }, }, { path: 'UIElement/editor', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/UIElement/editor/')) }, 'UIElement-editor') }, }, { path: 'chart/lineChart', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/chart/lineChart/')) }, 'chart-lineChart') }, }, { path: 'chart/barChart', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/chart/barChart/')) }, 'chart-barChart') }, }, { path: 'chart/areaChart', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/chart/areaChart/')) }, 'chart-areaChart') }, }, { path: '*', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/error/')) }, 'error') }, }, ], }, ] routes[0].childRoutes.map(item => { item.onEnter = handleChildRoute return item }) return <Router history={history} routes={routes} /> } Routers.propTypes = { history: PropTypes.object, app: PropTypes.object, } export default Routers
export default class AppController { constructor() { } static getTemplateUrl() { return '/angular/appController.html'; } static getControllerTemplateName() { return 'appController'; } }
/* kit.js from within kit */ /* *= require "../jquery" *= require "../jquery-ui" *= require "../jquery.validate" *= require "../best_in_place" *= require "jquery_ujs" *= require "./utilities.js" */
// passFox - A passwordstore.org extension for Firefox // Copyright (C) 2016 Tulir Asokan // 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/>. /** * Stateless pass script execution functions. * * @module pass/exec */ const child_process = require("sdk/system/child_process") const { emit } = require("sdk/event/core") const config = require("pass/config") /** * The callback for functions that give stdout and stderr. * * @callback stdioCallback * @param {string} data The text from stdout. * @param {string} error The text from stderr. */ /** * The callback for {@link #pass} * * @callback passCallback * @param {string} status The return value. * @param {string} data The text from stdout. * @param {string} error The text from stderr. */ /** * Run the Password Store script * * @param {string[]} args An array containing the arguments for pass. * @param {passCallback} callback The function to call after execution. */ function pass(args, callback) { let proc = child_process.spawn( config.prefs.passExec, args, {env: config.environment} ) let stdout = "" let stderr = "" proc.stdout.on("data", data => stdout += data) proc.stderr.on("data", data => stderr += data) proc.on("close", code => callback(code, stdout, stderr)) } /** * Initialize the password store using for the given GPG key * * @param {string} key The key to give to `pass init`. * @param {function} callback The function to call after execution. */ exports.init = function(key, callback) { pass(["init", key], (status, data, err) => callback()) } /** * Get the password store tree. * * @param {stdioCallback} callback The function to call after execution. */ exports.list = function(callback) { pass(["list"], (status, data, err) => callback(data, err)) } /** * Get the contents of the password at the given path. * * @param {string} fullPath The path to get the password from. * @param {stdioCallback} callback The function to call after execution. */ exports.get = function(fullPath, callback) { pass(["show", fullPath], (status, data, err) => callback(data, err)) } /** * Insert the given data into the password at the given path. * * @param {string} fullPath The path to the password. * @param {string} data The data to insert. * @param {function} callback The function to call after execution. */ exports.insert = function(fullPath, data, callback) { let proc = child_process.spawn( config.prefs.passExec, ["insert", "--force", "--multiline", fullPath], {env: config.environment} ) for (line of data.split("\n")) { emit(proc.stdin, "data", line + "\n") } emit(proc.stdin, 'end') proc.on("close", () => callback()) } /** * Delete a password. * * @param {string} fullPath The path to delete. * @param {stdioCallback} callback The function to call after execution. */ exports.delete = function(fullPath, callback) { pass(["rm", fullPath], (status, data, err) => callback(data, err)) } /** * The callback for {@link #getValue}. * * @callback valueCallback * @param {string} value The value (empty if none found). * @param {string} error The text from stderr. */ /** * Get a specific keyed value from a password. * * @param {string} fullPath The path to get the data from. * @param {(string|string[])} keys A string or list containing the key or keys to match. * @param {valueCallback} callback The function to call after execution. */ exports.getValue = function(fullPath, keys, callback) { let realKeys = [] if (typeof(keys) === "string") { realKeys.push(keys.toLowerCase() + ": ") } else { for (key of keys) { realKeys.push(key.toLowerCase() + ": ") } } pass(["show", fullPath], (status, data, err) => { for (line of data.split("\n")) { for (key of realKeys) { if (line.toLowerCase().startsWith(key)) { callback(line.substr(key.length), err) return } } } callback("", "Error: No " + keys[0].toLowerCase() + " found from " + fullPath.substr(1) + "\n" + err) }) } /** * The callback for {@link #getOTP} * * @callback otpCallback * @param {string} otp The one-time password. This is actually a number, but it shouldn't be handled as one. * @param {number} expiry The amount of seconds till the OTP expires. * @param {string} error The text from stderr. */ /** * Get a one-time password for the password at the given path. * * @param {string} fullPath The path to get the OTP secret from. * @param {otpCallback} callback The function to call after execution. */ exports.getOTP = function(fullPath, callback) { pass(["otp", "--raw", fullPath], (status, data, err) => { let lines = data.split("\n") let otp = "" let expiry = 0 if (lines.length > 1) { otp = lines[0] expiry = parseInt(lines[1]) } callback(otp, expiry, err) }) } /** * The callback for {@link #getPassword} * * @callback passwordCallback * @param {string} passwd The password. * @param {string} error The text from stderr. */ /** * Get the first line of the password at the given path. * * @param {string} fullPath The path to get the data from. * @param {otpCallback} callback The function to call after execution. */ exports.getPassword = function(fullPath, callback) { pass(["show", fullPath], (status, data, err) => { callback(data.split("\n")[0], err) }) }
define(['jquery', 'backbone', 'templates',], function($, Backbone, templates) { var LoadingView = Backbone.View.extend({ el : '.site-content', render : function(msg) { this.$el.html('<div class="loadingMsg" style="display:none"></div>'); var that = this; setTimeout(function() { var loadingMsg = that.$el.find(".loadingMsg"); if(loadingMsg.length > 0) { loadingMsg.html(templates.loading({msg: msg})); loadingMsg.css("display","block"); } }, 200); }, remove : function() { this.stopListening(); this.undelegateEvents(); this.$el.html(''); } }); return LoadingView; });
var SalesManBox = React.createClass({displayName: "SalesManBox", render: function(){ console.log('--'); var m = this.props.data.map( function(s){ console.log(s); return ( React.createElement("li", null, "s") ); }); return ( React.createElement("ul", null, React.createElement("li", null, "2"), m.value ) ); } }); var data = ['王晓龙', 'Tim', 'Dock'] React.render( React.createElement(SalesManBox, {data: data}), document.getElementById("content") );
/* 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/>. */ /** * javascript file for Click2Dial on infocenterDetails page */ $(document).ready( function () { InitiateCallButton(); } ); function AsteriskAnrufInfoCenter(telNumber) { // replace one or more '+' with exactly '00' telNumber = telNumber.replace(/\++/,'00'); $.ajax({url:FHC_JS_DATA_STORAGE_OBJECT.app_root+"/addons/asterisk/vilesci/asterisk_anruf.php?nummer="+telNumber}); } function InitiateCallButton() { var kontakttypen = ['mobil', 'telefon']; for (typ in kontakttypen) { var buttons = document.getElementsByClassName(kontakttypen[typ]); for (var i = buttons.length - 1; i >= 0; i--) { var buttonElem = buttons[i]; var telNum = buttonElem.innerHTML; buttonElem.innerHTML = telNum+'<input type="button" class="btn btn-default" value="Anruf" onclick="AsteriskAnrufInfoCenter(\''+telNum+'\')">'; } } }
/* This file is part of Streembit application. Streembit is an open source project to create a real time communication system for humans and machines. Streembit is a 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.0 of the License, or (at your option) any later version. Streembit 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 Streembit software. If not, see http://www.gnu.org/licenses/. ------------------------------------------------------------------------------------------------------------------------- Author: Tibor Z Pardi Copyright (C) 2016 The Streembit software development team ------------------------------------------------------------------------------------------------------------------------- */ /** * Implementation is based on https://github.com/kadtools/kad * Huge thanks to Gordon Hall https://github.com/gordonwritescode the author of kad library! * @module kad * @license GPL-3.0 * @author Gordon Hall gordon@gordonwritescode.com */ 'use strict'; var assert = require('assert'); /** * Factory for whitelist middleware * @function * @param {Array} whitelist - list of nodeID's to allow * @returns {Function} */ module.exports = function WhitelistFactory(whitelist) { assert(Array.isArray(whitelist), 'Invalid whitelist supplied'); return function whitelister(message, contact, next) { if (whitelist.indexOf(contact.nodeID) === -1) { return next(new Error('Contact is not in the whitelist')); } next(); }; };
import Db from '../config/db'; import { TABLE_NAME } from '../../migrations/20170309202310_create_orders'; import OrderDetail from './order-detail'; const Bookshelf = Db.Bookshelf; const Order = Bookshelf.Model.extend({ idAttribute: 'id', tableName: TABLE_NAME, orderDetails: () => this.hasMany(OrderDetail), }); export default Order;
describe("PermissionMapper service", function () { let Mock = {}; let service; const USER_EMAIL = "email@provider.com"; const SURVEY_GROUP_PERMISSION_JSON = { objectType: "SurveyGroupPermission", email: "email@provider.com", groups: ["Centro de Investigação", "Controle de qualidade"] }; const LABORATORY_PERMISSION_JSON = { objectType: "LaboratoryPermission", email: "email@provider.com", access: false }; beforeEach(function () { angular.mock.module('otusjs.user.permission'); inject(function (_$injector_) { _mock(_$injector_); service = _$injector_.get('otusjs.user.permission.PermissionMapper', { "otusjs.user.permission.SurveyGroupPermissionFactory": Mock.SurveyGroupPermissionFactory, "otusjs.user.permission.LaboratoryPermissionFactory": Mock.LaboratoryPermissionFactory }); }); }); it("should create accordingly to objectType - SurveyGroupPermission", function () { spyOn(Mock.SurveyGroupPermissionFactory, "create"); service.create(SURVEY_GROUP_PERMISSION_JSON, USER_EMAIL); expect(Mock.SurveyGroupPermissionFactory.create).toHaveBeenCalledWith(SURVEY_GROUP_PERMISSION_JSON, USER_EMAIL); }); it("should create accordingly to objectType - LaboratoryPermission", function () { spyOn(Mock.LaboratoryPermissionFactory, "create"); service.create(LABORATORY_PERMISSION_JSON, USER_EMAIL); expect(Mock.LaboratoryPermissionFactory.create).toHaveBeenCalledWith(LABORATORY_PERMISSION_JSON, USER_EMAIL); }); function _mock(_$injector_) { Mock.SurveyGroupPermissionFactory = _$injector_.get('otusjs.user.permission.SurveyGroupPermissionFactory'); Mock.LaboratoryPermissionFactory = _$injector_.get('otusjs.user.permission.LaboratoryPermissionFactory'); } });
/////////////////////////////////////////// ////// /////// ////// /////// ////// /////// ////// JavaScript pour accompagner /////// ////// Le bootstap.js /////// ////// /////// ////// /////// ////// /////// /////////////////////////////////////////// // Je sélectionne tous les Formations $(function() { $('#side-menu').metisMenu(); }); //Loads the correct sidebar on window load, //collapses the sidebar on window resize. $(function() { $(window).bind("load resize", function() { width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width; if (width < 768) { $('div.sidebar-collapse').addClass('collapse') } else { $('div.sidebar-collapse').removeClass('collapse') } }) })
var searchData= [ ['algorithmtype',['AlgorithmType',['../_object_agent_8h.html#a9243adfb7445f1adcf51b73329e774c9',1,'ObjectAgent.h']]] ];
GNATdoc.InheritanceIndex = [ { "label": "Abc", "docHref": "docs/amc_types___spec.html#L136C9" }, { "label": "Alfa_Beta", "docHref": "docs/amc_types___spec.html#L149C9" }, { "label": "Angle", "docHref": "docs/amc_types___spec.html#L116C9" }, { "label": "Base_Stream", "docHref": "docs/stream_interface___spec.html#L12C9", "inherited": [ { "label": "COBS_Stream", "docHref": "docs/serial_cobs___spec.html#L13C9" }, { "label": "UART_Stream", "docHref": "docs/amc_uart___spec.html#L20C9" } ] }, { "label": "Dq", "docHref": "docs/amc_types___spec.html#L143C9" }, { "label": "Interface_Type", "docHref": "docs/communication___spec.html#L40C9" }, { "label": "Kpid", "docHref": "docs/pid___spec.html#L12C9" }, { "label": "Port_Type", "docHref": "docs/communication___spec.html#L38C9" }, { "label": "Timer", "docHref": "docs/amc_utils___spec.html#L95C9" } ];
var functions = require("./functions"); var date = new Array; exports.text = function() { date[0] = parseInt(functions.get_line_from_event(1)); date[1] = parseInt(functions.get_line_from_event(2)); date[2] = parseInt(functions.get_line_from_event(3)); var week_day = functions.day_of_week_94(date); var place = functions.get_line_from_event(4) == "SRC" ? "مرکز تحقیقات دانشگاه" : functions.get_line_from_event(4); var str = "خدمت ت عارضم که جلسه بعدی گروه کیوت مرکز تحقیقات در تاریخ "; str += week_day; str += " " + functions.get_line_from_event(1) + "/" + functions.get_line_from_event(2) + "/" + functions.get_line_from_event(3); str += " در " + place + " برگزار میشه. 😊"; str += "\nموضوع جلسه: " + functions.get_line_from_event(5); str += "\nتوضیحات: " + functions.get_line_from_event(6); return str; };
'use strict'; var expect = require('expect.js'); describe('models/index', function () { var models = require('../../models'); it('returns the task model', function () { expect(models.Task).to.be.ok(); }); it('returns the user model', function () { expect(models.User).to.be.ok(); }); it('return the customer model', function(){ expect(models.Customer).to.be.ok(); }); });
angular.module("risevision.developer") .controller("CommonHeaderNavbarCtrl", ["$scope", "$rootScope", "$state", function($scope, $rootScope, $state) { $rootScope.navOptions = [{ title: "Developer Documentation", link: $state.href("documentation", {}, {absolute: true}), cid: true, states: [ "documentation", "documentation-documentation", "documentation-post", "documentation-post-category", "documentation-post-sub", "page-not-found" ] }, { title: "App Registration", link: $state.href("apps.list"), cid: true, states: [ "apps", "apps.withoutPermission", "apps.list", "apps.add", "apps.edit" ] }, { title: "API Explorer", link: $state.href("api-explorer.list"), cid: true, states: [ "api-explorer", "api-explorer.list", "api-explorer.explore", "api-explorer.explore.endpoint" ] }]; $scope.navSelected = 'documentation'; $scope.hideCommonHeader = false; $rootScope.$on('$stateChangeSuccess', function () { $scope.navSelected = $state.current.name; $scope.hideCommonHeader = $state.current.name.indexOf('common.auth') !== -1; }); }]);