text
stringlengths 2
6.14k
|
|---|
var path = require('path');
var express = require('express');
var app = express();
if(process.env.NODE_ENV !== 'production') {
var webpack = require('webpack');
var config = require('./webpack.config');
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/src/index.html'));
});
} else if(process.env.NODE_ENV === 'production') {
console.log('production mode');
app.use(express.static(__dirname + '/build'))
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/build/index.html'));
});
}
app.listen(8000, '0.0.0.0', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://0.0.0.0:8000');
});
|
var express = require('express')
var fs = require('fs')
var path = require('path')
var Telegram = require('./telegram')
var bodyParser = require('body-parser')
var IMAP = require('./imap')
var NNTP = require('./nntp')
class Backend {
constructor (inOptions) {
this.app = express()
this.app.use(bodyParser.json())
this.options = inOptions
this.loadPlugins(inOptions)
this.start()
this.imap = new IMAP(inOptions)
this.nntp = new NNTP(inOptions)
let backendOpts = this.options.backend
if (backendOpts['telegram-key']) {
this.telegram = new Telegram(this.options)
}
}
loadPlugins (inOptions) {
const testFolder = path.join(__dirname, 'plugins')
fs.readdirSync(testFolder).forEach(file => {
var _plugin = require(path.join(testFolder, file))
_plugin(inOptions, this)
})
}
start () {
let backendOpts = this.options.backend
this.app.use(express.static(path.join(__dirname, '../fronend')))
this.app.listen(backendOpts.portnum)
}
}
module.exports = Backend
|
var app = angular.module("myapp", ["firebase"]);
var FB = "";
function TodoCtrl($scope, $firebase) {
$scope.hidden = false;
var ref = new Firebase(FB);
$scope.todos = $firebase(ref);
$scope.addTodo = function() {
$scope.todos.$add({text: $scope.todoText, done: false});
$scope.todoText = '';
};
$scope.done = function(key) {
// Figure out how to "edit the current entry"
var ref2 = new Firebase(FB + key);
$scope.update = $firebase(ref2);
$scope.update.$update({done: $scope.todos[key].done});
$scope.todoText = '';
};
$scope.archive = function(){
$scope.todos.$update({hidden : true});
$scope.todos.hidden = true;
};
$scope.showAll = function(){
$scope.todos.$update({hidden : false});
};
$scope.hide = function(value) {
if (value != null)
{
if ($scope.todos.hidden)
{
return value;
}
else
{
return false;
}
}
else
{
return true;
}
};
}
|
"use strict";
var React = require("react");
var Button = require("react-bootstrap/lib/Button");
var Ticket = require("../../models/client/Ticket");
var User = require("../../models/client/User");
var Actions = require("../../Actions");
/**
* ToggleFollowButton
*
* @namespace components
* @class TicketView.ToggleFollowButton
* @constructor
* @param {Object} props
* @param {models.client.Ticket} props.ticket
* @param {models.client.User} props.user
*/
var ToggleFollowButton = React.createClass({
propTypes: {
user: React.PropTypes.instanceOf(User).isRequired,
ticket: React.PropTypes.instanceOf(Ticket).isRequired,
},
getInitialState: function() {
return {
fetching: false
};
},
onClick: function(e) {
var ticket = this.props.ticket;
this.setState({ fetching: true });
var op;
if (this.props.ticket.isFollower(this.props.user)) {
op = ticket.removeFollower(this.props.user);
} else {
op = ticket.addFollower(this.props.user);
}
Actions.ajax.write(op);
op.catch(Actions.error.haltChain("Tukipyynnön seuraaminen epäonnistui"))
.then(Actions.refresh);
},
componentWillReceiveProps: function(nextProps) {
var followingChanged = (
this.props.ticket.isFollower(this.props.user) !==
nextProps.ticket.isFollower(this.props.user));
if (followingChanged) {
// remove spinner on successful toggle
this.setState({ fetching: false });
}
},
render: function() {
var isFollower = this.props.ticket.isFollower(this.props.user);
var icon = "fa " + (isFollower ? "fa-check-square-o" : "fa-square-o");
if (this.state.fetching) icon = "fa fa-spinner";
return (
<Button bsStyle="primary" onClick={this.onClick}>
<i className={icon}></i> Seuraa
</Button>
);
}
});
module.exports = ToggleFollowButton;
|
showWord(["n. ","zak mechanste, tandans pou fè moun soufri."
])
|
/**
* Pie Chart
* Init Pie Chart
* by Luiz Ricardo (https://github.com/luizrw)
*
* This plugin this licensed as GPL.
*/
jQuery(document).ready(function($) {
$('.lrw-pie-chart').each( function() {
var pie = $(this),
unit = pie.data('unit'),
settings = pie.data('settings'),
trigger = ( settings.trigger ? !0 : !1 );
function initpie() {
pie.easyPieChart({
easing: settings.easing,
lineCap: settings.linecap,
lineWidth: settings.linewidth,
size: settings.size,
animate: settings.animate,
rotate: ( settings.rotate ? settings.rotate : 0 ),
scaleLength: ( settings.scalelength ? settings.scalelength : 0 ),
trackWidth: settings.trackwidth,
onStep: function(from, to, percent) {
$(this.el).find('.lrw-pie-percent').text(Math.round(percent) + ' ' + unit );
}
}).find('.lrw-pie-wrapper').css({ width: settings.size }).find('.lrw-pie-percent').css({
width: settings.size,
height: settings.size,
"line-height": settings.size + "px"
});
}
if ( 0 == trigger ) {
initpie();
} else {
pie.waypoint(function(direction) {
initpie();
this.destroy();
}, {
offset: 'bottom-in-view',
triggerOnce: !0
})
}
});
});
|
define(["controllers/module"],
function (controllers) {
controllers.controller('LoginCtrl', ["$scope", "$state", "$stateParams", "securityService",
function ($scope, $state, $stateParams, securityService) {
$scope.login = function () {
var name = $scope.saUsername;
var pass = $scope.saPassword;
securityService.login(name, pass)
.then(function (data) {
var state = $stateParams.action || "articles.list";
$state.go(state);
}, function (error) {
$scope.error = true;
$scope.errorMessage = error.message;
});
};
$scope.register = function () {
var name = $scope.saNewUsername;
var pass1 = $scope.saNewPassword1;
var pass2 = $scope.saNewPassword2;
var fields = {
Email: $scope.saNewEmail
};
if (pass1 !== pass2) {
$scope.registerError = true;
$scope.errorMessage = "The passwords don't match.";
}
securityService.register(name, pass1, fields)
.then(function (data) {
var state = $stateParams.action || "articles.list";
$state.go(state);
}, function (error) {
$scope.registerError = true;
$scope.errorMessage = error.message;
});
};
$scope.facebookLogin = function () {
securityService.loginWithFacebook();
}
} ]);
});
|
/**
* navigation.js
*
* Handles toggling the navigation menu for small screens.
( function() {
var container, button, menu;
container = document.getElementById( 'site-navigation' );
if ( ! container )
return;
button = container.getElementsByTagName( 'h1' )[0];
if ( 'undefined' === typeof button )
return;
menu = container.getElementsByTagName( 'ul' )[0];
// Hide menu toggle button if menu is empty and return early.
if ( 'undefined' === typeof menu ) {
button.style.display = 'none';
return;
}
if ( -1 === menu.className.indexOf( 'nav-menu' ) )
menu.className += ' nav-menu';
button.onclick = function() {
if ( -1 !== container.className.indexOf( 'toggled' ) )
container.className = container.className.replace( ' toggled', '' );
else
container.className += ' toggled';
};
} )();
*/
|
/*!
* CSSViewer, A Google Chrome Extension for fellow web developers, web designers, and hobbyists.
*
* https://github.com/miled/cssviewer
* https://chrome.google.com/webstore/detail/cssviewer/ggfgijbpiheegefliciemofobhmofgce
*
* This source code is licensed under the GNU General Public License,
* Version 2. See the file COPYING for more details.
*/
var cssViewerLoaded = false;
var cssCiewerContextMenusParent = null;
// Check whether new version is installed
// chrome.runtime.onInstalled.addListener(function(details){
// if(details.reason == "install" || details.reason == "update" ){
// chrome.tabs.create( {url: "option.html"} );
// }
// });
/*
* Inject cssviewer.js/cssviewer.css into the current page
*/
chrome.browserAction.onClicked.addListener(function(tab)
{
if( tab.url.indexOf("https://chrome.google.com") === 0 || tab.url.indexOf("chrome://") === 0 )
{
alert( "CSSViewer doesn't work on Google Chrome webstore!" );
return;
}
if( ! cssViewerLoaded )
{
cssCiewerContextMenusParent = chrome.contextMenus.create( { "title" : "ColoursAndSmiles", contexts:["all"], "onclick": debugColoursAndSmiles } );
// cssCiewerContextMenusParent = chrome.contextMenus.create( { "title" : "CSSViewer console", contexts:["all"] } );
// chrome.contextMenus.create( { "title": "parents" , contexts:["all"] , "parentId": cssCiewerContextMenusParent, "onclick": cssCiewerDebugParents } );
// chrome.contextMenus.create( { "title": "element" , contexts:["all"] , "parentId": cssCiewerContextMenusParent, "onclick": cssCiewerDebugEl } );
// chrome.contextMenus.create( { "title": "element.id" , contexts:["all"] , "parentId": cssCiewerContextMenusParent, "onclick": cssCiewerDebugElId } );
// chrome.contextMenus.create( { "title": "element.tagName" , contexts:["all"] , "parentId": cssCiewerContextMenusParent, "onclick": cssCiewerDebugElTagName } );
// chrome.contextMenus.create( { "title": "element.className" , contexts:["all"] , "parentId": cssCiewerContextMenusParent, "onclick": cssCiewerDebugElClassName } );
// chrome.contextMenus.create( { "title": "element.style" , contexts:["all"] , "parentId": cssCiewerContextMenusParent, "onclick": cssCiewerDebugElStyle } );
// chrome.contextMenus.create( { "title": "element.cssText" , contexts:["all"] , "parentId": cssCiewerContextMenusParent, "onclick": cssCiewerDebugElCssText } );
// chrome.contextMenus.create( { "title": "element.getComputedStyle" , contexts:["all"] , "parentId": cssCiewerContextMenusParent, "onclick": cssCiewerDebugElGetComputedStyle } );
// chrome.contextMenus.create( { "title": "element.simpleCssDefinition", contexts:["all"] , "parentId": cssCiewerContextMenusParent, "onclick": cssCiewerDebugElSimpleCssDefinition } );
}
chrome.tabs.executeScript(tab.id, {file:'js/CSSJSON/json2.js'});
// chrome.tabs.executeScript(tab.id, {file:'js/cssTemplate/cssTemplate_Terra.js'});
chrome.tabs.executeScript(tab.id, {file:'js/CSSJSON/cssjson.js'});
chrome.tabs.executeScript(tab.id, {file:'js/CSSJSON/cSTemplates.js'});
chrome.tabs.executeScript(tab.id, {file:'js/cssviewer.js'});
chrome.tabs.insertCSS(tab.id, {file:'css/cssviewer.css'});
cssViewerLoaded = true;
});
function debugColoursAndSmiles( info, tab )
{
chrome.tabs.executeScript(tab.id, {code:'cssViewerCopyCssToConsole("coloursAndSmiles")'});
}
function cssCiewerDebugEl( info, tab )
{
chrome.tabs.executeScript(tab.id, {code:'cssViewerCopyCssToConsole("el")'});
}
function cssCiewerDebugElId( info, tab )
{
chrome.tabs.executeScript(tab.id, {code:'cssViewerCopyCssToConsole("id")'});
}
function cssCiewerDebugElTagName( info, tab )
{
chrome.tabs.executeScript(tab.id, {code:'cssViewerCopyCssToConsole("tagName")'});
}
function cssCiewerDebugElClassName( info, tab )
{
chrome.tabs.executeScript(tab.id, {code:'cssViewerCopyCssToConsole("className")'});
}
function cssCiewerDebugElStyle( info, tab )
{
chrome.tabs.executeScript(tab.id, {code:'cssViewerCopyCssToConsole("style")'});
}
function cssCiewerDebugElCssText( info, tab )
{
chrome.tabs.executeScript(tab.id, {code:'cssViewerCopyCssToConsole("cssText")'});
}
function cssCiewerDebugElGetComputedStyle( info, tab )
{
chrome.tabs.executeScript(tab.id, {code:'cssViewerCopyCssToConsole("getComputedStyle")'});
}
function cssCiewerDebugElSimpleCssDefinition( info, tab )
{
chrome.tabs.executeScript(tab.id, {code:'cssViewerCopyCssToConsole("simpleCssDefinition")'});
}
|
Ext.define('Rd.view.nas.winMapPreferences', {
extend: 'Ext.window.Window',
alias : 'widget.winMapPreferences',
title : i18n('sPreferences'),
layout: 'fit',
autoShow: false,
width: 350,
height: 350,
iconCls: 'settings',
initComponent: function() {
var me = this;
var types = Ext.create('Ext.data.Store', {
fields: ['id', 'text'],
data : [
{"id":"HYBRID", "text": i18n("sHybrid")},
{"id":"ROADMAP", "text": i18n("sRoadmap")},
{"id":"SATELLITE", "text": i18n("sSatellite")},
{"id":"TERRAIN", "text": i18n("sTerrain")}
]
});
this.items = [
{
xtype: 'form',
border: false,
layout: 'anchor',
autoScroll: true,
defaults: {
anchor: '100%'
},
fieldDefaults: {
msgTarget: 'under',
labelClsExtra: 'lblRd',
labelAlign: 'left',
labelSeparator: '',
margin: 15
},
defaultType: 'textfield',
items: [
{
xtype : 'numberfield',
name : 'lng',
itemId : 'lng',
fieldLabel : i18n('sLongitude'),
value : 0,
maxValue : 180,
minValue : -180,
decimalPrecision: 14,
labelClsExtra: 'lblRdReq'
},
{
xtype : 'numberfield',
name : 'lat',
itemId : 'lat',
fieldLabel : i18n('sLatitude'),
value : 0,
maxValue : 90,
minValue : -90,
decimalPrecision: 14,
labelClsExtra: 'lblRdReq'
},
{
xtype : 'numberfield',
name : 'zoom',
itemId : 'zoom',
fieldLabel : i18n('sZoom_level'),
value : 17,
maxValue : 22,
minValue : 0,
labelClsExtra: 'lblRdReq'
},
{
xtype : 'combobox',
name : 'type',
itemId : 'type',
fieldLabel : i18n('sType'),
store : types,
queryMode : 'local',
displayField : 'text',
valueField : 'id',
allowBlank : false,
forceSelection: true,
labelClsExtra: 'lblRdReq'
}
],
buttons: [
{
itemId: 'snapshot',
text: i18n('sSnapshot'),
scale: 'large',
iconCls: 'b-snapshot',
margin: '0 20 40 0'
},
{
itemId: 'save',
text: i18n('sOK'),
scale: 'large',
iconCls: 'b-save',
formBind: true,
margin: '0 20 40 0'
}
]
}
];
this.callParent(arguments);
}
});
|
Ext.define('Planche.controller.table.AdvancedProperties', {
extend: 'Ext.app.Controller',
initWindow : function(db, tb, result){
Ext.create('Planche.lib.Window', {
stateful: true,
title : 'Advanced properties \''+tb+'\' in \''+db+'\'',
layout : 'fit',
bodyStyle:"background-color:#FFFFFF",
width : 400,
height: 300,
overflowY: 'auto',
autoScroll : true,
modal : true,
plain: true,
fixed : true,
shadow : false,
autoShow : true,
constrain : true,
items : this.initGrid(),
buttons : [{
text : 'close',
scope : this,
handler : this.close
}],
listeners: {
scope : this,
boxready : function(){
this.initTableData(result);
}
}
});
},
initGrid : function(){
var columns = this.makeListColumns();
var fields = [];
Ext.each(columns, function(obj){
fields.push(obj.dataIndex);
});
this.columnGrid = Ext.create('Ext.grid.Panel', {
border : false,
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2
})
],
columnLines: true,
width : '100%',
flex : 1,
columns : columns,
store: Ext.create('Ext.data.Store', {
fields:fields
})
});
return this.columnGrid;
},
initTableData : function(result){
var store = this.columnGrid.getStore();
var records = [];
Ext.Object.each(result.fields, function(idx, col){
records.push({
variable : col.name,
values : result.records[0][idx]
});
});
store.insert(0, records);
},
makeListColumns : function(){
return [
{ text: 'Variable', dataIndex: 'variable', width : 120},
{ text: 'Values', dataIndex: 'values', flex : 1}
];
},
close : function(btn){
btn.up('window').destroy();
}
});
|
#pragma strict
import System.IO;
var FontT:Font;
var Wall:Texture;
var TimerS=0;
var Shutdown=false;
var INVISIBLE:GUISkin;
var EasterEgg=0;
var RESET_DATA=false;
function Start () {
}
function Update () {
Display.main.SetRenderingResolution(Display.main.systemWidth,Display.main.systemHeight);
if(Input.GetKeyDown(KeyCode.I)){
RESET_DATA=true;
}
if(Application.platform!=RuntimePlatform.LinuxPlayer){
Screen.fullScreen=true;
}
TimerS++;
if(TimerS==750)
{
if(Application.platform==RuntimePlatform.LinuxPlayer){
PlayerPrefs.SetString("USER_STAT","OFFLINE");
PlayerPrefs.SetString("USER_ID_SISPIC","");
PlayerPrefs.SetString("USER_Nick","");
PlayerPrefs.SetString("USER_PASS","");
PlayerPrefs.SetString("UserProfile","");
PlayerPrefs.SetString("ListContacts","");
try
{
for(file in System.IO.Directory.GetFileSystemEntries(PlayerPrefs.GetString("SYSTEM_PATH")+"/TMP/"))
{
System.IO.File.Delete(file);
}
}
catch(e){
}
var LINUX_R = File.CreateText("/ZED/command");
var TMP_CMD=PlayerPrefs.GetString("EXIT_CMD");
PlayerPrefs.SetString("EXIT_CMD","");
LINUX_R.WriteLine(TMP_CMD);
LINUX_R.Close();
}
}
if(TimerS==800)
{
if(RESET_DATA){
PlayerPrefs.DeleteAll();
}
Shutdown=true;
Application.Quit();
}
}
function OnGUI(){
GUI.DrawTexture(Rect(0,0,Screen.width,Screen.height),Wall);
GUI.skin.font=FontT;
var FontTMP1=GUI.color;
GUI.skin.label.fontSize=30;
GUI.color=Color.black;
GUI.skin.label.alignment=TextAnchor.MiddleCenter;
GUI.skin.label.fontStyle=FontStyle.Bold;
GUI.color.a=0.5;
if(EasterEgg<=5){
GUI.Label(Rect(0,(Screen.height/2)-1,Screen.width,50),PlayerPrefs.GetString("SYS_STRING_44"));
GUI.color=Color.blue;
GUI.Label(Rect(1,(Screen.height/2)-2,Screen.width,50),PlayerPrefs.GetString("SYS_STRING_44"));
}else{
GUI.Label(Rect(0,(Screen.height/2)-1,Screen.width,50),"Hasta la vista baby");
GUI.color=Color.red;
GUI.Label(Rect(0,(Screen.height/2)-1,Screen.width,50),"Hasta la vista baby");
}
GUI.color=FontTMP1;
GUI.skin=INVISIBLE;
if(GUI.Button(Rect(0,0,Screen.width,Screen.height),"")){
EasterEgg=EasterEgg+1;
}
}
function OnApplicationQuit () {
if(!Shutdown)
{
Application.CancelQuit();
}
}
|
/*!
* This file is part of Aloha Editor
* Author & Copyright (c) 2010 Gentics Software GmbH, [email protected]
* Licensed unter the terms of http://www.aloha-editor.com/license.html
*/
// Start Closure
// Ensure GENTICS Namespace
GENTICS = window.GENTICS || {};
GENTICS.Utils = GENTICS.Utils || {};
define(['aloha/jquery'],
function(jQuery) {
var
$ = jQuery,
GENTICS = window.GENTICS,
Class = window.Class,
console = window.console;
/**
* position utility, which will provide scroll and mouse positions
* please note that the positions provided by this class are not
* realtime - instead they are calculated with a 0.5 second delay
*/
GENTICS.Utils.Position = {};
/**
* jquery reference to the window object
*/
GENTICS.Utils.Position.w = jQuery(window);
/**
* contains the current scroll top and left position, and indicates if the user is currently scrolling
* @api
*/
GENTICS.Utils.Position.Scroll = {
top : 0,
left : 0,
isScrolling : false
};
/**
* contains the scroll corrections to apply on special cases (ribbon for example)
* @api
*/
GENTICS.Utils.Position.ScrollCorrection = {
top : 100,
left : 50
};
/**
* contains the current mouse position (x,y) as well as an indicator if the mouse is moving
* @api
*/
GENTICS.Utils.Position.Mouse = {
x : 0,
y : 0,
oldX : 0,
oldY : 0,
isMoving : false,
triggeredMouseStop : true
};
/**
* contains all mousestop callbacks
*/
GENTICS.Utils.Position.mouseStopCallbacks = [];
/**
* contains all mousemove callbacks
*/
GENTICS.Utils.Position.mouseMoveCallbacks = [];
/**
* updates scroll position and the scrolling status
*/
GENTICS.Utils.Position.update = function () {
// update scroll position
var
st = this.w.scrollTop(),
sl = this.w.scrollLeft(),
i;
if (this.Scroll.isScrolling) {
if (this.Scroll.top == st && this.Scroll.left == sl) {
// stopped scrolling
this.Scroll.isScrolling = false;
}
} else {
if (this.Scroll.top != st || this.Scroll.left != sl) {
// started scrolling
this.Scroll.isScrolling = true;
}
}
// update scroll positions
this.Scroll.top = st;
this.Scroll.left = sl;
// check wether the user has stopped moving the mouse
if (this.Mouse.x == this.Mouse.oldX && this.Mouse.y == this.Mouse.oldY) {
this.Mouse.isMoving = false;
// now check if we've triggered the mousestop event
if (!this.Mouse.triggeredMouseStop) {
this.Mouse.triggeredMouseStop = true;
// iterate callbacks
for (i=0; i<this.mouseStopCallbacks.length; i++) {
this.mouseStopCallbacks[i].call();
}
}
} else {
this.Mouse.isMoving = true;
this.Mouse.triggeredMouseStop = false;
// iterate callbacks
for (i=0; i<this.mouseMoveCallbacks.length; i++) {
this.mouseMoveCallbacks[i].call();
}
}
// update mouse positions
this.Mouse.oldX = this.Mouse.x;
this.Mouse.oldY = this.Mouse.y;
};
/**
* adds a callback method which is invoked when the mouse has stopped moving
* @param callback the callback method to be invoked
* @return index of the callback
*/
GENTICS.Utils.Position.addMouseStopCallback = function (callback) {
this.mouseStopCallbacks.push(callback);
return (this.mouseStopCallbacks.length - 1);
};
/**
* adds a callback method which is invoked when the mouse is moving
* @param callback the callback method to be invoked
* @return index of the callback
*/
GENTICS.Utils.Position.addMouseMoveCallback = function (callback) {
this.mouseMoveCallbacks.push(callback);
return (this.mouseMoveCallbacks.length - 1);
};
// Mousemove Hooks
jQuery(function () {
window.setInterval(function (){
GENTICS.Utils.Position.update();
}, 500);
});
jQuery('html').mousemove(function (e) {
GENTICS.Utils.Position.Mouse.x = e.pageX;
GENTICS.Utils.Position.Mouse.y = e.pageY;
});
});
|
/*
Copyright (C) 2015 Mark Baird
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/>.
*/
module.exports = function TopicModule(pb) {
//pb dependencies
var util = pb.util;
var Index = require('./index.js')(pb);
/**
* Index page of the pencilblue theme
*/
function Topic(){}
util.inherits(Topic, Index);
Topic.prototype.init = function(context, cb) {
var self = this;
var init = function(err) {
//get content settings
var contentService = new pb.ContentService();
contentService.getSettings(function(err, contentSettings) {
if (util.isError(err)) {
return cb(err);
}
//create the service
self.contentSettings = contentSettings;
var asContext = self.getServiceContext();
asContext.contentSettings = contentSettings;
self.service = new pb.ArticleServiceV2(asContext);
//create the loader context
var cvlContext = self.getServiceContext();
cvlContext.contentSettings = contentSettings;
cvlContext.service = self.service;
self.contentViewLoader = new pb.ContentViewLoader(cvlContext);
self.contentViewLoader.getDefaultTemplatePath = function() {
return 'topic';
};
//provide a dao
self.dao = new pb.DAO();
cb(null, true);
});
};
Topic.super_.prototype.init.apply(this, [context, init]);
};
Topic.prototype.render = function(cb) {
var self = this;
var topicName = decodeURIComponent(this.pathVars.topicName);
var where = {name: topicName};
//attempt to load object
var dao = new pb.DAO();
dao.loadByValues(where, 'topic', function(err, topic) {
if (util.isError(err) || topic == null) {
if (where.name) {
self.reqHandler.serve404();
return;
}
}
if (topic) {
self.renderTopic(topic, cb);
}
else {
self.reqHandler.serve404();
return;
}
});
};
Topic.prototype.renderTopic = function(topic, cb) {
this.ts.registerLocal('topic_name', topic.name);
this.req.pencilblue_topic = topic._id.toString();
this.setPageName(topic.name);
Topic.super_.prototype.render.apply(this, [cb]);
};
/**
* Provides the routes that are to be handled by an instance of this prototype.
* The route provides a definition of path, permissions, authentication, and
* expected content type.
* Method is optional
* Path is required
* Permissions are optional
* Access levels are optional
* Content type is optional
*
* @param cb A callback of the form: cb(error, array of objects)
*/
Topic.getRoutes = function(cb) {
var routes = [
{
method: 'get',
path: '/topic/:topicName',
auth_required: false,
content_type: 'text/html'
},
{
method: 'get',
path: '/tag/:topicName',
auth_required: false,
content_type: 'text/html'
}];
cb(null, routes);
};
//exports
return Topic;
};
|
function include_file(filename, filetype) {
if(!filetype)
var filetype = 'js'; //js default filetype
var th = document.getElementsByTagName('head')[0];
var s = document.createElement((filetype == "js") ? 'script' : 'link');
s.setAttribute('type',(filetype == "js") ? 'text/javascript' : 'text/css');
if (filetype == "css")
s.setAttribute('rel','stylesheet');
s.setAttribute((filetype == "js") ? 'src' : 'href', filename);
th.appendChild(s);
}
function redirect_to_page (url, timer) {
setTimeout('self.location.href="'+url+'"', timer);
}
$(document).ready(function()
{
if($(".jcalendar").length) {
$.insert(WB_URL+"/include/jscalendar/calendar-system.css");
}
if($(".jsadmin").length) {
$.insert(WB_URL+"/modules/jsadmin/backend.css");
}
//Add external link class to external links -
$('a[href^="http://"]').filter(function() {
//Compare the anchor tag's host name with location's host name
return this.hostname && this.hostname !== location.hostname;
}).addClass("external").attr("target", "_blank");
/* Add internal link class to external links - */
$('a[href^="http://"]').filter(function() {
//Compare the anchor tag's host name with location's host name
return this.hostname && this.hostname == location.hostname;
}).addClass("internal");
$('form').attr('autocomplete', 'off');
});
|
"use strict"
function Bullet (x, y, rotation, type, damage) {
this.pos = [x, y];
this.rotation = rotation || 0;
this.alive = true;
this.type= type;
switch (type) {
case 1:
this.damage = damage || 5;
this.speed = 250;
this.sprite = new Sprite ('img/bullet1.png', [0,0], [9, 9], 15, [0, 1]);
break;
case 2:
this.damage = damage || 52;
this.speed = 300;
this.sprite = new Sprite ('img/bullet1.png', [0,0], [9, 9], 15, [0, 1]);
break;
default:
break;
}
}
Bullet.prototype = {
draw: function(ctx, dt){
this.sprite.update(dt);
this.sprite.render(ctx, this.pos, this.rotation);
},
deal_damage: function(enemy_index){
switch (this.type) {
case 1:
if (mainscreen.cell.armor <= 0){
mainscreen.cell.armor = 0;
mainscreen.cell.hp -= this.damage;
}
else {
if (mainscreen.cell.armor<this.damage*1.5){
mainscreen.cell.hp -= (this.damage-(mainscreen.cell.armor/1.5));
mainscreen.cell.armor = 0;
}
else
mainscreen.cell.armor-=this.damage*1.5;
}
break;
case 2:
mainscreen.enemies[enemy_index].hp-=this.damage;
break;
default:
break;
}
},
update: function (dt) {
switch (this.type) {
case 1:
var cp = mainscreen.cell.pos;
if (Math.sqrt((this.pos[0]-cp[0])*(this.pos[0]-cp[0])+(this.pos[1]-cp[1])*(this.pos[1]-cp[1]))<=
mainscreen.cell.sprite.size[0]/2+this.sprite.size[1]/2) {
this.deal_damage(null);
this.alive = false;
} else {
this.pos[0] += -this.speed*Math.sin((this.rotation).degree())*(dt/1000);
this.pos[1] += this.speed*Math.cos((this.rotation).degree())*(dt/1000);
}
break;
case 2:
if (this.pos[0]<0 || this.pos[0]>mainscreen.width || this.pos[1]<0 || this.pos[1]>mainscreen.height){
this.alive = false;
break;
}
else{
this.pos[0] += -this.speed*Math.sin((this.rotation).degree())*(dt/1000);
this.pos[1] += this.speed*Math.cos((this.rotation).degree())*(dt/1000);
}
for (var i= 0, il=mainscreen.enemies.length; i<il; i++){
var enemy = mainscreen.enemies[i];
if (testRectAndCircleIntersection(enemy.pos, enemy.sprite.size, enemy.rotation, this.pos, this.sprite.size[0]/2))
{
this.deal_damage(i);
this.alive = false;
break;
}
}
break;
default:
break;
}
}
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from 'App';
import ErrorPage from 'domains/error';
import registerServiceWorker from 'utils/registerServiceWorker';
import 'bootswatch/dist/slate/bootstrap.min.css';
import { Provider as ReduxProvider } from 'react-redux';
import store from 'store';
import ReactGA from 'react-ga';
import * as Sentry from '@sentry/react';
import 'utils/i18n';
// Avoid proxies that may interfer with the site
if (process.env.NODE_ENV !== 'development' && document.location.host !== process.env.REACT_APP_HOST) {
// eslint-disable-next-line no-restricted-globals
parent.window.location.href = `//${process.env.REACT_APP_HOST}/`;
}
// Break out of frames
// eslint-disable-next-line no-restricted-globals
if (top.location !== self.location) {
// eslint-disable-next-line no-restricted-globals
top.location = self.location.href;
}
const sentryEnabled = !!process.env.REACT_APP_SENTRY_DSN;
if (sentryEnabled) {
Sentry.init({
dsn: process.env.REACT_APP_SENTRY_DSN,
debug: process.env.NODE_ENV === 'development',
release: process.env.REACT_APP_VERSION,
environment: process.env.NODE_ENV,
sanitizeKeys: [/token/],
ignoreErrors: ['ResizeObserver'],
ignoreUrls: [
// Avoid browser extensions reporting errors
/extensions\//i,
/^chrome:\/\//i,
],
});
}
if (process.env.REACT_APP_ANALYTICS_CODE) {
const appVersion = process.env.REACT_APP_VERSION;
let userId;
let clientId;
try {
userId = localStorage.getItem('hashedUID');
clientId = localStorage.getItem('GA_LOCAL_STORAGE_KEY');
} catch (err) {
const cookieID = document.cookie.match(/PHPSESSID=([^;]*)/);
if (cookieID) {
clientId = cookieID[1];
}
}
ReactGA.initialize(process.env.REACT_APP_ANALYTICS_CODE, {
debug: process.env.NODE_ENV === 'development',
gaOptions: {
clientId,
userId,
},
onerror: (err) => {
// eslint-disable-next-line no-console
console.debug('⚠️ Unable to load Google Analytics'); // (I'm avoiding console.warn here)
err.stopPropagation();
},
testMode: process.env.NODE_ENV === 'test',
});
ReactGA.set({
appName: 'Open Scrobbler',
appVersion,
});
}
const baseApp = (
<ReduxProvider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</ReduxProvider>
);
ReactDOM.render(
sentryEnabled ? <Sentry.ErrorBoundary fallback={ErrorPage}>{baseApp}</Sentry.ErrorBoundary> : baseApp,
document.getElementById('root')
);
registerServiceWorker(store);
|
var searchData=
[
['t_5ftimer',['T_Timer',['../struct_t___timer.html',1,'']]],
['t_5fword',['T_word',['../union_t__word.html',1,'']]],
['tec_2ec',['tec.c',['../tec_8c.html',1,'']]],
['tec_2eh',['tec.h',['../tec_8h.html',1,'']]],
['tmr_2ec',['tmr.c',['../tmr_8c.html',1,'']]],
['tmr_2eh',['tmr.h',['../tmr_8h.html',1,'']]]
];
|
var app = angular.module('profileApp', []);
app.controller('profileController', ['$scope', '$sce', '$http', function ($scope, $sce, $http) {
$scope.profile = {};
$http.get('/app/getUserInfo').then(function success(response) {
$scope.profile = response.data
}, function error(response) {
});
}]);
|
//= require iD
/* globals iD */
document.addEventListener("DOMContentLoaded", function () {
var container = document.getElementById("id-container");
if (typeof iD === "undefined" || !iD.Detect().support) {
container.innerHTML = "This editor is supported " +
"in Firefox, Chrome, Safari, Opera, Edge, and Internet Explorer 11. " +
"Please upgrade your browser or use Potlatch 2 to edit the map.";
container.className = "unsupported";
} else {
var id = iD.Context()
.embed(true)
.assetPath("iD/")
.nominatim(container.dataset.nominatim)
.assetMap(JSON.parse(container.dataset.assetMap))
.locale(container.dataset.locale, container.dataset.localePath)
.preauth({
urlroot: location.protocol + "//" + location.host + container.dataset.sitePrefix,
oauth_consumer_key: container.dataset.consumerKey,
oauth_secret: container.dataset.consumerSecret,
oauth_token: container.dataset.token,
oauth_token_secret: container.dataset.tokenSecret
});
id.map().on("move.embed", parent.$.throttle(250, function () {
if (id.inIntro()) return;
var zoom = ~~id.map().zoom(),
center = id.map().center(),
llz = { lon: center[0], lat: center[1], zoom: zoom };
parent.updateLinks(llz, zoom);
// Manually resolve URL to avoid iframe JS context weirdness.
// http://bl.ocks.org/jfirebaugh/5439412
var hash = parent.OSM.formatHash(llz);
if (hash !== parent.location.hash) {
parent.location.replace(parent.location.href.replace(/(#.*|$)/, hash));
}
}));
parent.$("body").on("click", "a.set_position", function (e) {
e.preventDefault();
var data = parent.$(this).data();
// 0ms timeout to avoid iframe JS context weirdness.
// http://bl.ocks.org/jfirebaugh/5439412
setTimeout(function () {
id.map().centerZoom(
[data.lon, data.lat],
Math.max(data.zoom || 15, 13));
}, 0);
});
id.ui()(container);
}
});
|
var searchData=
[
['program_5fversion',['PROGRAM_VERSION',['../task__user_8h.html#a2f10abd650e471fae2d7e8c63d41206a',1,'task_user.h']]]
];
|
/*
* Copyright (C) 2013 vrivas
*
* Javier Guzmán García: [email protected]
*
* 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/>.
*/
var mongoose = require('mongoose')
,Schema = mongoose.Schema
,ObjectId = mongoose.ObjectId,
autoIncrement = require('mongoose-sequence')(mongoose);
var jsEOExperimentsSchema = new Schema({
Ip: {type: String},
Problem: {type: String},
Poblation: {type: Number},
NumberGen: {type: Number},
Time: {type: Number},
FitnessInitial: {type: Number},
FitnessFinal: {type: Number}
}, {_id: false, collection: 'Experiments'});
jsEOExperimentsSchema.plugin(autoIncrement);
module.exports = mongoose.model('jsEOExperiments', jsEOExperimentsSchema);
|
// $Id: editor_plugin.js,v 1.3.4.5 2008/12/27 12:42:53 sun Exp $
(function() {
// Load plugin specific language pack.
//tinymce.PluginManager.requireLangPack('img_assist');
tinymce.create('tinymce.plugins.ImageAssistPlugin', {
/**
* Initialize the plugin, executed after the plugin has been created.
*
* This call is done before the editor instance has finished it's
* initialization so use the onInit event of the editor instance to
* intercept that event.
*
* @param ed
* The tinymce.Editor instance the plugin is initialized in.
* @param url
* The absolute URL of the plugin location.
*/
init : function(ed, url) {
// Register the ImageAssist execCommand.
ed.addCommand('ImageAssist', function() {
// captionTitle and captionDesc for backwards compatibility.
var data = {nid: '', title: '', captionTitle: '', desc: '', captionDesc: '', link: '', url: '', align: '', width: '', height: '', id: ed.id, action: 'insert'};
var node = ed.selection.getNode();
if (node.name == 'mceItemDrupalImage') {
data.width = node.width;
data.height = node.height;
data.align = node.align;
// Expand inline tag in alt attribute
node.alt = decodeURIComponent(node.alt);
var chunks = node.alt.split('|');
for (var i in chunks) {
chunks[i].replace(/([^=]+)=(.*)/g, function(o, property, value) {
data[property] = value;
});
}
data.captionTitle = data.title;
data.captionDesc = data.desc;
data.action = 'update';
}
ed.windowManager.open({
file : Drupal.settings.basePath + 'index.php?q=img_assist/load/tinymce&textarea=' + ed.id,
width : 700 + parseInt(ed.getLang('img_assist.delta_width', 0)),
height : 500 + parseInt(ed.getLang('img_assist.delta_height', 0)),
inline : 1
}, data);
});
// Register Image Assist button.
ed.addButton('img_assist', {
title : 'img_assist.desc',
cmd : 'ImageAssist',
image : url + '/images/drupalimage.gif'
});
// Load Image Assist's CSS for editor contents on startup.
ed.onInit.add(function() {
if (!ed.settings.drupalimage_skip_plugin_css) {
ed.dom.loadCSS(url + "/css/img_assist.css");
}
});
// Replace images with inline tags in editor contents upon data.save.
// @todo Escape regular | pipes.
ed.onBeforeGetContent.add(function(ed, data) {
if (!data.save) {
return;
}
jQuery.each(ed.dom.select('img', data.content), function(node) {
if (this.name != 'mceItemDrupalImage') {
return;
}
var inlineTag = '[img_assist|' + decodeURIComponent(this.alt) + '|align=' + this.align + '|width=' + this.width + '|height=' + this.height + ']';
ed.dom.setOuterHTML(this, inlineTag);
});
});
// Replace inline tags in data.content with images.
ed.onBeforeSetContent.add(function(ed, data) {
data.content = data.content.replace(/\[img_assist\|([^\[\]]+)\]/g, function(orig, match) {
var node = {}, chunks = match.split('|');
for (var i in chunks) {
chunks[i].replace(/([^=]+)=(.*)/g, function(o, property, value) {
node[property] = value;
});
}
node.name = 'mceItemDrupalImage';
node.src = Drupal.settings.basePath + 'index.php?q=image/view/' + node.nid;
node.alt = 'nid=' + node.nid + '|title=' + node.title + '|desc=' + node.desc;
if (node.link.indexOf(',') != -1) {
var link = node.link.split(',', 2);
node.alt += '|link=' + link[0] + '|url=' + link[1];
}
else {
node.alt += '|link=' + node.link;
}
if (typeof node.url != 'undefined') {
node.alt += '|url=' + node.url;
}
node.alt = encodeURIComponent(node.alt);
return ed.dom.createHTML('img', node);
});
return;
});
// Add a node change handler, selects the button in the UI when an image is selected.
ed.onNodeChange.add(function(ed, command, node) {
command.setActive('img_assist', node.nodeName == 'IMG' && ed.dom.getAttrib(node, 'name').indexOf('mceItemDrupalImage') != -1);
});
},
/**
* Return information about the plugin as a name/value array.
*/
getInfo : function() {
return {
longname : 'Image Assist',
author : 'Daniel F. Kudwien',
authorurl : 'http://www.unleashedmind.com',
infourl : 'http://drupal.org/project/img_assist',
version : "2.0"
};
}
});
// Register plugin.
tinymce.PluginManager.add('img_assist', tinymce.plugins.ImageAssistPlugin);
})();
|
//= require jquery
//= require jquery_ujs
//= require leaflet
//= require turbolinks
//= require_self
//= require_tree ./application-head
|
if (typeof CMUPDATER == 'undefined' || CMUPDATER == null) {
CMUPDATER = {};
CMUPDATER.batoto = {};
}
CMUPDATER.batoto.RequestUpdate = function WaitForReaderData() {
//console.log("batoto wait for reader data");
let readerDOM = document.getElementById("reader");
if (!readerDOM || readerDOM.textContent.indexOf("ERROR [") >= 0) {
CERTAINMANGA.UpdateMangaResponse();
return;
}
// create an observer instance
let observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes && mutation.addedNodes.length > 0) {
if ( CMUPDATER.chapterListLoadingTimeOut ) {
clearTimeout(CMUPDATER.chapterListLoadingTimeOut);
CMUPDATER.chapterListLoadingTimeOut = null;
}
observer.disconnect();
CMUPDATER.FinishedReaderData();
return;
}
if ( CMUPDATER.chapterListLoadingTimeOut ) {
clearTimeout(CMUPDATER.chapterListLoadingTimeOut);
}
CMUPDATER.chapterListLoadingTimeOut = setTimeout(function() {
observer.disconnect();
CMUPDATER.chapterListLoadingTimeOut = null;
CMUPDATER.FinishedReaderData();
}, 300);
});
});
// pass in the target node, as well as the observer options
observer.observe(readerDOM, {childList: true});
};
CMUPDATER.batoto.FinishedReaderData = function FinishedReaderData() {
//console.log("batoto finished reader data");
let readerDOM = document.getElementById("reader");
if (!readerDOM || readerDOM.textContent.indexOf("ERROR [") >= 0) {
CERTAINMANGA.UpdateMangaResponse();
return;
}
let list = document.getElementsByName("chapter_select");
if (!list || list.length === 0) {
CMREADER.options.chapters = [];
CERTAINMANGA.UpdateMangaResponse();
return;
}
list = list[0];
let options = list.options;
let count = options.length;
let listOfChapters = [];
let listOfChapterNames = [];
let chN;
while(count--) {
chN = {
name: list.options[count].textContent.trim(),
url: list.options[count].value
};
listOfChapters.push(chN);
listOfChapterNames.push(chN.name);
}
CERTAINMANGA.UpdateMangaResponse(listOfChapters, self.options);
};
|
jQuery('.social-navigation>li>a').on('click',function(){
//window.open('https://google.de', 'facebook_share', 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
});
|
angular.module('plasmii.directives').directive('fileUpload', function () {
return {
require: ['Upload', 'CONSTANTS'],
restrict: 'EA',
scope: {
uploadedFile: '=',
small: '@'
},
controller: function ($scope, Upload, CONSTANTS) {
$scope.CONSTANTS = CONSTANTS;
$scope.uploading = false;
$scope.upload = function (files) {
if (files && files.length) {
$scope.uploading = true;
var file = files[0];
Upload.upload({
url: '/api/upload/',
file: file
}).success(function (data, status, headers, config) {
$scope.uploading = false;
$scope.uploadedFile = data;
});
}
};
$scope.clear = function () {
$scope.uploadedFile = {};
};
},
templateUrl: 'file-upload.html'
};
});
|
///////////////////////////////////////////////////////////////////////////////
// Main Module
///////////////////////////////////////////////////////////////////////////////
angular.module('mainModule', [])
.controller('mainController',['$scope',function($scope){
$scope.scopeVar = 'Base Scope Value';
}])
.directive('transcludeTrue', function(){
console.log('TranscludeTrue - Initialization');
return {
scope: {},
transclude: true,
restrict: 'E',
replace: true,
template:
"<div>"
+ "<label>[Directive Template Content - Blue]</label><br/>"
+ "<label>Enter </label> <input type='text' ng-model='scopeVar'/><br/>"
+ "<label>Scope ID:</label> {{$id}} <br/>"
+ "<label>Parent Scope ID:</label> {{$parent.$id}} <br/>"
+ "<label>Scope Variable:</label> {{scopeVar}} <br/>"
+ "<label>Original Content: </label>"
+ "<div style='border: 1px solid black;background-color: lightgreen' ng-transclude>"
+ "This conetent would be replaced by element.html()"
+ "</div>"
+ "</div>",
link: function(scope, element, attributes){
console.log('TranscludeTrue - post link');
scope.scopeVar = 'Directive Scope Value';
}
};
})
.directive('transcludeElementPreBoundScope', function(){
console.log('TranscludeElementPreBoundScope - Initialization');
return {
scope: {},
transclude: 'element',
replace: true,
link: function(scope, element, attributes, controller, transcludeFn){
console.log('TranscludeElementPreBoundScope - post link');
scope.scopeVar = 'Transclude Element Directive Scope Value';
var attrValue = attributes.transcludeElementPreBoundScope;
// Cloning the content
if (attrValue == 'clone' || attrValue == 'scopeclone'){
var cloneContent = null;
// getting clone object
if (attrValue == 'scopeclone'){
// with local scope
transcludeFn(scope, function(divContent){
cloneElement = divContent;
});
} else {
transcludeFn(function(divContent){
cloneElement = divContent;
});
}
// Changing attributes
cloneElement.attr("style", "background-color: lightcoral; border: 1px solid black;")
cloneElement.find('h4').text('This Conetent belongs to Clone');
// Addding to Element
element.after(cloneElement);
}
// Adding divcontent
element.after(transcludeFn());
}
};
})
|
(function ($, rf) {
rf.ui = rf.ui || {};
/**
* Backing object for rich:collapsibleSubTableToggler
*
* @memberOf! RichFaces.ui
* @constructs RichFaces.ui.CollapsibleSubTableToggler
*
* @param id
* @param options
*/
rf.ui.CollapsibleSubTableToggler = function(id, options) {
this.id = id;
this.eventName = options.eventName;
this.expandedControl = options.expandedControl;
this.collapsedControl = options.collapsedControl;
this.forId = options.forId;
this.element = $(document.getElementById(this.id));
if (this.element && this.eventName) {
this.element.bind(this.eventName, $.proxy(this.switchState, this));
}
};
$.extend(rf.ui.CollapsibleSubTableToggler.prototype, (function () {
var getElementById = function(id) {
return $(document.getElementById(id))
}
return {
switchState: function(e) {
var subtable = rf.component(this.forId);
if (subtable) {
var mode = subtable.getMode();
if (rf.ui.CollapsibleSubTable.MODE_CLNT == mode) {
this.toggleControl(subtable.isExpanded());
}
subtable.setOption(this.id);
subtable.switchState(e);
}
},
toggleControl: function(collapse) {
var expandedControl = getElementById(this.expandedControl);
var collapsedControl = getElementById(this.collapsedControl);
if (collapse) {
expandedControl.hide();
collapsedControl.show();
} else {
collapsedControl.hide();
expandedControl.show();
}
}
};
})());
})(RichFaces.jQuery, window.RichFaces);
|
'use strict';
let webpack = require('webpack');
let webpackDevServer = require('webpack-dev-server');
let configDev = require('./webpack.dev.config');
// let configDev = require('./webpack.config');
let configure = require('./webpack/configure');
let compiler = webpack(configDev);
new webpackDevServer(compiler, {
contentBase: configure.build,
// contentBase: './build/',
publicPath: configDev.output.publicPath,
hot: true,
noInfo: false,
historyApiFallback: true,
progress: true,
status: {
colors: true
}
}).listen(configure.port, configure.host, function (err, result) {
if (err) {
console.log(err);
}
console.log('Listening at ' + configure.host + ':' + configure.port);
});
|
/*
* Copyright (c) 2017 Vignesan Selvam
*
* Mu Maps 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.
*
* Mu Maps 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 Mu Maps; if not, see <http://www.gnu.org/licenses/>.
*
* Author: Vignesan Selvam <[email protected]>
*/
var map = new L.Map('map',{
center: [11.660978698779758, 78.15742492675781],
zoom: 7,
zoomControl:false
});
map.attributionControl.setPrefix('');
map.on('click', function(e) {
var popLocation= e.latlng;
var popup = L.popup()
.setLatLng(popLocation)
.setContent("<center><b>Options</b></br> <input type=hidden id=value1 value="+e.latlng.lat+" /><input type=hidden id=value2 value="+e.latlng.lng+" /><img src=./css/images/bell.png onClick=location_alert(); /><img src=./css/images/toll.png onClick=toll(); /></br><img src=./css/images/speed-limit.png onClick=speed_limit(); /> <img src=./css/images/info.png onClick=info(); /></center>")
.openOn(map);
});
//watermark lines
L.Control.Watermark = L.Control.extend({
onAdd: function(map) {
var img = L.DomUtil.create('img');
img.src = './css/images/logo.png';
img.style.width = '50px';
return img;
},
});
L.control.watermark = function(opts) {
return new L.Control.Watermark(opts);
}
L.control.watermark({ position: 'bottomleft' }).addTo(map);
L.tileLayer.grayscale('https://a.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
noWrap: true,
attribution: ' © <a href="http://openstreetmap.org/copyright">osm.org</a> '
}).addTo(map);
//location
map.locate({
watch: true,
dragging: true,
enableHighAccuracy: true,
timeout: 1000*60,
maximumAge: 60000*60*60*60,
frequency: 1,
});
var current_position, current_accuracy;
function onLocationFound(e) {
if (current_position) {
map.removeLayer(current_position);
map.removeLayer(current_accuracy);
}
var radius = e.accuracy / 8;
lat=e.latlng.lat;
lng=e.latlng.lng;
current_position = L.marker(e.latlng).bindPopup("<b>Current Position</b></br><center><img src=./css/images/bus.png onClick=find_busstop(); /> <img src=./css/images/info.png onClick=info(); /></center>").addTo(map);
current_accuracy = L.circle(e.latlng, radius).addTo(map);
store();
}
function onLocationError(e) {
alert(e.message);
}
map.on('locationfound', onLocationFound);
//map.on('locationerror', onLocationError);
|
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import Debug from 'debug';
import express from 'express';
import logger from 'morgan';
// import favicon from 'serve-favicon';
import path from 'path';
import lessMiddleware from 'less-middleware';
import index from './routes/index';
// ***********************************************
// OPENBUS - API
// ***********************************************
import openbus from './routes/openbus/gtfs';
import openbus_opendata from './routes/openbus/opendata';
import openbus_bot from './routes/openbus/bot';
const app = express();
const debug = Debug('net-api:app');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(lessMiddleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/opendata', express.static('opendata'));
// VIEWS
app.use('/', index);
// ***********************************************
// OPENBUS - API
// ***********************************************
app.use('/openbus', index);
// Import data
app.get('/openbus/import', openbus);
app.get('/openbus/opendata/:agencyID', openbus_opendata);
app.get('/openbus/agencies/:lat/:lng', openbus);
app.get('/openbus/stops/:lat/:lng/:size', openbus);
app.get('/openbus/stoptimes/:agencyID/:stopID', openbus);
app.get('/openbus/trips/:tripID', openbus);
app.post('/openbus/bot', openbus_bot);
// ***********************************************
app.locals.title = 'GioiaLAB';
app.locals.email = '[email protected]';
app.locals.version = '1.0.1';
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
/* eslint no-unused-vars: 0 */
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error', {
title: 'GioiaLAB'
});
});
// Handle uncaughtException
process.on('uncaughtException', (err) => {
debug('Caught exception: %j', err);
process.exit(1);
});
export default app;
|
var express = require('express');
var router = express.Router();
var User = require('../models/user')
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/', function(req, res, next) {
var user = new User(req.body);
user.save(function(err, user) {
if (err){
res.send(err);
}
res.json(user)
});
});
module.exports = router;
|
getPopulation = function (isoCode) {
var date = new Date().getFullYear() + "-" + new Date().getMonth() + "-" + new Date().getDay();
var CountryName = getCountryName(isoCode);
$.ajax({
url: "http://api.population.io/1.0/population/" + CountryName + "/" + date + "/",
dataType: 'json',
async: false,
success: function(data) {
return data.total_population.population;
}
});
}
getCountryName = function(isoCode) {
var retour = "";
$.ajax({
url: 'https://restcountries.eu/rest/v2/alpha/' + isoCode,
dataType: 'json',
async: false,
success: function(data) {
retour = data.name;
}
});
return retour;
}
|
YUI.add('moodle-atto_managefiles-button', function (Y, NAME) {
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package atto_managefiles
* @copyright 2014 Frédéric Massart
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* @module moodle-atto-managefiles-button
*/
/**
* Atto text editor managefiles plugin.
*
* @namespace M.atto_link
* @class button
* @extends M.editor_atto.EditorPlugin
*/
var LOGNAME = 'atto_managefiles';
Y.namespace('M.atto_managefiles').Button = Y.Base.create('button', Y.M.editor_atto.EditorPlugin, [], {
/**
* A reference to the current selection at the time that the dialogue
* was opened.
*
* @property _currentSelection
* @type Range
* @private
*/
_currentSelection: null,
initializer: function() {
if (this.get('disabled')) {
return;
}
var host = this.get('host'),
area = this.get('area'),
options = host.get('filepickeroptions');
if (options.image && options.image.itemid) {
area.itemid = options.image.itemid;
this.set('area', area);
} else {
Y.log('Plugin managefiles not available because itemid is missing.',
'warn', LOGNAME);
return;
}
this.addButton({
icon: 'e/manage_files',
callback: this._displayDialogue
});
},
/**
* Display the manage files.
*
* @method _displayDialogue
* @private
*/
_displayDialogue: function(e) {
e.preventDefault();
var dialogue = this.getDialogue({
headerContent: M.util.get_string('managefiles', LOGNAME),
width: '800px',
focusAfterHide: true
});
var iframe = Y.Node.create('<iframe></iframe>');
// We set the height here because otherwise it is really small. That might not look
// very nice on mobile devices, but we considered that enough for now.
iframe.setStyles({
height: '700px',
border: 'none',
width: '100%'
});
iframe.setAttribute('src', this._getIframeURL());
dialogue.set('bodyContent', iframe)
.show();
this.markUpdated();
},
/**
* Returns the URL to the file manager.
*
* @param _getIframeURL
* @return {String} URL
* @private
*/
_getIframeURL: function() {
var args = Y.mix({
elementid: this.get('host').get('elementid')
},
this.get('area'));
return M.cfg.wwwroot + '/lib/editor/atto/plugins/managefiles/manage.php?' +
Y.QueryString.stringify(args);
}
}, {
ATTRS: {
disabled: {
value: true
},
area: {
value: {}
}
}
});
}, '@VERSION@', {"requires": ["moodle-editor_atto-plugin"]});
|
var scrolltotop={
//startline: Integer. Number of pixels from top of doc scrollbar is scrolled before showing control
//scrollto: Keyword (Integer, or "Scroll_to_Element_ID"). How far to scroll document up when control is clicked on (0=top).
setting: {startline:100, scrollto: 0, scrollduration:100, fadeduration:[500, 100]},
controlHTML: '<img src="images/up.png" style="width:50px; height:50px" />', //HTML for control, which is auto wrapped in DIV w/ ID="topcontrol"
controlattrs: {offsetx:50, offsety:50}, //offset of control relative to right/ bottom of window corner
anchorkeyword: '#top', //Enter href value of HTML anchors on the page that should also act as "Scroll Up" links
state: {isvisible:false, shouldvisible:false},
scrollup:function(){
if (!this.cssfixedsupport) //if control is positioned using JavaScript
this.$control.css({opacity:0}) //hide control immediately after clicking it
var dest=isNaN(this.setting.scrollto)? this.setting.scrollto : parseInt(this.setting.scrollto)
if (typeof dest=="string" && jQuery('#'+dest).length==1) //check element set by string exists
dest=jQuery('#'+dest).offset().top
else
dest=0
this.$body.animate({scrollTop: dest}, this.setting.scrollduration);
},
keepfixed:function(){
var $window=jQuery(window)
var controlx=$window.scrollLeft() + $window.width() - this.$control.width() - this.controlattrs.offsetx
var controly=$window.scrollTop() + $window.height() - this.$control.height() - this.controlattrs.offsety
this.$control.css({left:controlx+'px', top:controly+'px'})
},
togglecontrol:function(){
var scrolltop=jQuery(window).scrollTop()
if (!this.cssfixedsupport)
this.keepfixed()
this.state.shouldvisible=(scrolltop>=this.setting.startline)? true : false
if (this.state.shouldvisible && !this.state.isvisible){
this.$control.stop().animate({opacity:1}, this.setting.fadeduration[0])
this.state.isvisible=true
}
else if (this.state.shouldvisible==false && this.state.isvisible){
this.$control.stop().animate({opacity:0}, this.setting.fadeduration[1])
this.state.isvisible=false
}
},
init:function(){
jQuery(document).ready(function($){
var mainobj=scrolltotop
var iebrws=document.all
mainobj.cssfixedsupport=!iebrws || iebrws && document.compatMode=="CSS1Compat" && window.XMLHttpRequest //not IE or IE7+ browsers in standards mode
mainobj.$body=(window.opera)? (document.compatMode=="CSS1Compat"? $('html') : $('body')) : $('html,body')
mainobj.$control=$('<div id="topcontrol">'+mainobj.controlHTML+'</div>')
.css({position:mainobj.cssfixedsupport? 'fixed' : 'absolute', bottom:mainobj.controlattrs.offsety, right:mainobj.controlattrs.offsetx, opacity:0, cursor:'pointer'})
.attr({title:'Scroll Back to Top'})
.click(function(){mainobj.scrollup(); return false})
.appendTo('body')
if (document.all && !window.XMLHttpRequest && mainobj.$control.text()!='') //loose check for IE6 and below, plus whether control contains any text
mainobj.$control.css({width:mainobj.$control.width()}) //IE6- seems to require an explicit width on a DIV containing text
mainobj.togglecontrol()
$('a[href="' + mainobj.anchorkeyword +'"]').click(function(){
mainobj.scrollup()
return false
})
$(window).bind('scroll resize', function(e){
mainobj.togglecontrol()
})
})
}
}
scrolltotop.init()
|
$(document).ready(function () {
$('a.load-more').click(function (e) {
e.preventDefault();
$('.load-more').hide();
var last_id = $('.abstract').last().attr('data-id');
$.ajax({
type: "GET",
url: $(this).attr('href'),
data: {
id: last_id
},
dataType: "script",
success: function () {
$('.load-more').show();
}
});
});
});
|
GO.projects2.SubProjectsGrid = Ext.extend(GO.grid.GridPanel, {
initComponent: function () {
var subProjectFields = {
fields: ['id', 'name', 'reference_no', 'status_name', 'user_name', 'type_name', 'template_name', 'responsible_user_name', 'icon', 'start_time', 'due_time', 'customer_name', 'contact'],
columns: [{
header: '',
dataIndex: 'icon',
xtype: 'iconcolumn'
}, {
header: 'ID',
dataIndex: 'id',
id: 'id',
width: 50,
hidden: true
}, {
header: t("Name"),
dataIndex: 'name',
id: 'name',
width: 150
}, {
header: t("Reference no.", "projects2"),
dataIndex: 'reference_no',
id: 'reference_no',
width: 150,
hidden: true
}, {
header: t("Status", "projects2"),
dataIndex: 'status_name',
id: 'status_name',
width: 100
}, {
header: t("Start time", "projects2"),
dataIndex: 'start_time',
id: 'start_time',
width: 100,
scope: this,
hidden: true
}, {
header: t("Due at", "projects2"),
dataIndex: 'due_time',
id: 'due_time',
width: 100,
// renderer: function (value, metaData, record) {
// return '<span class="' + this.projectPanel.templateConfig.getClass(record.data) + '">' + value + '</span>';
// },
scope: this
}, {
header: t("User"),
dataIndex: 'user_name',
id: 'user_name',
width: 150,
sortable: false,
hidden: true
}, {
header: t("Permission type", "projects2"),
dataIndex: 'type_name',
id: 'type_name',
width: 80,
hidden: true
}, {
header: t("Template", "projects2"),
dataIndex: 'template_name',
id: 'template_name',
width: 80,
hidden: true
}, {
header: t("Manager", "projects2"),
dataIndex: 'responsible_user_name',
id: 'responsible_user_name',
width: 120,
sortable: false,
hidden: true
}, {
header: t("Customer", "projects2"),
dataIndex: 'customer_name',
id: 'customer_name',
width: 150,
sortable: false
}, {
header: t("Contact", "projects2"),
dataIndex: 'contact',
id: 'contact',
width: 120,
sortable: false,
hidden: true
}]
}
if (go.Modules.isAvailable("core", "customfields"))
GO.customfields.addColumns("GO\\Projects2\\Model\\Project", subProjectFields);
// var exportBtn = new GO.base.ExportMenu({className: 'GO\\Projects2\\Export\\CurrentGrid'});
// exportBtn.iconCls = null;
this.store = new GO.data.JsonStore({
url: GO.url('projects2/project/store'),
baseParams: {
parent_project_id: 0
},
root: 'results',
totalProperty: 'total',
id: 'id',
fields: subProjectFields.fields,
remoteSort: true
});
Ext.apply(this, {
// tbar: [exportBtn,
// this.searchField = new GO.form.SearchField({
// store: this.store,
// width: 120,
// emptyText: t("Search")
// }),
// this.showMineOnlyField = new Ext.form.Checkbox({
// boxLabel: t("Show my projects only", "projects2"),
// labelSeparator: '',
// name: 'show_mine_only',
// allowBlank: true,
// ctCls: 'apr-show-mine-only-cb'
// })],
// autoExpandColumn: 'name',
border: false,
autoHeight: true,
title: t("Sub projects", "projects2"),
enableDragDrop: true,
ddGroup: 'ProjectsDD',
id: 'pr2-sub-projects',
split: true,
autoScroll: true,
// paging: true,
cm: new Ext.grid.ColumnModel({
defaultSortable: true,
columns: subProjectFields.columns
}),
scope: this
});
GO.projects2.SubProjectsGrid.superclass.initComponent.call(this);
// exportBtn.setColumnModel(this.getColumnModel());
//
// this.store.on('load', function (store, records, options) {
// this.showMineOnlyField.setValue(!GO.util.empty(store.reader.jsonData.showMineOnly));
// }, this);
//
// this.showMineOnlyField.on('check', function (checkBox, checked) {
// this.store.baseParams.showMineOnly = checked;
// //this.getTreePanel().getRootNode().reload();
// this.store.load();
// delete this.store.baseParams.showMineOnly;
// //delete this.getTreePanel().treeLoader.baseParams.showMineOnly;
// }, this);
}
});
|
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-5-b-168.js
* @description Object.defineProperties - value of 'writable' property of 'descObj' is 0 (8.10.5 step 6.b)
*/
function testcase() {
var obj = {};
Object.defineProperties(obj, {
property: {
writable: 0
}
});
obj.property = "isWritable";
return obj.hasOwnProperty("property") && typeof (obj.property) === "undefined";
}
runTestCase(testcase);
|
{
id: "kuugarize_x01",
name: "トーテムキマイラ",
desc: "",
overlap: false,
aprnum: 1,
data: [
{
appearance: [
1
],
enemy: [
{
name: "號なき混沌 トーテムキマイラ",
hp: 3200000,
imageno: 10558,
attr: 2,
spec: 1,
isStrong: true,
move: {
on_popup: [
m_enemy_once(s_enemy_attrreverse(99, 5)),
m_enemy_once(skill_counter_func(s_enemy_continue_damage, "-", 100, false, 5, 7500, 7500)),
damage_switch(s_enemy_when_hpdown(0.6), m_enemy_angry(), true)
],
on_move: [
s_enemy_attack(1750, 3, 2, true),
s_enemy_multibarrier_own(30, 99),
s_enemy_attack(1750, 3, 2, true),
s_enemy_poison(1500, 5, 5),
s_enemy_attack(1750, 5, 1, true),
],
on_angry: [
s_enemy_cursed(1600, 5, 5, 0)
],
on_move_angry: [
s_enemy_attack(1750, 5, 1, true)
],
atrandom: false,
turn: 1,
wait: 1
}
}
]
}
]
}
|
/**
Show message in message-area
*/
showMsg=function(text,time) {
$("#msgarea").text(text);
setTimeout(function() {
$("#msgarea").html(" ");
}, time);
};
/**
Handle action connect
*/
handlePPP0up=function() {
$.post("php/ppp0up.php");
showMsg("Connecting...",2000);
};
/**
Handle action disconnect
*/
handlePPP0down=function() {
$.post("php/ppp0down.php");
showMsg("Disconnecting...",2000);
};
/**
Handle action shutdown
*/
handleShutdown=function() {
$.post("php/shutdown.php");
showMsg("Shutting the system down...",2000);
};
/**
Handle action reboot
*/
handleReboot=function() {
$.post("php/reboot.php");
showMsg("Rebooting the system down...",2000);
};
/**
Update status information
*/
var conStatus="";
updateStatus=function() {
$.getJSON("php/getstatus.php", function( data ) {
if (data.constatus == 'down' && conStatus!="down") {
showMsg("no connection!",2000);
}
conStatus=data.constatus;
$("#constatus").text(data.constatus);
$("#contime").text(data.contime);
$("#localip").text(data.localip);
$("#remoteip").text(data.remoteip);
$("#conclients").text(data.conclients);
});
};
|
function loadBS3ReadyJS(){
$("#modal, #modal-transparent, #modal-fullscreen").on("hidden.bs.modal", function(e){
$(this).removeData();
});
var currentYear = (new Date).getFullYear();
$('#year').text((new Date).getFullYear());
$.fn.reloadeffect = function(url){
$(this).animateCSS('{{main_settings.releffout}}', function() {
$(this).css('visibility', 'hidden');
$(this).load(url);
$(this).animateCSS('{{main_settings.releffin}}',{
delay: 1000,
callback: function(){
$(this).css('visibility', 'visible');
}
})
});
};
}
function loadBS3BothJS(){
$('.ajaxlink').off('click').on('click',function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url : url,
success:function(data){
$.notify(data, {
animate: {
enter: "animated bounceInRight",
exit: "animated bounceOutRight"
},
delay: 3000,
type: "success"
});
}
});
})
}
$(document).ready(loadBS3ReadyJS);
$(document).ready(loadBS3BothJS);
$(document).ajaxComplete(loadBS3BothJS);
|
import React from 'react';
import { Link } from 'react-router';
import { Card, CardActions, CardHeader, CardMedia, CardText } from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import ActionFavoriteBorder from 'material-ui/svg-icons/action/favorite-border';
import ActionFavorite from 'material-ui/svg-icons/action/favorite';
const Post = React.createClass({
likes() {
return (this.props.post.likes.find((url) => this.props.user.url === url)) ?
this.props.decrementLikes.bind(null, this.props.post.id, this.props.i) :
this.props.incrementLikes.bind(null, this.props.post.id, this.props.i);
},
heartIcon() {
return (this.props.post.likes.find((url) => this.props.user.url === url)) ?
(<ActionFavorite />) : (<AcionFavoriteBorder />);
},
render() {
const { post, i } = this.props;
return (
<Card>
<Link to={`/user/${post.author.url}`}><CardHeader title={`${post.author.name.charAt(0).toUpperCase() + post.author.name.slice(1)} ${post.author.lastname.charAt(0).toUpperCase() + post.author.lastname.slice(1)}`} subtitle={post.timestamp} avatar={post.author.profile_photo} /></Link>
<CardText>{post.body.split('\n').map((item) => (
<span>
{item}
<br/>
</span>
))}
</CardText>
<CardActions>
<FlatButton icon={!!(post.likes.find((url) => url === this.props.user.url)) ?
<ActionFavorite /> :
<ActionFavoriteBorder />} onClick={this.likes()} labelPosition="after" label={`${post.likes.length}`} />
<Link to={`/post/${post.id}`}><FlatButton label={`${post.comments.length} Comentarios`} /></Link>
</CardActions>
</Card>
)
}
});
export default Post;
/*
<div className="socials">
<button onClick={this.props.increment.bind(null, i)}>♥ {post.likes}</button>
<Link to={`/post/${post.id}`}><span className="comments">{comments[post.id] ? comments[post.id].length : 0}</span></Link>
</div>
*/
|
/**
* Hearthstone common helpers
*
* @author tim.tang
*/
"use strict";
// Hearthstone Helper.
// --------------
var crypto = require('crypto'),
config = require('../conf/hearthstone-conf').config,
_ = require('underscore');
var HearthstoneHelper = function HearthstoneHelper() {};
_.extend(HearthstoneHelper.prototype, {
// Populate user session and cookies. By following attributes:
// `user._id`
// `user.name`
// `user.pass`
// `user.email`.
popSession: function(user, res) {
//cookie valid in 30 days.
var authToken = this.genAuthToken(user);
res.cookie(config.auth_cookie_name, authToken, {
path: '/',
maxAge: 1000 * 60 * 60 * 24 * 30
});
},
// Generate authentication token.
genAuthToken: function(user) {
return this.encrypt(user._id + '\t' + user.name + '\t' + user.pass + '\t' + user.email, config.session_secret);
},
// Clear http response cookies.
clearCookie: function(res) {
res.clearCookie(config.auth_cookie_name, {
path: '/'
});
},
// Encrypt string with AES192.
encrypt: function(str, secret) {
var cipher = crypto.createCipher('aes192', secret);
var enc = cipher.update(str, 'utf8', 'hex');
enc += cipher.final('hex');
return enc;
},
// Decrypt string with AES192.
decrypt: function(str, secret) {
var decipher = crypto.createDecipher('aes192', secret);
var dec = decipher.update(str, 'hex', 'utf8');
dec += decipher.final('utf8');
return dec;
},
// Encrypt string with MD5.
md5: function(str) {
var md5sum = crypto.createHash('md5');
md5sum.update(str);
str = md5sum.digest('hex');
return str;
},
// Generate random string.
randomString: function(size) {
size = size || 6;
var code_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var max_num = code_string.length + 1;
var new_pass = '';
while (size > 0) {
new_pass += code_string.charAt(Math.floor(Math.random() * max_num));
size--;
}
return new_pass;
}
});
var hearthstoneHelper = new HearthstoneHelper();
module.exports = hearthstoneHelper;
|
var searchData=
[
['values_5fbegin',['values_begin',['../a00015.html#a37dd90ce0eaeec98e1ca495e2f2270cd',1,'gaml::mlp::InputLayer::values_begin()'],['../a00016.html#abc1605a1a208fde1df576a6f0d1a3033',1,'gaml::mlp::Layer::values_begin()']]],
['values_5fend',['values_end',['../a00015.html#a018bd10c65f01b626cfc929eb2c367cb',1,'gaml::mlp::InputLayer::values_end()'],['../a00016.html#aa0d22e64d3d8b8047f6c41091d75739c',1,'gaml::mlp::Layer::values_end()']]]
];
|
/*
* main.js: Client-side initialization and setup routines.
*
* (c) 2011 Lee Supe (lain_proliant)
* Released under the GNU General Public License, version 3
*
* Requires jquery.js.
*/
/*
* Set focus to the first input element on the page.
*/
$(document).ready (function () {
$("input:eq(0)").focus ();
});
|
function solve(arr) {
let dict = [];
for(let line of arr){
let spl = line.split(' -> ');
dict.push({Name: spl[0], Age: spl[1], Grade: spl[2]});
}
for(let obj of dict){
console.log(`Name: ${obj.Name}`);
console.log(`Age: ${obj.Age}`);
console.log(`Grade: ${obj.Grade}`);
}
}
|
/*
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of fiware-iotagent-lib
*
* fiware-iotagent-lib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* fiware-iotagent-lib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with fiware-iotagent-lib.
* If not, seehttp://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::[email protected]
*/
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Device = new Schema({
id: { type: String, unique: true },
type: String,
name: String,
lazy: Array,
active: Array,
commands: Array,
apikey: String,
resource: String,
protocol: String,
staticAttributes: Array,
subscriptions: Array,
service: String,
subservice: String,
timezone: String,
registrationId: String,
internalId: String,
creationDate: { type: Date, default: Date.now },
internalAttributes: Object
});
function load(db) {
module.exports.model = db.model('Device', Device);
module.exports.internalSchema = Device;
}
module.exports.load = load;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _FormatAlignLeft = require('material-ui-icons/FormatAlignLeft');
var _FormatAlignLeft2 = _interopRequireDefault(_FormatAlignLeft);
var _FormatAlignCenter = require('material-ui-icons/FormatAlignCenter');
var _FormatAlignCenter2 = _interopRequireDefault(_FormatAlignCenter);
var _FormatAlignRight = require('material-ui-icons/FormatAlignRight');
var _FormatAlignRight2 = _interopRequireDefault(_FormatAlignRight);
var _FormatAlignJustify = require('material-ui-icons/FormatAlignJustify');
var _FormatAlignJustify2 = _interopRequireDefault(_FormatAlignJustify);
var _helpers = require('../helpers');
var _Plugin2 = require('./Plugin');
var _Plugin3 = _interopRequireDefault(_Plugin2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint-disable prefer-reflect */
var AlignmentPlugin = function (_Plugin) {
_inherits(AlignmentPlugin, _Plugin);
function AlignmentPlugin() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, AlignmentPlugin);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = AlignmentPlugin.__proto__ || Object.getPrototypeOf(AlignmentPlugin)).call.apply(_ref, [this].concat(args))), _this), _this.createButton = function (align, icon) {
return function (_ref2) {
var editorState = _ref2.editorState,
onChange = _ref2.onChange;
var onClick = function onClick(e) {
e.preventDefault();
var indent = void 0;
var isActive = editorState.blocks.some(function (block) {
indent = block.data.get('indent');
block.data.get('align') === align;
});
onChange(editorState.transform().setBlock({ data: { align: isActive ? null : align, indent: indent } }).apply());
};
var isActive = editorState.blocks.some(function (block) {
return block.data.get('align') === align;
});
return _react2.default.createElement(_helpers.ToolbarButton, { onClick: onClick, isActive: isActive, icon: icon });
};
}, _this.name = 'alignment', _this.toolbarButtons = [_this.createButton('left', _react2.default.createElement(_FormatAlignLeft2.default, null)), _this.createButton('center', _react2.default.createElement(_FormatAlignCenter2.default, null)), _this.createButton('right', _react2.default.createElement(_FormatAlignRight2.default, null)), _this.createButton('justify', _react2.default.createElement(_FormatAlignJustify2.default, null))], _temp), _possibleConstructorReturn(_this, _ret);
}
// eslint-disable-next-line react/display-name
return AlignmentPlugin;
}(_Plugin3.default);
exports.default = AlignmentPlugin;
//# sourceMappingURL=alignment.js.map
|
const Assert = require("assert");
const Generator = require("../Generator");
const Unit = require("../Unit");
const Collection = require("../../Data/Collection");
const CollectionRules = require("./CollectionRules");
const Int = require("../../Data/Int").Int;
const Maybe = require("../../Data/Maybe");
const OrderedRules = require("./OrderedRules");
const ParityRules = require("./ParityRules");
const SequenceRules = require("./SequenceRules");
const Array = require("../../Data/Array").Array;
const mkList = gen => n => {
let result = [];
let lp = 0;
while (lp < n) {
result.push(gen());
lp += 1;
}
return Array.of(result);
};
const IntGenerator = () => Int.of(Generator.integerInRange(Int.minBound)(Int.maxBound));
const ArrayGenerator = () => mkList(IntGenerator)(Generator.integerInRange(Int.of(0))(Int.of(20)));
Unit.suite("Data.Array", s => s
.suite("Data.Parity Rules", s =>
ParityRules(ArrayGenerator)(s))
// .case("show", Generator.forall([StringGenerator], ([s]) => {
// const replaceQuote = NativeString.replaceAll("\"")("\\\"");
// const replaceBackslash = NativeString.replaceAll("\\")("\\\\");
//
// Assert.equal(s.show(), '"' + replaceQuote(replaceBackslash(s.content)) + '"');
// }))
.suite("Data.Collection Rules", s =>
CollectionRules(ArrayGenerator)(s))
.suite("Data.Sequence Rules", s =>
SequenceRules(ArrayGenerator)(s))
//
// .case("unapplyCons", Generator.forall([NonEmptyStringGenerator], ([s]) => {
// Assert.deepEqual(
// s.unapplyCons(),
// Maybe.Just([s.at(Int.of(0)).withDefault(Char.minBound), String.of(NativeString.substringFrom(1)(s.content))])
// );
// }))
// .case("at", () => {
// Assert.deepEqual(String.of("Hello").at(Int.of(0)), Char.ofNativeString("H"));
// Assert.deepEqual(String.of("Hello").at(Int.of(-1)), Maybe.Nothing);
// })
// .case("length", () => {
// Assert.deepEqual(String.of("").length(), Int.of(0));
// Assert.deepEqual(String.of("Hello").length(), Int.of(5));
// })
// .case("endsWith", () => {
// Assert.equal(String.of("Hello").endsWith(String.of("llo")), true);
// Assert.equal(String.of("Hello").endsWith(String.of("ll")), false);
// })
);
|
'use strict'
const cp = require('child_process')
const logger = require('winston')
module.exports = (router) => {
router.get('/reboot', (req, res) => {
cp.execSync('shutdown -k -r now')
logger.info('User able to perform reboot action. Rebootting the device.')
res.json({ reboot: true, countdown: 30 })
// delaying action so browser can load resources
setTimeout(() => { cp.execSync('shutdown -r now') }, 300)
})
}
|
// Copyright 2015, 2016 Ethcore (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 React, { Component, PropTypes } from 'react';
import keycode from 'keycode';
import { MenuItem, AutoComplete as MUIAutoComplete } from 'material-ui';
import { PopoverAnimationVertical } from 'material-ui/Popover';
export default class AutoComplete extends Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
onUpdateInput: PropTypes.func,
disabled: PropTypes.bool,
label: PropTypes.string,
hint: PropTypes.string,
error: PropTypes.string,
value: PropTypes.string,
className: PropTypes.string,
filter: PropTypes.func,
renderItem: PropTypes.func,
entry: PropTypes.object,
entries: PropTypes.oneOfType([
PropTypes.array,
PropTypes.object
])
}
state = {
lastChangedValue: undefined,
entry: null,
open: false,
fakeBlur: false
}
render () {
const { disabled, error, hint, label, value, className, filter, onUpdateInput } = this.props;
const { open } = this.state;
return (
<MUIAutoComplete
className={ className }
disabled={ disabled }
floatingLabelText={ label }
hintText={ hint }
errorText={ error }
onNewRequest={ this.onChange }
onUpdateInput={ onUpdateInput }
searchText={ value }
onFocus={ this.onFocus }
onBlur={ this.onBlur }
animation={ PopoverAnimationVertical }
filter={ filter }
popoverProps={ { open } }
openOnFocus
menuCloseDelay={ 0 }
fullWidth
floatingLabelFixed
dataSource={ this.getDataSource() }
menuProps={ { maxHeight: 400 } }
ref='muiAutocomplete'
onKeyDown={ this.onKeyDown }
/>
);
}
getDataSource () {
const { renderItem, entries } = this.props;
const entriesArray = (entries instanceof Array)
? entries
: Object.values(entries);
if (renderItem && typeof renderItem === 'function') {
return entriesArray.map(entry => renderItem(entry));
}
return entriesArray.map(entry => ({
text: entry,
value: (
<MenuItem
primaryText={ entry }
/>
)
}));
}
onKeyDown = (event) => {
const { muiAutocomplete } = this.refs;
switch (keycode(event)) {
case 'down':
const { menu } = muiAutocomplete.refs;
menu.handleKeyDown(event);
this.setState({ fakeBlur: true });
break;
case 'enter':
case 'tab':
event.preventDefault();
event.stopPropagation();
event.which = 'useless';
const e = new CustomEvent('down');
e.which = 40;
muiAutocomplete.handleKeyDown(e);
break;
}
}
onChange = (item, idx) => {
if (idx === -1) {
return;
}
const { entries } = this.props;
const entriesArray = (entries instanceof Array)
? entries
: Object.values(entries);
const entry = entriesArray[idx];
this.handleOnChange(entry);
this.setState({ entry, open: false });
}
onBlur = (event) => {
const { onUpdateInput } = this.props;
// TODO: Handle blur gracefully where we use onUpdateInput (currently replaces
// input where text is allowed with the last selected value from the dropdown)
if (!onUpdateInput) {
window.setTimeout(() => {
const { entry, fakeBlur } = this.state;
if (fakeBlur) {
this.setState({ fakeBlur: false });
return;
}
this.handleOnChange(entry);
}, 200);
}
}
onFocus = () => {
const { entry } = this.props;
this.setState({ entry, open: true }, () => {
this.handleOnChange(null, true);
});
}
handleOnChange = (value, empty) => {
const { lastChangedValue } = this.state;
if (value !== lastChangedValue) {
this.setState({ lastChangedValue: value });
this.props.onChange(value, empty);
}
}
}
|
'use strict';
// Core module
const core = require('mongodb-core');
const Instrumentation = require('./lib/apm');
// Set up the connect function
const connect = require('./lib/mongo_client').connect;
// Expose error class
connect.MongoError = core.MongoError;
connect.MongoNetworkError = core.MongoNetworkError;
// Actual driver classes exported
connect.Admin = require('./lib/admin');
connect.MongoClient = require('./lib/mongo_client');
connect.Db = require('./lib/db');
connect.Collection = require('./lib/collection');
connect.Server = require('./lib/topologies/server');
connect.ReplSet = require('./lib/topologies/replset');
connect.Mongos = require('./lib/topologies/mongos');
connect.ReadPreference = require('mongodb-core').ReadPreference;
connect.GridStore = require('./lib/gridfs/grid_store');
connect.Chunk = require('./lib/gridfs/chunk');
connect.Logger = core.Logger;
connect.Cursor = require('./lib/cursor');
connect.GridFSBucket = require('./lib/gridfs-stream');
// Exported to be used in tests not to be used anywhere else
connect.CoreServer = require('mongodb-core').Server;
connect.CoreConnection = require('mongodb-core').Connection;
// BSON types exported
connect.Binary = core.BSON.Binary;
connect.Code = core.BSON.Code;
connect.Map = core.BSON.Map;
connect.DBRef = core.BSON.DBRef;
connect.Double = core.BSON.Double;
connect.Int32 = core.BSON.Int32;
connect.Long = core.BSON.Long;
connect.MinKey = core.BSON.MinKey;
connect.MaxKey = core.BSON.MaxKey;
connect.ObjectID = core.BSON.ObjectID;
connect.ObjectId = core.BSON.ObjectID;
connect.Symbol = core.BSON.Symbol;
connect.Timestamp = core.BSON.Timestamp;
connect.BSONRegExp = core.BSON.BSONRegExp;
connect.Decimal128 = core.BSON.Decimal128;
// Add connect method
connect.connect = connect;
// Set up the instrumentation method
connect.instrument = function(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
const instrumentation = new Instrumentation();
instrumentation.instrument(connect.MongoClient, callback);
return instrumentation;
};
// Set our exports to be the connect function
module.exports = connect;
|
'use strict';
module.exports = {
errorModel: require('../models/error_model'),
//mongoose: require('mongoose'),
errorParser: require('error-stack-parser'),
create: function(error,userId) {
////console.log('ERROR LIB CREATE | ', error);
return new Promise((resolve, reject) => {
this.errorModel.getInstance().model.create({
stackArray: this.errorParser.parse(error),
message:error.message,
userId:userId
},
function(err, error) {
if (err) {
reject(err);
}
}
);
});
},
getAll: function(component) {
return new Promise((resolve, reject) => {
this.errorModel.getInstance().model.find({}).sort({date:-1}).limit(100).lean().exec(function(err, errors) {
if (err) {
reject(err);
}else{
resolve(errors);
}
});
});
}
};
|
import { Template } from 'meteor/templating';
import { Academy } from '/imports/api/databasedriver.js';
import { Challenges } from '/imports/api/databasedriver.js';
Template.TableCharacter.helpers({
user(nb) {
var latestAcademy = Academy.findOne({}, {sort: {date: -1, limit: 1}});
var user = $.grep(latestAcademy.users, function(e){ return e.nb == nb; });
return user[0];
},
/*
score(nb) {
var latestAcademy = Academy.findOne({}, {sort: {date: -1, limit: 1}});
var user = $.grep(latestAcademy.users, function(e){ return e.nb == nb; });
var user_points = 0;
$.each(user[0].score, function(index, value){
user_points += value.points;
});
return user_points;
},
*/
isAdmin: function (name) {
return name !== "Admin"
},
academyPlayers: function () {
var latestAcademy = Academy.findOne({}, {sort: {date: -1, limit: 1}});
var users = latestAcademy.users;
users.splice(0, 3);
return users;
},
tableSettings : function () {
return {
showFilter: false,
rowsPerPage: 10,
showNavigation: 'auto',
showRowCount: true,
rowsPerPage: 10,
showNavigationRowsPerPage: true,
showColumnToggles: true,
fields: [
{
key: 'name',
label: 'Name',
headerClass: 'col-md-2',
sortDirection: 'ascending',
hidden: false
},
{
key: 'skills.0.people',
label: 'People',
headerClass: 'col-md-2',
sortDirection: 'descending',
hidden: false
},
{
key: 'skills.0.communication',
label: 'Communication',
headerClass: 'col-md-2',
sortDirection: 'descending',
hidden: false
},
{
key: 'skills.0.problemSolving',
label: 'Problem solving',
headerClass: 'col-md-2',
sortDirection: 'descending',
hidden: false
},
{
key: 'skills.0.management',
label: 'Management',
headerClass: 'col-md-2',
sortDirection: 'descending',
hidden: false
},
{
key: 'skills.0.android',
label: 'Android',
headerClass: 'col-md-2',
sortDirection: 'descending',
hidden: false
},
/*
{
key: 'score',
label: 'Score',
headerClass: 'col-md-2',
fn: function (value, object, key) {
var user_points = 0;
$.each(value, function(index, value){
user_points += value.points;
});
return user_points;
},
sortByValue : true,
sortable: true,
hidden: true
},
*/
{
key: 'counter',
label: 'Tap my Back',
headerClass: 'col-md-2',
sortDirection: 'descending',
hidden: true
},
{
key: 'mbti',
label: 'MBTI',
headerClass: 'col-md-2',
hidden: true
},
{
key: 'businessUnit',
label: 'Unit',
headerClass: 'col-md-2',
hidden: true
},
{
key: 'dateOfBirth',
label: 'Date of Birth',
headerClass: 'col-md-2',
hidden: true
}
]
};
},
});
|
.import QtQuick.LocalStorage 2.0 as LS
// Code derived from 'Noto' by leszek -- Thanks :)
// Structure of stats table
// 0: Birds scared (total)
// 1: Birds scared (best)
// 2: Distance traveled (total)
// 3: Distance traveled (best)
// 4: Jumps (total)
// 5: Jumps (best)
// 6: Current Level (starting at 0)
// 7: Current Character (0-3)
// 8: Realpix conversion rate
// 9: Objective basecount
// 10: Moose character eegg unlocked (default 0)
// 11: Backround music mute (0: music on 1: music muted)
// 12: # of games played
// First, let's create a short helper function to get the database connection
function getDatabase() {
return LS.LocalStorage.openDatabaseSync("2107", "1.0", "StorageDatabase", 1000);
}
// At the start of the application, we can initialize the tables we need if they haven't been created yet
function initialize() {
var db = getDatabase();
db.transaction(
function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS stats (uid INTEGER UNIQUE, value INTEGER)');
});
sanitize();
}
// This function is used to update stats
function setstat(uid, value) {
var db = getDatabase();
var res = "";
db.transaction(function(tx) {
var rs = tx.executeSql('INSERT OR REPLACE INTO stats VALUES (?,?);', [uid,value]);
if (rs.rowsAffected > 0) {
res = "OK";
} else {
res = "Error";
console.log ("Error saving to database");
}
}
);
return res;
}
// This function is used to retrieve stats
function getstat(uid) {
var db = getDatabase();
var res="";
db.transaction(function(tx) {
var rs = tx.executeSql('SELECT value FROM stats WHERE uid=?;', [uid]);
if (rs.rows.length > 0) {
res = rs.rows.item(0).value
} else {
res = 0;
}
})
return res;
}
// Attempts to fix data anomalies
function sanitize(){
for(var i = 0; i <= 12; i++){
if(getstat(i) < 0){
setstat(i, 0);
}
}
}
// This function resets all stats
function hardreset(){
var db = getDatabase();
db.transaction(function(tx) {
tx.executeSql('DROP TABLE stats;');
})
}
|
var sys = require('sys');
var http = require('http');
var multipart = require('multipart');
var md5 = require('./md5');
var OUTPUTDIR = "/var/www/streamencoder";
var FLV_BASEURL = "http://localhost/streamencoder";
var PLAYERURL = "http://localhost/streamencoder/player-viral.swf";
var FILESECRET = "salt123";
var server = http.createServer(function(req, res) {
sys.puts(req.uri.path);
if (req.uri.path == '/')
{
display_form(req, res);
}
else if (req.uri.path == '/upload')
{
upload_file(req, res);
}
else
{
show_404(req, res);
}
});
server.listen(8000);
function display_form(req, res) {
res.sendHeader(200, {'Content-Type': 'text/html'});
res.sendBody(
'<p>video is encoded while you upload</p>'+
'<p>please keep files small-- not much space on server</p>'+
'<form action="/upload" method="post" enctype="multipart/form-data">'+
'<input type="file" name="upload-file">'+
'<input type="submit" value="Upload">'+
'</form>'
);
res.finish();
}
function upload_file(req, res) {
req.setBodyEncoding('binary');
res.sendHeader(200, {'Content-Type': 'text/html'});
var foo = new Date; // Generic JS date object
var unixtime_ms = foo.getTime(); // Returns milliseconds since the epoch
//var unixtime = parseInt(unixtime_ms / 1000);
id = md5.md5sum(req.connection.remoteAddress + unixtime_ms + FILESECRET);
fname = id + ".mp4";
sys.puts(fname + "\n");
res.sendBody("<p>If it worked, here's your video:<p> I do not move\
mpeg4 atoms yet, so you probably have to download the whole\
file first." + player(fname));
res.sendBody("<pre>");
var fullpath = OUTPUTDIR + "/" + fname;
// start mencoder
sys.puts("starting encode.\n");
var menc = process.createChildProcess("ffmpeg", ["-i", "-", "-acodec", "libfaac", "-ab", "32k", "-ac", "1", "-vcodec", "libx264", "-vpre", "hq", "-crf", "22", "-threads", "0", fullpath]);
//var menc = process.createChildProcess("mencoder", ["-noidx", "-o", fullpath, "-oac", "faac", "-ovc", "x264", "-x264encopts", "threads=auto:subq=5:8x8dct:frameref=2:bframes=3:b_pyramid:weight_b:bitrate=1000", "-"]);
menc.addListener("output", function (data) {
//sys.puts(data);
if (data != null)
{
//sys.puts(data);
res.sendBody(data);
}
});
menc.addListener("error", function(data) {
if (data != null){
sys.puts(data);
res.sendBody(data);
}
});
menc.addListener("exit", function(code) {
res.sendBody("finished encode.");
sys.puts("finished encode.\n");
menc.close();
res.finish();
});
var stream = new multipart.Stream(req);
stream.addListener('part', function(part) {
part.addListener('body', function(chunk) {
var progress = (stream.bytesReceived / stream.bytesTotal * 100).toFixed(2);
var mb = (stream.bytesTotal / 1024 / 1024).toFixed(1);
res.sendBody("Uploading "+mb+"mb ("+progress+"%)\n");
//sys.print("Uploading "+mb+"mb ("+progress+"%)\n");
menc.write(chunk)
// chunk could be appended to a file if the uploaded file needs to be saved
});
});
stream.addListener('complete', function() {
menc.close();
res.sendBody("Finished uploading. still encoding.");
//res.finish();
sys.puts("Finished uploading. still encoding.");
});
}
function show_404(req, res) {
res.sendHeader(404, {'Content-Type': 'text/html'});
res.sendBody('<html><h1>404</h1></html>');
res.finish();
}
function player(fname) {
fname = FLV_BASEURL + "/" + fname;
data='\
<object id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="player" width="800" height="600"> \
<param name="movie" value="'+PLAYERURL+'" /> \
<param name="allowfullscreen" value="true" /> \
<param name="allowscriptaccess" value="always" /> \
<param name="flashvars" value="file='+fname+'&provider=video" /> \
<embed \
type="application/x-shockwave-flash" \
id="player2" \
name="player2" \
src="'+PLAYERURL+'" \
width="800" \
height="600" allowscriptaccess="always" \
allowfufdefaewfllscreen="true" \
flashvars="file='+fname+'&provider=video" \
/> \
</object> \
';
return data;
}
|
var classRedisList =
[
[ "push", "d8/dc8/classRedisList.html#a2a2ca25191c2b3ae50e75a3b41515904", null ],
[ "push", "d8/dc8/classRedisList.html#a9932ee447a93910514ab8f75eb85c3c0", null ],
[ "pop", "d8/dc8/classRedisList.html#a941e12250013a5c002b3e3d5593c7458", null ],
[ "rpush", "d8/dc8/classRedisList.html#aac41c5209574e61ab57f2a1153956750", null ],
[ "rpush", "d8/dc8/classRedisList.html#ad39dcf8b76630b252337dbc70c5d0fe9", null ],
[ "rpop", "d8/dc8/classRedisList.html#a6da451046bc93c96bfe0cf8104d9c729", null ],
[ "set", "d8/dc8/classRedisList.html#a4d7201eb2fab564735e94bfbd4520c32", null ],
[ "get", "d8/dc8/classRedisList.html#ae25495b5a6c48a1ac80954026b46a4e4", null ],
[ "insertBefore", "d8/dc8/classRedisList.html#a01e77ae5ed3b771a993f9473c52d1a6f", null ],
[ "insertAfter", "d8/dc8/classRedisList.html#a4163e7aeaa525e280a8ce87a9e8373ef", null ],
[ "remove", "d8/dc8/classRedisList.html#a683d5ebbd3a50e78ec4bbf46e7410ad5", null ],
[ "trim", "d8/dc8/classRedisList.html#a5604e7fbd71da4e72701e7b03db3b344", null ],
[ "len", "d8/dc8/classRedisList.html#aa976e16b1b36eb515c2c3779445bdf6e", null ],
[ "range", "d8/dc8/classRedisList.html#a2e91d5546f59e6261181b203c9c62963", null ],
[ "dispose", "d8/dc8/classRedisList.html#a6b88dbc459449d2280338e5b702a68b4", null ],
[ "toString", "d8/dc8/classRedisList.html#ac61f07a7d6c5471293371086af3186bd", null ],
[ "toJSON", "d8/dc8/classRedisList.html#ad66be13eb5b7c5f560fd8511565138c4", null ],
[ "ValueOf", "d8/dc8/classRedisList.html#a561030ca5d5b23349b5bab2cc8afa739", null ]
];
|
/**
* Created by rajan on 2/10/16.
*/
(function() {
'use strict';
angular.module('pasapi')
.controller('CalendarController',calenderController);
function calenderController ($scope, $http) {
$http.get('appComponents/data/data.json').success(function(data) {
$scope.calendar = data.calendar;
$scope.onItemDelete = function(dayIndex, item) {
$scope.calendar[dayIndex].schedule.splice($scope.calendar[dayIndex].schedule.indexOf(item), 1);
};
$scope.doRefresh =function() {
$http.get('appComponents/data/data.json').success(function(data) {
$scope.calendar = data.calendar;
$scope.$broadcast('scroll.refreshComplete');
});
};
$scope.toggleStar = function(item) {
item.star = !item.star;
};
});
}
})();
|
// file: tag.js
// 给某一用户添加标签
var SalesManItem = React.createClass({displayName: "SalesManItem",
handleClick: function(uid, e) {
this.props.handleOp(uid);
},
render: function(){
return (
React.createElement("li", {"data-uid": this.props.data.id, onClick: this.handleClick.bind(this, this.props.data.id)},
React.createElement("a", {href: "#"}, " name:", this.props.data.name, " Job:", this.props.agent)
)
);
}
});
React.render(
React.createElement(TagBox, null),
document.getElementById("content")
);
|
module.exports = {
runtimeCompiler: true,
pwa: {
name: "waterbear"
},
chainWebpack: config => {
const rule = config.module.rule("ts");
rule.uses.delete("thread-loader");
rule
.use("ts-loader")
.loader("ts-loader")
.tap(options => {
options.transpileOnly = false;
options.happyPackMode = false;
options.allowTsInNodeModules = true;
return options;
});
}
};
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Backup from './Backup.component';
export class BackupContainer extends PureComponent {
static propTypes = {
boards: PropTypes.array.isRequired,
open: PropTypes.bool,
onImportClick: PropTypes.func,
onRequestClose: PropTypes.func
};
handleExportClick = () => {
const exportFilename = 'board.json';
const { boards } = this.props;
const jsonData = new Blob([JSON.stringify(boards)], {
type: 'text/json;charset=utf-8;'
});
// IE11 & Edge
if (navigator.msSaveBlob) {
navigator.msSaveBlob(jsonData, exportFilename);
} else {
// In FF link must be added to DOM to be clicked
const link = document.createElement('a');
link.href = window.URL.createObjectURL(jsonData);
link.setAttribute('download', exportFilename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
};
render() {
const { open, onRequestClose, onImportClick } = this.props;
return (
<Backup
open={open}
onExportClick={this.handleExportClick}
onImportClick={onImportClick}
onRequestClose={onRequestClose}
/>
);
}
}
export default BackupContainer;
|
import Part from "erizo-webmail/models/part"
export default Part.extend({
content: null,
encoding: null,
params: null,
size: null,
name: function () {
if (this.get("isAttachment") && this.get("disposition.params.filename")) {
return this.get("disposition.params.filename")
} else {
return null
}
}.property("isAttachment", "disposition"),
partID: function () {
var data = this.get("data")
return data == null ? null : data.partID
}.property("data"),
realSize: function () {
let size = this.get("size")
if (size) {
let encoding = this.get("encoding")
if (encoding === "base64") {
return size / 1.37
} else {
return size
}
} else {
return null
}
}.property("size", "encoding"),
})
|
import { Migrations } from "meteor/percolate:migrations";
import { Orders } from "/lib/collections";
/**
* Going up, migrates order.shipping.$.items -> order.shipping.$.itemIds and adds type
* Going down, migrates order.shipping.$.itemIds -> order.shipping.$.items and removes type
*/
Migrations.add({
version: 34,
up() {
Orders.find({}).forEach((order) => {
const shipping = (order.shipping || []).map((group) => {
const itemIds = (group.items || []).map((item) => item._id);
const newGroup = {
...group,
itemIds,
type: "shipping"
};
delete newGroup.items;
return newGroup;
});
Orders.update({ _id: order._id }, {
$set: {
shipping
}
}, { bypassCollection2: true });
});
},
down() {
Orders.find({}).forEach((order) => {
const shipping = (order.shipping || []).map((group) => {
const items = (group.itemIds || []).map((itemId) => {
const item = order.items.find((orderItem) => orderItem._id === itemId);
return {
_id: item._id,
productId: item.productId,
quantity: item.quantity,
shopId: item.shopId,
variantId: item.variantId
};
});
const newGroup = {
...group,
items
};
delete newGroup.itemIds;
delete newGroup.type;
return newGroup;
});
Orders.update({ _id: order._id }, {
$set: {
shipping
}
}, { bypassCollection2: true });
});
}
});
|
define([
"message",
"scope"
], function(message, scope){
'use strict';
var controler = {};
controler.do = function(id){
var obj;
var el = new Array(2);
$('.dot').click(function(){
if(!$(this).hasClass('clicked')){
$(this).addClass('clicked');
if(el[0] == null){
$(this).addClass('first-clicked');
el[0] = {x: $(this).attr('posx'), y: $(this).attr('posy')};
}
else{
el[1] = {x: $(this).attr('posx'), y: $(this).attr('posy')};
obj = {curx: el[0].x, cury: el[0].y, nextx: el[1].x, nexty: el[1].y};
scope.update(obj);
$('.dot').removeClass('clicked first-clicked');
el[0] = null;
el[1] = null;
}
}
else{
if($(this).hasClass('first-clicked')){
$(this).removeClass('clicked first-clicked');
el[0] = null;
}
else{
$(this).removeClass('clicked');
el[1] = null;
}
}
});
return 0;
}
return controler;
});
|
'use strict';
angular.module('risevision.editor.controllers')
.controller('PresentationListController', ['$scope',
'ScrollingListService', 'presentation', 'editorFactory', '$loading',
'$filter', 'userState',
function ($scope, ScrollingListService, presentation, editorFactory,
$loading, $filter, userState) {
$scope.search = {
sortBy: 'changeDate',
reverse: true
};
console.log('presentation.list---->', presentation.list);
$scope.factory = new ScrollingListService(presentation.list, $scope.search);
$scope.editorFactory = editorFactory;
$scope.filterConfig = {
placeholder: $filter('translate')(
'editor-app.list.filter.placeholder'),
id: 'presentationSearchInput'
};
$scope.$watch('factory.loadingItems', function (loading) {
if (loading) {
$loading.start('presentation-list-loader');
} else {
$loading.stop('presentation-list-loader');
}
});
}
]);
|
import styled from 'styled-components';
export default styled.div`
color: #30568a;
font-weight: bold;
text-transform: uppercase;
padding-top: 5px;
margin-top: 5px;
margin-left: 10px;
cursor: pointer;
`;
|
import React from 'react';
import ReactDOM from 'react-dom';
import NavMenu from './NavMenu';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<NavMenu/>, div);
});
|
/**
* Russian translation for Extended Qgis Web Client
*
* NOT COMPLETED
*
*/
var TR = {
appName: 'Spatial info. system - ',
loginTitle: 'Login',
loginMessage: 'Access for authorized users.' +
'<br />Please type your username and password.',
loginFailMessage: 'Unable to log in',
loginWaitMessage: 'Пожалуйста, подождите...',
loginButton: 'Login',
guestButton: 'Guest',
loginUsernameLabel: 'Имя пользователя',
loginPasswordLabel: 'Пароль',
loginLanguageLabel: 'Язык',
loginRememberMeLabel: 'Запомнить меня на этом компьютере',
loginForgotPasswordLabel: '',
logoutLabel: 'выход',
noProject: 'Project doesn\'t exist.',
noProjectText: 'Add correct project name and reload the page.',
wrongPassword: 'Неправильный пароль.',
noUser: 'User doesn\'t exist.',
noPermission: 'You don\'t have permissions to use this project.',
noPublicAccess: 'Public access is not allowed with this project.',
clearFilter: 'Очистить все фильтры',
clearSelection: 'Очистить выбор',
select: 'Select element to display its geometry',
menuFilterText: 'Фильтры',
editData: 'Редактировать данные',
editMode: 'Режим редактирования',
editDisabled: 'Редактирование отключено',
editAdd: 'Add',
editEdit: 'Edit',
editDelete: 'Удалить',
editSave: 'Сохранить',
mapBasic: 'Карта',
mapSatellite: 'Спутник',
mapHybrid: 'Гибрид',
mapTerrain: 'Terrain',
fiLocation: 'Координаты',
fiElevation: 'above sea level',
cancel: 'Отменить',
send: 'Отправить',
feedback: 'Обратная связь',
feedbackTitle: 'Отправить отзыв',
feedbackDescription: 'Your name, project and current map link will be added to the message!',
feedbackErrorTitle: "Error",
feedbackErrorMsg: "There was error sending your message!",
feedbackSuccessTitle: "Success",
feedbackSuccessMsg: "Your message was successfully sent.",
transactionFail: 'Сбой транзакции',
show: 'Отобразить',
properties: 'Свойства',
description: 'Описание',
emptyPrintTitleText: 'Добавить заголовок ...',
emptyPrintDescriptionText: 'Добавить описание ...',
loadMore: 'Загрузить больше...',
loadMoreToolTip: 'Table is not complete.Click to load more data from server!',
height: 'Height',
exportData: 'Export data',
exportFormat: 'Format',
exportCrs: 'CRS',
exportLayer: 'Layer',
exportExtent: 'Extent',
exportLayerExtent: 'Use layer extent',
exportUseMapCrs: "Use map CRS",
exportFilter: "Filter",
exportUseTableFilter: "Use attribute filter set on table",
tableUseExtent: "Only show features in map extent",
tableAddRecord: "Add new record",
style: "Style",
navigation: "Navigation",
relations: "Relations",
bookmarks: "Bookmarks",
bookmarkName: "Name",
bookmarkGroup: "Group",
bookmarkEmptyGroupText: "no group",
link: "LINK"
};
/**
* Mobile Viewer translation strings
*/
var I18n = {};
I18n.title = "Mobile Viewer";
I18n.search = {
header: "Поиск",
results: "Результаты",
failed: "Search failed:"
};
I18n.properties = {
header: "Map Settings",
mapFollowing: "Tracking",
mapRotation: "Auto Rotation",
mapLoading: "Загрузка карты...",
scaleBar: "Scale",
about: "Imprint",
share: "Share",
login: "Login",
on: "On",
off: "Off"
};
I18n.about = {
header: "Imprint",
content: "Development version"
};
I18n.layers = {
project: "Project",
topics: "Themes",
layers: "Layers",
layerOrder: "Layer order",
background: "Background",
overlays: "Overlays",
selection: "Selection",
redlining: "Redlining",
transparency: "Transparency"
};
I18n.featureInfo = {
header: "Information",
feature: "Feature ID:",
raster: "Raster",
noFeatureFound: "No objects found"
};
I18n.geolocation = {
permissionDeniedMessage: "Location is not available.\n\nPlease check your browser or device settings.",
accuracy: "Accuracy",
altitude: "Altitude",
heading: "Heading",
speed: "Speed",
obtaining: "Obtaining location...",
lowAccuracy: "Low Accuracy!"
};
I18n.login = {
header: "Login",
user: "User",
password: "Password",
signIn: "Login",
cancel: "Cancel",
signOut: "Logout",
signInFailed: "Username or password are wrong",
signOutFailed: "Login failed",
statusFailed: "Login Status failed"
};
I18n.networkDown = 'Internet connection lost';
|
define( [ 'ifuture', 'jquery', 'config', 'toolcase' ],
function( ifuture, $, config, Toolcase ) {
ProfileTool = function ( app, opt_options ) {
Toolcase.call( this, app );
this.name = 'profile';
this.title = '设置';
}
ifuture.inherits( ProfileTool, Toolcase );
ProfileTool.prototype.create = function ( container ) {
var scope = this;
var element = document.createElement( 'DIV' );
element.className = 'dx-toolcase';
var html = [
'<nav class="navbar navbar-expand-sm navbar-light bg-light">' +
' <span class="navbar-brand mr-auto"> 设置 </span>' +
' <div class="collapse navbar-collapse justify-content-center">' +
' <div class="navbar-nav nav-tabs">' +
' <a class="nav-item nav-link px-2 active">个人信息</a>' +
' <a class="nav-item nav-link px-2" id="map-tab">地图设置</a>' +
' <a class="nav-item nav-link px-2 disabled">实名认证</a>' +
' </div>' +
' </div>' +
' <div class="d-block d-sm-none w-50" style="overflow-x: auto;">' +
' <div class="navbar-nav flex-row">' +
' <a class="nav-item nav-link text-nowrap px-2 active">个人信息</a>' +
' <a class="nav-item nav-link text-nowrap px-2">地图设置</a>' +
' <a class="nav-item nav-link text-nowrap px-2 disabled">实名认证</a>' +
' </div>' +
' </div>' +
' <button class="bg-light text-secondary border-0 mx-2" type="button"><i class="fas fa-times"></i></button>' +
'</nav>' +
'<div class="tab-content">' +
' <div class="tab-pane fade show active" role="tabpanel">' +
' <form class="p-5 border-bottom">' +
' <div class="form-group">' +
' <label for="userFullname">用户名称</label>' +
' <input type="text" class="form-control" id="userFullname" placeholder="用户名称">' +
' </div>' +
' </form>' +
' </div>' +
' <div class="tab-pane fade" role="tabpanel">' +
' <form class="p-5 border-bottom">' +
' <div class="form-check">' +
' <input class="form-check-input" type="checkbox" value="" id="toggle-map-house-feature">' +
' <label class="form-check-label" for="toggle-map-house-feature">' +
' 显示房屋特征' +
' </label>' +
' </div>' +
' </form>' +
' </div>' +
' <div class="tab-pane fade" role="tabpanel">' +
' </div>' +
'</div>'
];
element.innerHTML = html.join( '' );
$( '.navbar-nav > a', element ).on( 'click', function ( e ) {
e.preventDefault();
var j = $( this ).index() + 1;
$( '.navbar-nav > a', element ).removeClass( 'active' );
$( '.navbar-nav > a:nth-child(' + j + ')', element ).addClass( 'active' );
$( '.tab-content > .tab-pane', element ).removeClass( 'show active' );
$( '.tab-content > .tab-pane:nth-child(' + j + ')', element ).addClass( 'show active' );
});
element.querySelector( 'nav.navbar > button' ).addEventListener( 'click', function ( e ) {
scope.dispatchEvent( new ifuture.Event( 'task:close' ) );
}, false );
element.querySelector( '#userFullname' ).addEventListener( 'change', function ( e ) {
config.userName = e.currentTarget.value;
scope.dispatchEvent( new ifuture.Event( 'userName:changed' ) );
}, false );
container.appendChild( element );
};
return ProfileTool;
} );
|
function createTempoSlider(initialValue) {
$("#tempo").slider({
// Initializing values
animate: false,
step: 10,
min: 50,
max: 200,
value: initialValue,
orientation: 'horizontal',
// when value is changed
change: function(event, ui){
update_bpmValueOnPage();
}
});
}
function createPlayerSlider(initialValue) {
$("#playbackSlider").slider({
// Initializing values
animate: true,
step: 1,
min: 0,
value: initialValue,
orientation: 'horizontal',
});
$("#playbackSlider").slider("disable");
}
function update_bpmValueOnPage(){
// get the location to update
var bpm = document.getElementById("sliderValue");
// get the value from the slider
var value = $('#tempo').slider('option', 'value');
// set the value on the page
bpm.innerHTML = "BPM = " + value;
}
|
/**
* @author Martin Micunda {@link http://martinmicunda.com}
* @copyright Copyright (c) 2015, Martin Micunda
* @license GPL-3.0
*/
'use strict';
import 'angular-mocks';
import './modal-error.js';
describe('ModalError', () => {
beforeEach(angular.mock.module('ngDecorator'));
describe('Component', () => {
let $compile, $rootScope, scope, render, element,
component = '<error-modal error="vm.error" cancel="vm.cancel()"></error-modal>', vm = {error: {status: 404}, cancel: () => {}};
beforeEach(inject((_$compile_, _$rootScope_) => {
$compile = _$compile_;
$rootScope = _$rootScope_;
scope = $rootScope.$new();
scope.vm = vm;
render = () => {
let element = angular.element(component);
let compiledElement = $compile(element)(scope);
$rootScope.$digest();
return compiledElement;
};
}));
it('should contain `error-modal` component', () => {
element = render();
expect(element.controller('errorModal')).toBeDefined();
expect(element['0']).not.toEqual(component);
});
describe('Show title', () => {
it('should have `Error` modal title defined', () => {
element = render();
const errorModalTitle = angular.element(element[0].getElementsByClassName('modal-title'));
expect(errorModalTitle.text()).toEqual('Error');
});
it('should have `Error!` alert title defined', () => {
element = render();
const errorAlertTitle = angular.element(element[0].getElementsByClassName('display-inline-block'));
expect(errorAlertTitle.text().trim()).toEqual('Error!');
});
});
describe('Show error messages', () => {
it('should render 404 error message', () => {
element = render();
const errorMessageText = angular.element(element[0].getElementsByClassName('ng-binding'));
expect(errorMessageText.text().trim()).toEqual('The requested record could not be found.');
});
it('should render 500 error message', () => {
scope.vm.error.status = 500;
element = render();
const errorMessageText = angular.element(element[0].getElementsByClassName('ng-binding'));
expect(errorMessageText.text().trim()).toEqual('An error occurred while processing your request. Please try again.');
});
});
describe('Close modal', () => {
it('should have `×` label defined for close button', () => {
element = render();
expect(angular.element(element[0].getElementsByClassName('close')).text()).toEqual('×');
});
it('should close the Error modal when `×` button is clicked', () => {
spyOn(vm, 'cancel');
element = render();
angular.element(element[0].getElementsByClassName('close')).triggerHandler('click');
expect(vm.cancel).toHaveBeenCalled();
});
it('should have `Close` label defined for close button', () => {
element = render();
expect(angular.element(element[0].getElementsByClassName('btn-white')).text()).toEqual('Close');
});
it('should close the Error modal when `Close` button is clicked', () => {
spyOn(vm, 'cancel');
element = render();
angular.element(element[0].getElementsByClassName('btn-white')).triggerHandler('click');
expect(vm.cancel).toHaveBeenCalled();
});
});
});
});
|
System.register(['moment'], function (_export) {
'use strict';
var moment, validData, validationConfig, DEFAULT_CONFIG, Boolean, Number, NotBlank, NotNull, String, Temporal;
_export('Enum', Enum);
_export('Max', Max);
_export('Min', Min);
_export('Range', Range);
function assertValidType(config, propertyName, val) {
if (typeof val != config.type) {
throw new Error(propertyName + ' must be a ' + config.type);
}
}
function assertValidRange(config, propertyName, val) {
if (config.type == 'number') {
var tooLow = false;
var tooHigh = false;
var range = config.min != null && config.max != null;
if (config.min != null && val < config.min) {
tooLow = true;
}
if (config.max != null && val > config.max) {
tooHigh = true;
}
if (tooLow || tooHigh) {
var rangeError = propertyName + ' must be';
if (range) {
rangeError = rangeError + ' between ' + config.min + ' and ' + config.max;
} else if (tooLow) {
rangeError = rangeError + ' at least ' + config.min;
} else if (tooHigh) {
rangeError = rangeError + ' at most ' + config.max;
}
throw new Error(rangeError);
}
}
}
function createValidationDecorator(configUpdate) {
return function (target, propertyName, descriptor) {
if (!validationConfig.has(target)) {
validationConfig.set(target, new Map());
}
var targetConfig = validationConfig.get(target);
if (!targetConfig.has(propertyName)) {
targetConfig.set(propertyName, Object.assign({}, DEFAULT_CONFIG));
}
var config = targetConfig.get(propertyName);
if (config.type && config.type != configUpdate.type) {
throw new Error(propertyName + ' has conflicting decorators');
}
Object.assign(config, configUpdate);
if (config.type) {
(function () {
var isValid = config.isValid;
config.isValid = function (val) {
assertValidType(config, propertyName, val);
assertValidRange(config, propertyName, val);
return isValid(val);
};
})();
}
var setter = descriptor.set;
delete descriptor.initializer;
delete descriptor.value;
delete descriptor.writable;
var assertValid = function assertValid(val) {
if (val == null) {
if (!config.nullable) {
throw new Error(propertyName + ' must not be null');
}
} else if (!config.isValid(val)) {
throw new Error(propertyName + ' must ' + config.invalidError);
}
};
if (setter) {
descriptor.set = function (val) {
assertValid(val);
Reflect.apply(setter, this, [val]);
};
} else {
descriptor.set = function (val) {
assertValid(val);
if (!validData.has(this)) {
validData.set(this, {});
}
validData.get(this)[propertyName] = val;
};
descriptor.get = function (val) {
return (validData.get(this) || {})[propertyName];
};
}
};
}
function Enum(values) {
if (!Array.from(values).length) {
throw new Error('@Enum() requires values');
}
return createValidationDecorator({
isValid: function isValid(val) {
return values.includes(val);
},
invalidError: 'be any of {' + values.join(', ') + '}',
type: null
});
}
function Max(max) {
if (max == null || typeof max != 'number') {
throw new Error('@Max() requires a value');
}
return createValidationDecorator({
max: max,
type: 'number'
});
}
function Min(min) {
if (min == null || typeof min != 'number') {
throw new Error('@Min() requires a value');
}
return createValidationDecorator({
min: min,
type: 'number'
});
}
function Range(min, max) {
if (min == null || typeof min != 'number' || max == null || typeof max != 'number') {
throw new Error('@Range() requires a range');
}
return createValidationDecorator({
min: min,
max: max,
type: 'number'
});
}
return {
setters: [function (_moment) {
moment = _moment['default'];
}],
execute: function () {
validData = new WeakMap();
validationConfig = new WeakMap();
DEFAULT_CONFIG = {
invalidError: '',
isValid: function isValid(val) {
return true;
},
nullable: true,
type: null
};
Boolean = createValidationDecorator({
type: 'boolean'
});
_export('Boolean', Boolean);
Number = createValidationDecorator({
type: 'number'
});
_export('Number', Number);
NotBlank = createValidationDecorator({
nullable: false,
type: 'string',
isValid: function isValid(val) {
return !!val;
},
invalidError: 'not be blank'
});
_export('NotBlank', NotBlank);
NotNull = createValidationDecorator({
nullable: false
});
_export('NotNull', NotNull);
;
String = createValidationDecorator({
type: 'string'
});
_export('String', String);
Temporal = createValidationDecorator({
isValid: function isValid(val) {
return moment(val).isValid();
},
invalidError: 'be a valid date'
});
_export('Temporal', Temporal);
}
};
});
|
(function(){
angular.module('lup1')
.controller('PanelMenuController', [ 'fileManager', function(fileManagerFactory){
var controller = this;
controller.selectPanel = function(folder,filename){
var path = '/models/panels/'+folder+'/'+filename+'.json';
fileManagerFactory.getFile(path).then(function(data) {
controller.panel = data;
});
};
}]);
})();
|
/*******************************************************************************
* This file is part of Arionide.
*
* Arionide is an IDE used to conceive applications and algorithms in a three-dimensional environment.
* It is the work of Arion Zimmermann for his final high-school project at Calvin College (Geneva, Switzerland).
* Copyright (C) 2016-2020 Innovazion. All rights reserved.
*
* Arionide 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.
*
* Arionide 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 Arionide. If not, see <http://www.gnu.org/licenses/>.
*
* The copy of the GNU General Public License can be found in the 'LICENSE.txt' file inside the src directory or inside the JAR archive.
*******************************************************************************/
var searchData=
[
['fboframe_2757',['FBOFrame',['../classch_1_1innovazion_1_1arionide_1_1ui_1_1core_1_1gl_1_1fx_1_1_f_b_o_frame.html',1,'ch::innovazion::arionide::ui::core::gl::fx']]],
['fboframecontext_2758',['FBOFrameContext',['../classch_1_1innovazion_1_1arionide_1_1ui_1_1core_1_1gl_1_1fx_1_1_f_b_o_frame_context.html',1,'ch::innovazion::arionide::ui::core::gl::fx']]],
['fboframesettings_2759',['FBOFrameSettings',['../classch_1_1innovazion_1_1arionide_1_1ui_1_1core_1_1gl_1_1fx_1_1_f_b_o_frame_settings.html',1,'ch::innovazion::arionide::ui::core::gl::fx']]],
['fieldmodifieranimation_2760',['FieldModifierAnimation',['../classch_1_1innovazion_1_1arionide_1_1ui_1_1animations_1_1_field_modifier_animation.html',1,'ch::innovazion::arionide::ui::animations']]],
['focusevent_2761',['FocusEvent',['../classch_1_1innovazion_1_1arionide_1_1events_1_1_focus_event.html',1,'ch::innovazion::arionide::events']]],
['focusgainedevent_2762',['FocusGainedEvent',['../classch_1_1innovazion_1_1arionide_1_1events_1_1_focus_gained_event.html',1,'ch::innovazion::arionide::events']]],
['focuslostevent_2763',['FocusLostEvent',['../classch_1_1innovazion_1_1arionide_1_1events_1_1_focus_lost_event.html',1,'ch::innovazion::arionide::events']]],
['focusmanager_2764',['FocusManager',['../classch_1_1innovazion_1_1arionide_1_1ui_1_1_focus_manager.html',1,'ch::innovazion::arionide::ui']]],
['fontrenderer_2765',['FontRenderer',['../interfacech_1_1innovazion_1_1arionide_1_1ui_1_1render_1_1font_1_1_font_renderer.html',1,'ch::innovazion::arionide::ui::render::font']]],
['fontresources_2766',['FontResources',['../classch_1_1innovazion_1_1arionide_1_1ui_1_1render_1_1font_1_1_font_resources.html',1,'ch::innovazion::arionide::ui::render::font']]]
];
|
const presetEnvConfig = {
corejs: 'core-js@2',
debug: false,
modules: false,
targets: {
browsers: ['chrome >= 51', 'firefox >= 60', 'edge >= 15', 'opera >= 43'],
},
useBuiltIns: 'usage',
};
module.exports = {
env: {
test: {
plugins: [
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-nullish-coalescing-operator',
'@babel/plugin-proposal-optional-chaining',
],
presets: [
'@babel/preset-react',
'@babel/preset-typescript',
['@babel/preset-env', {...presetEnvConfig, modules: 'commonjs'}],
'@emotion/babel-preset-css-prop',
],
},
},
plugins: [
['@babel/plugin-proposal-decorators', {legacy: true}],
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-nullish-coalescing-operator',
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-syntax-dynamic-import',
],
presets: [
'@babel/preset-react',
'@babel/preset-typescript',
['@babel/preset-env', presetEnvConfig],
'@emotion/babel-preset-css-prop',
],
};
|
var __v=[
{
"Id": 3099,
"Panel": 1536,
"Name": "_beginthreadex",
"Sort": 0,
"Str": ""
},
{
"Id": 3100,
"Panel": 1536,
"Name": "注意",
"Sort": 0,
"Str": ""
}
]
|
var cinestarz = {};
cinestarz.js1 = function(){
var films = document.getElementsByClassName("movie-text"),
_cinema = {},
_cinemaName = "Cinéstarz Langelier",
_cinemaAdress = "7305, Boulevard Langelier, Montréal",
_shows = {fr: {}, en: {}},
week = getCinemaWeek();
for(var i = 0; i<films.length;i++){
var film = films[i],
filmname = film.children[0].textContent,
filmhoraire = film.children[1].children,
_horaire = {},
_film = {},
dates = [],
times = [];
for(var j = 0; j<filmhoraire.length;j++){
if(filmhoraire[j].tagName !== "BR"){
var child = filmhoraire[j];
if(parseInt(child.textContent)){
times.push(child.textContent);
} else {
var theseDates = child.textContent.split(", "),
fixedDates = [];
for(var k = 0; k< theseDates.length;k++){
var fixed = fixDates(theseDates[k]);
fixedDates.push(fixed);
}
dates.push(fixedDates);
}
}
}
for(var j = 0;j<dates.length;j++){
createFilm(filmname, dates[j], times[j]);
}
}
_cinema.shows = _shows;
_cinema.name = _cinemaName;
_cinema.adress = _cinemaAdress;
_cinema.scraper = "indie";
return _cinema;
//console.log();
function getCinemaWeek(){
var curr = new Date; // get current date
var week = [];
var friday = curr.getDate() - curr.getDay() - 2;
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var month = months[curr.getMonth()];
for(var i = 0;i<7;i++){
week.push(friday + i + " " + month);
}
return week;
}
function fixDates(theDate){
var days = ['Friday','Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday'];
for(var i = 0;i<days.length;i++){
if(theDate.indexOf(days[i]) !== -1){
return week[i];
}
}
return "n";
}
function createFilm(name,date,time){
var aFilm = {};
aFilm.name = name;
aFilm.time = time;
for(var i = 0;i<date.length;i++){
var theDate = date[i];
if(typeof _shows.fr[theDate] !== "object"){
_shows.fr[theDate] = [];
}
_shows.fr[theDate].push({name:name,time:time})
}
}
}
cinestarz.js2 = function(){
var films = document.getElementsByClassName("movie-text"),
_cinema = {},
_cinemaName = "Cinéstarz Côte-Des-Neiges",
_cinemaAdress = "6700, Cote des Neiges #300 AB, Montréal",
_shows = {fr: {}, en: {}},
week = getCinemaWeek(),
bb = [];
for(var i = 0; i<films.length;i++){
var film = films[i],
filmname = film.children[0].textContent,
filmhoraire = film.children[1].children,
_horaire = {},
_film = {},
dates = [],
times = [];
for(var j = 0; j<filmhoraire.length;j++){
if(filmhoraire[j].tagName !== "BR"){
var child = filmhoraire[j];
if(parseInt(child.textContent)){
times.push(child.textContent);
} else {
var theseDates = child.textContent.split(", "),
fixedDates = [];
for(var k = 0; k< theseDates.length;k++){
var fixed = fixDates(theseDates[k]);
fixedDates.push(fixed);
}
dates.push(fixedDates);
}
}
}
for(var j = 0;j<dates.length;j++){
createFilm(filmname, dates[j], times[j]);
}
}
_cinema.shows = _shows;
_cinema.name = _cinemaName;
_cinema.adress = _cinemaAdress;
_cinema.scraper = "indie";
return _cinema;
//console.log(_cinema);
function getCinemaWeek(){
var curr = new Date; // get current date
var week = [];
var friday = curr.getDate() - curr.getDay() - 2;
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var month = months[curr.getMonth()];
for(var i = 0;i<7;i++){
week.push(friday + i + " " + month);
}
return week;
}
function fixDates(theDate){
var days = ['Friday','Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday'];
for(var i = 0;i<days.length;i++){
if(theDate.indexOf(days[i]) !== -1){
return week[i];
}
}
return "n";
}
function createFilm(name,date,time){
var aFilm = {};
aFilm.name = name;
aFilm.time = time;
for(var i = 0;i<date.length;i++){
var theDate = date[i];
if(typeof _shows.en[theDate] !== "object"){
_shows.en[theDate] = [];
}
_shows.en[theDate].push({name:name,time:time});
}
}
}
cinestarz.liens1 = ["http://cinestarz.ca/now-playing/?thr=lan", cinestarz.js1, "Cinéstarz Langelier"];
cinestarz.liens2 = ["http://cinestarz.ca/now-playing/?thr=cote", cinestarz.js2, "Cinéstarz Côte-Des-Neiges"];
module.exports = cinestarz;
|
'use strict';
const create = function () {
let queueStart = [];
let queue = [];
let queueEnd = [];
const addStart = function (task) {
queueStart.push(task);
};
const addEnd = function (task) {
queueEnd.push(task);
};
const add = function (task) {
queue.push(task);
};
const next = function () {
if (queueStart.length > 0) return queueStart.shift();
if (queue.length > 0) return queue.shift();
if (queueEnd.length > 0) return queueEnd.shift();
return false;
};
const has = function () {
if (queueStart.length > 0) return true;
if (queue.length > 0) return true;
if (queueEnd.length > 0) return true;
return false;
};
const length = function () {
return queueStart.length + queue.length + queueEnd.length;
};
return {
add: add,
addStart: addStart,
addEnd: addEnd,
next: next,
has: has,
length: length,
};
};
module.exports = {
create: create,
};
|
const { Router } = require('express');
const router = Router({ mergeParams: true });
const databases = require('./databases');
router.use('/databases', databases);
module.exports = router;
|
Bitrix 16.5 Business Demo = 0b963a3f10477f5ecf713999ae3851d1
Bitrix 17.0.9 Business Demo = 3edc47b31a183eb1e0291fc5c5dc7666
|
'use strict';
module.exports = function() {
var _this = this;
var timeout;
window.addEventListener('scroll', pauseWhenNotInView);
pauseWhenNotInView(true);
function pauseWhenNotInView(init) {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function() {
var elPos = _this.canvas.getBoundingClientRect();
var isNotInView =
elPos.bottom < 0 ||
elPos.right < 0 ||
elPos.left > window.innerWidth ||
elPos.top > window.innerHeight;
if (isNotInView) {
if (!_this.isPaused && !_this.isPausedBecauseNotInView) {
_this.isPausedBecauseNotInView = true;
_this.pause('isPausedBecauseNotInView');
}
} else {
if (!_this.isPaused || init === true) {
_this.isPausedBecauseNotInView = false;
_this.play('isPausedBecauseNotInView');
}
}
}, 300);
}
};
|
'use strict'
const fs = require('fs')
const Asyncs = require('./Asyncs')
module.exports = new class Files {
needDir(path, callback) {
if (fs.existsSync(path)) {
callback && callback()
} else {
fs.mkdir(path, (err) => {
if (err) {
throw err
}
callback && callback()
})
}
}
removeDir(path) {
return new Promise((resolve, reject) => {
if (!fs.existsSync(path)) {
resolve()
return
}
fs.readdir(path, (err, files) => {
if (err) {
throw err
}
Asyncs.forEach(files, (file, i, next) => {
fs.unlink(path + file, (err) => {
if (err) {
throw err
}
next()
})
}, () => {
fs.rmdir(path, (err) => {
if (err) {
throw err
}
resolve()
})
})
})
})
}
copy(src, dst) {
return new Promise((resolve, reject) => {
fs.readFile(src, (err, data) => {
if (err) {
throw err
}
fs.writeFile(dst, data, (err) => {
if (err) {
throw err
}
resolve(true)
})
})
})
}
copyBack(dst, src) {
return this.copy(src, dst)
}
touch(path) {
return new Promise((resolve, reject) => {
fs.writeFile(path, Buffer.from([]), (err) => {
if (err) {
throw err
}
resolve(true)
})
})
}
}
|
module.exports = function() {
return this.data;
}
|
OsciTk.views.Toolbar = OsciTk.views.BaseView.extend({
id: 'toolbar-view',
template: OsciTk.templateManager.get('toolbar'),
initialize: function() {
// tracks the state of the content area drawer
this.activeToolbarItemView = undefined;
this.listenTo(Backbone, "packageLoaded", function(packageModel) {
//Add the publication title to the Toolbar
this.title = packageModel.getTitle();
});
this.listenTo(Backbone, "figuresAvailable", function(figures) {
this.figureSize = figures.size();
this.render();
});
},
render: function() {
this.$el.html(this.template({'title': this.title}));
_.each(app.toolbarItems, function(toolbarItem) {
if(toolbarItem.text != 'figures' || this.figureSize != 0) {
var item = new OsciTk.views.ToolbarItem({toolbarItem: toolbarItem});
this.addView(item, '#toolbar-area');
item.render();
}
}, this);
}
});
|
{
"translatorID":"7e51d3fb-082e-4063-8601-cda08f6004a3",
"translatorType":4,
"label":"Education Week",
"creator":"Ben Parr",
"target":"^https?://(?:www\\.|blogs\\.|www2\\.)?edweek",
"minVersion":"1.0.0b4.r1",
"maxVersion":"",
"priority":100,
"inRepository":true,
"lastUpdated":"2007-07-31 16:45:00"
}
function detectWeb(doc,url)
{
var namespace = doc.documentElement.namespaceURI;
var nsResolver = namespace ? function(prefix) {
if (prefix == 'x') return namespace; else return null;
} : null;
var xpath='//meta[@name="Story_type"]/@content';
var temp=doc.evaluate(xpath, doc, nsResolver,XPathResult.ANY_TYPE,null).iterateNext();
if(temp)
{
if(temp.value=="Blog")
{return "blogPost";}
if(temp.value.indexOf("Story")>-1)
{return "magazineArticle";}
}
}
function associateMeta(newItem, metaTags, field, zoteroField) {
if(metaTags[field]) {
newItem[zoteroField] = metaTags[field];
}
}
function scrape(doc, url) {
var newItem = new Zotero.Item("magazineArticle");
if(url&&url.indexOf("blogs.edweek.org")>-1)
{newItem.itemType="blogPost";}
newItem.url = doc.location.href;
var metaTags = new Object();
var metaTagHTML = doc.getElementsByTagName("meta");
var i;
for (i = 0 ; i < metaTagHTML.length ; i++) {
metaTags[metaTagHTML[i].getAttribute("name")]=Zotero.Utilities.cleanTags(metaTagHTML[i].getAttribute("content"));
}
associateMeta(newItem, metaTags, "Title", "title");
associateMeta(newItem, metaTags, "Cover_date", "date");
associateMeta(newItem, metaTags, "Description", "abstractNote");
associateMeta(newItem, metaTags, "ArticleID", "accessionNumber");
associateMeta(newItem,metaTags,"Source","publicationTitle");
if (metaTags["Authors"]) {
var author = Zotero.Utilities.cleanString(metaTags["Authors"]);
if (author.substr(0,3).toLowerCase() == "by ") {
author = author.substr(3);
}
var authors = author.split(" and ");
for each(var author in authors) {
var words = author.split(" ");
for (var i in words) {
words[i] = words[i][0].toUpperCase() +words[i].substr(1).toLowerCase();
}
author = words.join(" ");
newItem.creators.push(Zotero.Utilities.cleanAuthor(author, "author"));
}
}
newItem.complete();
}
function doWeb(doc,url)
{
var namespace = doc.documentElement.namespaceURI;
var nsResolver = namespace ? function(prefix) {
if (prefix == 'x') return namespace; else return null;
} : null;
var xpath='//meta[@name="Story_type"]/@content';
var temp=doc.evaluate(xpath, doc, nsResolver,XPathResult.ANY_TYPE,null).iterateNext();
if(temp)
{
if(temp.value.indexOf("Story")>-1 || temp.value=="Blog")
{scrape(doc,url);}
}
}
|
/**
* @license
* This file is part of the Game Closure SDK.
*
* The Game Closure SDK is free software: you can redistribute it and/or modify
* it under the terms of the Mozilla Public License v. 2.0 as published by Mozilla.
* The Game Closure SDK 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
* Mozilla Public License v. 2.0 for more details.
* You should have received a copy of the Mozilla Public License v. 2.0
* along with the Game Closure SDK. If not, see <http://mozilla.org/MPL/2.0/>.
*/
/**
* @package timestep.env.browser.dev_error;
*
* Displays a developer error.
*
* ??? TODO move to a debug package.
*/
exports.render = function (e) {
logger.error("unhandled tick exception");
logger.error(e.stack);
var c = document.getElementsByTagName('canvas');
for (var i = 0, el; el = c[i]; ++i) {
render(el.getContext('2d'), e);
}
}
function render(ctx, e) {
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
var x = 30, y = 40;
ctx.fillStyle = "#FFF";
ctx.font = "bold 12px Monaco,\"Bitstream Vera Sans Mono\",\"Lucida Console\",Terminal,monospace";
function drawLine(msg) {
ctx.fillText(msg, x, y);
y += 20;
}
drawLine(e.message);
y += 40;
e.stack.split('\n').map(drawLine);
}
|
define('gmaps', ['async!http://maps.googleapis.com/maps/api/js?v=3.17&key=AIzaSyCqDP4qFf7d0uW2P20b7ctUaCwwVglu8OQ&sensor=false'], function() {
return window.google.maps;
});
|
module.exports = {
assignJobs: (room, creeps) => {
_.forEach(creeps, saboteur => {
if (saboteur.pos.roomName != saboteur.memory.targetRoom) {
saboteur.memory.job = {
action: 'gotoTargetRoom',
room: saboteur.memory.targetRoom,
target: null
}
} else {
let target = saboteur.pos.findClosestByPath(FIND_STRUCTURES, {
filter: struct => struct.structureType == STRUCTURE_EXTENSION || struct.structureType == STRUCTURE_LINK || struct.structureType == STRUCTURE_TERMINAL
});
if (target) {
saboteur.memory.job = {
action: 'dismantle',
room: target.pos.roomName,
target: target.id
};
} else {
target = saboteur.pos.findClosestByPath(FIND_STRUCTURES, {
filter: struct => struct.structureType != STRUCTURE_SPAWN && struct.structureType != STRUCTURE_CONTROLLER && struct.structureType != STRUCTURE_ROAD && struct.hits < 10000
});
if (target) {
saboteur.memory.job = {
action: 'dismantle',
room: target.pos.roomName,
target: target.id
};
} else {
let target = saboteur.pos.findClosestByPath(FIND_HOSTILE_CONSTRUCTION_SITES);
if (target) {
saboteur.memory.job = {
action: 'dismantle',
room: target.pos.roomName,
target: target.id
};
}
}
}
}
});
}
}
|
jQuery(document).ready(function() {
// Opacity range sliders
jQuery('#barTra').on('input', function() {
jQuery('#barTraFilter').css('opacity', jQuery(this).val());
});
jQuery('#barTraFilter').css('opacity', jQuery('#barTra').val());
jQuery('#ovrTra').on('input', function() {
jQuery('#ovrTraFilter').css('opacity', jQuery(this).val());
});
jQuery('#ovrTraFilter').css('opacity', jQuery('#ovrTra').val());
// media uploader
// Instantiates the variable that holds the media library frame.
var meta_image_frame;
// Runs when the image button is clicked.
jQuery('#shift8_fullnav_image_button').click(function(e){
// Prevents the default action from occuring.
e.preventDefault();
// If the frame already exists, re-open it.
if ( meta_image_frame ) {
meta_image_frame.open();
return;
}
// Sets up the media library frame
meta_image_frame = wp.media.frames.meta_image_frame = wp.media({
title: shift8_fullnav_logo.title,
button: { text: shift8_fullnav_logo.button },
library: { type: 'image' }
});
// Runs when an image is selected.
meta_image_frame.on('select', function(){
// Grabs the attachment selection and creates a JSON representation of the model.
var media_attachment = meta_image_frame.state().get('selection').first().toJSON();
// Sends the attachment URL to our custom image input field.
jQuery('#shift8_fullnav_logo').val(media_attachment.url);
});
// Opens the media library frame.
meta_image_frame.open();
});
});
|
var interfacemod__class__abstract__rsm_1_1fit__interface =
[
[ "fit_interface", "interfacemod__class__abstract__rsm_1_1fit__interface.html#a944715ad48c931a1b2ded26da7132145", null ]
];
|
var class_login =
[
[ "Login", "class_login.html#a57323a0401a0d1d62b5fbd8da29d8df5", null ],
[ "process_username", "class_login.html#a1df0700504a3c9f7f9def1a9591f078e", null ],
[ "save_transaction", "class_login.html#a8e5996ad33eb07eef44f55deba6c298e", null ]
];
|
'use strict';
const React = require('react');
const ReactNative = require('react-native');
import Button from 'apsl-react-native-button';
import {PropTypes, Component} from 'react'
const {
View,
Text,
TextInput,
StyleSheet,
Modal,
TouchableWithoutFeedback
} = ReactNative;
class Register extends Component {
doLogin = function(){
}
doRegister = function(){
}
doPrivacy = function(){
}
render() {
const {visible, modalClose, showLogin} = this.props
return (
<Modal
animationType="slide"
transparent={false}
visible={visible}
onRequestClose={modalClose}>
<View style={styles.register}>
<Text style={styles.title}>豆田,为美好驻足</Text>
<TextInput placeholder="请输入邮箱" />
<TextInput placeholder="请输入密码" secureTextEntry={true} />
<TextInput placeholder="请输入昵称" />
<Button style={styles.registerBtn} onPress={this.doRegister.bind(this)}>注册</Button>
<TouchableWithoutFeedback onPress={showLogin}>
<View>
<Text style={styles.login}>已有账号,登录</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={this.doPrivacy.bind(this)}>
<View>
<Text style={styles.login}>使用条款和隐私政策</Text>
</View>
</TouchableWithoutFeedback>
<Button
style={styles.closeBtn}
textStyle={styles.closeText}
onPress={modalClose}>X</Button>
</View>
</Modal>
);
}
}
const styles = StyleSheet.create({
register: {
paddingLeft: 20,
paddingRight: 20
},
title: {
marginTop: 40,
textAlign: "center",
fontSize: 26,
height: 60,
lineHeight: 40
},
registerBtn: {
marginTop: 30,
},
login: {
textAlign: "center",
marginTop: 20,
color: "#06c"
},
closeBtn: {
position: "absolute",
width: 40,
height: 40,
top: 10,
right: 10,
borderWidth: 0
},
closeText: {
color: "rgba(255, 0, 51, 1)",
fontSize: 20
}
});
Register.propTypes = {
visible: PropTypes.bool.isRequired,
modalClose: PropTypes.func.isRequired,
showLogin: PropTypes.func.isRequired
}
module.exports = Register;
|
// Initialize when the form is loaded
$(document).ready(start);
// Start this instance
function start()
{
// Animate the background image
if ($(window).width() >= 1046)
{
var bgImage = $("#backgroundImage");
bgImage.attr("src", bgImage.attr("data-src"));
bgImage.fadeIn(2000);
}
// Register events
$(document).on("click", "#toggleMobileMenu", toggleMobileMenu);
} // End of the start method
// Toggle the visibility of the menu
function toggleMobileMenu()
{
// Get the mobile menu
var mobileMenu = $("#mobileMenu");
// Toggle the visibility for the menu
mobileMenu.slideToggle(500);
} // End of the toggleMobileMenu method
// Hide the mobile menu
function hideMobileMenu(event)
{
if ($(window).width() < 1000)
{
// Get the mobile menu
var mobileMenu = $("#mobileMenu");
if (mobileMenu.is(":hidden") == false && $("#toggleMobileMenu").is(event.target) == false
&& mobileMenu.is(event.target) == false && mobileMenu.has(event.target).length == 0) {
mobileMenu.slideToggle();
}
}
} // End of the hideMobileMenu method
|
/// <binding BeforeBuild='scripts' />
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var typescript = require('gulp-typescript');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var debugFileName = 'appngine.debug.js';
var releaseFileName = 'appngine.js'
var debugProject = typescript.createProject('tsconfig.json', {
removeComments: true,
sortOutput: true,
outFile: debugFileName
});
var releaseProject = typescript.createProject('tsconfig.json', {
removeComments: true,
sortOutput: true,
outFile: releaseFileName
});
var debugOut = 'out/debug';
var releaseOut = 'out/release';
gulp.task('scripts', function () {
var debugResults = debugProject.src()
.pipe(sourcemaps.init())
.pipe(typescript(debugProject));
var releaseResults = releaseProject.src()
.pipe(typescript(releaseProject));
debugResults.js
.pipe(concat(debugFileName))
.pipe(sourcemaps.write())
.pipe(gulp.dest(debugOut));
releaseResults.js
.pipe(concat(releaseFileName))
.pipe(gulp.dest(releaseOut))
.pipe(uglify())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest(releaseOut));
debugResults.dts
.pipe(gulp.dest(debugOut));
releaseResults.dts
.pipe(gulp.dest(releaseOut));
});
gulp.task('watch', ['scripts'], function () {
gulp.watch(['**/*.ts', 'tsconfig.json'], ['scripts']);
});
|
"use strict";
/*
* MiddleWare for the entire app
*/
module.exports = exports = {
fourohfour: function(req, res, next){
//res.status(404);
// redirect to angular frontend
if (req.accepts('html')) {
//res.redirect("/#/notFound");
res.sendFile('index.html', { root: __dirname + '/../../client'});
return;
}
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
},
logError: function (err, req, res, next) {
if (err) {
console.error(err);
return next(err);
}
next();
},
handleError: function (err, req, res, next) {
if (err) {
res.status(500).send({error: err.message, errorType: err.name });
}
},
cors: function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:9000');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Header', 'Content-type, Authorization, X-Requested-With');
if (req.method === 'Options') {
res.send(200);
} else {
return next();
}
}
};
|
'use strict';
/**
* Created with IntelliJ IDEA.
* User: shenyanchao
* Date: 3/5/13
* Time: 5:51 PM
* To change this template use File | Settings | File Templates.
*/
var assert = chai.assert;
// var should = chai.should();
describe('Array', function() {
before(function() {
console.log('this called in before all');
});
beforeEach(function() {
console.log('invoke before each method');
});
afterEach(function() {
console.log('invoke after each method');
});
after(function() {
console.log('this called in after all');
});
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
console.log('invoke one assert');
assert.equal(-1, [1, 2, 3].indexOf(5));
assert.equal(-1, [1, 2, 3].indexOf(0));
});
});
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
console.log('invoke second should');
[1, 2, 3].indexOf(5).should.equal(-1);
[1, 2, 3].indexOf(0).should.equal(-1);
});
});
});
|
const NAVER_ID = "cYoIkNBqhZ0VfPCaE2qq";
const NAVER_SECRET = "dK851bgR8m";
const GOOGLE_ID = "311377055307-bb5b7rjhb7jibllu9lfjmnjqkg1vpq5s.apps.googleusercontent.com";
const GOOGLE_API = "Google API ID";
const GOOGLE_SECRET = "P0TtjQQ_yasg0dTaKkFWg4wX";
// const TWITTER_KEY = "";
var Web = require("request");
var Lizard = require("../sub/lizard");
var JLog = require("../sub/jjlog");
JLog.init("jauth");
// var Ajae = require("../sub/ajae").checkAjae;
exports.login = function(type, token, sid, token2){
var R = new Lizard.Tail();
var now = new Date();
var MONTH = now.getMonth() + 1, DATE = now.getDate();
var $p = {};
if(type == "naver"){
Web.post("https://nid.naver.com/oauth2.0/token", { form: {
grant_type: "authorization_code",
client_id: NAVER_ID,
client_secret: NAVER_SECRET,
code: token,
state: sid
} }, function(err, res, doc){
if(err){
JLog.warn("Error on oAuth-naver: "+err.toString());
R.go({ error: 500 });
}else{
try{ doc = JSON.parse(doc); }catch(e){ return R.go({ error: 500 }); }
$p.token = doc.access_token;
Web.post({
url: "https://openapi.naver.com/v1/nid/me",
headers: { 'Authorization': "Bearer " + $p.token }
}, function(err, res, doc){
if(err) return R.go({ error: 400 });
if(!doc) return R.go({ error: 500 });
try{ doc = JSON.parse(doc); }catch(e){ return R.go({ error: 500 }); }
if(doc.resultcode == "00"){
$p.type = "naver";
$p.id = doc.response.id;
$p.name = doc.response.name;
$p.title = doc.response.nickname;
$p.image = doc.response.profile_image;
/* 망할 셧다운제
$p._age = doc.response.age.split('-').map(Number);
$p._age = { min: ($p._age[0] || 0) - 1, max: $p._age[1] - 1 };
$p.birth = doc.response.birthday.split('-').map(Number);
if(MONTH < $p.birth[0] || (MONTH == $p.birth[0] && DATE < $p.birth[1])){
$p._age.min--;
$p._age.max--;
}
$p.isAjae = Ajae($p.birth, $p._age);
*/
// $p.sex = doc.response[0].gender[0];
R.go($p);
}else{
R.go({ error: 401 });
}
});
}
});
}else if(type == "facebook"){
$p.token = token;
Web.get({
url: "https://graph.facebook.com/v2.4/me",
qs: {
access_token: $p.token,
fields: "id,name,gender"
}
}, function(err, res, doc){
if(err){
JLog.warn("Error on oAuth-facebook: "+err.toString());
R.go({ error: 500 });
}else{
try{ doc = JSON.parse(doc); }catch(e){ return R.go({ error: 500 }); }
$p.type = "facebook";
$p.id = doc.id;
$p.name = doc.name;
$p.image = "https://graph.facebook.com/"+doc.id+"/picture?width=20&height=20";
/* 망할 셧다운제
$p._age = doc.age_range;
if(doc.birthday){
$p.birth = doc.birthday.split('/').map(Number);
}
$p.isAjae = Ajae($p.birth, $p._age);
*/
// $p.sex = doc.gender[0].toUpperCase();
R.go($p);
}
});
}else if(type == "google"){
$p.token = token;
Web.get({
url: "https://www.googleapis.com/oauth2/v3/tokeninfo",
qs: {
id_token: token
}
}, function(err, res, doc){
if(err){
JLog.warn("Error on oAuth-google: "+err.toString());
R.go({ error: 500 });
}else{
try{ doc = JSON.parse(doc); }catch(e){ return R.go({ error: 500 }); }
if(doc.aud != GOOGLE_ID) return R.go({ error: 401 });
if(!doc.email_verified) return R.go({ error: 402 });
/*Web.get({
url: "https://www.googleapis.com/plus/v1/people/me",
qs: {
fields: "ageRange,birthday",
// key: GOOGLE_API,
access_token: token2
},
headers: { 'Authorization': "Bearer " + token2 }
}, function(_err, _res, _doc){
if(_err){
JLog.warn("Error on profile-google: "+err.toString());
R.go({ error: 500 });
}else{
try{ _doc = JSON.parse(_doc); }catch(e){ return R.go({ error: 500 }); }
if(_doc.error) return R.go({ error: _doc.error.code });*/
$p.type = "google";
$p.id = doc.sub;
$p.name = doc.name;
$p.image = doc.picture+"?sz=20";
R.go($p);
/* 망할 셧다운제
$p._age = _doc.ageRange;
if(_doc.birthday){
$p.birth = _doc.birthday.split('-').map(Number);
$p.birth.push($p.birth.shift());
}
$p.isAjae = Ajae($p.birth, $p._age);
R.go($p);
}
});*/
}
});
}
return R;
};
exports.logout = function($p){
var R = new Lizard.Tail();
if($p.type == "naver"){
Web.post("https://nid.naver.com/oauth2.0/token", { form: {
grant_type: "delete",
client_id: NAVER_ID,
client_secret: NAVER_SECRET,
code: $p.token,
service_provider: "NAVER"
} }, function(err, res, doc){
R.go(doc);
});
}else if($p.type == "facebook"){
R.go(true);
}else if($p.type == "google"){
R.go(true);
}
return R;
};
|
//time-out
function processData(input) {
//Enter your code here
input=input.split("\n");
for(k=1;k<=parseInt(input[0]);k++)
{
var str=input[k];
var len=input[k].length;
var count=0;
var total=0;
for(i=1;i<len;i++)
{
count=0;
for(j=i;j<len;j++)
{
if(str.charAt(j-i)==str.charAt(j))
count++;
else
break;
}
total=total+count;
}
console.log(total+len);
}
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
|
'use strict';
// Setting up route
angular
.module('users')
.config(routeConfig);
routeConfig.$inject= ['$stateProvider', '$urlRouterProvider'];
function routeConfig($stateProvider, $urlRouterProvider) {
// Users state routing
$stateProvider
.state('settings', {
abstract: true,
url: '/settings',
templateUrl: 'modules/users/client/views/settings/settings.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('settings.profile', {
url: '/profile',
templateUrl: 'modules/users/client/views/settings/edit-profile.client.view.html'
})
.state('settings.password', {
url: '/password',
templateUrl: 'modules/users/client/views/settings/change-password.client.view.html'
})
.state('settings.picture', {
url: '/picture',
templateUrl: 'modules/users/client/views/settings/change-profile-picture.client.view.html'
})
.state('authentication', {
abstract: true,
url: '/authentication',
templateUrl: 'modules/users/client/views/authentication/authentication.client.view.html'
})
.state('authentication.signup', {
url: '/signup',
templateUrl: 'modules/users/client/views/authentication/signup.client.view.html'
})
.state('authentication.signin', {
url: '/signin?err',
templateUrl: 'modules/users/client/views/authentication/signin.client.view.html'
})
.state('password', {
abstract: true,
url: '/password',
template: '<ui-view/>'
})
.state('password.forgot', {
url: '/forgot',
templateUrl: 'modules/users/client/views/password/forgot-password.client.view.html'
})
.state('password.reset', {
abstract: true,
url: '/reset',
template: '<ui-view/>'
})
.state('password.reset.invalid', {
url: '/invalid',
templateUrl: 'modules/users/client/views/password/reset-password-invalid.client.view.html'
})
.state('password.reset.success', {
url: '/success',
templateUrl: 'modules/users/client/views/password/reset-password-success.client.view.html'
})
.state('password.reset.form', {
url: '/:token',
templateUrl: 'modules/users/client/views/password/reset-password.client.view.html'
})
.state('myProfile', {
url: '/myProfile/:userName',
templateUrl: 'modules/users/client/views/view-profile.client.html'
})
.state('terms', {
url: '/terms',
templateUrl: 'modules/users/client/views/terms.client.view.html'
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.