text
stringlengths
2
6.14k
version https://git-lfs.github.com/spec/v1 oid sha256:bf3b77d3c917de71ce94a4ac1d820687dfbb6ce9d20792738c6bf350bf430636 size 1440
version https://git-lfs.github.com/spec/v1 oid sha256:e530aa6dacb353f635cf98ccc8d607b49f57db53264f23fe3511729e47bb9b85 size 7991
version https://git-lfs.github.com/spec/v1 oid sha256:572cca94d30a4570ad4594613b35bd70d63a13b83ea7d81126d327a318efd864 size 599823
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Comment Schema */ var CommentSchema = new Schema({ created: { type: Date, default: Date.now }, comment: { type: String, default: '', required: 'Pls enter a comment', trim: true }, user: { type: Schema.ObjectId, ref: 'User' }, program: { type: Schema.ObjectId, ref: 'Program' } }); mongoose.model('Comment', CommentSchema);
'use strict'; const expect = require('chai').expect; const valueTRUE = [new Object(), [], {name: 'Carlos'}]; const valueFALSE = ['1', undefined, null, 0]; const testFalse = (values) =>{ values.forEach((element, index) =>{ it('Testando: ' + element, ()=>{ expect(require('./isObject')(element)).to.equal(false); }); }); }; const testTrue = (values) => { values.forEach((element, index)=>{ it('Testando: ' + element, () =>{ expect(require('./isObject')(element)).to.equal(true); }); }); }; describe('Teste de objetos', ()=>{ describe('objetos inválidos: ', () => testFalse(valueFALSE)); describe('objetos válidos: ', () => testTrue(valueTRUE)); });
// Generated by CoffeeScript 1.6.2 define(function(require, exports, module) { var ALIAS, Cell, Wrap, filter; filter = function(attrs) { var attr, key, name, tasks; tasks = {}; for (key in attrs) { attr = attrs[key]; if (typeof attr !== "object") { continue; } name = attr.name.toLowerCase(); if (!/^task-/.test(name)) { continue; } name = name.replace(/^task-/, ""); tasks[name] = attr.value; } return tasks; }; ALIAS = { "INPUT:text": "text", "INPUT:password": "password", "INPUT:radio": "radio", "INPUT:checkbox": "checkbox", "TEXTAREA": "textarea", "SELECT": "select" }; Wrap = function(form) { var cells, sel, type; cells = []; for (sel in ALIAS) { type = ALIAS[sel]; $(form).find(sel).each(function() { return cells.push(new Cell(type, this)); }); } return cells; }; Cell = (function() { function Cell(type, cell) { var attrs, value; this.type = type; attrs = cell.attributes; cell = $(cell); this.dom = cell; this.group_dom = this.dom.parents(".form-group"); this.name = cell.attr("name"); this["default"] = cell.attr("default"); value = cell.attr("value"); if (this["default"] !== void 0 && value === void 0) { cell.val(this["default"]); } this.tasks = filter(attrs); } return Cell; })(); return module.exports = Wrap; });
var fileUp = function( ul , callback ){ var formatFileSize = function (bytes) { if (typeof bytes !== 'number') { return ''; } if (bytes >= 1000000000) { return (bytes / 1000000000).toFixed(2) + ' GB'; } if (bytes >= 1000000) { return (bytes / 1000000).toFixed(2) + ' MB'; } return (bytes / 1000).toFixed(2) + ' KB'; } return { // This element will accept file drag/drop uploading dropZone: $('#drop'), // This function is called when a file is added to the queue; // either via the browse button, or via drag/drop: add: function (e, data) { var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"'+ ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>'); // Append the file name and file size tpl.find('p').text(data.files[0].name) .append('<i>' + formatFileSize(data.files[0].size) + '</i>'); // Add the HTML to the UL element data.context = tpl.appendTo(ul); // Initialize the knob plugin tpl.find('input').knob(); // Listen for clicks on the cancel icon tpl.find('span').click(function(){ if(tpl.hasClass('working')){ jqXHR.abort(); } tpl.fadeOut(function(){ tpl.remove(); }); }); // Automatically upload the file once it is added to the queue var jqXHR = data.submit(); jqXHR.success(function(result, textStatus, jqXhr){ if(textStatus == "success" ){ callback(result,undefined); }else{ callback(undefined,textStatus); } }).error( function( jqXHR, textStatus, errorThrown ){ }).complete( function( result, textStatus, jqXHR ){ }); }, progress: function(e, data){ // Calculate the completion percentage of the upload var progress = parseInt(data.loaded / data.total * 100, 10); // Update the hidden input field and trigger a change // so that the jQuery knob plugin knows to update the dial data.context.find('input').val(progress).change(); if(progress == 100){ data.context.removeClass('working'); } }, fail:function(e, data){ // Something has gone wrong! data.context.addClass('error'); } } }
var basicAuth = require('basic-auth') var config = require('../app/config.js') var fs = require('fs') var marked = require('marked') var path = require('path') var portScanner = require('portscanner') var prompt = require('prompt') var request = require('sync-request') // Variables var releaseUrl = null // require core and custom filters, merges to one object // and then add the methods to nunjucks env obj exports.addNunjucksFilters = function (env) { var coreFilters = require('./core_filters.js')(env) var customFilters = require('../app/filters.js')(env) var filters = Object.assign(coreFilters, customFilters) Object.keys(filters).forEach(function (filterName) { env.addFilter(filterName, filters[filterName]) }) return } /** * Simple basic auth middleware for use with Express 4.x. * * Based on template found at: http://www.danielstjules.com/2014/08/03/basic-auth-with-express-4/ * * @example <<<<<<< HEAD * app.use('/api-requiring-auth', utils.basicAuth('username', 'password')); ======= * app.use('/api-requiring-auth', utils.basicAuth('username', 'password')) >>>>>>> fb45d4fe0a6b972ec5d2d027ea5828f59d853324 * * @param {string} username Expected username * @param {string} password Expected password * @returns {function} Express 4 middleware requiring the given credentials */ exports.basicAuth = function (username, password) { return function (req, res, next) { if (!username || !password) { console.log('Username or password is not set.') return res.send('<h1>Error:</h1><p>Username or password not set. <a href="https://github.com/alphagov/govuk_prototype_kit/blob/master/docs/guides/publishing-on-heroku.md#5-set-a-username-and-password">See guidance for setting these</a>.</p>') } var user = basicAuth(req) if (!user || user.name !== username || user.pass !== password) { res.set('WWW-Authenticate', 'Basic realm=Authorization Required') return res.sendStatus(401) } next() } } exports.findAvailablePort = function (app, callback) { var port = null try { port = Number(fs.readFileSync(path.join(__dirname, '/../.port.tmp'))) } catch (e) { port = Number(process.env.PORT || config.port) } console.log('') // Check that default port is free, else offer to change portScanner.findAPortNotInUse(port, port + 50, '127.0.0.1', function (error, availablePort) { if (error) { throw error } if (port === availablePort) { callback(port) } else { // Default port in use - offer to change to available port console.error('ERROR: Port ' + port + ' in use - you may have another prototype running.\n') // Set up prompt settings prompt.colors = false prompt.start() prompt.message = '' prompt.delimiter = '' // Ask user if they want to change port prompt.get([{ name: 'answer', description: 'Change to an available port? (y/n)', required: true, type: 'string', pattern: /y(es)?|no?/i, message: 'Please enter y or n' }], function (err, result) { if (err) { throw err } if (result.answer.match(/y(es)?/i)) { // User answers yes port = availablePort fs.writeFileSync(path.join(__dirname, '/../.port.tmp'), port) console.log('Changed to port ' + port) callback(port) } else { // User answers no - exit console.log('\nYou can set a new default port in server.js, or by running the server with PORT=XXXX') console.log("\nExit by pressing 'ctrl + c'") process.exit(0) } }) } }) } exports.forceHttps = function (req, res, next) { if (req.headers['x-forwarded-proto'] !== 'https') { console.log('Redirecting request to https') // 302 temporary - this is a feature that can be disabled return res.redirect(302, 'https://' + req.get('Host') + req.url) } next() } // Synchronously get the url for the latest release on github and store exports.getLatestRelease = function () { var url = '' if (releaseUrl !== null) { // Release url already exists console.log('Release url cached:', releaseUrl) return releaseUrl } else { // Release url doesn't exist var options = { headers: {'user-agent': 'node.js'} } var gitHubUrl = 'https://api.github.com/repos/alphagov/govuk_prototype_kit/releases/latest' try { console.log('Getting latest release from github') var res = request('GET', gitHubUrl, options) var data = JSON.parse(res.getBody('utf8')) var zipballUrl = data['zipball_url'] var releaseVersion = zipballUrl.split('/').pop() var urlStart = 'https://github.com/alphagov/govuk_prototype_kit/archive/' var urlEnd = '.zip' var zipUrl = urlStart + releaseVersion + urlEnd console.log('Release url is', zipUrl) releaseUrl = zipUrl url = releaseUrl } catch (err) { url = 'https://github.com/alphagov/govuk_prototype_kit/releases/latest' console.log("Couldn't retrieve release url") } } return url } // Matches routes exports.matchRoutes = function (req, res) { var path = (req.params[0]) res.render(path, function (err, html) { if (err) { res.render(path + '/index', function (err2, html) { if (err2) { res.status(404).send(err + '<br>' + err2) } else { res.end(html) } }) } else { res.end(html) } }) } exports.matchMdRoutes = function (req, res) { var docsPath = '/../docs/documentation/' var filePath = path.join(__dirname, docsPath, req.params[0] + '.md') console.log('file path is:', filePath) if (fs.existsSync(path.join(__dirname, docsPath, req.params[0] + '.md'), 'utf8')) { var doc = fs.readFileSync(path.join(__dirname, docsPath, req.params[0] + '.md'), 'utf8') var html = marked(doc) res.render('documentation_template', {'document': html}) return true } return false }
const Person = function(name, id, x, y) { this.name = name; this.id = id; this.x = x; this.y = y; console.log('X: ', this.x); console.log('Y: ', this.y); this.scores = {}; this.responses = []; this.response = undefined; this.addRoundResponse = response => { if (response === true || response === false) this.response = response; else this.response = undefined; }; this.addResponse = () => { this.responses.push(this.response); }; } module.exports = Person;
import React, { PropTypes } from 'react'; import TweetEmbed from './TweetEmbed/index'; import styles from './styles'; const propTypes = { twitterId: PropTypes.string.isRequired, }; function Twitter({ twitterId }) { return ( <div className={styles.root}> <TweetEmbed id={twitterId} /> </div> ); } Twitter.propTypes = propTypes; export default Twitter;
module.exports = function ( karma ) { karma.configure({ /** * From where to look for files, starting with the location of this file. */ basePath: '../', /** * This is the list of file patterns to load into the browser during testing. */ files: [ 'vendor/angular/angular.js', 'vendor/angular-bootstrap/ui-bootstrap-tpls.min.js', 'vendor/placeholders/angular-placeholders-0.0.1-SNAPSHOT.min.js', 'vendor/angular-ui-router/release/angular-ui-router.min.js', 'vendor/angular-ui-utils/modules/route/route.js', 'vendor/lodash/dist/lodash.min.js', 'vendor/restangular/dist/restangular.min.js', 'vendor/angular-local-storage/angular-local-storage.js', 'build/templates-app.js', 'build/templates-common.js', 'vendor/angular-mocks/angular-mocks.js', 'src/**/*.js', 'src/**/*.coffee', ], exclude: [ 'src/assets/**/*.js' ], frameworks: [ 'jasmine' ], plugins: [ 'karma-jasmine', 'karma-firefox-launcher', 'karma-chrome-launcher', 'karma-phantomjs-launcher', 'karma-coffee-preprocessor' ], preprocessors: { '**/*.coffee': 'coffee', }, /** * How to report, by default. */ reporters: 'dots', /** * On which port should the browser connect, on which port is the test runner * operating, and what is the URL path for the browser to use. */ port: 9018, runnerPort: 9100, urlRoot: '/', /** * Disable file watching by default. */ autoWatch: false, /** * The list of browsers to launch to test on. This includes only "Firefox" by * default, but other browser names include: * Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS * * Note that you can also use the executable name of the browser, like "chromium" * or "firefox", but that these vary based on your operating system. * * You may also leave this blank and manually navigate your browser to * http://localhost:9018/ when you're running tests. The window/tab can be left * open and the tests will automatically occur there during the build. This has * the aesthetic advantage of not launching a browser every time you save. */ browsers: [ 'Chrome' ] }); };
define([ 'jquery', 'underscore', 'backbone', 'collections/colors', 'bootstrap/typeahead' ], function($, _, Backbone, ColorCollection) { 'use strict'; var ColorEditView = Backbone.View.extend({ el: '#similarity', initialize: function() { var tableContainers = this.$('.tablecontainer'); this.scrollContainers = _.debounce(function() { tableContainers.each(function() { var tc = $(this); if (tc.scrollTop() > 0) { tc.animate({scrollTop: 0}, 'fast'); } }); }, 500); this.similarTBody = this.$('#similar-colors tbody'); this.dissimilarTBody = this.$('#dissimilar-colors tbody'); this.model.on('change', _.throttle(this.render, 100), this); this.render(); }, render: function() { var count = 75, sorted = ColorCollection.getSortedIdsByDistanceTo(this.model, 'lowcost'), best = sorted.slice(0, count), worst = sorted.slice(-count); worst.reverse(); this.scrollContainers(); this.updateTBody(this.similarTBody, best); this.updateTBody(this.dissimilarTBody, worst); }, updateTBody: function(element, ids) { var children = element.children(), diff = ids.length - children.length, firstChild; while (diff > 0) { if (typeof firstChild === 'undefined') { firstChild = children.first(); } element.append(firstChild.clone()); diff--; } element.find('tr').each(function(idx) { var $this = $(this), color = ColorCollection.get(ids[idx]), colorName = color.get('name'), previewDiv = $this.find('.colorpreview'); previewDiv.css('background-color', color.get('hex')); previewDiv.text(colorName); $this.find('a').attr('href', '#' + colorName); }); element.addClass('hovered').delay(1000).queue( function(next) { $(this).removeClass('hovered'); next(); }); } }); return ColorEditView; });
$(".delete-contentType").on('click', function(event){ event.preventDefault(); if(!confirm('Are you sure you want to delete this contentType?')){ return 0; } $(this).text('deleting...').attr('disabled', true); $(this).parent('form').submit(); });
var Substance = require("substance"); var Document = Substance.Document; var Emphasis = Document.Annotation.extend({ name: "emphasis" }); // Html import // ----------- Emphasis.static.matchElement = function(el) { var tagName = el.tagName.toLowerCase(); return (tagName === 'i' || tagName === 'em'); }; module.exports = Emphasis;
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdCreateNewFolder(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M40 12c2.21 0 4 1.79 4 4v20c0 2.21-1.79 4-4 4H8c-2.21 0-4-1.79-4-4l.02-24c0-2.21 1.77-4 3.98-4h12l4 4h16zm-2 16v-4h-6v-6h-4v6h-6v4h6v6h4v-6h6z" /> </IconBase> ); } export default MdCreateNewFolder;
/** * JavaScript 队列 * 优先队列 * * 优先级别 1 > 2 > 3 */ function PriorityQueue() { let items = []; function PriorityElement(element, priority) { this.element = element; this.priority = priority; } this.enqueue = function (element, priority) { let priorityelement = new PriorityElement(element, priority); if (this.isEmpty()) { items.push(priorityelement) } else { let added = false; for (let i = 0; i < items.length; i++) { if (priorityelement.priority < items[i].priority) { items.splice(i,0,priorityelement) added = true; break; } } if(!added){ items.push(priorityelement) } } } this.dequeue = function () { return items.shift(); } this.front = function () { return items[0] } this.size = function () { return items.length } this.isEmpty = function () { return items.length == 0 } this.print = function () { console.log(JSON.stringify(items)) } } let queue = new PriorityQueue(); queue.enqueue("jack",10) queue.enqueue("tom",5) queue.enqueue("lisa",1) queue.enqueue("lily",1) queue.print()
import { isUndefined } from 'lodash'; export default function createReducer(initialState, handlers) { return function reducer(state = initialState, action) { if (Object.prototype.hasOwnProperty.call(handlers, action.type)) { return handlers[action.type](state, action); } return state; }; }
// =================================================== // =============== PARSING =========================== // =================================================== // Input // { links : [ {source: sourceName, dest : destName} * ] } // Output: let objcdv = { version: "0.0.1", _createGraph: function () { return { nodes: [], links: [], nodesSet: {}, addLink: function (link) { var source_node = this.getNode(link.source); source_node.source++; var dest_node = this.getNode(link.dest); dest_node.dest++; this.links.push({ // d3 js properties source: source_node.idx, target: dest_node.idx, // Additional link information sourceNode: source_node, targetNode: dest_node }) }, getNode: function (nodeName) { var node = this.nodesSet[nodeName]; if (node == null) { var idx = Object.keys(this.nodesSet).length; this.nodesSet[nodeName] = node = {idx: idx, name: nodeName, source: 1, dest: 0}; } return node }, updateNodes: function (f) { _.values(this.nodesSet).forEach(f) }, d3jsGraph: function () { // Sorting up nodes, since, in some cases they aren't returned in correct number var nodes = _.values(this.nodesSet).slice(0).sort((a, b) => a.idx - b.idx); return {nodes: nodes, links: this.links}; }, nodesStartingFromNode: function (node, {max_level = 100, use_backward_search = false, use_forward_search = true } = {} ) { // Figure out the neighboring node id's with brute strength because the graph is small var neighbours = {}; neighbours[node.index] = node; var nodesToCheck = [node.index]; let current_level = 0; while (Object.keys(nodesToCheck).length != 0) { var forwardNeighbours = []; var backwardNeighbours = []; let tmpNeighbours = {}; if (use_forward_search) { forwardNeighbours = this.links .filter((link) => link.source.index in neighbours) .filter((link) => !(link.target.index in neighbours)) .map((link) => { tmpNeighbours[link.target.index] = link.target; return link.target.index; }); } if (use_backward_search) { backwardNeighbours = this.links .filter((link) => link.target.index in neighbours) .filter((link) => !(link.source.index in neighbours)) .map((link) => { tmpNeighbours[link.source.index] = link.source; return link.source.index; }); } _.extend(neighbours, tmpNeighbours); nodesToCheck = forwardNeighbours.concat(backwardNeighbours); console.log("Nodes to check" + nodesToCheck); // Skip if we reached max level current_level++; if (current_level == max_level) { console.log("Reached max at level" + current_level); break; } } return _.values(neighbours); } }; }, _createPrefixes: function () { return { _prefixesDistr: {}, _sortedPrefixes: null, addName: function (name) { this._sortedPrefixes = null; var prefix = name.substring(0, 2); if (!(prefix in this._prefixesDistr)) { this._prefixesDistr[prefix] = 1; } else { this._prefixesDistr[prefix]++; } }, prefixIndexForName: function (name) { var sortedPrefixes = this._getSortedPrefixes(); var prefix = name.substring(0, 2); return _.indexOf(sortedPrefixes, prefix) }, _getSortedPrefixes: function () { if (this._sortedPrefixes == null) { this._sortedPrefixes = _.map(this._prefixesDistr, (v, k) => ({"key": k, "value": v})) .sort((a, b) => b.value - a.value) .map(o => o.key) } return this._sortedPrefixes } }; }, parse_dependencies_graph: function (dependencies) { var graph = this._createGraph(); var prefixes = this._createPrefixes(); dependencies.links.forEach((link) => { graph.addLink(link); prefixes.addName(link.source); prefixes.addName(link.dest); }); graph.updateNodes((node) => { node.weight = node.source; node.group = prefixes.prefixIndexForName(node.name) + 1 }); return graph } };
Bindings({ render(){ <div class="ui segment"> <h2 class="ui header">Bindings</h2> <a class="anchor active" id="BasicsBindings"></a> <p> We've used a few bindings here and there but what are they? Bindings are just shortcuts to make code cleaner, more readable, and succinct. There's nothing magical or scary about them. It's just a shortcut, plain and simple. Nothing stops you from writing the longer version of what the binding would do. </p> <p>For example, let's take a very simple binding. You could write the following:</p> <pre><code>Example({ message: 'Hello World', render() { <div>{this.message()}</div> } })</code></pre> <p>Or you could use the text binding:</p> <pre><code>Example({ message: 'Hello World', render() { <div b="text: message" /> } })</code></pre> <p>A more complex one is the value binding. For input boxes you typically end up writing a change handler function that updates some state. The input then listens for a change event and calls the change handler (one way bind from the input to the state). Finally the input may or may not have another one way binding from the state to the input. That's called a two-way binding.</p> <p>Instead of performing all those ceremonies over and over again, you can just use the value binding:</p> <pre><code>Example({ message: '', render() { <input b="value: message" /> } })</code></pre> <p>That's it. And again, nothing stops you from writing the longer version if you want to.</p> </div> } });
/** * Shopware 4.0 * Copyright © 2012 shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ /** * Shopware View Detail * * This is the detail-window to edit an accessory-group */ //{namespace name="backend/accessory/article/view/main"} //{block name="backend/article/view/accessory/detail/group_detail"} Ext.define('Shopware.apps.Article.view.accessory.detail.GroupDetail', { extend:'Enlight.app.Window', alias:'widget.accessory-main-group-detail', cls:'createWindow', modal: true, layout:'border', autoShow:true, border:0, width:600, height:220, stateful:true, stateId:'shopware-accessory-group-detail', footerButton: false, snippets: { groupDetailsNameLabel: '{s name=group_details/name_label}Name{/s}', groupDetailsDescriptionLabel: '{s name=group_details/description_label}Description{/s}', accessoryCancelButton: '{s name=cancel_button}Cancel{/s}', accessorySaveButton: '{s name=save_button}Save{/s}' }, title: '{s name=group_details/title}Group details{/s}', /** * This function creates the form-panel and adds a toolbar. */ initComponent:function () { var me = this; me.accessoryForm = me.createFormPanel(); me.dockedItems = [{ xtype: 'toolbar', ui: 'shopware-ui', dock: 'bottom', cls: 'shopware-toolbar', items: me.createButtons() }]; me.items = [me.accessoryForm]; me.callParent(arguments); }, /** * This function creates the form-panel. * If a record is set, it automatically loads the record into the form. * @return [object] accessoryForm - Ext.form.Panel */ createFormPanel: function(){ var me = this; var accessoryForm = Ext.create('Ext.form.Panel', { collapsible:false, split:false, name: 'accessory-form-panel', region:'center', defaults: { labelWidth: 155, labelStyle: 'font-weight: bold' }, bodyPadding:10, items:[ { xtype:'textfield', name:'name', fieldLabel: me.snippets.groupDetailsNameLabel, allowBlank:false, required: true }, { xtype:'textarea', name:'description', fieldLabel: me.snippets.groupDetailsDescriptionLabel, allowBlank:true }, { xtype: 'hidden', name: 'id' } ] }); if(me.record){ accessoryForm.loadRecord(me.record); } return accessoryForm; }, /** * This function creates the buttons to save or cancel the form-panel. * @return array buttons - Contains the buttons */ createButtons: function(){ var me = this; var buttons = ['->', { text: me.snippets.accessoryCancelButton, cls: 'secondary', scope:me, handler:me.destroy }, { text: me.snippets.accessorySaveButton, action:'saveGroup', cls:'primary' } ]; return buttons; } }); //{/block}
/** * MongoDB User Model * Author: Matthew Murphy */ var mongoose = require('mongoose'); var userSchema = require('./user.schema.server'); var q = require('q'); var bcrypt = require("bcrypt-nodejs"); var userModel = mongoose.model('ProjectUserModel', userSchema); // API Functions userModel.createUser = createUser; userModel.findUserById = findUserById; userModel.findUserByCredentials = findUserByCredentials; userModel.findUserByUsername = findUserByUsername; userModel.deleteUser = deleteUser; userModel.updateUser = updateUser; userModel.addWebsite = addWebsite; userModel.removeWebsite = removeWebsite; userModel.updateUrl = updateUrl; userModel.addFollower = addFollower; userModel.removeFollower = removeFollower; userModel.addFollowing = addFollowing; userModel.removeFollowing = removeFollowing; userModel.findUsersByIds = findUsersByIds; userModel.updatePassword = updatePassword; userModel.addRep = addRep; userModel.removeRep = removeRep; userModel.findUserByFacebookId = findUserByFacebookId; userModel.updateFacebookToken = updateFacebookToken; userModel.findUserByGoogleId = findUserByGoogleId; userModel.updateGoogleToken = updateGoogleToken; module.exports = userModel; function findUserByGoogleId(googleId) { return userModel.findOne({'google.id': googleId}); } function updateGoogleToken(userId, googleId, token) { var google = { id: googleId, token: token }; return userModel .update({_id: userId}, { $set : { google: google } }); } function updateFacebookToken(userId, facebookId, token) { var facebook = { id: facebookId, token: token }; return userModel .update({_id: userId}, { $set : { facebook: facebook } }); } function findUserByFacebookId(facebookId) { return userModel.findOne({'facebook.id': facebookId}); } function addRep(userId, repId) { return userModel.update({_id: userId}, { $addToSet: { reps: repId } }) } function removeRep(userId, repId) { return userModel.update({_id: userId}, { $pull: { reps: repId } }) } function updatePassword(userId, password) { var hashed = bcrypt.hashSync(password); return userModel.update({_id: userId}, { $set : { password: hashed } }) } function findUsersByIds(ids) { return userModel.find({_id: {$in: ids}}); } function addFollowing(userId, followerId) { return userModel.update({_id: userId}, { $addToSet: { following: followerId } }) } function removeFollowing(userId, followerId) { return userModel.update({_id: userId}, { $pull: { following: followerId } }) } function addFollower(userId, followerId) { return userModel.update({_id: userId}, { $addToSet: { followers: followerId } }) } function removeFollower(userId, followerId) { return userModel.update({_id: userId}, { $pull: { followers: followerId } }) } function updateUrl(userId, url) { return userModel.update({_id: userId}, { $set : { photo: url } }); } function removeWebsite(userId, websiteId) { return userModel .update({_id: userId}, { $pull : { websites: websiteId } }); } function addWebsite(userId, websiteId) { return userModel .update({_id: userId}, { $push : { websites: websiteId } }); } function findUserByUsername(username) { return userModel.findOne({username: username}); } function updateUser(userId, newUser) { delete newUser.password; delete newUser.username; return userModel.update({_id: userId}, { $set : { firstName: newUser.firstName, lastName: newUser.lastName, email: newUser.email, phone: newUser.phone } }); } function deleteUser(userId) { return userModel.remove({_id: userId}); } function findUserByCredentials(username, password) { return userModel .find({username: username}) .then(function (user) { if (!user) { return user; } if (user.username === username && bcrypt.compareSync(password, user.password)) { return user; } return null; }); } function findUserById(userId) { return userModel.findById(userId); } function createUser(user) { if (user.password) { user.password = bcrypt.hashSync(user.password); } return userModel.create(user); }
"use strict"; const messages = require("..").messages; const ruleName = require("..").ruleName; const rules = require("../../../rules"); const rule = rules[ruleName]; testRule(rule, { ruleName, config: [true], skipBasicChecks: true, fix: true, accept: [ { code: "" }, { code: "\n" }, { code: "a { color: pink; }\n" }, { code: "a { color: pink; }\r\n" }, { code: "a { color: pink; }\n\n\n" }, { code: "a { color: pink; }\r\n\r\n\r\n" } ], reject: [ { code: "a { color: pink; }", fixed: "a { color: pink; }\n", message: messages.rejected, line: 1, column: 18 }, { code: "a { color: pink; }\n\n\nb{ color: orange; }", fixed: "a { color: pink; }\n\n\nb{ color: orange; }\n", message: messages.rejected, line: 4, column: 19 }, { code: "a { color: pink; }\r\n\r\n\r\nb{ color: orange; }", fixed: "a { color: pink; }\r\n\r\n\r\nb{ color: orange; }\r\n", message: messages.rejected, line: 4, column: 19 }, { code: "&.active {\n top:\n .tab {}\n}", fixed: "&.active {\n top:\n .tab {}\n}\n", message: messages.rejected, line: 4, column: 1 }, { code: "&.active {\r\n top:\r\n .tab {}\r\n}", fixed: "&.active {\r\n top:\r\n .tab {}\r\n}\r\n", message: messages.rejected, line: 4, column: 1 } ] }); testRule(rule, { ruleName, config: [true], skipBasicChecks: true, syntax: "sugarss", fix: true, accept: [ { code: "a\n" }, { code: "a\r\n" } ], reject: [ { code: "a", fixed: "a\n", message: messages.rejected, line: 1, column: 1 }, { code: "body\n padding: 5% 2% 5%", fixed: "body\n padding: 5% 2% 5%\n", message: messages.rejected, line: 2, column: 17 }, { code: "body\r\n padding: 5% 2% 5%", fixed: "body\r\n padding: 5% 2% 5%\r\n", message: messages.rejected, line: 2, column: 17 } ] });
import fetch from "isomorphic-fetch"; import * as userDao from "../dao/users.js"; const fakingURL = "https://jsonplaceholder.typicode.com"; const URLS = { fetchAll: `${fakingURL}/users` }; function toJSON(fetchP) { return fetchP.then(checkStatus).then(parseJSON); } function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response; } else if (response.headers.get("content-type") === "application/json") { const error = new Error("content-type error,is not a json"); error.response = response; throw error; } else { const error = new Error(response.statusText); error.response = response; throw error; } } function parseJSON(response) { return response.json(); } function warrpData(json) { return { data: json }; } function warrpError(error) { return { error }; } export const getUsers = async () => { let list = await userDao.getUsers(); if (list.length) { return warrpData(list); } try { list = await toJSON(fetch(URLS.fetchAll)); list = list.map(user => { return { name: user.name, phone: user.phone, website: user.website, key: user.id }; }); list = await userDao.setUsers(list); return warrpData(list); } catch (e) { return warrpError(e); } }; export const addUser = async user => { return await userDao.addUser(user); }; export const deleteUser = async key => { return await userDao.deleteUser(key); }; export const uptadeUser = async user => { return await userDao.uptadeUser(user); };
(function (app, specieMap) { 'use strict'; app.controller('SpeciesDetailCtrl', function ($scope, $route, api, geolocation) { // Initialise geo-location var params = $route.current.params, species = specieMap[params.speciesId]; $scope.pos = {}; $scope.zoom = 8; $scope.radius = $route.current.params.radius || 10; $scope.name = params.speciesId; $scope.occurrences = {}; $scope.center = { lat: 0, lng: 0, zoom: $scope.zoom }; api.fetch('singleSpecies|' + species.guid, {}) .success(function(data, status, headers, config) { if (data.images && data.images.length) { $scope.image = data.images[0].largeImageUrl; } if (data.simpleProperties && data.simpleProperties.length) { $scope.description = data.simpleProperties[0].value; } }).error(function(data, status, headers, config) { console.log('Error', arguments); }); $scope.refresh = function () { params = $route.current.params; species = specieMap[params.speciesId]; if ($scope.pos.coords) { api.fetch('specieDetail', { params: { 'fq': 'species_guid:' + species.guid, 'pageSize': 100, 'flimit' : 0, //'sort' : 'count', 'radius': $scope.radius, 'lat' : $scope.pos.coords.latitude, 'lon' : $scope.pos.coords.longitude, 'facets': 'taxon_name' } }).success(function(data, status, headers, config) { $scope.occurrences = data.occurrences.reduce(function (obj, marker, index) { //we stupidly need a hash map Object here obj['m' + index] = { lat: marker.decimalLatitude, lng: marker.decimalLongitude, message: marker.collectionName, draggable: false }; return obj; }, {}); }).error(function(data, status, headers, config) { console.log('Error', arguments); }); } else { //not ready todo retry } }; geolocation.getCurrentPosition(function(pos) { $scope.pos = pos; $scope.center = { lat: $scope.pos.coords.latitude, lng: $scope.pos.coords.longitude, zoom: $scope.zoom }; $scope.refresh(); }); }); }(angular.module('botanApp'), specieMap));
var button1 = document.getElementById("button1"); var button2 = document.getElementById("button2"); var button3 = document.getElementById("button3"); var aPressed = false; var bPressed = false; var cPressed = false; document.addEventListener('keydown', pressed(a) { if(event.keyCode == 74) { alert('j was pressed'); } else if(event.keyCode == 73) { alert('i was pressed'); } else if(event.keyCode == 79) { alert('o was pressed'); } });
var app = app || {}; (function() { 'use strict'; app.NewWorkoutView = Backbone.View.extend({ el: '#main', template: _.template($('#newWorkoutTpl').html()), events: { 'click .js-circle': 'toggleCircle', 'click #selectWorkout': 'showWorkoutDropdown' }, initialize: function() { this.render(); }, render: function() { console.log('Rendered new workout'); // Just append the template to the main view, since the router toggles visibility this.$el.append(this.template()); }, toggleCircle: function(e) { e.target.classList.toggle('js-circle-filled-in'); }, showWorkoutDropdown: function() { $('#workoutDropdown').toggleClass('hide'); } }); })();
define(["./lib"], function(lib) { return { name: "function", noArgs: function(Dicta, callback) { var model = new Dicta(); model.read("../dicta/coretest/function/noArgs.dicta", function() { var a = model.get("a"); if (a != 1) { callback(false); return; } callback(true); }); }, constArgs: function(Dicta, callback) { var model = new Dicta(); model.read("../dicta/coretest/function/constArgs.dicta", function() { var a = model.get("a"); if (a != 3) { callback(false); return; } callback(true); }); }, varArgs: function(Dicta, callback) { var model = new Dicta(); model.read("../dicta/coretest/function/varArgs.dicta", function() { model.set("a", 1); model.set("b", 2); var c = model.get("c"); if (c != 3) { callback(false); return; } callback(true); }); }, localVar: function(Dicta, callback) { var model = new Dicta(); model.read("../dicta/coretest/function/localVar.dicta", function() { var b = model.get("b"); var a = model.get("a"); if (a != 1) { callback(false); return; } callback(true); }); }, globalVar: function(Dicta, callback) { var model = new Dicta(); model.read("../dicta/coretest/function/globalVar.dicta", function() { var b = model.get("b"); var a = model.get("a"); if (a != 2) { callback(false); return; } callback(true); }); }, declaration: function(Dicta, callback) { var model = new Dicta(); model.read("../dicta/coretest/function/declaration.dicta", function() { var a = model.get("a"); if (a != 1) { callback(false); return; } callback(true); }); }, global: function(Dicta) { var text = "b = parseInt(a);"; var model = new Dicta(); model.parse(text); model.set("a", "01"); var b = model.get("b"); if (b != 1) { return false; } return true; }, lib: function(Dicta) { var text = "c = Math.max(a, b);"; var model = new Dicta(); model.parse(text); model.set("a", 1); model.set("b", 2); var c = model.get("c"); if (c != 2) { return false; } return true; }, functionProp: function(Dicta, callback) { var model = new Dicta(); model.read("../dicta/coretest/function/functionProp.dicta", function() { var b = model.get("b"); if (b != 1) { callback(false); return; } callback(true); }); }, mutableArgs: function(Dicta, callback) { var model = new Dicta(); model.read("../dicta/coretest/function/mutableArgs.dicta", function() { var d = model.get("d"); var c = model.get("c"); d = model.get("d"); if (d != 1) { callback(false); return; } callback(true); }); }, external: function(Dicta, callback) { var model = new Dicta(); model.use(lib); model.read("../dicta/coretest/function/external.dicta", function() { var b = model.get("b"); if (b != 6) { callback(false); return; } callback(true); }); }, library: function(Dicta, callback) { var model = new Dicta(); model.read("../dicta/coretest/function/library.dicta", function() { model.set("x", 1); var a = model.get("a"); if (a != "1") { callback(false); return; } model.set("x", 2); var a = model.get("a"); if (a != "3") { callback(false); return; } callback(true); }); } }; });
function disconnect({services}) { services.live.disconnect(); } export default disconnect;
exports.version = '1.0.1'; var plugins = []; exports.use = function(plugin) { plugins.push(plugin); } exports.pluginInfo = function() { var a = []; for (var i = 0, len = plugins.length; i < len; ++i) { a.push(plugins[i].info()); } return a; }
/** * The decorator for adding `margin*` methods. */ export default ({x, y, left, right, top, bottom}) => Cls => { const prototype = Cls.prototype if (x) { prototype.marginX = () => x } if (y) { prototype.marginY = () => y } if (left) { prototype.marginLeft = () => left } if (right) { prototype.marginRight = () => right } if (top) { prototype.marginTop = () => top } if (bottom) { prototype.marginBottom = () => bottom } return Cls }
// Read config const env = global.env = require('../../config.json'); // Require all tests require('./test.example');
var searchData= [ ['sections2shell',['sections2shell',['../namespacesections2shell.html',1,'']]] ];
angular.module('taskMaster', ['angular-meteor', 'famous.angular']) .controller('mainController', ['$scope', function($scope){ $scope.myGridLayoutOptions = { dimensions: [1,3] }; $scope.items = [ {name: 'header', height: 50, color: 'yellow'}, {name: 'body', height: 'undefined', color: 'green'}, {name: 'footer', height: 100, color: 'blue'} ]; }]); Meteor.startup(function () { angular.bootstrap(document, ['taskMaster']); });
import './root_edit_panel.html'; import {Template} from 'meteor/templating'; /** * Template Helpers */ Template.RootEditPanel.helpers({}); /** * Template Helpers */ Template.RootEditPanel.events({}); /** * Template Rendered */ Template.RootEditPanel.rendered = function () { }; /** * Template Destroyed */ Template.RootEditPanel.destroyed = function () { };
'use strict'; var path = require('path'); var gulp = require('gulp'); var conf = require('./conf'); var browserSync = require('browser-sync'); var webpack = require('webpack-stream'); var $ = require('gulp-load-plugins')(); function webpackWrapper(watch, test, callback) { var webpackOptions = { resolve: { extensions: ['', '.ts'] }, watch: watch, module: { preLoaders: [{ test: /\.ts$/, exclude: /node_modules/, loader: 'tslint-loader'}], loaders: [{ test: /\.ts$/, exclude: /node_modules/, loaders: ['ng-annotate', 'awesome-typescript-loader']}] }, output: { filename: 'index.module.js' } }; if(watch) { webpackOptions.devtool = 'inline-source-map'; } var webpackChangeHandler = function(err, stats) { if(err) { conf.errorHandler('Webpack')(err); } $.util.log(stats.toString({ colors: $.util.colors.supportsColor, chunks: false, hash: false, version: false })); browserSync.reload(); if(watch) { watch = false; callback(); } }; var sources = [ path.join(conf.paths.src, '/app/index.module.ts') ]; if (test) { sources.push(path.join(conf.paths.src, '/app/**/*.spec.ts')); } return gulp.src(sources) .pipe(webpack(webpackOptions, null, webpackChangeHandler)) .pipe(gulp.dest(path.join(conf.paths.tmp, '/serve/app'))); } gulp.task('scripts', function () { return webpackWrapper(false, false); }); gulp.task('scripts:watch', ['scripts'], function (callback) { return webpackWrapper(true, false, callback); }); gulp.task('scripts:test', function () { return webpackWrapper(false, true); }); gulp.task('scripts:test-watch', ['scripts'], function (callback) { return webpackWrapper(true, true, callback); });
function hashPasswordForLocal(password) { var hashWordArray = CryptoJS.SHA512(password); return hashWordArray.toString(CryptoJS.enc.Base64); } function hashPasswordForSignin(password) { var hashWordArray = CryptoJS.SHA256(password); return hashWordArray.toString(CryptoJS.enc.Base64); } function decryptValue(str, password) { return CryptoJS.AES.decrypt(str,password).toString(CryptoJS.enc.Utf8); } function encryptValue(str, password) { return CryptoJS.AES.encrypt(str, password).toString(); }
import { CHANGE_SEARCH_RESULTS_COUNT } from '../constants'; const totalSearchResultsCount = (state = 0, action) => { switch(action.type) { case CHANGE_SEARCH_RESULTS_COUNT: return action.totalSearchResults; default: return state; } }; export default totalSearchResultsCount;
String.prototype.bind = function (obj) { var prop, reContent, reHref, reClass, result = this; for (prop in obj) { reContent = new RegExp('(<.*data-bind-content="' + prop + '".*>)(.*)(<.*>)', 'gi'), reHref = new RegExp('(<.*data-bind-href="' + prop + '")', 'gi'), reClass = new RegExp('(data-bind-class="' + prop + '")', 'gi'); result = result.replace(reContent, function (none, opening, content, closing) { content = obj[prop]; return opening + content + closing; }) .replace(reHref, function (none, content) { return content + ' href="' + obj[prop] + '"'; }) .replace(reClass, 'data-bind-class="' + obj[prop] + '"'); } return result; }; var str = '<a data-bind-content="name" data-bind-href="link" data-bind-class="name"></а>'; result = str.bind({ name: 'Elena', link: 'http://telerikacademy.com' }); console.log('Problem 2: ' + result);
define([ '../core', '../selector' ], function (jQuery) { jQuery.expr.filters.hidden = function (elem) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 } jQuery.expr.filters.visible = function (elem) { return !jQuery.expr.filters.hidden(elem) } })
import Filters from './FiltersComponent' export default Filters
var nodebb = require('../../nodebb'), db = nodebb.db, async = nodebb.async; var config = require('../../config'); var utils = require('../../utils'); var Marks = require('../marks'); module.exports = function (Article) { Article.createTopicMark = function (uid, tid, markTag, timestamp, callback) { db.getObject(config.db.root + ':topic:' + tid, function (err, oldTag) { async.series([ function (next) { db.setObject(config.db.root + ':topic:' + tid, { tag: markTag, marker: uid, timestamp: timestamp }, next); }, function (next) { db.sortedSetAdd(config.db.root + ':mark:' + markTag + ':topics', timestamp, tid, next); }, function (next) { if (oldTag) { db.sortedSetRemove(config.db.root + ':mark:' + oldTag.tag + ':topics', tid, function (err) { Marks.updateMarkCount(oldTag.tag); }); } Marks.updateMarkCount(markTag, next); }, function (next) { //send to generate list Article.pushToGenerate(tid, next); } ], callback); }) }; Article.markTopics = function (uid, tids, markTag, callback) { var curCid, timestamp = Date.now(); async.eachLimit(tids, 10, function (tid, next) { async.waterfall([ function (next) { utils.canMark(tid, uid, next); }, function (canMark, next) { if (!canMark) { next(new Error('[[error:no-privileges]]' + markTag)); } else { Marks.isExistsMark(markTag, next); } }, function (exists, next) { if (!exists) { next(new Error('[[portalmark:err_mark_tag_no_found,' + markTag + ']]')); } else { Article.createTopicMark(uid, tid, markTag, timestamp, next); } } ], function (err) { if (err) { return next(err); } // websockets.in('topic_' + tid).emit('event:topic_marked', { // tid: tid // }); // // websockets.in('category_' + curCid).emit('event:topic_marked', { // tid: tid // }); //TODO:sendNotificationToTopicOwner next(); }); }, callback); }; };
version https://git-lfs.github.com/spec/v1 oid sha256:ed95cd4e77ddc71b5ebd0ccea048bb0c2f47f1544f14b60d9488d0ff9852793b size 201427
version https://git-lfs.github.com/spec/v1 oid sha256:0b89504f5cc76db54e24eb4e0b42c70508e1f947ec0c3c87c9af43d68bfbb267 size 1463
/** * Core * Global tenant permissions methods and tenant initialization */ _.extend(Core, { tenantId: null, init: function () { let self; self = this; return Tracker.autorun(function () { let domain = document.location.hostname; let tenant; let tenantHandle; // keep an eye out for tenant change if (Meteor.userId()) tenantHandle = Meteor.subscribe('CurrentTenant'); else { tenantHandle = Meteor.subscribe('TenantForDomain', domain); } if (tenantHandle.ready()) { //domain = Meteor.absoluteUrl().split("/")[2].split(":")[0]; tenant = Tenants.findOne({ // domains: domain }); if (tenant) { self.tenantId = tenant._id; self.country = tenant.country; self.baseCurrency = tenant.baseCurrency; self.settings = tenant.settings; self.timezone = tenant.timezone; return self; } } }); }, getTenantId: function () { return this.tenantId; }, getTenantCountry: function () { return this.country; }, getTenantTaxRate: function () { let tax = Taxes.findOne({}); if (tax) { let rate = tax.rates[0]; return rate.rate; } }, getTenantBaseCurrency: function () { return this.baseCurrency; }, getTenantSettings: function () { return this.settings; }, }); /* * configure bunyan logging module for client * See: https://github.com/trentm/node-bunyan#levels * client we'll cofigure WARN as default */ let isDebug = "WARN"; if (Meteor.settings !== undefined) { if (Meteor.settings.public) { if (Meteor.settings.public.debug) { isDebug = Meteor.settings.public.debug; } } } levels = ["FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"]; if (typeof isDebug !== "boolean" && typeof isDebug !== undefined) { isDebug = isDebug.toUpperCase(); } if (!_.contains(levels, isDebug)) { isDebug = "INFO"; } Core.Log = bunyan.createLogger({ name: "core-client" }); Core.Log.level(isDebug); Tracker.autorun(function() { Meteor.userId(); }); /** * Startup TradeDepot Central * Init TDC client */ Meteor.startup(function () { Core.init(); });
define(['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-router', 'aurelia-path', 'aurelia-metadata'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaRouter, _aureliaPath, _aureliaMetadata) { 'use strict'; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (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) subClass.__proto__ = superClass; }; Object.defineProperty(exports, '__esModule', { value: true }); var TemplatingRouteLoader = (function (_RouteLoader) { function TemplatingRouteLoader(compositionEngine) { _classCallCheck(this, TemplatingRouteLoader); _get(Object.getPrototypeOf(TemplatingRouteLoader.prototype), 'constructor', this).call(this); this.compositionEngine = compositionEngine; } _inherits(TemplatingRouteLoader, _RouteLoader); _createClass(TemplatingRouteLoader, [{ key: 'loadRoute', value: function loadRoute(router, config) { var childContainer = router.container.createChild(), instruction = { viewModel: _aureliaPath.relativeToFile(config.moduleId, _aureliaMetadata.Origin.get(router.container.viewModel.constructor).moduleId), childContainer: childContainer, view: config.view || config.viewStrategy }, childRouter; childContainer.registerHandler(_aureliaRouter.Router, function (c) { return childRouter || (childRouter = router.createChild(childContainer)); }); return this.compositionEngine.createViewModel(instruction).then(function (instruction) { instruction.executionContext = instruction.viewModel; instruction.router = router; return instruction; }); } }]); exports.TemplatingRouteLoader = TemplatingRouteLoader = inject(CompositionEngine)(TemplatingRouteLoader) || TemplatingRouteLoader; return TemplatingRouteLoader; })(_aureliaRouter.RouteLoader); exports.TemplatingRouteLoader = TemplatingRouteLoader; });
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import { BrowserRouter as Router } from 'react-router-dom'; import '../node_modules/toastr/build/toastr.min.css' ReactDOM.render(( <Router> <App /> </Router>), document.getElementById('root')); registerServiceWorker();
const axios = require('axios'); const theStarUri = 'https://www.thestar.com'; const apiFeed = '/api/feed'; const apiEndpoint = theStarUri + apiFeed; module.exports = function getSection(section) { return axios.get(apiEndpoint + section) // TODO: Abstract away the domains, paths, & URLs .then((response) => { let data = response.data; let articles = data.items[0].assets; let elements = articles.map((article, index) => { if(index === 5) { return { title: 'How to pack like a pro for your next business trip, & a special deal, just for you.', subtitle: 'Partner Content', item_url: theStarUri + '/partner_content/betterbusinesstravel/2016/03/07/how-to-pack-like-a-pro-for-your-next-business-trip.html', image_url: theStarUri + '/content/dam/thestar/static_images/sponsoredsections/betterbusinesstravel/STAR_Mar07_VIA_Pack_Lightly_v2.jpg', buttons: [ { type: "web_url", url: theStarUri + '/partner_content/betterbusinesstravel/2016/03/07/how-to-pack-like-a-pro-for-your-next-business-trip.html', title: "Read" }, { type: "web_url", url: theStarUri + '/partner_content/betterbusinesstravel/2016/03/07/how-to-pack-like-a-pro-for-your-next-business-trip.html', title: "Visit Sponsor" }, { type: "web_url", url: theStarUri + '/partner_content/betterbusinesstravel/2016/03/07/how-to-pack-like-a-pro-for-your-next-business-trip.html', title: "Claim Deal" } ], }; } return { title: article.headline, subtitle: article.abstract, item_url: theStarUri + article.url, image_url: theStarUri + article.image.url, buttons: [ { type: "web_url", url: theStarUri + article.url, title: "Read" }, { "type":"element_share" } ], }; }); let message = { attachment: { type: "template", payload: { template_type: "generic", elements: elements.slice(0,10) // 10 Element Limit } } }; // console.log(JSON.stringify(message)); return new Promise((resolve, reject) => { return resolve(message); }); }); } // getSection('/news').then((message) => { // console.log('message', message); // })
import {Chart, BubbleController} from 'chart.js'; class Custom extends BubbleController { draw() { // Call bubble controller method to draw all the points super.draw(arguments); // Now we can do some custom drawing for this dataset. // Here we'll draw a box around the first point in each dataset, // using `boxStrokeStyle` dataset option for color var meta = this.getMeta(); var pt0 = meta.data[0]; const {x, y} = pt0.getProps(['x', 'y']); const {radius} = pt0.options; var ctx = this.chart.ctx; ctx.save(); ctx.strokeStyle = this.options.boxStrokeStyle; ctx.lineWidth = 1; ctx.strokeRect(x - radius, y - radius, 2 * radius, 2 * radius); ctx.restore(); } } Custom.id = 'derivedBubble'; Custom.defaults = { // Custom defaults. Bubble defaults are inherited. boxStrokeStyle: 'red' }; // Overrides are only inherited, but not merged if defined // Custom.overrides = Chart.overrides.bubble; // Stores the controller so that the chart initialization routine can look it up Chart.register(Custom);
/* * This encapsulates the search field and its events */ bbGrid.SearchView = Backbone.View.extend({ initialize: function (options) { this.events = { 'keyup input[name=search]': 'onSearch', }; this.view = options.view; if (this.view.css) { switch(this.view.css) { case 'bootstrap': this.templateBody = this.bootstrapTemplate; break; case 'foundation': this.templateBody = this.foundationTemplate; break; default: this.templateBody = this.defaultTemplate; } } else { this.templateBody = this.defaultTemplate; } }, //tagName: 'tr', defaultTemplate: '<input name="search" type="text" placeholder="<%=dict.search%>">', bootstrapTemplate: '<input name="search" type="text" placeholder="<%=dict.search%>" class="form-control input-med">', foundationTemplate: '<input name="search" type="text" placeholder="<%=dict.search%>">', onSearch: function (event) { var self = this, $el = $(event.target), text = $el.val(); this.view.collection.search(text); //this.view.collection.trigger('reset'); }, render: function () { var searchBarHtml = _.template(this.templateBody,{ dict: this.view.dict, }, bbGrid.templateSettings); this.$el.html(searchBarHtml);//.attr({colspan:this.colspan}); return this.$el; } });
import React from "react"; export default class Checkbox extends React.Component{ render(){ return ( <div className="checkb"> <input className="check" type="checkbox" value="1" name="" id="check1"/> <label htmlFor="check1" onClick={this.props.check}><span>{this.props.content}</span></label> </div> ); } }
'use strict'; // FUNCTIONS // var exp = Math.exp; // MGF // /** * FUNCTION: mgf( x, a, b ) * Evaluates the moment-generating function (MGF) for a uniform distribution with minimum support `a` and maximum support `b` at a value `t`. * * @param {Number} t - input value * @param {Number} a - minimum support * @param {Number} b - maximum support * @returns {Number} evaluated MGF */ function mgf( t, a, b ) { var ret; if ( t === 0 ) { return 1; } // Case: t not equal to zero ret = exp( t * b ) - exp( t * a ); ret /= t * ( b - a ); return ret; } // end FUNCTION mgf() // EXPORTS // module.exports = mgf;
'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise('/'); // Home state routing $stateProvider. state('home', { url: '/', templateUrl: 'modules/core/views/home.client.view.html' }); } ]);
var path = require('path'); var fs = require('fs'); // hide warning // var emitter = require('events'); emitter.defaultMaxListeners = 20; var appRoot = 'src/'; var pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8')); var paths = { root: appRoot, source: appRoot + '**/*.js', html: appRoot + '**/*.html', style: 'styles/**/*.css', output: 'dist/', doc:'./doc', sample: 'sample', e2eSpecsSrc: 'test/e2e/src/*.js', e2eSpecsDist: 'test/e2e/dist/', packageName: pkg.name, useTypeScriptForDTS: false, importsToAdd: [], sort: true }; paths.ignore = ['aurelia-keycloak.js']; paths.files = [ paths.source ]; module.exports = paths;
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; export var ProxyService = (function () { function ProxyService(http) { this.http = http; } ProxyService.prototype.getUsers = function () { return this.http.get('https://api.github.com/users'); }; ProxyService.decorators = [ { type: Injectable }, ]; /** @nocollapse */ ProxyService.ctorParameters = function () { return [ { type: Http, }, ]; }; return ProxyService; }()); //# sourceMappingURL=proxy.service.js.map
'use strict' const http = require('http') const autocannon = require('../autocannon') const server = http.createServer(handle) server.listen(0, startBench) function handle (req, res) { const body = [] // this route handler simply returns whatever it gets from response req .on('data', chunk => body.push(chunk)) .on('end', () => res.end(Buffer.concat(body))) } function startBench () { const url = 'http://localhost:' + server.address().port autocannon({ url: url, requests: [ { // let's create a new user method: 'POST', path: '/users', body: JSON.stringify({ firstName: 'Jane', id: 10 }), onResponse: (status, body, context) => { if (status === 200) { context.user = JSON.parse(body) } // on error, you may abort the benchmark } }, { // now we'll give them a last name method: 'PUT', setupRequest: (req, context) => ({ ...req, path: `/user/${context.user.id}`, body: JSON.stringify({ ...context.user, lastName: 'Doe' }) }) } ] }, finishedBench) function finishedBench (err, res) { console.log('finished bench', err, res) } }
'use strict'; var winston = require('winston'); module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.addColumn('settings', 'company_logo', { type: Sequelize.STRING(255), allowNull: false, defaultValue: '/admin/images/mago.png', after: 'company_url' }) .then(function (success) { return queryInterface.addColumn('settings', 'company_name', { type: Sequelize.STRING(45), allowNull: false, defaultValue: "MAGOWARE", after: 'company_url' }) .catch(function (err) { winston.error('Adding column settings.company_name failed with error message: ', err.message); }); }).catch(function (err) { winston.error('Adding column settings.company_logo failed with error message: ', err.message); }); }, down: function (queryInterface, Sequelize) { return queryInterface.removeColumn('settings', 'company_logo').then(function (success) { return queryInterface.removeColumn('settings', 'company_name') .catch(function (err) { winston.error('Dropping column settings.company_name failed with error message: ', err.message); }); }).catch(function (err) { winston.error('Dropping column settings.company_logo failed with error message: ', err.message); }); } };
var webpack = require('webpack'); var path = require('path'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var dirname = process.cwd(); module.exports = { entry: { vendor: ['underscore'], main: path.resolve(dirname, 'src/index.js') }, output: { path: path.resolve(dirname, 'assets'), filename: 'js/[name]-[chunkhash:8].js', chunkFilename: 'js/chunks/chunk-[id]-[chunkhash:8].js' }, module: { rules: [{ test: /\.less$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: [{ loader: 'css-loader' }, { loader: 'less-loader' }] }) }] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: ['vendor', 'manifest'], minChunks: Infinity }), new HtmlWebpackPlugin({ filename: path.resolve(dirname, 'assets/index.html'), template: path.resolve(dirname, 'config/index.html'), chunks: ['manifest', 'vendor', 'main'] }), new ExtractTextPlugin("css/[name]-[contenthash:8].css"), ] }
import { eventChannel } from 'redux-saga'; import ipc from '~shared/data/ipc'; const getAlbumsCollectionApi = (worker) => { const getAlbumsCollectionInfo = () => worker.call({ type: ipc.GET_ALBUMS_COLLECTION_INFO, }); const findAlbumInCollectionByCid = cid => worker.call({ type: ipc.FIND_ALBUM_IN_COLLECTION_BY_CID, payload: cid, }); const findAlbumsInCollectionByCids = cids => worker.call({ type: ipc.FIND_ALBUMS_IN_COLLECTION_BY_CIDS, payload: cids, }); const findOutdatedAlbumsInCollection = period => worker.call({ type: ipc.FIND_OUTDATED_ALBUMS_IN_COLLECTION, payload: period, }); const findAlbumsInCollection = async (payload) => { await worker.call({ type: ipc.OPEN_ALBUMS_STREAM, payload, }); return eventChannel((emitt) => { const handleMessage = ({ data }) => { const { type, payload: messagePayload, errorMessage } = data; if (type === ipc.ALBUMS_STREAMED) { if (errorMessage) { emitt({ error: new Error(errorMessage), }); } else { emitt({ albums: messagePayload }); } } }; worker.addEventListener('message', handleMessage); return () => { worker.removeEventListener('message', handleMessage); worker.call({ type: ipc.CLOSE_ALBUMS_STREAM, }); }; }); }; const saveAlbumIfNotExists = payload => worker.call({ type: ipc.SAVE_ALBUM_IF_NOT_EXISTS, payload, }); const saveOrUpdateAlbum = payload => worker.call({ type: ipc.SAVE_OR_UPDATE_ALBUM, payload, }); const saveOrUpdateAlbums = payload => worker.call({ type: ipc.SAVE_OR_UPDATE_ALBUMS, payload, }); const deleteAlbumsFromCollection = cids => worker.call({ type: ipc.DELETE_ALBUMS_IN_COLLECTION_BY_CIDS, payload: cids, }); return { saveAlbumIfNotExists, saveOrUpdateAlbum, saveOrUpdateAlbums, findAlbumInCollectionByCid, findAlbumsInCollectionByCids, findOutdatedAlbumsInCollection, findAlbumsInCollection, deleteAlbumsFromCollection, getAlbumsCollectionInfo, }; }; export default getAlbumsCollectionApi;
// https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET const { createRequest } = require('./request'); const token = (corpid, corpsecret) => { return createRequest('GET', `/gettoken?corpid=${corpid}&corpsecret=${corpsecret}`) }; module.exports = { token, };
/** * Created by ogi on 27.05.16. */ module.exports = function (source) { // console.log("start reactIntlJson-loader source:", source); this.cacheable && this.cacheable(); var value = typeof source === "string" ? JSON.parse(source) : source; // console.log(" plugin value:", value); var result = {}; value.map(function (e) { result [e.id] = e.defaultMessage; }) // console.log(" plugin result:", result); // this.value = [value]; return "module.exports = " + JSON.stringify(result, undefined, "\t") + ";"; }
/*global define*/ define( ['marionette','tpl!templates/login.tmpl','models/Login'], function (Marionette, tmpl, Login) { 'use strict'; return Marionette.ItemView.extend({ template: tmpl, className: 'loginContainer', events: { 'change [name]' : 'updateModel', 'submit #login-form' : 'verify' }, initialize: function() { this.model = new Login(); Backbone.Validation.bind(this); }, updateModel: function(ev) { this.model.set($(ev.currentTarget).attr('name'), $(ev.currentTarget).val()); if (this.submit) { this.doValidate(); } }, doValidate: function() { this.model.set('valid', this.model.validate()); this.render(); }, verify: function() { // Verify the form is filled out correctly. this.submit = true; if (!this.model.isValid()) { this.doValidate(); return false; } $(this.el).find('#login-form').submit(); } }); } );
define([ 'require', './applications-total-weekly', '../mixins/authorityhelpers', 'extensions/models/group' ], function (require, Applications, AuthorityHelpersMixin, Group) { /** * Retrieves data for a specific licence, grouped by authority, * for the "top 5" authorities */ var LicenceApplications = Applications.extend({ model: Group, queryParams: function () { return { group_by: 'licenceUrlSlug', limit: 5, sort_by: '_count:descending', collect: ['authorityName', 'licenceName'] }; }, queryId: 'applications-top5licences-weekly', comparator: function (a, b) { // sort by last value var aVal = a.get('values').last().get('_count'); var bVal = b.get('values').last().get('_count'); return aVal < bVal ? 1 : aVal > bVal ? -1 : 0; }, parse: function (response) { var data = []; _.each(response.data, function (group) { var attributes = { id: group.licenceUrlSlug, values: group.values }; if (group.licenceName) { attributes.title = group.licenceName[0]; } else { attributes.title = group.licenceUrlSlug; } if (group.authorityName) { var authorityName = group.authorityName[0] attributes.subTitle = this.getAuthorityShortName(authorityName); } data.push(attributes); }, this); return data; } }); _.extend(LicenceApplications.prototype, AuthorityHelpersMixin); return LicenceApplications; });
/*! * 页面目录生成器. * 比如,我们有如下代码: <article class="abc"> <h1>OAuth 1.0 的认证流程</h1> <h2>OAuth 2.0 的认证流程</h2> <h3>OAuth 3.0 的认证流程</h3> </article> <div id="catalog"></div> 要生成目录,按如下方式初始化: $.catalog("#catalog", ".abc"); * @since: 1.0.0 2017-03-26 * @author Way Lau <https://waylau.com> */ (function($) { "use strict"; $.catalog = function(selector, target) { $(target + " :header").each(function(i,item){ var tag = $(item).get(0).localName; $(item).attr("id","wow"+i); $(selector).append('<a class="new'+tag+'" href="#wow'+i+'">'+$(this).text()+'</a></br>'); $(".newh1").css("margin-left",0); $(".newh2").css("margin-left",5); $(".newh3").css("margin-left",10); $(".newh4").css("margin-left",15); $(".newh5").css("margin-left",20); $(".newh6").css("margin-left",25); }); }; })(jQuery);
import React from "react"; import Jumbotron from "./HelloWorld/Jumbotron" export default class HelloWorld extends React.Component { constructor(){ super(); this.state = {name: ""}; } changeName(e){ this.setState({name: e.target.value}); } render() { return ( <main> <Jumbotron name={this.state.name} /> <input onChange={this.changeName.bind(this)}/> </main> ); } }
'use strict'; const _ = require('lodash'); // Get attachments and cache them // function get_attachments(data, ids) { let cache = data.params.rpc_cache.sandbox.attachments; if (!cache) { cache = data.params.rpc_cache.sandbox.attachments = {}; } let attachments = {}; let pending = []; _(ids).uniq().sort().forEach(function (id) { if (!cache.hasOwnProperty(id)) { pending.push(id); attachments[id] = null; } else { attachments[id] = cache[id]; } }); let result = data.params.rpc_cache.get('common.content.attachments', { ids: pending }); if (result?.attachments) { pending.forEach(function (id) { attachments[id] = cache[id] = result.attachments[id]; }); } return attachments; } N.wire.once('init:parser', function attachment_plugin_init() { const sizes = '$$ JSON.stringify(N.config.users.uploads.resize) $$'; N.parser.addPlugin( 'attachment:fetch_attachment_info', function (parser) { parser.bus.on('ast2html', function fetch_attachment_data(data, callback) { if (!data.params.rpc_cache) { callback(); return; } // find all images that point to an attachment and set data-nd-media-id attr data.ast.find('.image').each(function () { let $attach = $(this); let match = N.router.matchAll($attach.attr('src')).find(match => match.meta.methods.get === 'users.media'); if (!match) return; $attach.attr('data-nd-media-id', match.params.media_id); // Get a size from img alt attribute, e.g.: // - ![md](link) // - ![arbitrary text|md](link) // let alt = $attach.attr('alt') || ''; let pos = alt.lastIndexOf('|'); let size; if (pos !== -1) { size = alt.slice(pos + 1).trim(); alt = alt.slice(0, pos); } else { size = alt.trim(); alt = ''; } if (sizes[size]) { $attach.attr('alt', alt); } else { size = 'sm'; } $attach.data('nd-media-size', size); }); // Fetch all images // let refs = []; data.ast.find('[data-nd-media-id]').map(function () { refs.push($(this).data('nd-media-id')); }); let attachments = get_attachments(data, refs); data.ast.find('[data-nd-media-id]').each(function () { let $attach = $(this); let media_id = $attach.data('nd-media-id'); // attachments[media_id] could be: // - object { type, file_name } - if attachment exists // - undefined - if attachment does not exist // - null - if we don't have that information yet // if (attachments[media_id]) { $attach.data('nd-media-type', attachments[media_id].type); $attach.data('nd-media-filename', attachments[media_id].file_name); } else if (attachments[media_id] === null) { $attach.data('nd-media-placeholder', true); } }); callback(); }); } ); N.parser.addPlugin( 'attachment', require('nodeca.core/lib/parser/plugins/attachment')(N, { types: '$$ JSON.stringify(N.models.users.MediaInfo.types) $$' }) ); });
'use strict'; /** * Approve Videos Controller */ angular.module("nodeVideoCMSAdmin.video").controller("ApproveVideosCtrl", function($scope){ $scope.title = "Approve Videos Controller" });
{ "bitwise" : false, "curly" : true, "eqeqeq" : true, "forin" : true, "immed" : true, "indent" : 4, "latedef" : true, "newcap" : true, "noarg" : true, "noempty" : true, "nomen" : true, "nonew" : true, "onevar" : true, "plusplus" : false, "quotmark" : "single", "regexp" : true, "strict" : true, "undef" : true, "unused" : true, "white" : false, "trailing" : true, "node" : true, "maxlen" :80 }
'use strict' // var speed = require('./second') // speed.set('dracontic-year', 'second', 1 / 3.3391244e-8) // module.exports = speed module.exports = ['dracontic-year', 'second', 1 / 3.3391244e-8]
export default function request() { }
/** * Created by duoyi on 2016/9/8. */ /** * Created by duoyi on 2016/9/8. */ import $ from 'jquery' import html from './template.html' import datepicker from '../../../componment/datepicker' import dropdown from '../../../componment/dropdown' import api from 'api' let Timer; let Timer2; export default { template: html, replace: true, props: { }, data () { return { /**商品*/ GoodInfo:{}, goodName:"", goodPinyin:"", danWei:"", //danwei count_jian:"", //件數 price:"", //單價 count_weight:"", //数量 packFee:"", //包装费 weightFee:"", //过磅费 supplier:"", //供货商 total:"", //合计金额 goodCode:'', goodIDList:[], //商品搜索列表 goodNameList:[], //商品搜索列表 goodSpellList:[], //商品搜索列表 selectGoodList:[], delGoodList:-1, beginDate:'', endDate:'', goodSaleList:[] } }, computed:{ }, ready(){ var self = this; $('body').on('click',function () { self.goodIDList=[]; self.goodNameList=[]; self.goodSpellList=[]; }) }, methods:{ //查找商品 id spell searchGood(key,cb){ var self = this; clearTimeout(Timer); Timer=setTimeout(function () { api.searchGoods(key,function (data) { cb&&cb(data.goods); }) },500) }, goodRender(item){ this.GoodInfo=item; }, //根据id searchGoodByName(key){ var self = this; this.searchGood(key,function (data) { self.goodNameList=data }) }, searchGoodByID(key){ var self = this; this.searchGood(key,function (data) { self.goodIDList=data }) }, searchGoodBySpell(key){ var self = this; this.searchGood(key,function (data) { self.goodSpellList=data }) }, checkList(){ var self = this; api.checkGoodsSale({ startDate:self.beginDate, endDate:self.endDate, supplier:self.GoodInfo.supplier },function (data) { self.goodSaleList=data.list }) }, //添加商品 /*add(){ if(this.GoodInfo.name&&this.GoodInfo.spell&&this.price&&(this.count_jian||this.count_weight) &&this.GoodInfo.supplier){ this.selectGoodList.push({ 'id':this.GoodInfo.id, "spell": this.GoodInfo.spell, "name": this.GoodInfo.name, "unit": this.GoodInfo.unit, "weighFee": this.GoodInfo.weighFee, "packFee": this.GoodInfo.packFee, "supplier": this.GoodInfo.supplier, price:this.price, count_jian:this.count_jian, count_weight:this.count_weight, //todo:计算 total:this.getGoodTotal(this.GoodInfo.unit,this.price,this.count_jian,this.count_weight,this.GoodInfo.packFee,this.GoodInfo.weighFee) }) this.GoodInfo={}; this.count_jian=""; this.price=""; this.count_weight="" ; }else { alert('商品信息不全') } },*/ //计算总价 toggleSelect(index){ }, render(index){ /*this.goodName=this.selectGoodList[index].goodName; this.goodPinyin=this.selectGoodList[index].goodPinyin; this.price=this.selectGoodList[index].price; this.danWei=this.selectGoodList[index].danWei; this.count_jian=this.selectGoodList[index].count_jian; this.count_weight=this.selectGoodList[index].count_weight; this.weightFee=this.selectGoodList[index].weightFee; this.packFee=this.selectGoodList[index].packFee; this.supplier=this.selectGoodList[index].supplier;*/ }, //删除商品 del(){ for(let i=this.delGoodList.length;i--;){ this.selectGoodList.splice(this.delGoodList[i],1); this.delGoodList=[] } }, //修改商品 correct(){ } }, ready (){ }, components : { datepicker, dropdown } }
import { Platform, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'black', ...Platform.select({ ios: { paddingTop: 64 }, android: { paddingTop: 64 } }), ...Platform.select({ ios: { marginBottom: 55 }, android: { marginBottom: 5 } }), }, textInput: { backgroundColor: 'white', ...Platform.select({ ios: { height: 35 }, android: { height: 48 } }) }, searchboxBorder: { borderRadius: 3, backgroundColor: 'white', paddingHorizontal: 3 }, searchbox: { backgroundColor: '#191919', paddingHorizontal: 16, paddingVertical: 8, marginBottom: 16 }, seperator: { marginTop: 10, backgroundColor: '#8E8E8E' } }); export default styles;
'use strict'; require('./_edit-user.scss'); module.exports = { template: require('./edit-user.html'), controller: ['$log', 'profileService','authService', EditUserController], controllerAs: 'editUserCtrl', bindings: { user: '<', changeEdit: '=' } }; function EditUserController($log, profileService, authService){ $log.debug('EditUserController'); this.updateUserInfo = function(){ $log.debug('editUserCtrl.updateUserInfo()'); profileService.updateUserInfo(authService.currentUserID, this.user) .then(() => { this.changeEdit.showEditProfile = false; $log.log('user updated'); }) .catch(err => { $log.error(err.message); }); }; }
/*** * Excerpted from "Mastering Dojo", * published by The Pragmatic Bookshelf. * Copyrights apply to this code. It may not be used to create training material, * courses, books, articles, and the like. Contact us if you are in doubt. * We make no guarantees that this code is fit for any purpose. * Visit http://www.pragmaticprogrammer.com/titles/rgdojo for more book information. ***/ /* * Copyright (c) 2000-2008, Vista Information Technologies, Inc. * Use, modification, and distribution subject to terms of license "Vista Information Technologies, Inc., - Browser Application Framework - BSD License". */ function(){ function getWsoInstance( wsoDefId, //identifier for the type of WSO to return dataQuery //the data to fill the WSO ){ var wsoDef= WsoDefinitionManager.get(wsoDefId); var data= DataManager.get(dataQuery); return new WSO(wsoDef, data); } var fileCommandItem= { id: "file", type: baf.commandType.submenu, order: 100, group: baf.commandGroup.top, text: "File"}; var saveCommandItem= { id: "save", type: baf.commandType.command, order: 160, group: baf.commandGroup.save, text: "Save"}; var saveAsCommandItem= { id: "saveAs", type: baf.commandType.command, order: 170, group: baf.commandGroup.save, text: "Save As..."}; var menu= { file: { save: 0, saveAs: 0, saveAll: 0, close: 0, closeAll: 0, logoff: 0, switchUser: 0, }, edit: 0, //etc... }; /* /<document-root> /baf /command /data /dijit /test /mocks /services /wso /obe /test */ obe.test.data.command.set001.commandItems= { identifier: "id", label: "text", items: [{ id: "file", type: baf.commandType.submenu, text: "File", order: 1000 },{ id: "save", type: baf.commandType.command, text: "Save", order: 1520, group: "save" } //et cetera.... ] }; obe.test.data.command.set001.mainMenu= { file: { save: 0, saveAll: 0, saveAll: 0, close:0, closeAll: 0, send: { sendToContact: 0, sendToList: 0 }, logoff: 0, switchUser: 0 }, edit: { //et cetera.... } //et cetera.... }; var aStatusBar= new obe.Status(); aStatusBar.createStaticPane("message", {"class": "statusMessage"}); aStatusBar.createStaticPane("userName", {"class": "statusUserName", style: "width: 20em"}); aStatusBar.createStaticPane("role", {"class": "statusRole", style: "width: 10em"}); var junk = { //begin a singe WSO definition tid: 1, //the type identifier size: ["51em", "25em"], //the w x h of this WSO "class": "crf", //the HTML class of this WSO requires: [ //the classes this WSO uses "baf.dijit.StaticText"], children: { //the contained widgets title: [ //each child is an object in the hash "baf.dijit.StaticText", //[0] => the class { //[1] => ctor args "class": "crfTitle", posit: { t: "1em", h: "5em", l: "1em", w: "10em" }, q: "tl", text: "Demographics" }, { //[2] => children of this child //et cetera... //therefore, forming a hierarchy! } ], //end the child named 'title' someOtherChild: [ //et cetera... ] //end the child named 'someOtherChild' } } ; obe.test.data.metadata.set002.metadata= [ { tid: 1, size: ["51em", "25em"], "class": "crf", requires: [baf.dijit.StaticText], children: { tl: [ "baf.dijit.StaticText", { //ctor args for baf.dijit.StaticText style: "background-color: #D0D0D0;", posit: {t:"1em", h:"5em", l:"1em", w:"10em"}, q: "tl", text: "top-left" } ], tc: [ "baf.dijit.StaticText", { //ctor args for baf.dijit.StaticText style: "background-color: #D0D0D0;", posit: { t: "1em", h: "5em", l: "12em", w: "10em" }, q: "tc", text: "top-center" } ], tr: [] } }]; }
less = { env: "development", // or "production" async: false, // load imports async fileAsync: false, // load imports async when in a page under // a file protocol poll: 1000, // when in watch mode, time in ms between polls functions: {}, // user functions, keyed by name dumpLineNumbers: "comments", // or "mediaQuery" or "all" relativeUrls: true,// whether to adjust url's to be relative // if false, url's are already relative to the // entry less file rootpath: "/DataSpotGhent/public/"// a path to add on to the start of every url //resource };
'use strict'; module.exports = function buildTask(gulp, plugins, config) { gulp.task('clean', () => plugins.del([config.dest.base])); <% if(projectType == 'wp-with-fe') { %> gulp.task( 'build', plugins.sequence( 'clean', 'styles-build', 'lint-js', 'scripts-build', 'vendor-build' ) );<% } else { %> gulp.task( 'build', plugins.sequence( 'clean', 'styles-build', 'lint-js', 'scripts-build', 'vendor-build', 'templates-build', 'validate-html' ) );<% } %> };
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var A1 = require('./A1'); var A2 = (function (_super) { __extends(A2, _super); function A2() { _super.apply(this, arguments); } A2.prototype.a2 = function () { return this.a1() + "a2"; }; return A2; })(A1); module.exports = A2; //# sourceMappingURL=A2.js.map
/** * This source file is subject to the license that is bundled with this package in the file LICENSE. */ (function () { "use strict"; var $button = $("button"); var $grid = $(".grid").isotope({ itemSelector: ".grid-item", layoutMode: "fitRows" }); $button.on('click', function () { $button.removeClass("active"); var cssClass = $(this).data("filter"); var filter = cssClass !== "*" ? "." + cssClass : cssClass; $grid.isotope({ filter: filter }); $(this).addClass("active"); }); })();
import React from 'react' import { connect } from 'react-redux' import io from 'socket.io-client' import Radium, { StyleRoot } from 'radium' import Players from './Player/Players' import style from './style/liveplayer' class LivePlayer extends React.Component { constructor (props) { super(props) this.state = { playing: false, song: '' } this.togglePlay = this.togglePlay.bind(this) } togglePlay () { this.setState({ playing: !this.state.playing }) } componentDidMount () { // const socket = io('http://localhost:5050') const socket = io() socket.on('news', function (data) { this.setState({ song: data.hello }) }.bind(this)) } render () { let element if (this.state.playing) { element = (<svg fill="#fff" viewBox="0 0 24 24" height="100%" xmlns="http://www.w3.org/2000/svg"> <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/> <path d="M0 0h24v24H0z" fill="none"/> </svg>) } else { element = (<svg fill="#fff" viewBox="0 0 24 24" height="100%" xmlns="http://www.w3.org/2000/svg"> <path d="M8 5v14l11-7z"/> <path d="M0 0h24v24H0z" fill="none"/> </svg>) } return ( <StyleRoot> <div style={{ display: 'flex', width: '100vw', justifyContent: 'flex-start', alignItems: 'center', position: 'absolute', left: 0, top: 0 }}> <Players /> <div style={style.song}> {this.state.song} </div> </div> </StyleRoot> ) } } const mapStateToProps = (state) => { return { // fuck: state.searchTerm } } LivePlayer = Radium(LivePlayer) export default connect(mapStateToProps)(LivePlayer)
(function(Snap, window, undefined) { "use strict"; var stage; var $unselectall = document.getElementById('unselectall'); var options = { onselect:function() { console.log('selected!'); }, onunselect:function() { console.log('un-selected!'); } }; var elements = []; var init = function() { // elements.push(stage.rect(10,10, 300, 400, 5, 5)); elements.push(stage.circle(300,300, 70)); for (var i=0; i<elements.length; i++) { elements[i].controllable(options); } }; $unselectall.onclick = function() { for (var i=0; i<elements.length; i++) { var c = elements[i].data('containerObject'); c.hideControls(); } } window.onload = function() { stage = new Snap("#demo"); init(); }; })(Snap, window);
/** * CI.Storage.Session class with * @module CI * @submodule Storage * @class CI.Storage.Session * @static */ (function(CI) { var Storage = Storage || {}; CI.Storage = CI.Storage || Storage /** * Decription * @method addItemToLocalStorage * @param {string} Key to store the item under * @param {object} the object to store * @return * @since 1.9.0 */ function Session() {} Session.prototype.addItem = function(key, object) { if (CI.Storage.canIUserWebstorage()) { sessionStorage.setItem(key, object); return "Success"; } else { return 'Sorry! No Web Storage support'; } } /** * Decription * @method getItemFromLocalStorage * @param {string} Key * @return {object} The object * @since 1.9.0 */ Session.prototype.getItem = function(Key) { if (CI.Storage.canIUserWebstorage()) { return sessionStorage.getItem(Key); } else { return 'Sorry! No Web Storage support'; } } /** * Decription * @method removeItemFromLocalStorage * @param {string} Key * @since 1.9.0 */ Session.prototype.removeItem = function(Key) { if (CI.Storage.canIUserWebstorage()) { sessionStorage.removeItem(Key); return "Success"; } else { return 'Sorry! No Web Storage support'; } } /** * Decription * @method getAllKeysfromLocalStorage * @return {array} Array of Keys * @since 1.9.0 */ Session.prototype.getAllKeys = function() { if (CI.Storage.canIUserWebstorage()) { return Object.keys(sessionStorage); } else { return 'Sorry! No Web Storage support'; } } CI.Storage.Session = Session; })(CI = CI || {}); if (!CI) { var CI; }
"use strict"; var test = require('../test').module('util/oo'); var oo = require('../../util/oo'); function A() {} oo.initClass(A); A.prototype.bla = function() { return "bla"; }; test("Class.extend without a protoype", function(t) { var B = A.extend(); var b = new B(); t.equal(b.bla(), 'bla', 'B should have inherited method A#bla().'); t.end(); }); test("Class.extend with a protoype object", function(t) { var B = A.extend({ blupp: function() { return "blupp"; } }); var b = new B(); t.equal(b.blupp(), 'blupp', 'B should have a prototype function blupp().'); t.end(); }); test("Class.extend with static properties", function(t) { var B = A.extend({ static: { name: "foo" } }); t.equal(B.static.name, 'foo', 'B should have a static property "name".'); t.end(); }); test("Class.extend with a ChildClass", function(t) { function B() {} A.extend(B); var b = new B(); t.equal(b.bla(), 'bla', 'B should have inherited method A#bla().'); t.end(); }); test("Class.extend with a ChildClass and a prototype object", function(t) { function B() {} A.extend(B, { blupp: function() { return "blupp"; } }); var b = new B(); t.equal(b.blupp(), 'blupp', 'B should have a prototype function blupp().'); t.end(); }); test("Class.extend with a ChildClass and a Prototype function", function(t) { function B() {} A.extend(B, function() { //eslint-disable-next-line no-invalid-this this.blupp = function() { return "blupp"; }; }); var b = new B(); t.equal(b.blupp(), 'blupp', 'B should have a prototype function blupp().'); t.end(); }); test("Legacy: Class.extend with a ChildClass with ChildClass.Prototype", function(t) { function B() {} B.Prototype = function() { this.blupp = function() { return "blupp"; }; }; A.extend(B); var b = new B(); t.equal(b.blupp(), 'blupp', 'B should have a prototype function blupp().'); t.end(); }); test("Class.extend with a ChildClass and mixins.", function(t) { function B() {} var MixinA = { foo: "foo" }; var MixinB = { bar: "bar" }; A.extend(B, MixinA, MixinB); var b = new B(); t.equal(b.foo, 'foo', 'b should have a prototype property foo.'); t.equal(b.bar, 'bar', 'b should have a prototype property bar.'); t.end(); }); test("Class.extend with ChildClass, mixins, and a prototype function.", function(t) { function B() {} var MixinA = { foo: "foo", blupp: function() { return "This should not be mixed in"; } }; A.extend(B, MixinA, function() { //eslint-disable-next-line no-invalid-this this.blupp = function() { return "blupp"; }; }); var b = new B(); t.equal(b.foo, 'foo', 'b should have a prototype property foo.'); t.equal(b.blupp(), 'blupp', 'b should have a prototype method blupp() coming from the Prototype function.'); t.end(); });
import { API } from './api'; export class AuthenticationAPI extends API { constructor() { super('/auth'); } login(username, password) { return this.callNodeServer('/login', { username: username, password: password }); } register(username, password, email) { return this.callNodeServer('/register', { username: username, email: email, password: password }); } }
exports.greeting = ' _\n' + ' / _)\n' + ' _.----._/ /\n' + ' / / Promptosaurus would like to\n' + ' __/ ( | ( | ask you some questions...\n' + ' /__.-\'|_|--|_|\n'; exports.farewell = 'Promptosaurus thanks you for your time.'; exports.tryAgain = 'Promptosaurus does not allow that answer. Try again:';
/* Stwórz obiekt aspect z następującymi metodami: add, która ma za zadanie podpiąć funkcję aspectFn pod wykonanie metody fnName w obiekcie obj. Metoda przyjmuje następujące parametry: obj – referencja do obiektu (w przypadku null/undefined – odwołanie do obiektu globalnego) fnName – nazwa funkcji (string || array || regexp) aspectFn – funkcja 'aspektowa' when – string 'after' lub 'before' (domyślnie 'before') once – boolean; jeśli true aspekt wykona się tylko raz (domyślnie false) remove – usuwa wcześniej zadeklarowany aspekt; parametry wejściowe: obj, fnName, aspectFn, when Jeśli fnName nie jest metodą obiektu obj, metody rzucają TypeError. Jeśli obj nie wskazuje na obiekt - TypeError (jeśli obj null/undefined to ma wskazywać na obiekt globalny) fnName może być tablicą funkcji bądź wyrażeniem regularnym, np. /get.+/ */ (function() { var id = 0; uniqueId = function (obj) { if ( typeof obj.__uniqueid == "undefined" ) { obj.__uniqueid = ++id; } return obj.__uniqueid; }; var aspect = { aspects: {}, /** * * @param obj * @param fnName * @param aspectFn * @param when * @param once */ add: function (obj, fnName, aspectFn, when, once) { var i, that = this; if(fnName.constructor == Array) { for(i in fnName) that.add(obj, fnName[i], aspectFn, when, once); } if(fnName.constructor == RegExp) { for(i in obj) if(i.match(fnName)) that.add(obj, i, aspectFn, when, once); } if(obj === null || obj === undefined) {obj = window; } if(!(obj instanceof Object)) {throw TypeError("invalid obj type"); } if(when === undefined) {when = 'before'; } if(once === undefined) {once = false; } var objectID = uniqueId(obj); if(!this.aspects[objectID]) this.aspects[objectID] = {}; if(!this.aspects[objectID][fnName]) this.aspects[objectID][fnName] = []; var tmpF; if(this.aspects[objectID][fnName].length == 0) { tmpF = obj[fnName]; } else { tmpF = this.aspects[objectID][fnName][0].tmpF; } this.aspects[objectID][fnName][that.aspects[objectID][fnName].length] = { fun: aspectFn, when: when, once: once, tmpF: tmpF }; obj[fnName] = function() { var asp = that.aspects[objectID][fnName]; for(i=0; i < asp.length; i += 1){ if(asp[i].when === 'before') { asp[i].fun(); if(asp[i].once === true) { asp.splice(i, 1); i--; if(asp.length == 0) obj[fnName] = tmpF; } } } var ret = tmpF.apply(obj, arguments); for(i=0; i < asp.length; i += 1){ if(asp[i].when === 'after') { asp[i].fun(); if(asp[i].once === true) { asp.splice(i, 1); i--; if(asp.length == 0) obj[fnName] = tmpF; } } } return ret; } }, /** * * @param obj * @param fnName * @param aspectFn * @param when */ remove: function (obj, fnName, aspectFn, when) { var that = this, i, tmpF; var objectID = uniqueId(obj); if(that.aspects[objectID][fnName].length == 0) {return; } for(i in that.aspects[objectID][fnName]){ if(that.aspects[objectID][fnName][i].fun === aspectFn && that.aspects[objectID][fnName][i].when === when) { tmpF = that.aspects[objectID][fnName][i].tmpF; that.aspects[objectID][fnName].splice(i, 1); if(that.aspects[objectID][fnName].length == 0) { obj[fnName] = tmpF; } } } } }; window.aspect = aspect; }());
'use strict'; /** @lends Fluxex */ var Fluxex = require('./lib/fluxex'); var React = require('react'); // jscs:disable checkRedundantParams /** * Create an fluxex application by provided defintion. * @param {Object} stores - Store defination as {storeName: implement} pairs * @param {React} HtmlJsx - The Html element defined as a React component * @param {Object=} mixins - Extra methods/properties want to be merged into application prototype * @returns {Object} The created fluxex application instance * @example var myApp = require('fluxex').createApp({ product: require('./stores/product') // Define a 'product' store }, process.cwd() + '/components/Html.jsx'); // Your Html.jsx */ // jscs:enable Fluxex.createApp = function (stores, HtmlJsx) { var App = function FluxexApp() { this.stores = stores; this.HtmlJsx = HtmlJsx; Fluxex.apply(this, arguments); }; if (!stores) { throw new Error('You should create app with information of stores as first parameter'); } if (!HtmlJsx) { throw new Error('You should create app with HtmlJsx as second parameter'); } App.prototype = new Fluxex(); if (arguments.length > 2) { Object.assign.apply(null, [App.prototype].concat(Array.prototype.slice.call(arguments, 2))); } App.prototype.constructor = App; return App; }; Fluxex.mixin = require('./lib/fluxmixin'); Fluxex.InitScript = require('./lib/fluxscript'); Fluxex.Title = require('./lib/fluxtitle'); module.exports = Fluxex;
import { Router } from 'express' const r = Router() r.get('/', async (req, res, next) => { try { res.json({ status: 'healthly' }) } catch (err) { res.status(500).json({ status: 'unhealthy' }) } }) export default r
"use strict"; const client = { repos: { createRelease: jest.fn(), }, }; module.exports.client = client; module.exports.createGitHubClient = () => client; module.exports.parseGitRepo = () => ({ owner: "lerna", name: "lerna", });
'use strict'; import { expect } from 'chai'; import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; chai.use(chaiAsPromised); chai.should(); import { translate } from '../../src/intents'; import ActionMock from '../actions/action.mock' describe('IntentTranslate', () => { let state = {}; beforeEach( () => { state.action = undefined; }); it('Up & Running', async () => { expect(translate).to.be.ok; }); it('Detected with {syntax} (rule n1) ', async () => { state.sentence = 'How can I translate into italian i have hungry'; await translate(state, [ActionMock]); expect(state.action).to.be.ok; }); it('Detected with {syntax} (rule n1) and gerund verb', async () => { state.sentence = 'can you help me translating into spanish hello i am javi'; await translate(state, [ActionMock]); expect(state.action).to.be.ok; }); // -- @TODO: 👻 when compromise fix the syntax matching --------------------- // it('Detected with {syntax} (rule n2) ', async () => { // state.sentence = 'Ava, how can translate hello world in thai'; // await translate(state, [ActionMock]); // expect(state.action).to.be.ok; // }); // --------------------------------------------------------------------------- it('Not detected', async () => { state.sentence = 'Hello world!'; expect( translate(state, [ActionMock]) ).to.be.rejected; }); });
import React, { Component } from 'react' import { connect } from 'react-redux' import { render } from 'react-dom' import { setInactiveLoading, setActiveLoading } from '../../action/LoadingAction' import { setActivePages } from '../../action/MenuAction' const mapStateToProps = (state, ownProps) => { return {loading: state.LoadingReducers.loading, menu: state.MenuReducers.page} } const mapDispatchToProps = (dispatch) => { return { inactive: () => dispatch(setInactiveLoading()), active: () => dispatch(setActiveLoading()), setActive : (key) => dispatch(setActivePages(key)) } } @connect(mapStateToProps, mapDispatchToProps) export default class NotFoundComponent extends Component{ componentDidMount() { document.title = '404 Error' document.body.removeAttribute("style"); document.body.style.backgroundColor = '#cb9e7d'; document.body.style.backgroundImage = 'url(./asset/images/patern.png)' document.body.style.backgroundSize = '32px' } componentWillMount() { setTimeout(() => { this.props.inactive() }, 1000) this.props.setActive(0) } componentWillUnmount() { this.props.active() } render() { return ( <div className='error-404 animated fadeIn'> <h1>404</h1> Oo'ps Page Not Found </div> ) } }
var gulp = require('gulp'); var imagemin = require('gulp-imagemin'); var imageResize = require('gulp-image-resize'); var rename = require('gulp-rename'); var cleanCSS = require('gulp-clean-css'); var minifyJS = require('gulp-minify'); var tasks = []; var PIZZA_IMG_MIN_TASK = 'pizza_images_min'; gulp.task(PIZZA_IMG_MIN_TASK, function () { gulp.src('src/images/cam/*') .pipe(imagemin()) .pipe(gulp.dest('dist/img')) gulp.src('src/images/pizzeria/*') .pipe(imagemin()) .pipe(gulp.dest('dist/views/images')) }); tasks.push(PIZZA_IMG_MIN_TASK); var PIZZA_THUMBNAIL_TASK = 'pizza_thumbnail'; gulp.task(PIZZA_THUMBNAIL_TASK, function () { gulp.src('src/images/pizzeria/pizzeria.jpg') .pipe(imageResize({ width : 100, imageMagick: true })) .pipe(imagemin()) .pipe(rename(function (path) { path.basename += '-thumbnail'; })) .pipe(gulp.dest('dist/views/images/')); }); tasks.push(PIZZA_THUMBNAIL_TASK); var PIZZA_RESIZE_TASK = 'pizza_resize'; var sizes = [360, 720]; var taskName; sizes.forEach(function (size) { taskName = PIZZA_THUMBNAIL_TASK + size; gulp.task(taskName, function () { gulp.src('src/images/pizzeria/pizzeria.jpg') .pipe(imageResize({ width : size, imageMagick: true })) .pipe(imagemin()) .pipe(rename(function (path) { path.basename += '-' + size; })) .pipe(gulp.dest('dist/views/images/')); }); tasks.push(taskName); }); var MINIFY_JS = 'minify_js'; gulp.task(MINIFY_JS, function () { gulp.src('src/js/main/*.js') .pipe(minifyJS({ ext:{ min:'-min.js' }, ignoreFiles: ['-min.js'] })) .pipe(gulp.dest('dist/js')) gulp.src('src/js/pizza/*.js') .pipe(minifyJS({ ext:{ min:'-min.js' }, ignoreFiles: ['-min.js'] })) .pipe(gulp.dest('dist/views/js')) }); tasks.push(MINIFY_JS); var MINIFY_CSS = 'minify_css'; gulp.task(MINIFY_CSS, function () { gulp.src('src/css/main/*.css') .pipe( cleanCSS({ compatibility: 'ie8'} ) ) .pipe(rename(function (path) { path.basename += '-min'; })) .pipe(gulp.dest('dist/css')); gulp.src('src/css/pizza/*.css') .pipe( cleanCSS({ compatibility: 'ie8'} ) ) .pipe(rename(function (path) { path.basename += '-min'; })) .pipe(gulp.dest('dist/views/css')); }); tasks.push(MINIFY_CSS); gulp.task('optimize', tasks);
var expect = require('chai').expect; var request = require('request'); it('Main page content', function() { request('http://localhost:3000' , function(error, response, body) { expect(body).to.equal('Hello World!'); }); }); it('Main page status', function() { request('http://localhost:3000' , function(error, response, body) { expect(response.statusCode).to.equal(200); }); }); it('About page content', function() { request('http://localhost:3000/about' , function(error, response, body) { expect(response.statusCode).to.equal(404); }); });
// Copyright 2014 Samsung Electronics Co., Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; var temp; try { a = 1; assert (false); } catch (e) { assert (e instanceof ReferenceError); } try { NaN = 1; assert (false); } catch (e) { assert (e instanceof TypeError); } function f() { assert(this === undefined); } f(); Object.function_prop = function () { assert (this === Object); } Object.function_prop (); try { var temp = f.caller; assert (false); } catch (e) { //ROB//assert (e instanceof TypeError); } try { delete this.NaN; assert (false); } catch (e) { assert (e instanceof TypeError); } (function (a) { (function (a) { }); });
"use strict"; const _ = require("lodash"); const clc = require("cli-color"); const project = require("../package.json"); const settings = require("./settings"); const magellanHelp = require("./help").help; const logger = require("./logger"); const MAX_HELP_KEY_WIDTH = 60; /*eslint max-len: 0*/ /*eslint max-statements: 0*/ module.exports = { /*eslint no-unused-vars: 0 */ help: (opts) => { logger.loghelp(""); logger.loghelp("Usage: magellan [options]"); logger.loghelp(""); logger.loghelp("Available options:"); logger.loghelp(""); const help = {}; // load magellan help by default _.forEach(magellanHelp, (v, k) => { if (v.visible === undefined || v.visible) { if (!help[v.category]) { help[v.category] = {}; } help[v.category][k] = v; } }); // load desire framework help if (settings.testFramework && settings.testFramework.help) { help[` Framework-specific (${clc.greenBright(settings.framework)})`] = {}; _.forEach(settings.testFramework.help, (v, k) => { if (v.visible === undefined || v.visible) { help[` Framework-specific (${clc.greenBright(settings.framework)})`][k] = v; } }); } // load desire executor(s) help if (settings.testExecutors) { _.forEach(settings.testExecutors, (v) => { if (v.help) { help[` Executor-specific (${clc.greenBright(v.name)})`] = {}; _.forEach(v.help, (itemValue, itemKey) => { if (itemValue.visible === undefined || itemValue.visible) { help[` Executor-specific (${clc.greenBright(v.name)})`][itemKey] = itemValue; } }); } }); } // load desire strategy help if (settings.strategies) { _.forEach(settings.strategies, (v) => { if (v.help) { help[` Strategy-specific (${clc.greenBright(v.name)})`] = {}; _.forEach(v.help, (itemValue, itemKey) => { if (itemValue.visible === undefined || itemValue.visible) { help[` Strategy-specific (${clc.greenBright(v.name)})`][itemKey] = itemValue; } }); } }); } if (help) { _.forEach(help, (helpValue, helpKey) => { logger.loghelp(` ${clc.cyanBright(helpKey)}`); _.forEach(helpValue, (itemValue, itemKey) => { let str = " --" + itemKey; if (itemValue.example) { str += "=" + itemValue.example; } while (str.length < MAX_HELP_KEY_WIDTH) { str += " "; } // truncate just in case the example was too long to begin with str = str.substr(0, MAX_HELP_KEY_WIDTH); str += itemValue.description; logger.loghelp(str); }); logger.loghelp(""); }); } logger.log(`Magellan@${project.version}`); } };
version https://git-lfs.github.com/spec/v1 oid sha256:44cdcf7be79b15447faff1bdb0ddf612b2a0b22ce9aa96fc5acc6553a6081d12 size 30712
function MostrarDivAcesso(divAcesso){ document.getElementById(divAcesso).style.display = "block"; }
import React, {Component} from 'react'; class Search extends Component { render() { return ( <div className="Search"> </div> ); } } export default Search;
// Adapted from: http://blog.excelstrategiesllc.com/2014/11/18/coding-your-first-javascript-bmi-calculator /* BMI Calculator function*/ function BMICalculate() /* Accept input variables*/ { var weight = document.getElementById('weight').value; var heightft = document.getElementById('heightft').value; if (weight == "") { alert("Please enter your weight."); return; } if (heightft == "") { alert("Please enter your height."); return; } /* Error Handling for invalid data entered*/ if (weight < 0) { alert("Your weight can only be negative in Theoretical Physics..., NOT in real life."); return; } if (weight < 30) { alert("Weighing " + weight + " lbs, you must be a child, this is Adult BMI calculator!"); return; } if (weight > 1500) { alert("Do you really weigh " + weight + " pounds?!"); return; } if (heightft < 0) { alert("Your can not possibly have a negative height!"); return; } if (heightft < 3) { alert("Standing " + heightft + " feet tall, you must be a child, this is Adult BMI calculator!"); return; } if (heightft > 10) { alert("Are you really " + heightft + " feet tall?!"); return; } /* Performing calculations */ var heightin = document.getElementById('heightin').value; var height = heightft * 12 + +heightin; BMI.innerHTML = Math.round((weight / (height * height)) * 703.06957964); getDescription(BMI.innerHTML); } /* Interpretation of BMI value */ function getDescription(thisBMI) { var Description = ""; if (thisBMI < 18.5) Description = "Underweight - eat a bagel!"; else if (thisBMI >= 18.5 && thisBMI <= 24.99) Description = "Normal - keep it up!"; else if (thisBMI >= 25 && thisBMI <= 29.99) Description = "Overweight - exercise more!"; else if (thisBMI >= 30 && thisBMI <= 39.99) Description = "Obese - get off the couch!"; else if (thisBMI >= 40) Description = "Morbidly Obese - take action!"; else Description = "Please check your input values, BMI cannot be calculated."; var DESC = document.getElementById('DESC'); /*send deskription to cookes*/ document.cookie = Description; } /* Reset Button */ function Clear() { document.getElementById('weight').value = ""; document.getElementById('heightft').value = ""; document.getElementById('heightin').value = ""; BMI.innerHTML = ""; }
'use strict'; var _get = require('babel-runtime/helpers/get')['default']; var _inherits = require('babel-runtime/helpers/inherits')['default']; var _createClass = require('babel-runtime/helpers/create-class')['default']; var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default']; var _objectWithoutProperties = require('babel-runtime/helpers/object-without-properties')['default']; var _extends = require('babel-runtime/helpers/extends')['default']; var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; Object.defineProperty(exports, '__esModule', { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactRouter = require('react-router'); var _stylesScss = require('./styles.scss'); var _stylesScss2 = _interopRequireDefault(_stylesScss); var _classnames = require('classnames'); /** * A button component with different options: * * @type link Render the component as an <a> instead of <button>. * @type light White instead of black. * @type outline Don't fill the button. * @type external Internal buttons use react-router's Link instead of <a> or <button>. * @type loading Whether a loading indicator should be shown instead of text. * @type children Text to display inside the button. * @type className Add classes to the element. * @type type Button type. * @type href A link to redirect to. */ var _classnames2 = _interopRequireDefault(_classnames); var Button = (function (_React$Component) { _inherits(Button, _React$Component); function Button() { var _this = this; _classCallCheck(this, Button); _get(Object.getPrototypeOf(Button.prototype), 'constructor', this).apply(this, arguments); this.handleClick = function () { if (!_this.props.loading && _this.props.href) { document.location = _this.props.href; } }; } _createClass(Button, [{ key: 'render', value: function render() { var _props = this.props; var link = _props.link; var light = _props.light; var outline = _props.outline; var external = _props.external; var loading = _props.loading; var children = _props.children; var className = _props.className; var onClick = _props.onClick; var href = _props.href; var props = _objectWithoutProperties(_props, ['link', 'light', 'outline', 'external', 'loading', 'children', 'className', 'onClick', 'href']); var fillClass = outline ? _stylesScss2['default'].outline : _stylesScss2['default'].filled; var colorClass = light ? _stylesScss2['default'].light : _stylesScss2['default'].dark; var classes = (0, _classnames2['default'])(fillClass, colorClass, className); if (loading) { children = _react2['default'].createElement( 'div', { className: _stylesScss2['default'].loader }, _react2['default'].createElement('div', null), _react2['default'].createElement('div', null) ); } if (!link) { return _react2['default'].createElement( 'button', _extends({ className: classes, onClick: onClick || this.handleClick, disabled: loading }, props), children ); } else if (external) { return _react2['default'].createElement( 'a', _extends({ className: classes, onClick: onClick, href: href }, props), children ); } else { return _react2['default'].createElement( _reactRouter.Link, _extends({ className: classes, onClick: onClick, to: href }, props), children ); } } }], [{ key: 'propTypes', value: { link: _react.PropTypes.bool, light: _react.PropTypes.bool, outline: _react.PropTypes.bool, external: _react.PropTypes.bool, loading: _react.PropTypes.bool, children: _react.PropTypes.node, className: _react.PropTypes.string, onClick: _react.PropTypes.func, href: _react.PropTypes.string, type: _react.PropTypes.string }, enumerable: true }]); return Button; })(_react2['default'].Component); exports['default'] = Button; module.exports = exports['default'];
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const vscode_1 = require("vscode"); const vscode_2 = require("vscode"); const constants = require("../../constants"); const child_process_1 = require("../child-process"); const common_1 = require("../../common"); function executeXQuery(editor, edit) { return __awaiter(this, void 0, void 0, function* () { // this disposable will be used for creating status bar messages let disposable; if (editor.document.languageId !== constants.languageIds.xquery) { vscode_1.window.showErrorMessage("This action can only be performed on an XQuery file."); return; } const executable = common_1.Configuration.xqueryExecutionEngine; let args = common_1.Configuration.xqueryExecutionArguments || []; if (!executable || executable === "") { const action = yield vscode_1.window.showWarningMessage("An XQuery execution engine has not been defined.", "Define Now"); if (action === "Define Now") { common_1.NativeCommands.openGlobalSettings(); } return; } let inputFile; disposable = vscode_1.window.setStatusBarMessage("Searching for XML files in folder..."); const searchPattern = common_1.Configuration.xqueryExecutionInputSearchPattern; const inputLimit = common_1.Configuration.xqueryExecutionInputLimit; const files = yield vscode_1.workspace.findFiles(searchPattern, "", inputLimit); disposable.dispose(); // user does not have a folder open - prompt for file name if (typeof files === "undefined") { vscode_1.window.showErrorMessage("You must have a folder opened in VS Code to use this feature."); return; } // if there is only one XML file, default it // otherwise, prompt the user to select one from the open folder if (files.length > 1) { const qpItems = new Array(); files.forEach((file) => { const filename = file.fsPath.replace("\\", "/"); qpItems.push({ label: filename.substring(filename.lastIndexOf("/") + 1), description: file.fsPath, file: file }); }); const selection = yield vscode_1.window.showQuickPick(qpItems, { placeHolder: "Please select an input file." }); if (!selection) { return; } inputFile = selection.file; } else { inputFile = files[0]; } // prompt for output file name let outputPath = null; let outputPathPos = -1; for (let i = 0; i < args.length; i++) { if (i > 0) { if (args[i].search(/out|result/) !== -1) { outputPath = args[i]; outputPathPos = i; } } } if (outputPath) { outputPath = yield vscode_1.window.showInputBox({ placeHolder: "ex. C:\\TEMP\XQueryOutput\\MyOutputFile.xml", prompt: "Please specify the output file path. Existing file behavior is determined by the execution engine you have specified.", value: outputPath }); args[outputPathPos] = outputPath; } // call out to the execution engine disposable = vscode_1.window.setStatusBarMessage("Executing XQuery Script..."); args = args.map((value) => { return value .replace("$(script)", editor.document.uri.fsPath) .replace("$(input)", inputFile.fsPath) .replace("$(project)", (vscode_1.workspace.workspaceFolders) ? vscode_1.workspace.workspaceFolders[0].uri.fsPath : ""); }); try { yield child_process_1.ChildProcess.spawn(executable, args); } catch (error) { if (error.message.search(/[Ll]ine:?\s*\d+/gm) > -1) { const match = /[Ll]ine:?\s*\d+/gm.exec(error.message); const line = (Number.parseInt(match[0].replace(/([Ll]ine:?\s*)|\s/, "")) - 1); const selection = yield vscode_1.window.showErrorMessage(error.message, `Go to Line ${line}`); if (selection === `Go to Line ${line}`) { editor.revealRange(new vscode_2.Range(line, 0, line, 0)); } } else { vscode_1.window.showErrorMessage(error.message); } } finally { disposable.dispose(); } }); } exports.executeXQuery = executeXQuery; //# sourceMappingURL=executeXQuery.js.map
'use strict'; var controllersModule = require('./_index'); /** * @ngInject */ function SearchCtrl($rootScope, $state, ItemService) { // ViewModel var vm = this; vm.loaded = false; vm.query = ''; // copy of $rootScope.searchQuery vm.findHallmeals = function(hallmealsRaw) { var hallmeals = []; hallmealsRaw.forEach(function(hm) { hallmeals.push({ hall: ItemService.hall(hm.hall), meal: ItemService.meal(hm.meal) }); }); return hallmeals; }; $rootScope.$watch('searchQuery', function() { vm.query = $rootScope.searchQuery; }); ItemService.allItems().then(function(items) { vm.items = items; vm.loaded = true; }); // Clear search box if we're leaving the search page $rootScope.$on('$stateChangeSuccess', function() { if (!$state.includes('search')) { $rootScope.searchQuery = ''; } }); } controllersModule.controller('SearchCtrl', SearchCtrl);