diff --git a/pool/shard011/JavaScript/0070299_playground.js b/pool/shard011/JavaScript/0070299_playground.js new file mode 100644 index 0000000000000000000000000000000000000000..e3cbfceb19323b39c25ca1f49f17bc22a59a08ea --- /dev/null +++ b/pool/shard011/JavaScript/0070299_playground.js @@ -0,0 +1,64 @@ +const memoryFS = require("memory-fs"); +const cloneDeep = require("lodash.clonedeep"); + +const webpackConfigurations = require("./webpack.config.shared"); + +const compile = (webpackEngine, config, fs) => { + const compiler = webpackEngine(cloneDeep(config)); + compiler.outputFileSystem = fs; + return new Promise((resolve, reject) => { + compiler.run((err, stats) => { + if (err || stats.hasErrors()) { + reject(new Error(err || stats.compilation.errors)); + } + const code = fs + .readFileSync(`${webpackConfigurations.buildPath}/main.js`) + .toString(); + console.log(code); + // eval(code); + resolve(); + }); + }); +}; + +const compileWithWebpackVersion = (webpackVersion, configName) => + compile( + require(`../${webpackVersion}/node_modules/webpack`), + { + mode: "development", + entry: { + main: "./test/common/src/index.js" + }, + output: { + filename: "[name].js", + chunkFilename: "[name].js", + publicPath: "originalPublicPath/", + path: webpackConfigurations.buildPath + }, + module: { + rules: [ + { + test: /index\.js$/, + use: { + loader: path.resolve( + `test/${webpackVersion}/node_modules/worker-loader` + ) + } + } + ] + }, + plugins: [ + new WebpackRequireFrom({ + path: "staticPath/" + }) + ] + }, + new memoryFS() + ); + +(async function run() { + await compileWithWebpackVersion( + "webpack4", + "replaceSrcMethodName_pluginConf" + ); +})(); diff --git a/pool/shard011/JavaScript/0070300_Images.react.js b/pool/shard011/JavaScript/0070300_Images.react.js new file mode 100644 index 0000000000000000000000000000000000000000..4c0c6621454b5ec8701b8495cc6faac32b528450 --- /dev/null +++ b/pool/shard011/JavaScript/0070300_Images.react.js @@ -0,0 +1,48 @@ +const React = require('react'); + +const Row = require('react-bootstrap/lib/row'); +const Col = require('react-bootstrap/lib/Col'); +const logs = require('../utilities/logsMixin'); + +var imgArray = ["./img/sf1.jpg", "./img/sf2.jpg", "./img/sf3.jpg", "./img/sf4.jpg"] + +const imageStyle ={ + width: "100%", + height: "auto" + +} +const Images = React.createClass({ + +//-------default API------------------ + +// getDefaultProps: function(){}, +//getInitialState: function(){}, +// componentWillMount: function(){}, +// componentDidMount: function(){}, +//componentWillReceiveProps: function(){}, +//shouldComponentUpdate: function(){}, +// componentWillUpdate: function(){}, + +render: function() { + var imgs; + + if (imgArray.length > 0) { + imgs = imgArray.map(function(val, idx){ + return ( + + ) + }) + } + + return ( + + {imgs} + + ) + +}, +// componetDidUpdate: function(){}, +// compoentWillUnmount: function(){} +}); + +module.exports = Images diff --git a/pool/shard011/JavaScript/0070301_star-rating-test.js b/pool/shard011/JavaScript/0070301_star-rating-test.js new file mode 100644 index 0000000000000000000000000000000000000000..07de191aa1aa592db99445393e987c741a50cdc0 --- /dev/null +++ b/pool/shard011/JavaScript/0070301_star-rating-test.js @@ -0,0 +1,125 @@ +import EmberObject from '@ember/object'; +import { module, test } from 'qunit'; +import { setupRenderingTest } from 'ember-qunit'; +import { render, click } from '@ember/test-helpers'; +import hbs from 'htmlbars-inline-precompile'; + +module('Integration | Component | star-rating', function(hooks) { + setupRenderingTest(hooks); + + test('Renders the full and empty stars correctly with integer ratings', async function(assert) { + let song = EmberObject.create({ rating: 4 }); + this.set('song', song); + this.set('maxRating', 5); + + await render(hbs`{{star-rating item=song rating=song.rating maxRating=maxRating}}`); + + assert.dom('.glyphicon-star').exists({ count: 4 }, "The right amount of full stars is rendered"); + assert.dom('.glyphicon-star-empty').exists({ count: 1 }, "The right amount of empty stars is rendered"); + + this.set('maxRating', 10); + assert.dom('.glyphicon-star').exists({ count: 4 }, "The right amount of full stars is rendered after changing maxRating"); + assert.dom('.glyphicon-star-empty').exists({ count: 6 }, "The right amount of empty stars is rendered after changing maxRating"); + + this.set('song.rating', 2); + assert.dom('.glyphicon-star').exists({ count: 2 }, "The right amount of full stars is rendered after changing rating"); + assert.dom('.glyphicon-star-empty').exists({ count: 8 }, "The right amount of empty stars is rendered after changing rating"); + }); + + test('Applies the passed fullClassNames and emptyClassNames', async function(assert) { + let song = EmberObject.create({ rating: 4 }); + this.set('song', song); + this.set('maxRating', 5); + + await render(hbs`{{star-rating item=song rating=song.rating maxRating=maxRating fullClassNames='fa fa-star' emptyClassNames='fa fa-star-o'}}`); + + assert.dom('.fa-star').exists({ count: 4 }, "The right amount of full stars is rendered"); + assert.dom('.fa-star-o').exists({ count: 1 }, "The right amount of empty stars is rendered"); + }); + + test('Renders the full and empty stars correctly with float ratings', async function(assert) { + let song = EmberObject.create({ rating: 3.2 }); + this.set('song', song); + this.set('maxRating', 5); + + await render(hbs`{{star-rating item=song rating=song.rating maxRating=maxRating}}`); + + assert.dom('.glyphicon-star').exists({ count: 3 }, "The right amount of full stars is rendered"); + assert.dom('.glyphicon-star-empty').exists({ count: 2 }, "The right amount of empty stars is rendered"); + + this.set('maxRating', 10); + + assert.dom('.glyphicon-star').exists({ count: 3 }, "The right amount of full stars is rendered after changing maxRating"); + assert.dom('.glyphicon-star-empty').exists({ count: 7 }, "The right amount of empty stars is rendered after changing maxRating"); + + this.set('song.rating', 1.9); + assert.dom('.glyphicon-star').exists({ count: 2 }, "The right amount of full stars is rendered after changing rating"); + assert.dom('.glyphicon-star-empty').exists({ count: 8 }, "The right amount of empty stars is rendered after changing rating"); + }); + + test('Triggers the passed-in action when clicked', async function(assert) { + let song = EmberObject.create({ rating: 4 }), + clickedRating; + + this.set('song', song); + this.set('maxRating', 5); + + this.actions = { + updateRating(params) { + clickedRating = params.rating; + } + }; + + await render(hbs`{{star-rating item=song rating=song.rating on-click=(action "updateRating")}}`); + + let firstStar = document.querySelectorAll('.rating-star')[0]; + await click(firstStar); + assert.equal(clickedRating, 1, "The `updateRating` action was called"); + }); + + test('In block form, yields back the decorated stars', async function(assert) { + let song = EmberObject.create({ rating: 4 }); + this.set('song', song); + this.set('maxRating', 5); + + await render(hbs` + {{#star-rating item=song rating=song.rating maxRating=maxRating as |stars|}} + {{#each stars as |star|}} + + {{/each}} + {{/star-rating}} + `); + + assert.dom('.full-star').exists({ count: 4 }, "The right amount of full stars is rendered"); + assert.dom('.empty-star').exists({ count: 1 }, "The right amount of empty stars is rendered"); + }); + + test('In block form, calls the passed in `on-click` action', async function(assert) { + let song = EmberObject.create({ rating: 4 }); + let clickedRating; + + this.set('song', song); + this.set('maxRating', 5); + this.actions = { + updateRating: function(params) { + clickedRating = params.rating; + } + }; + + await render(hbs` + {{#star-rating item=song rating=song.rating maxRating=maxRating on-click=(action "updateRating") as |stars setRating|}} + {{#each stars as |star|}} + + + + {{/each}} + {{/star-rating}} + `); + + let firstStar = document.querySelectorAll('.rating-star')[0]; + await click(firstStar); + assert.equal(clickedRating, 1, "The `updateRating` action was called"); + }); +}); diff --git a/pool/shard011/JavaScript/0070302_config.js b/pool/shard011/JavaScript/0070302_config.js new file mode 100644 index 0000000000000000000000000000000000000000..5a14529c1ebc97b924e163e30ef67a758264c863 --- /dev/null +++ b/pool/shard011/JavaScript/0070302_config.js @@ -0,0 +1,134 @@ +var HOST = ""; + +jsolait.baseURI = HOST + "/jsolait/"; +var serviceURL = HOST + "/rpc.cgi"; +var jsonrpc = null; +var Version = "1.0.1"; +var DEBUG = false; +var methods = [ "config.getVariable", + "config.setVariable", + "config.getConfig", + "file.exists", + "misc.remoteCmd", + "misc.fileDownload", + "misc.fileUpload", + "misc.getVersion", + "misc.getGatewayNetworkInfo", + "misc.setGatewayNetworkInfo", + "misc.getNtpServers", + "misc.setNtpServers", + "misc.softwareReset", + "misc.hardReset", + "misc.setGprsProviderInfo", + "misc.getGprsProviderInfo", + "user.secure_challenge", + "user.secure_login", + "user.logout" ]; + +function InitJSON(){ + try { + jsonrpc = imprt("jsonrpc"); + } catch (e) { + alert(e); + } +} + +function SetPageCommonElements(){ + document.title = "MCS Admin"; + var divHeader = document.getElementById("header"); + if (divHeader){ + divHeader.innerHTML = "" + + "" + + "" + + "" + "" + + "
/admin/ User Interface
"; + } + + var divFooter = document.getElementById("footer"); + if (divFooter){ + divFooter.innerHTML = "

Version " + Version + "       NIVIS® 2012

"; + } + + var divMenu = document.getElementById("columnB"); + if (divMenu != null) { + divMenu.innerHTML = "

Upgrade

"+ + ""+ + "

Configuration

"+ + ""+ + "

Session

"+ + ""; + } +} + +function HandleException(ex, msg){ + if (ex.message != null && + ex.message.toLowerCase().indexOf("login first") != -1 || + ex.message.toLowerCase().indexOf("unable to start session") != -1 || + ex.message.toLowerCase().indexOf("internal xml-rpc error") != -1 || + ex.message.toLowerCase().indexOf("internal json-rpc error") != -1) + { + top.location.href = "login.html?exp"; + return; + } + if(!DEBUG){ + alert(msg); + }else{ + alert(msg + "\n" + ex); + } +} + +function operationDoneListener(text) { + ToggleProgressOperation(false); + innerHTML = ""; + var operationStatus = document.getElementById('operationStatus'); + if ( text ){ + if ( text.result ){ + innerHTML = "Log results:
" + text.result + "
"; + DisplayOperationResult("operationStatus", "Operation successfully completed !"); + } else if ( text.error ){ + innerHTML = "Log results:
" + text.error + "
"; + DisplayOperationResultError("operationStatus", "Operation failed !"); + } + } + document.getElementById("result").innerHTML = innerHTML; +} + +function DisplayOperationResult(controlId, msg) { + var control = document.getElementById(controlId); + control.className = "opResultGreen"; + control.innerHTML = msg; +} + +function DisplayOperationResultError(controlId, msg) { + var control = document.getElementById(controlId); + control.className = "opResultRed"; + control.innerHTML = msg; +} + +function ClearOperationResult(controlId) { + DisplayOperationResult(controlId, ""); + var control = document.getElementById(controlId); + control.className = ""; +} + +function ToggleProgressOperation(bool){ + var operationStatus = document.getElementById("operationStatusImg"); + if(bool){ + operationStatus.style.display = "inline"; + } else{ + operationStatus.style.display = "none"; + } +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070304_tools.js b/pool/shard011/JavaScript/0070304_tools.js new file mode 100644 index 0000000000000000000000000000000000000000..bd1ca340818db5d8155f056747f2473ae9392fb7 --- /dev/null +++ b/pool/shard011/JavaScript/0070304_tools.js @@ -0,0 +1,83 @@ +var program = require('commander'); +var fs = require('fs'); +var path = require('path'); +var Imagemin = require('imagemin'); +var imageminOptipng = require('imagemin-optipng'); + +var redirectFilePath = './config/redirect-urls.json'; +var addRedirect = function(oldUrl, newUrl, callback) { + fs.readFile(redirectFilePath, function(err, json) { + if (err) { return callback(err); } + + var data = JSON.parse(json); + data.push({ + from: oldUrl, + to: newUrl + }); + + json = JSON.stringify(data, null, 2); + fs.writeFile(redirectFilePath, json, callback); + }); +}; + + +program + .version('0.0.1'); + + +program.command('mv ') + .action(function (oldUrl, newUrl) { + if (oldUrl[0] !== '/') { + oldUrl = '/' + oldUrl; + } + if (newUrl[0] !== '/') { + newUrl = '/' + newUrl; + } + var oldPath = 'articles' + oldUrl + '.md'; + var newPath = 'articles' + newUrl + '.md'; + fs.rename(oldPath, newPath, function(err) { + if (err) { return console.error(err); } + + addRedirect(oldUrl, newUrl, function(err) { + if (err) { return console.error(err); } + + console.log('File renamed'); + }); + }); + }); + + +program.command('imgs') + .action(function() { + new Imagemin() + .src('media/**/*.png') + .dest('media') + .use(imageminOptipng({optimizationLevel: 3})) + .run((err, files) => { + if (err) { + console.error(err); + } + console.log('Minified ' + files.length + ' images.'); + //=> {path: 'build/images/foo.jpg', contents: } + }); + }); + +program.command('img ') + .action(function(imgPath) { + new Imagemin() + .src(imgPath) + .dest(path.dirname(imgPath)) + .use(imageminOptipng({optimizationLevel: 3})) + .run((err, files) => { + if (err) { + console.error(err); + } + console.log('Minified ' + files.length + ' images.'); + //=> {path: 'build/images/foo.jpg', contents: } + }); + }); + + + + +program.parse(process.argv); diff --git a/pool/shard011/JavaScript/0070306_index.js b/pool/shard011/JavaScript/0070306_index.js new file mode 100644 index 0000000000000000000000000000000000000000..b97e7064d1f111ac90e00f653a1e6053a9046843 --- /dev/null +++ b/pool/shard011/JavaScript/0070306_index.js @@ -0,0 +1,89 @@ +import React, {Component} from 'react' +import Dropdown from 'rc-dropdown' +import Menu, {Item as MenuItem, Divider, SubMenu} from 'rc-menu'; +import 'rc-dropdown/assets/index.css'; +import 'rc-menu/assets/index.css'; +import {menu as fspMenu} from '../../settings/fspSettings'; +import './style.css' +import {createHashHistory} from 'history' +const history = createHashHistory({queryKey: false}); +class FSPMenu extends Component { + + state = { + visible: false + }; + + onClick({selectedKeys}) { + if (!this.props.multiple) { + this.setState({ + visible: false + }) + } + } + + onSelect({selectedKeys}) { + this.handleDropdownChanges(selectedKeys) + } + + onVisibleChange(visible) { + this.setState({visible}) + } + + getDefaultView() { + return 'uganda/mobilemoney'; + } + + handleDropdownChanges(selectedFilters) { + const selected = selectedFilters[0] || this.getDefaultView(); + const split = selected.split('/'); + const country = split[0]; + const view = split[1]; + history.replace(`/fsp/${country}/${view}`); + } + + render() { + + const menu = ( + + {fspMenu.map(({id, description, subMenu}) => { + if (subMenu) { + return ( + + { + subMenu.map(sub => ( + {sub.description} + )) + } + + ); + } else return ( + {description} + ); + } + )} + + ); + + return ( + {menu}} + onVisibleChange={this.onVisibleChange.bind(this)} + visible={this.state.visible} + defaultActiveFirst + overlayClassName="overlays-dropdown"> + Thematic Analysis ▾ + + ) + } + + +} + +export default FSPMenu \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070308_progress.js b/pool/shard011/JavaScript/0070308_progress.js new file mode 100644 index 0000000000000000000000000000000000000000..d3c5e71f6604c07fea7dc1ca23ff25afca0d4162 --- /dev/null +++ b/pool/shard011/JavaScript/0070308_progress.js @@ -0,0 +1,33 @@ +Progress = function (player, elapsed, total, meter) { + this.player = player; + this.elapsed = elapsed; + this.total = total; + this.meter = meter; + + var _this = this; + + this.player.addEventListener("timeupdate", function (event) { + function renderTime(seconds) { + var _minutes = Math.floor(seconds / 60); + var _seconds = Math.floor(seconds - _minutes * 60); + + _minutes = _minutes < 10 ? "0" + _minutes : _minutes; + _seconds = _seconds < 10 ? "0" + _seconds : _seconds; + + return _minutes + ":" + _seconds; + } + + var elapsed = event.target.currentTime; + var total = event.target.duration; + + _this.elapsed.textContent = renderTime(elapsed); + _this.total.textContent = renderTime(total); + _this.meter.setAttribute("style", "width: " + (elapsed / total * 100) + "%"); + }); + + this.player.addEventListener("ended", function (event) { + _this.elapsed.textContent = ""; + _this.total.textContent = ""; + _this.meter.setAttribute("style", "width: 0"); + }); +}; diff --git a/pool/shard011/JavaScript/0070309_setup.js b/pool/shard011/JavaScript/0070309_setup.js new file mode 100644 index 0000000000000000000000000000000000000000..4c3b4736d6cfac64408bfdfcf0a50dc5f11f975c --- /dev/null +++ b/pool/shard011/JavaScript/0070309_setup.js @@ -0,0 +1,30 @@ +var open = require('open'); + +module.exports = function (clientID, cb) { + var REDIRECT_URI = 'https://rogeriopvl.github.com/downstagram'; + + console.log('\n********** DOWNSTAGRAM OAUTH SETUP **********'); + console.log('\n To use downstagram you need to authorize it to access your instagram account.'); + console.log('Your browser will open for you to authorize the app...'); + + var authURI = [ + 'https://instagram.com/oauth/authorize/?', + 'client_id=' + clientID, + '&redirect_uri=' + REDIRECT_URI, + '&response_type=token' + ].join(''); + + console.log('\n If your browser does not open up, you can stil open it manually:'); + console.log(authURI, ' \n'); + + open(authURI); + + console.log('Now according to the intructions in the App page, insert your access token here:'); + + process.stdin.resume(); + process.stdin.on('data', function (chunk) { + var token = chunk.toString().trim(); + process.stdin.pause(); + cb(null, token); + }); +}; diff --git a/pool/shard011/JavaScript/0070311_step3_controller.js b/pool/shard011/JavaScript/0070311_step3_controller.js new file mode 100644 index 0000000000000000000000000000000000000000..ccd4da8944525f9d0e1718255ad55b1dd3a143b5 --- /dev/null +++ b/pool/shard011/JavaScript/0070311_step3_controller.js @@ -0,0 +1,158 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @typedef {object} hawqHaConfigDependencies + */ + +var App = require('app'); +require('utils/configs/hawq_ha_config_initializer'); + +App.AddHawqStandbyWizardStep3Controller = Em.Controller.extend({ + name: "addHawqStandbyWizardStep3Controller", + + // Used in service_config.hbs + // selectedService + // hideDependenciesInfoBar + // versionLoaded + + selectedService: null, + + hawqProps: null, + + hideDependenciesInfoBar: true, + + versionLoaded: true, + + // Used in step3.hbs + // isLoaded + // isSubmitDisabled + // hawqMasterDirectoryCleanUpMessage + isLoaded: false, + + isSubmitDisabled: Em.computed.not('isLoaded'), + + loadStep: function () { + this.renderConfigs(); + }, + + content: Em.Object.create({ + controllerName: 'addHawqStandbyWizardStep3Controller' + }), + + /** + * Render configs to show them in App.ServiceConfigView + */ + renderConfigs: function () { + + var configs = require('data/configs/wizards/hawq_ha_properties').haConfig; + + var serviceConfig = App.ServiceConfig.create({ + serviceName: configs.serviceName, + displayName: configs.displayName, + configCategories: [], + showConfig: true, + + configs: [] + }); + + configs.configCategories.forEach(function (configCategory) { + if (App.Service.find().someProperty('serviceName', configCategory.name)) { + serviceConfig.configCategories.pushObject(configCategory); + } + }, this); + + this.renderConfigProperties(configs, serviceConfig); + App.ajax.send({ + name: 'config.tags', + sender: this, + success: 'loadConfigTagsSuccessCallback', + error: '', + data: { + serviceConfig: serviceConfig + } + }); + + }, + + loadConfigTagsSuccessCallback: function (data, opt, params) { + var urlParams = '(type=hawq-site&tag=' + data.Clusters.desired_configs['hawq-site'].tag + ')'; + App.ajax.send({ + name: 'reassign.load_configs', + sender: this, + data: { + urlParams: urlParams, + serviceConfig: params.serviceConfig + }, + success: 'loadConfigsSuccessCallback', + error: 'loadConfigsSuccessCallback' + }); + }, + + loadConfigsSuccessCallback: function (data, opt, params) { + params = params.serviceConfig ? params.serviceConfig : {}; + this.setDynamicConfigValues(params, data); + this.setProperties({ + selectedService: params, + isLoaded: true, + hawqProps: data + }); + }, + + setDynamicConfigValues: function (configs, data) { + var topologyLocalDB = this.get('content').getProperties(['masterComponentHosts']); + configs.configs.forEach(function (config) { + App.HawqHaConfigInitializer.initialValue(config, topologyLocalDB); + }); + App.HawqHaConfigInitializer.cleanup(); + return configs; + }, + + /** + * Load child components to service config object + * @param _componentConfig + * @param componentConfig + */ + renderConfigProperties: function (_componentConfig, componentConfig) { + _componentConfig.configs.forEach(function (_serviceConfigProperty) { + var serviceConfigProperty = App.ServiceConfigProperty.create(_serviceConfigProperty); + componentConfig.configs.pushObject(serviceConfigProperty); + serviceConfigProperty.set('isEditable', serviceConfigProperty.get('isReconfigurable')); + }, this); + }, + + + submit: function () { + if (!this.get('isSubmitDisabled')) { + const dataDir = this.get('hawqProps').items[0].properties['hawq_master_directory']; + const hawqStandby = this.get('content.hawqHosts.newHawqStandby'); + App.showConfirmationPopup( + function() { + App.get('router.mainAdminKerberosController').getKDCSessionState(function() { + App.router.send("next"); + }); + }, + Em.I18n.t('admin.addHawqStandby.wizard.step3.confirm.dataDir.body').format(dataDir, hawqStandby), + null, + Em.I18n.t('admin.addHawqStandby.wizard.step3.confirm.dataDir.title'), + "Confirm" + ); + } + }, + +}); diff --git a/pool/shard011/JavaScript/0070313_post_draft.test.js b/pool/shard011/JavaScript/0070313_post_draft.test.js new file mode 100644 index 0000000000000000000000000000000000000000..407281edaaa1a09b4673ad43179014d41c99ef48 --- /dev/null +++ b/pool/shard011/JavaScript/0070313_post_draft.test.js @@ -0,0 +1,150 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +import React from 'react'; +import configureMockStore from 'redux-mock-store'; +import thunk from 'redux-thunk'; + +import Preferences from '@mm-redux/constants/preferences'; +import intitialState from '@store/initial_state'; +import {renderWithReduxIntl} from '@test/testing_library'; + +import PostDraft from './post_draft'; + +jest.mock('app/components/compass_icon', () => 'Icon'); + +const mockStore = configureMockStore([thunk]); +const state = { + ...intitialState, + entities: { + ...intitialState.entities, + channels: { + ...intitialState.entities.channels, + channels: { + 'channel-id': { + id: 'channel-id', + name: 'test-channel', + display_name: 'Display Name', + type: 'O', + }, + }, + channelMemberCountsByGroup: {}, + }, + }, + device: { + ...intitialState.device, + dimension: { + deviceWidth: 375, + deviceHeight: 812, + }, + }, +}; +const store = mockStore(state); + +describe('PostDraft', () => { + const baseProps = { + testID: 'post_draft', + canPost: true, + channelId: 'channel-id', + channelIsArchived: false, + channelIsReadOnly: false, + deactivatedChannel: false, + registerTypingAnimation: () => jest.fn(), + rootId: '', + screenId: 'NavigationScreen1', + theme: Preferences.THEMES.denim, + }; + + test('Should render the DraftInput', () => { + const {getByTestId, queryByText, toJSON} = renderWithReduxIntl( + , + store, + ); + + expect(toJSON()).toMatchSnapshot(); + expect(getByTestId('post_draft.post.input')).toBeTruthy(); + expect(queryByText('Close Channel')).toBeNull(); + }); + + test('Should render the Archived for channelIsArchived', () => { + const {queryByTestId, getByText, toJSON} = renderWithReduxIntl( + , + store, + ); + + expect(toJSON()).toMatchSnapshot(); + + // Should not render text input + expect(queryByTestId('post_draft.post.input')).toBeNull(); + + // Should match text description + expect(getByText('You are viewing an')).toBeTruthy(); + expect(getByText('archived channel')).toBeTruthy(); + expect(getByText('. New messages cannot be posted.')).toBeTruthy(); + expect(getByText('Close Channel')).toBeTruthy(); + }); + + test('Should render the Archived for deactivatedChannel', () => { + const {queryByTestId, getByText, toJSON} = renderWithReduxIntl( + , + store, + ); + + expect(toJSON()).toMatchSnapshot(); + + // Should not render text input + expect(queryByTestId('post_draft.post.input')).toBeNull(); + + // Should match text description + expect(getByText('You are viewing an')).toBeTruthy(); + expect(getByText('archived channel')).toBeTruthy(); + expect(getByText('. New messages cannot be posted.')).toBeTruthy(); + expect(getByText('Close Channel')).toBeTruthy(); + }); + + test('Should render the ReadOnly for channelIsReadOnly', () => { + const {queryByTestId, getByText, queryByText, toJSON} = renderWithReduxIntl( + , + store, + ); + + expect(toJSON()).toMatchSnapshot(); + + // Should not render text input + expect(queryByTestId('post_draft.post.input')).toBeNull(); + + // Should match text description + expect(getByText('This channel is read-only.')).toBeTruthy(); + expect(queryByText('Close Channel')).toBeNull(); + }); + + test('Should render the ReadOnly for canPost', () => { + const {queryByTestId, getByText, queryByText, toJSON} = renderWithReduxIntl( + , + store, + ); + + expect(toJSON()).toMatchSnapshot(); + + // Should not render text input + expect(queryByTestId('post_draft.post.input')).toBeNull(); + + // Should match text description + expect(getByText('This channel is read-only.')).toBeTruthy(); + expect(queryByText('Close Channel')).toBeNull(); + }); +}); diff --git a/pool/shard011/JavaScript/0070314_index.js b/pool/shard011/JavaScript/0070314_index.js new file mode 100644 index 0000000000000000000000000000000000000000..2a0b986d5be1937b25e1df00a9246ab36f0fe5b5 --- /dev/null +++ b/pool/shard011/JavaScript/0070314_index.js @@ -0,0 +1,26 @@ +/* global fetch */ +import search from './search'; +import album from './album'; + +import API_URL from './config'; +import toJSON from './utils'; + +export default class SpotifyWrapper { + constructor(options) { + this.apiURL = options.apiURL || API_URL; + this.token = options.token; + + this.album = album.bind(this)(); + this.search = search.bind(this)(); + } + + request(url) { + const headers = { + headers: { + Authorization: `'Bearer ${this.token}'`, + }, + }; + + return fetch(url, headers).then(toJSON); + } +} diff --git a/pool/shard011/JavaScript/0070320_cohorts.js b/pool/shard011/JavaScript/0070320_cohorts.js new file mode 100644 index 0000000000000000000000000000000000000000..2707b7693185c48ade9cab73bb4830ceedc5de2e --- /dev/null +++ b/pool/shard011/JavaScript/0070320_cohorts.js @@ -0,0 +1,272 @@ +// structure stolen from http://briancray.com/posts/javascript-module-pattern + +var CohortManager = (function ($) { + // private variables and functions + + // using jQuery + function getCookie(name) { + var cookieValue = null; + if (document.cookie && document.cookie != '') { + var cookies = document.cookie.split(';'); + for (var i = 0; i < cookies.length; i++) { + var cookie = $.trim(cookies[i]); + // Does this cookie string begin with the name we want? + if (cookie.substring(0, name.length + 1) == (name + '=')) { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; + } + var csrftoken = getCookie('csrftoken'); + + function csrfSafeMethod(method) { + // these HTTP methods do not require CSRF protection + return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); + } + $.ajaxSetup({ + crossDomain: false, // obviates need for sameOrigin test + beforeSend: function(xhr, settings) { + if (!csrfSafeMethod(settings.type)) { + xhr.setRequestHeader("X-CSRFToken", csrftoken); + } + } + }); + + // constructor + var module = function () { + var el = $(".cohort_manager"); + // localized jquery + var $$ = function (selector) { + return $(selector, el) + } + var state_init = "init"; + var state_summary = "summary"; + var state_detail = "detail"; + var state = state_init; + + var url = el.data('ajax_url'); + var self = this; + + // Pull out the relevant parts of the html + // global stuff + var errors = $$(".errors"); + + // cohort summary display + var summary = $$(".summary"); + var cohorts = $$(".cohorts"); + var show_cohorts_button = $$(".controls .show_cohorts"); + var add_cohort_input = $$(".cohort_name"); + var add_cohort_button = $$(".add_cohort"); + + // single cohort user display + var detail = $$(".detail"); + var detail_header = $(".header", detail); + var detail_users = $$(".users"); + var detail_page_num = $$(".page_num"); + var users_area = $$(".users_area"); + var add_members_button = $$(".add_members"); + var op_results = $$(".op_results"); + var cohort_id = null; + var cohort_title = null; + var detail_url = null; + var page = null; + + // *********** Summary view methods + + function show_cohort(item) { + // item is a li that has a data-href link to the cohort base url + var el = $(this); + cohort_title = el.text(); + detail_url = el.data('href'); + cohort_id = el.data('id'); + state = state_detail; + render(); + return false; + } + + function add_to_cohorts_list(item) { + var li = $('
  • '); + $("a", li).text(item.name) + .data('href', url + '/' + item.id) + .addClass('link') + .click(show_cohort); + cohorts.append(li); + }; + + function log_error(msg) { + errors.empty(); + errors.append($("
  • ").text(msg).addClass("error")); + }; + + function load_cohorts(response) { + cohorts.empty(); + if (response && response.success) { + response.cohorts.forEach(add_to_cohorts_list); + } else { + log_error(response.msg || "There was an error loading cohorts"); + } + summary.show(); + }; + + + function added_cohort(response) { + if (response && response.success) { + add_to_cohorts_list(response.cohort); + } else { + log_error(response.msg || "There was an error adding a cohort"); + } + } + + // *********** Detail view methods + + function remove_user_from_cohort(username, cohort_id, row) { + var delete_url = detail_url + '/delete'; + var data = {'username': username} + $.post(delete_url, data).done(function() {row.remove()}) + .fail(function(jqXHR, status, error) { + log_error('Error removing user ' + username + + ' from cohort. ' + status + ' ' + error); + }); + } + + function add_to_users_list(item) { + var tr = $('' + + '' + + ''); + var current_cohort_id = cohort_id; + + $(".name", tr).text(item.name); + $(".username", tr).text(item.username); + $(".email", tr).text(item.email); + + $(".remove", tr).html('remove') + .click(function() { + remove_user_from_cohort(item.username, current_cohort_id, tr); + return false; + }); + + detail_users.append(tr); + }; + + + function show_users(response) { + detail_users.html("NameUsernameEmail"); + if (response && response.success) { + response.users.forEach(add_to_users_list); + detail_page_num.text("Page " + response.page + " of " + response.num_pages); + } else { + log_error(response.msg || + "There was an error loading users for " + cohort.title); + } + op_results.empty(); + detail.show(); + } + + + function added_users(response) { + op_results.empty(); + if (response && response.success) { + function add_to_list(text, color) { + op_results.append($("
  • ").text(text).css("color", color)); + } + response.added.forEach( + function(item) { + add_to_list( + "Added: " + item.name + ", " + item.username + ", " + item.email, + "green" + ); + } + ); + response.changed.forEach( + function(item) { + add_to_list( + "Moved from cohort " + item.previous_cohort + ": " + item.name + ", " + item.username + ", " + item.email, + "purple" + ) + } + ); + response.present.forEach( + function(item) { + add_to_list("Already present: " + item, "black"); + } + ); + response.unknown.forEach( + function(item) { + add_to_list("Unknown user: " + item, "red") + } + ); + users_area.val('') + } else { + log_error(response.msg || "There was an error adding users"); + } + } + + // ******* Rendering + + + function render() { + // Load and render the right thing based on the state + + // start with both divs hidden + summary.hide(); + detail.hide(); + // and clear out the errors + errors.empty(); + if (state == state_summary) { + $.ajax(url).done(load_cohorts).fail(function() { + log_error("Error trying to load cohorts"); + }); + } else if (state == state_detail) { + detail_header.text("Members of " + cohort_title); + $.ajax(detail_url).done(show_users).fail(function() { + log_error("Error trying to load users in cohort"); + }); + } + } + + show_cohorts_button.click(function() { + state = state_summary; + render(); + return false; + }); + + add_cohort_input.change(function() { + if (!$(this).val()) { + add_cohort_button.removeClass('button').addClass('button-disabled'); + } else { + add_cohort_button.removeClass('button-disabled').addClass('button'); + } + }); + + add_cohort_button.click(function() { + var add_url = url + '/add'; + data = {'name': add_cohort_input.val()} + $.post(add_url, data).done(added_cohort); + return false; + }); + + add_members_button.click(function() { + var add_url = detail_url + '/add'; + data = {'users': users_area.val()} + $.post(add_url, data).done(added_users); + return false; + }); + + + }; + + // prototype + module.prototype = { + constructor: module, + }; + + // return module + return module; +})(jQuery); + +$(window).load(function () { + var my_module = new CohortManager(); +}) + diff --git a/pool/shard011/JavaScript/0070325_tr.js b/pool/shard011/JavaScript/0070325_tr.js new file mode 100644 index 0000000000000000000000000000000000000000..6779a8a9bc326223c02f9a2bb0b4a6c9259842c8 --- /dev/null +++ b/pool/shard011/JavaScript/0070325_tr.js @@ -0,0 +1,51 @@ +var catw = require('../'); +var test = require('tape'); +var fs = require('fs'); +var path = require('path'); +var os = require('os'); +var tmpdir = os.tmpdir || os.tmpDir; +var mkdirp = require('mkdirp'); +var concat = require('concat-stream'); +var through = require('through'); + +test('source transform', function (t) { + t.plan(4); + var dir = path.join(tmpdir(), 'cat-watch-test-exec', Math.random()+''); + mkdirp.sync(dir); + + fs.writeFileSync(path.join(dir, 'beep.txt'), 'beep'); + fs.writeFileSync(path.join(dir, 'boop.txt'), 'boop'); + + var cat = catw(path.join(dir, '*.txt'), { + transform: function (file) { + if (path.basename(file) !== 'beep.txt') return through(); + return through(write); + function write (buf) { + this.queue(buf.toString('utf8').toUpperCase()); + } + } + }); + t.on('end', function () { cat.close() }); + var expected = [ 'BEEPboop', 'BEEP boop', 'BEEP boop!', 'BEEP boop!!!' ]; + + cat.on('stream', function (stream) { + stream.pipe(concat(function (body) { + t.equal(body.toString('utf8'), expected.shift()); + setTimeout(nextUpdate, 100); + })); + }); + + var updates = [ + [ 'beep.txt', 'beep ' ], + [ 'boop.txt', 'boop!' ], + [ 'c.txt', '!!' ] + ]; + + function nextUpdate () { + if (updates.length === 0) return; + var file = updates.shift(); + fs.writeFile(path.join(dir, file[0]), file[1], function (err) { + if (err) return t.fail(err) + }); + } +}); diff --git a/pool/shard011/JavaScript/0070328_params.js b/pool/shard011/JavaScript/0070328_params.js new file mode 100644 index 0000000000000000000000000000000000000000..64cb83c824c3729ccbee120c29b0745addfbb00a --- /dev/null +++ b/pool/shard011/JavaScript/0070328_params.js @@ -0,0 +1,171 @@ +/** + * + * ProjectName:blogme + * Description: + * Created by qimuyunduan on 16/4/13 . + * Revise person:qimuyunduan + * Revise Time:16/4/13 下午3:27 + * @version + * + */ +var _ = require('lodash'), + Promise = require('bluebird'), + errors = require('../errors'), + utils = require('../utils'), + events = require('../events'), + appBookshelf = require('./base'), + validator = require('validator'), + param, + params; + +param = appBookshelf.Model.extend({ + + tableName: ' params ', + + saving: function saving() { + + var self = this; + + }, + + validate: function validate() { + + }, + + toJSON: function toJSON(options) { + options = options || {}; + + var attrs = appBookshelf.Model.prototype.toJSON.call(this, options); + // remove password hash for security reasons + delete attrs.password; + + if (!options || !options.context || (!options.context.user && !options.context.internal)) { + delete attrs.email; + } + + return attrs; + }, + + format: function format(options) { + if (!_.isEmpty(options.website) && + !validator.isURL(options.website, { + require_protocol: true, + protocols: ['http', 'https']})) { + options.website = 'http://' + options.website; + } + return appBookshelf.Model.prototype.format.call(this, options); + }, + + findOne: function findOne(data, options) { + + }, + + edit: function edit(data, options) { + + }, + + add: function add(data, options) { + + }, + + // Finds the user by email, and checks the password + check: function check(object) { + + }, + + changePassword: function changePassword(object, options) { + + }, + + generateResetToken: function generateResetToken(email, expires, dbHash) { + return this.getByEmail(email).then(function then(foundUser) { + if (!foundUser) { + return Promise.reject(new errors.NotFoundError('errors.models.user.noUserWithEnteredEmailAddr')); + } + + var hash = crypto.createHash('sha256'), + text = ''; + + // Token: + // BASE64(TIMESTAMP + email + HASH(TIMESTAMP + email + oldPasswordHash + dbHash )) + hash.update(String(expires)); + hash.update(email.toLocaleLowerCase()); + hash.update(foundUser.get('password')); + hash.update(String(dbHash)); + + text += [expires, email, hash.digest('base64')].join('|'); + return new Buffer(text).toString('base64'); + }); + }, + + validateToken: function validateToken(token, dbHash) { + + var tokenText = new Buffer(token, 'base64').toString('ascii'), + parts, + expires, + email; + + parts = tokenText.split('|'); + + // Check if invalid structure + if (!parts || parts.length !== 3) { + return Promise.reject(new errors.BadRequestError('errors.models.user.invalidTokenStructure')); + } + + expires = parseInt(parts[0], 10); + email = parts[1]; + + if (isNaN(expires)) { + return Promise.reject(new errors.BadRequestError('errors.models.user.invalidTokenExpiration')); + } + + if (expires < Date.now()) { + return Promise.reject(new errors.ValidationError('errors.models.user.expiredToken')); + } + + if (tokenSecurity[email + '+' + expires] && tokenSecurity[email + '+' + expires].count >= 10) { + return Promise.reject(new errors.NoPermissionError('errors.models.user.tokenLocked')); + } + + return this.generateResetToken(email, expires, dbHash).then(function then(generatedToken) { + // Check for matching tokens with timing independent comparison + var diff = 0, + i; + + // check if the token length is correct + if (token.length !== generatedToken.length) { + diff = 1; + } + + for (i = token.length - 1; i >= 0; i = i - 1) { + diff |= token.charCodeAt(i) ^ generatedToken.charCodeAt(i); + } + + if (diff === 0) { + return email; + } + + tokenSecurity[email + '+' + expires] = { + count: tokenSecurity[email + '+' + expires] ? tokenSecurity[email + '+' + expires].count + 1 : 1 + }; + return Promise.reject(new errors.BadRequestError('errors.models.user.invalidToken')); + }); + }, + +}); + +params = appBookshelf.Collection.extend({ + model:param +}); + +module.exports = { + param:{ + model: function(){ + return param; + }, + collection:function(){ + return params; + } + } + +}; diff --git a/pool/shard011/JavaScript/0070330_idempotency.spec.js b/pool/shard011/JavaScript/0070330_idempotency.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..087e45314bb37cacbccbdb53f3e6baa7b08724d8 --- /dev/null +++ b/pool/shard011/JavaScript/0070330_idempotency.spec.js @@ -0,0 +1,156 @@ +import { markdownToDraft, draftToMarkdown } from '../src/index'; + +/* + * Note: These tests are to make sure markdown to draft and then back to markdown have the exact same value before-and-after + * + * However, there are some cases where this will not be possible - + * For example, this is valid in draftjs: + * _I am italic content with a space included at the end _ + * but markdown will struggle with this so we need to convert it to: + * _I am italic content with a space after the closing italic symbol instead of before_ + * The end result should basically look the same to a human, but behind the scenes it has to be a bit different. + * + * Still, for the most part results should match, so these tests are for cases when they _should_ match. +*/ + +describe('idempotency', function () { + + it('renders new lines text correctly', function () { + var markdownString = 'Test\n\n\nHello There\n\nSmile\n\n\n\n\n\n\n\nYep Hi'; + var draftJSObject = markdownToDraft(markdownString, {preserveNewlines: true}); + var markdownFromDraft = draftToMarkdown(draftJSObject, {preserveNewlines: true}); + + expect(markdownFromDraft).toEqual(markdownString); + + markdownString = 'a\nb\n\nc\n\n\nd'; + draftJSObject = markdownToDraft(markdownString, {preserveNewlines: true}); + markdownFromDraft = draftToMarkdown(draftJSObject, {preserveNewlines: true}); + + expect(markdownFromDraft).toEqual(markdownString); + + markdownString = '\n\na'; + draftJSObject = markdownToDraft(markdownString, {preserveNewlines: true}); + markdownFromDraft = draftToMarkdown(draftJSObject, {preserveNewlines: true}); + expect(markdownFromDraft).toEqual(markdownString); + + }); + + it('renders new lines text correctly with styled blocks', function () { + var markdownString = '# Test\n\n\nHello There\n\nSmile\n\n\n\n\n\n\n\nYep Hi'; + var draftJSObject = markdownToDraft(markdownString, {preserveNewlines: true}); + var markdownFromDraft = draftToMarkdown(draftJSObject, {preserveNewlines: true}); + + expect(markdownFromDraft).toEqual(markdownString); + }); + + it ('renders preserved new lines after list correctly', function () { + var markdown = '- unordered item\n\n\n1. ordered item\n\n\nparagraph' + var rawDraftConversion = markdownToDraft(markdown, {preserveNewlines: true }); + var markdownConversion = draftToMarkdown(rawDraftConversion, {preserveNewlines: true}); + + expect(markdownConversion).toEqual(markdown); + }); + + it('renders blockquotes correctly', function () { + var markdownString = '> Hello I am Blockquote\n\nI am not\n\n> I am'; + var draftJSObject = markdownToDraft(markdownString, {preserveNewlines: true}); + var markdownFromDraft = draftToMarkdown(draftJSObject, {preserveNewlines: true}); + expect(markdownFromDraft).toEqual(markdownString); + }); + + it('renders italic text correctly', function () { + var markdownString = '_I am italic_ …I am not italic.'; + var draftJSObject = markdownToDraft(markdownString); + var markdownFromDraft = draftToMarkdown(draftJSObject); + + expect(markdownFromDraft).toEqual(markdownString); + }); + + it('renders bold text correctly', function () { + var markdownString = 'Hello **I am bold** I am not bold.'; + var draftJSObject = markdownToDraft(markdownString); + var markdownFromDraft = draftToMarkdown(draftJSObject); + + expect(markdownFromDraft).toEqual(markdownString); + }); + + it('renders nested styles correctly', function () { + var markdownString = '**bold** _italic_ test **bold _italic_** _italic_ _italic **bold** italic **bold italic**_'; + var draftJSObject = markdownToDraft(markdownString); + var markdownFromDraft = draftToMarkdown(draftJSObject); + + expect(markdownFromDraft).toEqual(markdownString); + }); + + it('renders inline code correctly', function () { + var markdownString = 'Test `here is some inline code`'; + var draftJSObject = markdownToDraft(markdownString); + var markdownFromDraft = draftToMarkdown(draftJSObject); + + expect(markdownFromDraft).toEqual(markdownString); + }); + + it('renders code fences correctly', function () { + var markdownString = '```\nHello I am Codefence\n```'; + var draftJSObject = markdownToDraft(markdownString); + var markdownFromDraft = draftToMarkdown(draftJSObject); + + expect(markdownFromDraft).toEqual(markdownString); + }); + + it('renders blockquotes correctly', function () { + var markdownString = '> Hello I am Blockquote'; + var draftJSObject = markdownToDraft(markdownString); + var markdownFromDraft = draftToMarkdown(draftJSObject); + + expect(markdownFromDraft).toEqual(markdownString); + }); + + // TODO this test should pass but markdown-to-draft doesn’t correctly create empty markdown blocks in this case currently. + xit('renders blockquotes with blank lines correctly', function () { + var markdownString = '> Hello I am Blockquote\n> more\n> \n> \n> hey'; + var draftJSObject = markdownToDraft(markdownString); + var markdownFromDraft = draftToMarkdown(draftJSObject); + + expect(markdownFromDraft).toEqual(markdownString); + }); + + it('renders links correctly', function () { + var markdown = 'This is a test of [a link](https://google.com)\n\nAnd [perhaps](https://facebook.github.io/draft-js/) we should test once more.'; + var rawDraftConversion = markdownToDraft(markdown); + var markdownConversion = draftToMarkdown(rawDraftConversion); + + expect(markdownConversion).toEqual(markdown); + }); + + it ('renders codeblock with syntax correctly', function () { + var markdown = '```javascript\nsingle line codeblock\n```'; + var rawDraftConversion = markdownToDraft(markdown); + var markdownConversion = draftToMarkdown(rawDraftConversion); + expect(markdownConversion).toEqual(markdown); + }); + + it('renders "the kitchen sink" correctly', function () { + var markdown = '# Hello!\n\nMy name is **Rose** :)\nToday, I\'m here to talk to you about how great markdown is!\n\n## First, here\'s a few bullet points:\n\n- One\n- Two\n- Three\n\n```\nA codeblock\n```\n\nAnd then... `some monospace text`?\nOr... _italics?_'; + var rawDraftConversion = markdownToDraft(markdown); + var markdownConversion = draftToMarkdown(rawDraftConversion); + + expect(markdownConversion).toEqual(markdown); + }); + + it ('renders escaped italics correctly', function () { + var markdown = 'test \\_not italic\\_ test'; + var rawDraftConversion = markdownToDraft(markdown); + var markdownConversion = draftToMarkdown(rawDraftConversion); + + expect(markdownConversion).toEqual(markdown); + }); + + it ('renders escaped bold correctly', function () { + var markdown = 'test \\*\\*not italic\\*\\* test'; + var rawDraftConversion = markdownToDraft(markdown); + var markdownConversion = draftToMarkdown(rawDraftConversion); + + expect(markdownConversion).toEqual(markdown); + }); +}); diff --git a/pool/shard011/JavaScript/0070333_a.js b/pool/shard011/JavaScript/0070333_a.js new file mode 100644 index 0000000000000000000000000000000000000000..3eae2db9926475567369b39553e682d5f2dfde18 --- /dev/null +++ b/pool/shard011/JavaScript/0070333_a.js @@ -0,0 +1,26 @@ +/** + * 2017-9-16 sunzhiyue + */ +var b = function(){ + +}; +b.arr = [1, 2, 3, 4, 5]; +b.obj = { + name : 'wan', + age : 18, + car : true +} +b.fun = function(){ + console.log('fun'); +} + +Object.defineProperty(b,'len',{ + enumerable: true, + configurable: false, + get: function() { return this.arr.length; } +} + +) +b.arr.length = 10; +console.log(b.len); +console.log(b.obj.len); diff --git a/pool/shard011/JavaScript/0070334_script.js b/pool/shard011/JavaScript/0070334_script.js new file mode 100644 index 0000000000000000000000000000000000000000..42c6e1e56883da3739716e5113b0ef4226d4dd61 --- /dev/null +++ b/pool/shard011/JavaScript/0070334_script.js @@ -0,0 +1,12 @@ +var onlyUniques = (...args) => { + let array = []; + for (let i = 0; i < args.length; i++) { + if (!array.includes(args[i])) { + array.push(args[i]); + } + } + return array; +}; + +console.log(onlyUniques("cat", "cat", "dog", "pig")); //['cat', 'dog', 'pig'] +console.log(onlyUniques(1, 4, 7, 1, 2, 7, 4)); //[1, 4, 7, 2] diff --git a/pool/shard011/JavaScript/0070335_express.js b/pool/shard011/JavaScript/0070335_express.js new file mode 100644 index 0000000000000000000000000000000000000000..17ad6032b61344d1a82a3a80478236a0ced4c4d5 --- /dev/null +++ b/pool/shard011/JavaScript/0070335_express.js @@ -0,0 +1,102 @@ +var Q = require('q'), + pkg = require('../package.json'), + + express = require('express'), + consolidate = require('consolidate'), + morgan = require('morgan'), + compression = require('compression'), + finalhandler = require('finalhandler'), + colors = require('colors/safe'), + http = require('http'), + env = require('./env.js'); + + +// ---------------------------------------------------------------------------- + + +console.log(colors.underline(pkg.name) + ' v' + pkg.version + ' starting up...'); + +Q.when(makeApp()).then(function(app) { + + var server = http.createServer(app), + port = env('expressPort'); + + server.listen(port, '0.0.0.0', function () { + console.info(colors.blue('listening on port %s'), port); + }); + +}); + + +// ---------------------------------------------------------------------------- + + +morgan.token('ms', function (req, res){ + if (!res._header || !req._startAt) { return ''; } + var diff = process.hrtime(req._startAt); + var ms = diff[0] * 1e3 + diff[1] * 1e-6; + return Math.ceil(ms)+'ms'; +}); + +function render404 (req, res) { + finalhandler(req, res)(false); +} + + +function makeApp () { + + var app = express(), + log = morgan( ':method :url :ms :status' ); + + app.engine('html', consolidate.lodash); + app.set('view engine', 'html'); + app.set('views', __dirname); + + + // middleware stack starts here + app.use(compression()); + + app.get('/robots.txt', [ + log, + function (req, res) { + res.type('text/plain'); + res.send('User-agent: *\nDisallow: /'); + } + ]); + + + app.use('/api/foo', [ + log, + function (req, res, next) { + var d = parseInt(req.query.delay, 10); + if(d>0) { setTimeout(next, Math.min(d,10) * 1000); } + else next(); + }, + render404 + ]); + + // serve the api + app.use('/api', [ + log, + require('./api/index.js'), + render404 + ]); + + // any other path, serve 404 + app.all('*', [ + log, + render404 + ]); + + var mongo = require('./mongo.js'); + + if(mongo.connection.readyState === 1) { + return app; + } + else { + return Q.ninvoke(mongo.connection, 'once', 'connected').then(function() { + return app; + }); + } + +} diff --git a/pool/shard011/JavaScript/0070336_index.js b/pool/shard011/JavaScript/0070336_index.js new file mode 100644 index 0000000000000000000000000000000000000000..349043dd6bec4a4389e8595fa2dde7a4256fd69f --- /dev/null +++ b/pool/shard011/JavaScript/0070336_index.js @@ -0,0 +1,55 @@ +import React, { Fragment } from 'react'; +import PropTypes from 'prop-types'; +import { connect } from 'react-redux'; +import { createStructuredSelector } from 'reselect'; + +import { titleCase, truncate } from 'voca'; + +import { selectPrimaryMeaning, selectSecondaryMeanings } from 'features/reviews/selectors'; + +import { PrimaryMeaning, SecondaryMeanings } from './styles'; + +VocabMeaning.propTypes = { + primaryMeaning: PropTypes.string.isRequired, + secondaryMeanings: PropTypes.arrayOf(PropTypes.string), + shouldTruncate: PropTypes.bool, + showSecondary: PropTypes.bool, + renderPrimary: PropTypes.func, + renderSecondary: PropTypes.func, +}; + +VocabMeaning.defaultProps = { + secondaryMeanings: [], + showSecondary: true, + shouldTruncate: false, + renderPrimary: ({ text }) => {text}, // eslint-disable-line react/prop-types + renderSecondary: ({ text }) => text && {text}, // eslint-disable-line react/prop-types +}; + +function VocabMeaning({ + primaryMeaning, + secondaryMeanings, + shouldTruncate, + showSecondary, + renderPrimary, + renderSecondary, +}) { + const noSplit = ["'"]; + let secondaryText = secondaryMeanings.join(', '); + secondaryText = truncate(secondaryText, shouldTruncate ? 30 : secondaryText.length); + return ( + + {renderPrimary({ text: titleCase(primaryMeaning, noSplit) })} + {showSecondary && + !!secondaryText.length && + renderSecondary({ text: titleCase(secondaryText, noSplit) })} + + ); +} + +const mapStateToProps = createStructuredSelector({ + primaryMeaning: selectPrimaryMeaning, + secondaryMeanings: selectSecondaryMeanings, +}); + +export default connect(mapStateToProps)(VocabMeaning); diff --git a/pool/shard011/JavaScript/0070337_utils.js b/pool/shard011/JavaScript/0070337_utils.js new file mode 100644 index 0000000000000000000000000000000000000000..d4958d4ea44f7fb882e99d61b6d3468bf0ee5d42 --- /dev/null +++ b/pool/shard011/JavaScript/0070337_utils.js @@ -0,0 +1,135 @@ +export class VisibilityTracker { + constructor( + {ratioThreshold = 0.9, durationThreshold = 2, upperDurationThreshold = 1800} = {}, + onFlush = () => {} + ) { + this.components = {}; + this.groups = {}; + this.ratioThreshold = ratioThreshold; + this.durationThreshold = durationThreshold; + // Upper duration threshold should remove any cases where the page is left + // open and forgotten + this.upperDurationThreshold = upperDurationThreshold; + + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') { + this.stopAndFlush(onFlush); + } else if (document.visibilityState === 'visible') { + this.restart(); + } + }); + } + + update(comp, entry) { + let screenCoveredRatio = 0; + if (entry.rootBounds && entry.rootBounds.height !== 0) { + const rootArea = entry.rootBounds.height * entry.rootBounds.width; + const cardArea = entry.boundingClientRect.height * entry.boundingClientRect.width; + screenCoveredRatio = 1 - (rootArea - (cardArea * entry.intersectionRatio)) / rootArea; + } + + // Update or add the component + if (!this.components[comp.$meta.uid]) { + this.components[comp.$meta.uid] = {} + } + const compData = this.components[comp.$meta.uid]; + compData.component = comp; + compData.intersectionRatio = entry.intersectionRatio; + compData.screenCoveredRatio = screenCoveredRatio; + compData.isVisible = this.isCompVisible(comp); + + const group = comp.$meta.group; + if (!group) return; + + // Group the component + if (!this.groups[group.$meta.uid]) { + const components = this.components; + this.groups[group.$meta.uid] = { + tag: group.$meta.tag, + components: [], + get isVisible() { + return this.components.some((uid) => components[uid].isVisible); + }, + }; + } + if ( + this.groups[group.$meta.uid].components.indexOf(comp.$meta.uid) === -1 + ) { + this.groups[group.$meta.uid].components.push(comp.$meta.uid); + } + + const timer = this.updateGroupTimer(group); + const duration = (Date.now() - timer) / 1000; + + return { + report: ( + !this.groups[group.$meta.uid].isVisible && + timer && + duration >= this.durationThreshold && + duration < this.upperDurationThreshold + ), + tag: group.$meta.tag, + duration: duration, + }; + } + + isCompVisible(comp) { + let onScreen = false; + const componentData = this.components[comp.$meta.uid]; + + // Report if the component it is mostly visible + if (componentData.intersectionRatio > this.ratioThreshold) { + onScreen = true; + } + + // Covers the most screen space + onScreen = onScreen || (Object.values(this.components).every( + (comp) => comp.screenCoveredRatio <= componentData.screenCoveredRatio, + ) && componentData.screenCoveredRatio > 0.1); + + return onScreen; + } + + updateGroupTimer(group) { + const groupData = this.groups[group.$meta.uid]; + + let timer = null; + if (groupData.isVisible) { + if (!groupData.timer) { + groupData.timer = Date.now(); + } + timer = groupData.timer; + } else { + timer = groupData.timer; + groupData.timer = null; + } + + return timer; + } + + stopAndFlush(callbackfn) { + Object.values(this.groups) + .filter((groupData) => groupData.isVisible) + .forEach((groupData) => { + const duration = (Date.now() - groupData.timer ?? Date.now()) / 1000; + + groupData.stopped = true; + groupData.timer = null; + + callbackfn({ + report: duration >= this.durationThreshold && duration < this.upperDurationThreshold, + tag: groupData.tag, + duration: duration, + }); + }); + } + + restart() { + Object.values(this.groups) + .filter((groupData) => groupData.stopped) + .forEach((groupData) => { + groupData.stopped = false; + groupData.timer = Date.now(); + }); + } +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070338_cMosca.js b/pool/shard011/JavaScript/0070338_cMosca.js new file mode 100644 index 0000000000000000000000000000000000000000..0ebd9097f3ecfdc0150d099eb83dca81482d9e3a --- /dev/null +++ b/pool/shard011/JavaScript/0070338_cMosca.js @@ -0,0 +1,114 @@ +/** + * Created by stitchcula on 2016/9/4. + */ + +import mosca from 'mosca' + +export default class Mosca { + constructor(mongo){ + this.mongo=mongo + var ascoltatore={ + type:'redis', + redis:require('redis'), + host:process.env['REDIS_HOST'], + port:process.env['REDIS_PORT'], + password:process.env['REDIS_AUTH'], + return_buffers:true + } + this.settings={ + port:1883, + backend:ascoltatore, + persistence:{ + factory: mosca.persistence.Redis, + host:process.env['REDIS_HOST'], + port:process.env['REDIS_PORT'], + password:process.env['REDIS_AUTH'] + } + } + } + listen(port){ + if(port) this.settings.port=port + this.server = new mosca.Server(this.settings) + this.server.on('ready',this.onReady.bind(this)) + this.server.on('published',this.onPublished.bind(this)) + this.server.on("clientDisconnected",this.onDisconnected.bind(this)) + } + async onReady(){ + this.server.authenticate =async function(client, obj, token, callback) {//online login + token=token.toString() + if(obj&&token) { + var {uin,device_id}=JSON.parse(obj) + var res =uin?(await this.mongo.collection("users").findOne({token, uin})): + (await this.mongo.collection("users").findOne({token, device_id})) + if (res) { + await this.mongo.collection("online_list") + .insertOne({session: client.id, uin,device_id, time: new Date().getTime()}) + /* + if(uin)//用户接入的时候报告设备状态 + setTimeout(function () { + this.server.publish({ + topic: "$SMTH/" + device_id + "/ONLINE", + payload: res.uin, + qos: 1, retain: false + })}.bind(this), 1000) + else//设备一上线就通知用户 + this.server.publish({ + topic: "$SMTH/" + device_id + "/ONLINE", + payload: res.uin, + qos: 1, retain: false + }) + */ + callback(null, true); + } else + callback(null, false); + } + }.bind(this) + this.server.authorizePublish=function (client, topic, payload, callback) { + console.log("authorizePublish:"+client.id) + callback(null,true) + } + this.server.authorizeSubscribe=function (client, topic, callback) { + console.log("authorizeSubscribe:"+client.id) + callback(null,true) + } + console.log("MQTT broker is running at "+new Date()) + } + async onPublished(packet){ + //Topic->device id or user uin + //node_id->modules id or user token + //node_type->modules or USER + //msg_type->data/notice + if(packet.topic.split('/')[0]!="$SMTH"||packet.topic.split('/')[2]) + return + var {node_id,node_type,msg_type,msg_id,msg_c}=JSON.parse(packet.payload.toString()) + console.log(packet.topic+":"+node_id+ + " SEND "+JSON.stringify({node_type,msg_type,msg_id,msg_c})+ + " at "+new Date()) + if(node_type=="USER"){//User->Edison + //todo: + //user's order, save to db + }else{//Edison->User + //save to db + //device's data or notice, if it's notice,user sure response. + await this.mongo.collection("publish_msg") + .insertOne({uin:packet.topic,node_id,node_type,msg_type,msg_id,msg_c}) + if(msg_type=="NOTICE"){ + this.server.publish({ + topic:packet.topic+"/NOTICE", + payload:packet.payload, + qos:1,retain:false + }) + } + } + } + async onDisconnected(client){//offline logout + var res=await this.mongo.collection("online_list") + .removeOne({session:client.id}) + /* + this.server.publish({topic:"$SMTH/"+res.device_id+"/OFFLINE", + payload:packet.payload, + qos:1,retain:false}) + */ + console.log(res.result) + } +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070339_main-resource-test.js b/pool/shard011/JavaScript/0070339_main-resource-test.js new file mode 100644 index 0000000000000000000000000000000000000000..cfd15d4c497d6ce9489730b4109f9d2eff6d9106 --- /dev/null +++ b/pool/shard011/JavaScript/0070339_main-resource-test.js @@ -0,0 +1,74 @@ +/** + * @license Copyright 2017 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + */ +'use strict'; + +/* eslint-env jest */ + +const Runner = require('../../../runner.js'); +const assert = require('assert'); + +describe('MainResource computed artifact', () => { + let computedArtifacts; + + beforeEach(() => { + computedArtifacts = Runner.instantiateComputedArtifacts(); + }); + + it('returns an artifact', () => { + const record = { + url: 'https://example.com', + }; + const networkRecords = [ + {url: 'http://example.com'}, + record, + ]; + computedArtifacts.requestNetworkRecords = _ => Promise.resolve(networkRecords); + const URL = {finalUrl: 'https://example.com'}; + + return computedArtifacts.requestMainResource({URL}).then(output => { + assert.equal(output, record); + }); + }); + + it('thows when main resource can\'t be found', () => { + const networkRecords = [ + {url: 'https://example.com'}, + ]; + computedArtifacts.requestNetworkRecords = _ => Promise.resolve(networkRecords); + const URL = {finalUrl: 'https://m.example.com'}; + + return computedArtifacts.requestMainResource({URL}).then(() => { + assert.ok(false, 'should have thrown'); + }).catch(err => { + assert.equal(err.message, 'Unable to identify the main resource'); + }); + }); + + it('should identify correct main resource in the wikipedia fixture', () => { + const wikiDevtoolsLog = require('../../fixtures/wikipedia-redirect.devtoolslog.json'); + const URL = {finalUrl: 'https://en.m.wikipedia.org/wiki/Main_Page'}; + const artifacts = {devtoolsLog: wikiDevtoolsLog, URL}; + + return computedArtifacts.requestMainResource(artifacts).then(output => { + assert.equal(output.url, 'https://en.m.wikipedia.org/wiki/Main_Page'); + }); + }); + + it('should identify correct main resource with hash URLs', () => { + const networkRecords = [ + {url: 'https://beta.httparchive.org/reports'}, + {url: 'https://beta.httparchive.org/reports/state-of-the-web'}, + ]; + + computedArtifacts.requestNetworkRecords = _ => Promise.resolve(networkRecords); + const URL = {finalUrl: 'https://beta.httparchive.org/reports/state-of-the-web#pctHttps'}; + const artifacts = {URL}; + + return computedArtifacts.requestMainResource(artifacts).then(output => { + assert.equal(output.url, 'https://beta.httparchive.org/reports/state-of-the-web'); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0070340_WFSService.js b/pool/shard011/JavaScript/0070340_WFSService.js new file mode 100644 index 0000000000000000000000000000000000000000..59c3bd954093c122b2f0906ed18cff76a20732c4 --- /dev/null +++ b/pool/shard011/JavaScript/0070340_WFSService.js @@ -0,0 +1,167 @@ +/** + * WFSService handles rendering of all wfs layers onto the map + * @module map + * @class WFSService + * + */ +allModules.service('WFSService',['$rootScope','GoogleMapService','LayerManagerService','Constants','GetWFSRelatedService','GMLParserService','QuerierPanelService','RenderStatusService','UtilitiesService','NVCLService', + function ($rootScope,GoogleMapService,LayerManagerService,Constants,GetWFSRelatedService,GMLParserService,QuerierPanelService,RenderStatusService,UtilitiesService,NVCLService) { + + /** + * Render a point data to the map + * @method renderPoint + * @param point - the point to render + * @param map - The map where the point is to be rendered + */ + this.renderPoint = function(point,map){ + var marker = new google.maps.Marker({ + position:point.coords, + map: map, + title: point.name + }); + + marker.addListener('click', function() { + // Ask the map to display a loading mask + GoogleMapService.busyStart(); + + // Invoke core tray image carousel + if (point.featureNode.nodeName=='gsml:Borehole') { + QuerierPanelService.setCarouselBusy(true); + NVCLService.getCoreDisplay(point.description, point.featureNode.nodeName, point.name); + } + + // Set data for the query panel and display it + var displayable = QuerierPanelService.setPanelNode(point.featureNode, "Feature", "WFS", false); + if (displayable) { + QuerierPanelService.openPanel(true); + } + + // Ask the map to dissolve the loading mask + GoogleMapService.busyEnd(); + }); + return marker; + }; + + /** + * Render a LINESTRING data to the map + * @method renderLineString + * @param linestring - the linestring to render + * @param map - The map where the point is to be rendered + */ + this.renderLineString = function(linestring,map){ + + }; + + /** + * Render a POLYGON data to the map + * @method renderPolygon + * @param polygon - the polygon to render + * @param map - The map where the point is to be rendered + */ + this.renderPolygon = function(polygon,map){ + + }; + + /** + * Method to decide how the wfs layer should be rendered and add the wfs to the map + * @method renderLayer + * @param layer - The layer containing the wfs to be rendered + */ + this.renderLayer = function(layer,param){ + var map = GoogleMapService.getMap(); + var me = this; + var onlineResources = LayerManagerService.getWFS(layer); + RenderStatusService.setMaxValue(layer,onlineResources.length); + for(var index in onlineResources){ + + if(UtilitiesService.filterProviderSkip(param.optionalFilters, onlineResources[index].url)){ + RenderStatusService.updateCompleteStatus(layer,onlineResources[index],Constants.statusProgress.SKIPPED); + continue; + } + + RenderStatusService.updateCompleteStatus(layer,onlineResources[index],Constants.statusProgress.RUNNING); + + GetWFSRelatedService.getFeature(layer, onlineResources[index],param).then(function(response){ + try{ + var rootNode = GMLParserService.getRootNode(response.data.gml); + var primitives = GMLParserService.makePrimitives(rootNode); + + RenderStatusService.updateCompleteStatus(layer,response.resource,Constants.statusProgress.COMPLETED); + + for(var key in primitives){ + switch(primitives[key].geometryType){ + case Constants.geometryType.POINT: + GoogleMapService.addMarkerToActive(layer.id,me.renderPoint(primitives[key],map)); + break; + case Constants.geometryType.LINESTRING: + me.renderLineString(primitives[key],map); + break; + case Constants.geometryType.POLYGON: + me.renderPolygon(primitives[key],map); + break; + default: + break; + } + } + }catch(err){ + RenderStatusService.updateCompleteStatus(layer,response.resource,Constants.statusProgress.ERROR); + } + + + },function(error){ + RenderStatusService.updateCompleteStatus(layer,error.onlineResource,Constants.statusProgress.ERROR); + }); + + } + + }; + + /** + * Method to decide how the wfs resource should be rendered and add the wfs to the map + * @method renderResource + * @param resource - The resource containing the wfs to be rendered + */ + this.renderCSWRecord = function(layer,cswRecord){ + var map = GoogleMapService.getMap(); + var me = this; + var onlineResources = LayerManagerService.getWFSFromCSW(cswRecord); + RenderStatusService.setMaxValue(layer,onlineResources.length); + + + for(var index in onlineResources){ + RenderStatusService.updateCompleteStatus(layer,onlineResources[index],Constants.statusProgress.RUNNING); + GetWFSRelatedService.getFeature(layer, onlineResources[index]).then(function(response){ + try{ + var rootNode = GMLParserService.getRootNode(response.data.gml); + var primitives = GMLParserService.makePrimitives(rootNode); + + RenderStatusService.updateCompleteStatus(layer,response.resource,Constants.statusProgress.COMPLETED); + + for(var key in primitives){ + switch(primitives[key].geometryType){ + case Constants.geometryType.POINT: + GoogleMapService.addMarkerToActive(layer.id,me.renderPoint(primitives[key],map)); + break; + case Constants.geometryType.LINESTRING: + me.renderLineString(primitives[key],map); + break; + case Constants.geometryType.POLYGON: + me.renderPolygon(primitives[key],map); + break; + default: + break; + } + } + }catch(err){ + RenderStatusService.updateCompleteStatus(layer,response.resource,Constants.statusProgress.ERROR); + } + + },function(error){ + RenderStatusService.updateCompleteStatus(layer,error.onlineResource,Constants.statusProgress.ERROR); + }); + } + + }; + + +}]); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070341_routes.js b/pool/shard011/JavaScript/0070341_routes.js new file mode 100644 index 0000000000000000000000000000000000000000..59013c46afe7b88376cb41cd2deb3d271ea3c633 --- /dev/null +++ b/pool/shard011/JavaScript/0070341_routes.js @@ -0,0 +1,57 @@ +(function() { + var nextId = 0; + var people = [ + { + "id": "" + (nextId++), + "name": "Saasha", + "age": "6" + }, { + "id": "" + (nextId++), + "name": "Planet", + "age": "8" + } + ]; + + var isUniqueName = function(name) { + var result = people.filter(function(person) { + return person.name === name; + }); + return result.length === 0; + }; + + module.exports = function(app, options) { + app.get('/', function(req, res) { + return res.render("" + options.base + "/index.html"); + }); + app.get('/people', function(req, res) { + return res.json(people); + }); + app.post('/people', function(req, res) { + var age, message, name, person; + name = req.body.name; + age = req.body.age; + message = { + "title": "Duplicate!", + "message": "" + name + " is a duplicate. Please enter a new name." + }; + if (!isUniqueName(name)) { + return res.send(message, 403); + } + person = { + "id": "" + (nextId++), + "name": "" + name, + "age": "" + age + }; + people.push(person); + return res.json(person); + }); + return app.get('/people/:id', function(req, res) { + var id = req.params.id; + var current = people.filter(function(person) { + return person.id === id; + }); + return res.json(current || null); + }); + }; + +}).call(this); diff --git a/pool/shard011/JavaScript/0070344_worker.js b/pool/shard011/JavaScript/0070344_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..c6ad85cb28609f5fabacf1691a6c033aa86cd826 --- /dev/null +++ b/pool/shard011/JavaScript/0070344_worker.js @@ -0,0 +1,53 @@ +var CACHE_NAME = 'pwa-zero-inside'; +var urlsToCache = [ + '/', + 'static', + 'images/myProfile.jpg', + 'images/portfolio/gponbot/web-home.png', + 'images/portfolio/pettracker/IMG_20200530_181223.jpg', + 'images/portfolio/shap/IMG_2020-11-30-20-36-25-499.jpg', + 'images/portfolio/watermonitoring/ss1.png' +]; + +// Install a service worker +self.addEventListener('install', event => { + // Perform install steps + event.waitUntil( + caches.open(CACHE_NAME) + .then(function(cache) { + console.log('Opened cache'); + return cache.addAll(urlsToCache); + }) + ); +}); + +// Cache and return requests +self.addEventListener('fetch', event => { + event.respondWith( + caches.match(event.request) + .then(function(response) { + // Cache hit - return response + if (response) { + return response; + } + return fetch(event.request); + } + ) + ); +}); + +// Update a service worker +self.addEventListener('activate', event => { + var cacheWhitelist = ['pwa-zero-inside']; + event.waitUntil( + caches.keys().then(cacheNames => { + return Promise.all( + cacheNames.map(cacheName => { + if (cacheWhitelist.indexOf(cacheName) === -1) { + return caches.delete(cacheName); + } + }) + ); + }) + ); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070348_not-equal-email-domain.js b/pool/shard011/JavaScript/0070348_not-equal-email-domain.js new file mode 100644 index 0000000000000000000000000000000000000000..26e971a6c62417fcb6198263326089f2421f3fc5 --- /dev/null +++ b/pool/shard011/JavaScript/0070348_not-equal-email-domain.js @@ -0,0 +1,45 @@ +import _ from 'lodash'; + +/** + * Validate email's domain to not equal to the listed domains + * in ruleObj.params[0]. Separate the domains using comma (,). + * + * @param val - email + * @param ruleObj + * + * @returns {Boolean} + */ + +const validate = (val, ruleObj) => { + if (!val) { + return true; + } + + const parts = val.split('@'); + + if (parts.length !== 2) { + // most likely not email + return false; + } + + const domain = parts.pop(); + + if (!domain) { + return false; + } + + const lowerDomain = domain.toLowerCase(); + + const prohibitedDomains = _.chain(ruleObj.params[0]) + .toLower() + .split(',') + .map(domain => _.trim(domain)) + .compact() + .value(); + + return !_.includes(prohibitedDomains, lowerDomain); +}; + +const message = '<%= propertyName %>\'s domain is not valid.'; + +export default {validate, message}; diff --git a/pool/shard011/JavaScript/0070350_file.js b/pool/shard011/JavaScript/0070350_file.js new file mode 100644 index 0000000000000000000000000000000000000000..6f5771dade1d0c58529d7cb24afadf7ee58ab439 --- /dev/null +++ b/pool/shard011/JavaScript/0070350_file.js @@ -0,0 +1,262 @@ +define("widget.FileInput", ["AbilianWidget", "jquery", "FileAPI", "Hogan"], ( + Abilian, + $, + api, + Hogan +) => { + "use strict"; + /** + * File input widget. Uses FileAPI (http://mailru.github.io/FileAPI/) + */ + const defaults = { + fileItemTemplate: Hogan.compile( + '
    \n' + + '{{ name }} ({{ size }}) ' + + '×' + + "\n
    " + ), + progressTemplate: + '
    ' + + '
    ' + + "
    " + + "
    ", + inputTemplate: '', + progressBarHeight: "0.2em", + }; + + function FileInput(node, options) { + const self = this; + this.currentlyUploaded = {}; + this.options = $.extend({}, defaults, options); + this.form = node.parent("form"); + this.$input = node.find(".js-fileapi-wrapper input"); + this.$input.attr("disabled", null); + this.rootNode = node; + this.button = node.find(".js-fileapi-wrapper .btn-file"); + this.multiple = Boolean(this.$input.attr("multiple")); + this.$input.attr("multiple", null); + this.inputName = this.$input.attr("name"); + this.$input.attr("name", null); + this.listNode = node.find(".selected-files"); + + if (node.data("cloned")) { + this.listNode.empty(); + } else { + this.listNode.find(".file-item-existing").each(function () { + self.setupExistingFileNode($(this)); + }); + this.listNode.find(".file-item-uploaded").each(function () { + self.setupFileNode($(this)); + }); + } + + this.button.on("change", "input", this.addFiles.bind(this)); + + this.form.on("submit", this.onFormSubmit.bind(this)); + } + + FileInput.prototype = { + addFiles(evt) { + const self = this; + let files = api.getFiles(evt); + + if (!this.multiple) { + this.listNode.empty(); + files = files.slice(0, 1); + } + + $(files).each(function () { + self.addFileNode(evt.target, this); + }); + }, + + setupExistingFileNode(node) { + const button = node.find("button"); + const unwrappedButton = button.get(0); + const deleted = button.data("deleted"); + + if (!unwrappedButton) { + return; + } + + unwrappedButton.markerInputElement = $("").attr({ + type: "hidden", + name: button.data("name"), + value: button.data("value"), + }); + + if (deleted) { + node.append(unwrappedButton.markerInputElement); + } + + button.on("click", { node: node }, this.onExistingNodeChange.bind(this)); + }, + + setupFileNode(node) { + node.find("a.close").on("click", this.removeFileNode.bind(this)); + }, + + addFileNode(input, file) { + const el = this.createFileNode(file); + this.setupFileNode(el); + this.listNode.append(el); + this.triggerUpload(el, file); + }, + + triggerUpload(element, file) { + const uid = api.uid(file); + this.currentlyUploaded[uid] = true; + + api.upload({ + url: Abilian.api.upload.newFileUrl, + headers: { + Accept: "application/json", + "X-CSRF-Token": Abilian.csrf_token, + }, + files: { file: file }, + progress: this.onFileProgress.bind(this), + complete: this.onFileComplete.bind(this), + }); + }, + + removeFileNode(evt) { + evt.preventDefault(); + $(evt.target).parent(".file-item").remove(); + }, + + createFileNode(file) { + const infos = this.getFileInfos(file); + const el = $(this.options.fileItemTemplate.render(infos)); + const progress = $(this.options.progressTemplate).css({ + height: this.options.progressBarHeight, + }); + + el.append(progress); + return el; + }, + + getElementForFile(file) { + const uid = api.uid(file); + return $(document.getElementById(uid)); + }, + + getFileInfos(file) { + return { + name: this.sanitizeFilename(file.name), + type: file.type, + size: this.humanSize(file.size), + uid: api.uid(file), + }; + }, + + onExistingNodeChange(evt) { + const button = $(evt.target); + const markerInputElement = evt.target.markerInputElement; + const isActive = button.hasClass("active"); + + button.toggleClass("active"); + + if (isActive) { + button.removeClass("btn-danger"); + button.addClass("btn-default"); + $(markerInputElement).remove(); + } else { + button.removeClass("btn-default"); + button.addClass("btn-danger"); + button.parent(".file-item").append(markerInputElement); + } + }, + + onFileProgress(evt, file, xhr, options) { + const progress = (evt.loaded / evt.total) * 100; + this.getElementForFile(file) + .find(".progress-bar") + .css({ width: `${progress}%` }); + }, + + onFileComplete(err, xhr, file, options) { + const $el = this.getElementForFile(xhr.currentFile); + const uid = api.uid(xhr.currentFile); + + delete this.currentlyUploaded[uid]; + + if (err) { + $el.remove(); + alert("Echec de l'envoi du fichier!"); // FIXME: i18n + return; + } + + const $input = $("").attr({ + type: "hidden", + name: this.inputName, + }); + const responseText = xhr.responseText; + const result = JSON.parse(responseText); + + $el.find(".progress").remove(); + $input.val(result.handle); + $el.append($input); + }, + + onFormSubmit(e) { + if (Object.keys(this.currentlyUploaded).length > 0) { + e.preventDefault(); + alert("Des fichiers sont en cours d'envoi"); // FIXME: i18n + } + }, + + sanitizeFilename(filename) { + return filename.replace(/\\/g, "/").replace(/.*\//, ""); + }, + + humanSize(size) { + let unit = "b"; + let divider = null; + + if (size > api.TB) { + unit = "TB"; + divider = api.TB; + } else if (size > api.GB) { + unit = "GB"; + divider = api.GB; + } else if (size > api.MB) { + unit = "MB"; + divider = api.MB; + } else if (size > api.KB) { + unit = "KB"; + divider = api.KB; + } + + if (divider) { + size = (size / divider).toFixed(2); + } + + return size.toString() + unit; + }, + }; + + function createFileInput(options) { + const element = $(this); + const widget = new FileInput(element, options); + element.data("file-input", widget); + return widget; + } + + Abilian.registerWidgetCreator("fileInput", createFileInput); + + $.fn.fileInput = function (options) { + return this.each(function () { + const node = $(this); + let widget = node.data("file-input"); + if (widget === undefined) { + widget = new FileInput(node, options); + node.data("file-input", widget); + } + return widget; + }); + }; + + return FileInput; +}); diff --git a/pool/shard011/JavaScript/0070351_app.js b/pool/shard011/JavaScript/0070351_app.js new file mode 100644 index 0000000000000000000000000000000000000000..2ff938884631ab6b0d91e57074f497dd169b0860 --- /dev/null +++ b/pool/shard011/JavaScript/0070351_app.js @@ -0,0 +1,34 @@ +var evalApp = angular.module( 'evalApp', +[ 'templates-app', + 'templates-common', + 'evalApp.home', + 'evalApp.about', + 'evalApp.login', + 'evalApp.admin', + 'evalApp.user', + 'evalApp.newTemplate', + 'evalApp.evaluations', + 'evalApp.course', + 'ui.router' +]); + +evalApp.constant('SERVER_URL', 'http://dispatch.ru.is/h48/api/v1/'); + +evalApp.config( function myAppConfig ( $stateProvider, $urlRouterProvider ) { + $urlRouterProvider.otherwise( '/login' ); +}); + +evalApp.run( function run () { +}); + +evalApp.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) { + $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ + if ( angular.isDefined( toState.data.pageTitle ) ) { + $scope.pageTitle = toState.data.pageTitle + ' | Evaluation App' ; + } + }); +}); + +evalApp.directive('evaluation-question', function() { + return ; +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070352_calendars-service.spec.js b/pool/shard011/JavaScript/0070352_calendars-service.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..61471e017a7cc5c882e8bd2390d07cc939f79653 --- /dev/null +++ b/pool/shard011/JavaScript/0070352_calendars-service.spec.js @@ -0,0 +1,107 @@ +const expect = require('chai').expect; +const rewire = require('rewire'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const mockEventList = require('./mocks/eventList.json'); + +const CalendarService = rewire('../services/calendar-service'); + +describe('Calendar Test', () => { + const calendar = CalendarService.__get__('calendar'); + let jwtRevert; + + beforeEach(done => { + const stub = sinon.stub().returns(Promise.resolve('a secured client')); + jwtRevert = CalendarService.__set__('createJWT', stub); + done(); + }); + + afterEach(() => jwtRevert()); + + it('should send an update to Google Calendar', done => { + const updateEvent = CalendarService.__get__('updateEvent'); + const updateSpy = sinon.spy(calendar.events, 'update'); + const fakeResourceBody = { + summary: 'testing', + foo: 'bar' + }; + + // Since it will fail as this isn't an actual event + updateEvent({eventId: 'event1', calendarId: 'calendar1'}, fakeResourceBody) + .catch(() => { + const expectedParams = { + eventId: 'event1', + calendarId: 'calendar1', + resource: fakeResourceBody, + auth: 'a secured client' + }; + + // eslint-disable-next-line no-unused-expressions + expect(updateSpy.calledWith(expectedParams)).to.be.true; + done(); + }); + }); + + it('should return a sync token', done => { + const mockFullSync = () => Promise.resolve(mockEventList); + const revert = CalendarService.__set__('getFullSync', mockFullSync); + const getSyncToken = CalendarService.__get__('getSyncToken'); + + getSyncToken() + .then(syncToken => { + expect(syncToken).to.equal('CPiw4dWUu84CEPiw4dWUu84CGAU='); + revert(); + done(); + }); + }); + + it('should perform a full sync', done => { + const getFullSync = CalendarService.__get__('getFullSync'); + const mock1 = { + events: [1, 2], + nextPageToken: 2 + }; + const mock2 = { + events: [3, 4], + syncToken: 'token' + }; + // Override eventList to check integrity of callback + const eventListMock = params => { + if (params.nextPageToken) { + return Promise.resolve(mock2); + } + return Promise.resolve(mock1); + }; + const revert = CalendarService.__set__('listEvents', eventListMock); + getFullSync('brhim@apidevdemo.com').then(lastPageResponse => { + expect(lastPageResponse.syncToken).to.equal('token'); + revert(); + done(); + }); + }); + + it('should perform an incremental sync', done => { + const listStub = sinon.stub().returns(Promise.resolve([])); + const listRevert = CalendarService.__set__('listEvents', listStub); + const getIncrementalSync = CalendarService.__get__('getIncrementalSync'); + const mockCalendarInfo = { + syncToken: '12345abcefg', + calendarId: 'calendarId1' + }; + + getIncrementalSync(mockCalendarInfo) + .then(() => { + const expectedParams = { + auth: 'a secured client', + calendarId: 'calendarId1', + singleEvents: false, + syncToken: '12345abcefg', + showDeleted: true + }; + // eslint-disable-next-line no-unused-expressions + expect(listStub.calledWith(expectedParams)).to.be.true; + listRevert(); + done(); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0070360_Leg.js b/pool/shard011/JavaScript/0070360_Leg.js new file mode 100644 index 0000000000000000000000000000000000000000..d2020eb26393d39144b95ee48a4e71938b5e1ee3 --- /dev/null +++ b/pool/shard011/JavaScript/0070360_Leg.js @@ -0,0 +1,51 @@ +import { LEG_CAVE } from '../core/constants'; + +class Leg { + + constructor ( factory, legInfo, s1, s2 ) { + + const s1Start = ( s1.shortestPathDistance() < s2.shortestPathDistance() ); + const survey = factory.survey; + + this.factory = factory; + this.legLength = legInfo.length; + this.index = legInfo.index; + this.segmentId = legInfo.segment; + this.startStation = s1Start ? s1 : s2; + this.endStation = s1Start ? s2 : s1; + this.legs = survey.getFeature( LEG_CAVE ); + + } + + start () { + + return this.startStation; + + } + + end () { + + return this.endStation; + } + + length () { + + return this.legLength; + + } + + color ( color = false ) { + + this.legs.setLegColor( this.index * 2, color ); + + } + + segment() { + + return this.factory.getSegment( this.segmentId ); + + } + +} + +export { Leg }; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070364_handler.js b/pool/shard011/JavaScript/0070364_handler.js new file mode 100644 index 0000000000000000000000000000000000000000..81d56e3551f72ec0dc4bca6572301e2447c90024 --- /dev/null +++ b/pool/shard011/JavaScript/0070364_handler.js @@ -0,0 +1,176 @@ +var AbstractAdminContentHandler = Class.create(AbstractContentHandler, { + show: function(data){ + this.data = data; + adminTemplateEngine.process(this.tpl, data, this.target, this.finished.bind(this)); + } +}); + +/** + * PkgNavHandler + */ +var ScriptListHandler = Class.create(AbstractAdminContentHandler, { + initialize: function($super, target){ + $super('tplScriptList', target); + this.provider = new ScriptListProvider(this.show.bind(this)); + this.ajaxload = true; + } +}); + +/** + * PkgNavHandler + */ +var PkgConfListHandler = Class.create(AbstractAdminContentHandler, { + initialize: function($super, target){ + $super('tplPkgSettings', target); + this.provider = new PkgConfListProvider(this.show.bind(this)); + this.ajaxload = true; + } +}); + +/** + * PkgListHandler + */ +var PkgListHandler = Class.create(AbstractAdminContentHandler, { + initialize: function($super, target){ + $super('tplPkgList', target); + this.provider = new PkgListProvider(this.show.bind(this)); + this.ajaxload = true; + this.fakeprovider = new PkgFakeProvider(this.show.bind(this)); + }, + + loadPkg: function(sel, needle){ + this.provider.setSelection(sel, needle); + if (this.provider.packages.length != 0) { + this.requestStarted(); + this.fakeprovider.setList(this.provider.getSelected()); + this.fakeprovider.load(); + } + else + this.load(); + + }, + + loadAll: function(){ + this.loadPkg(this.provider.ALL); + }, + + loadUpgradable: function(){ + this.loadPkg(this.provider.UPGRADE); + }, + + loadInstalled: function(){ + this.loadPkg(this.provider.INST); + }, + + loadFilter: function(needle){ + this.loadPkg(this.provider.SEARCH, needle); + } +}); + +/** + * PkgNavHandler + */ +var PkgNavHandler = Class.create(AbstractAdminContentHandler,{ + initialize: function($super, target){ + $super('tplNavPkgs', target); + }, + + load: function(){ + data = {}; + core.setAjaxLoad('navContent'); + this.show(data); + } +}); + +/** + * SwitchFeedHandler + * + */ +var SwitchFeedHandler = Class.create(AbstractAdminContentHandler, { + initialize: function(){ + this.provider = new SimpleRequestProvider(); + }, + + load: function(url, parms){ + this.provider.simpleResultQuery( + url, + parms, + this.simpleResultCallback.bind(this) + ); + }, + + showSimpleResult: function(result){ + id = result.getStateText(); + element = document.getElementById(id.replace('.off','') + "-pic"); + hiddenInput = document.getElementById(id.replace('.off','') + "-name"); + if (result.getState()) { + if (id.endsWith('.conf')) { + element.alt='disable'; + element.src = '/web-data/img/minus.png'; + var title = 'enable ' + id; + element.up('.sPkgConfFeedsLink').title='disable ' + id; + + } + else { + element.alt='enable'; + element.src = '/web-data/img/plus.png'; + var title = 'enable ' + id.replace('.off',''); + element.up('.sPkgConfFeedsLink').title='enable ' + id.replace('.off',''); + } + hiddenInput.value=id; + } + else { + alert(id); + }; + }, +}); + +/** + * MemoryHandler + * + */ + +var MemoryHandler = Class.create(AbstractAdminContentHandler, { + initialize: function(){ + this.provider = new MemoryProvider(this.show.bind(this)); + }, + + load: function(url, parms){ + this.provider.simpleResultQuery( + url, + parms, + this.simpleResultCallback.bind(this) + ); + }, + + getMem: function(){ + this.load('/webadmin/web/getmemory'); + }, + + showSimpleResult: function(result){ + str = result.getStateText(); + if (result.getState()) { + document.getElementById('memContent').innerHTML=result.getStateText() + " MB free"; + } + else { + alert(str); + }; + }, +}); + +/** + * SimpleWebAdminPageHandler + * + */ + +var templateEngine2 = new TemplateEngine('/webadmin/tpl/'); + +var SimpleWebAdminPageHandler = Class.create(AbstractContentHandler,{ + initialize: function($super, target){ + $super(null, target); + }, + + show: function(tpl, data){ + templateEngine2.process(tpl, data, this.target, this.finished.bind(this)); + } +}); diff --git a/pool/shard011/JavaScript/0070365_Tags.js b/pool/shard011/JavaScript/0070365_Tags.js new file mode 100644 index 0000000000000000000000000000000000000000..6fe8bc1882d508f633983106b4c59991a82131d6 --- /dev/null +++ b/pool/shard011/JavaScript/0070365_Tags.js @@ -0,0 +1,74 @@ +const React = require('react'); +const classNames = require('classnames'); +const Icon = require('./Icon'); + +const Tags = React.createClass({ + propTypes: { + children: React.PropTypes.node + }, + + render() { + return ( +
      + {this.props.children} +
    + ); + } +}); + +const TagItem = React.createClass({ + propTypes: { + title: React.PropTypes.string, + href: React.PropTypes.string, + active: React.PropTypes.bool, + onClick: React.PropTypes.func, + // count and showX are exclusive + count: React.PropTypes.number, + showX: React.PropTypes.bool + }, + + getDefaultProps() { + return { + href: '#', + showX: false + }; + }, + + onClick(e) { + const { onClick } = this.props; + + if (!onClick) { + return; + } + + e.preventDefault(); + onClick(); + }, + + render() { + const { active, count, showX, title, href } = this.props; + + const className = classNames('tag', { + active + }); + + let inner = ''; + if (showX) { + inner = ; + } else if (typeof count !== 'undefined') { + inner = | {count}; + } + + return ( +
  • + + {title} + {inner} + +
  • + ); + } +}); + +module.exports = Tags; +module.exports.Item = TagItem; diff --git a/pool/shard011/JavaScript/0070366_getNotifications.js b/pool/shard011/JavaScript/0070366_getNotifications.js new file mode 100644 index 0000000000000000000000000000000000000000..662e41dd781fad09431878f574f4ecae015458bd --- /dev/null +++ b/pool/shard011/JavaScript/0070366_getNotifications.js @@ -0,0 +1,40 @@ +import { createSelector } from 'reselect'; +import * as commons from './commons'; + +/** + * Select notifications for a member from state + * + * @alias module:Members.getNotifications + * @category selectors + * + * @example + * const mapStateToProps = (state, props) => ({ + * show: BetaSeries.getSelector('members', 'getNotifications')(state, { memberId: props.memberId }); + * }); + * + * @param {Object} [state] Redux state + * @param {Object} [obj] Accept the following: + * @param {Object} [obj.memberId] Member ID + * + * @returns {Array} Notifications array element or `undefined` + */ + +const getNotifications = createSelector( + [commons.getMembers, commons.getNotifications, commons.getMemberId], + (members, membersNotifications, memberId) => { + const notifications = !Object.prototype.hasOwnProperty.call( + membersNotifications, + memberId + ) + ? null + : membersNotifications[memberId]; + + if (!notifications) { + return undefined; + } + + return notifications; + } +); + +export default getNotifications; diff --git a/pool/shard011/JavaScript/0070373_form.js b/pool/shard011/JavaScript/0070373_form.js new file mode 100644 index 0000000000000000000000000000000000000000..9eff4e77c3805eca676e54c147a2d985d207845d --- /dev/null +++ b/pool/shard011/JavaScript/0070373_form.js @@ -0,0 +1,141 @@ +/** + * JavaScript for form editing date conditions. + * + * @module moodle-availability_date-form + */ +M.availability_date = M.availability_date || {}; + +/** + * @class M.availability_date.form + * @extends M.core_availability.plugin + */ +M.availability_date.form = Y.Object(M.core_availability.plugin); + +/** + * Initialises this plugin. + * + * Because the date fields are complex depending on Moodle calendar settings, + * we create the HTML for these fields in PHP and pass it to this method. + * + * @method initInner + * @param {String} html HTML to use for date fields + * @param {Number} defaultTime Time value that corresponds to initial fields + */ +M.availability_date.form.initInner = function(html, defaultTime) { + this.html = html; + this.defaultTime = defaultTime; +}; + +M.availability_date.form.getNode = function(json) { + var strings = M.str.availability_date; + var html = strings.direction_before + ' ' + + ' ' + this.html; + var node = Y.Node.create('' + html + ''); + + // Set initial value if non-default. + if (json.t !== undefined) { + node.setData('time', json.t); + // Disable everything. + node.all('select:not([name=direction])').each(function(select) { + select.set('disabled', true); + }); + + var url = M.cfg.wwwroot + '/availability/condition/date/ajax.php?action=fromtime' + + '&time=' + json.t; + Y.io(url, { on : { + success : function(id, response) { + var fields = Y.JSON.parse(response.responseText); + for (var field in fields) { + var select = node.one('select[name=x\\[' + field + '\\]]'); + select.set('value', fields[field]); + select.set('disabled', false); + } + }, + failure : function() { + window.alert(M.str.availability_date.ajaxerror); + } + }}); + } else { + // Set default time that corresponds to the HTML selectors. + node.setData('time', this.defaultTime); + } + if (json.d !== undefined) { + node.one('select[name=direction]').set('value', json.d); + } + + // Add event handlers (first time only). + if (!M.availability_date.form.addedEvents) { + M.availability_date.form.addedEvents = true; + + var root = Y.one('#fitem_id_availabilityconditionsjson'); + root.delegate('change', function() { + // For the direction, just update the form fields. + M.core_availability.form.update(); + }, '.availability_date select[name=direction]'); + + root.delegate('change', function() { + // Update time using AJAX call from root node. + M.availability_date.form.updateTime(this.ancestor('span.availability_date')); + }, '.availability_date select:not([name=direction])'); + } + + if (node.one('a[href=#]')) { + // Add the date selector magic. + M.form.dateselector.init_single_date_selector(node); + + // This special handler detects when the date selector changes the year. + var yearSelect = node.one('select[name=x\\[year\\]]'); + var oldSet = yearSelect.set; + yearSelect.set = function(name, value) { + oldSet.call(yearSelect, name, value); + if (name === 'selectedIndex') { + // Do this after timeout or the other fields haven't been set yet. + setTimeout(function() { + M.availability_date.form.updateTime(node); + }, 0); + } + }; + } + + return node; +}; + +/** + * Updates time from AJAX. Whenever the field values change, we recompute the + * actual time via an AJAX request to Moodle. + * + * This will set the 'time' data on the node and then update the form, once it + * gets an AJAX response. + * + * @method updateTime + * @param {Y.Node} component Node for plugin controls + */ +M.availability_date.form.updateTime = function(node) { + // After a change to the date/time we need to recompute the + // actual time using AJAX because it depends on the user's + // time zone and calendar options. + var url = M.cfg.wwwroot + '/availability/condition/date/ajax.php?action=totime' + + '&year=' + node.one('select[name=x\\[year\\]]').get('value') + + '&month=' + node.one('select[name=x\\[month\\]]').get('value') + + '&day=' + node.one('select[name=x\\[day\\]]').get('value') + + '&hour=' + node.one('select[name=x\\[hour\\]]').get('value') + + '&minute=' + node.one('select[name=x\\[minute\\]]').get('value'); + Y.io(url, { on : { + success : function(id, response) { + node.setData('time', response.responseText); + M.core_availability.form.update(); + }, + failure : function() { + window.alert(M.str.availability_date.ajaxerror); + } + }}); +}; + +M.availability_date.form.fillValue = function(value, node) { + value.d = node.one('select[name=direction]').get('value'); + value.t = parseInt(node.getData('time'), 10); +}; diff --git a/pool/shard011/JavaScript/0070375_Gruntfile.js b/pool/shard011/JavaScript/0070375_Gruntfile.js new file mode 100644 index 0000000000000000000000000000000000000000..83ffcf910ce71583bbd781185b833b98200c80f2 --- /dev/null +++ b/pool/shard011/JavaScript/0070375_Gruntfile.js @@ -0,0 +1,17 @@ +var UmxGruntConfig = require('umx-grunt-config'); +module.exports = function(grunt) { + var configurator = new UmxGruntConfig(require, grunt); + configurator.initBump(); + configurator.initWebpack(); + configurator.initWatch(); + configurator.initJshint(); + configurator.initMochaTest(); + configurator.initUglify(); + configurator.registerBumpTasks(); + grunt.initConfig(configurator.config); + grunt.registerTask('test', [ 'jshint', 'mochaTest' ]); + grunt.registerTask('build', [ 'test', 'webpack' ]); + grunt.registerTask('build-min', [ 'build', 'uglify' ]); + grunt.registerTask('commit', [ 'build-min', 'bump-commit' ]); + grunt.registerTask('default', [ 'build-min' ]); +} diff --git a/pool/shard011/JavaScript/0070376_util.js b/pool/shard011/JavaScript/0070376_util.js new file mode 100644 index 0000000000000000000000000000000000000000..22f16dab5f81c4631ea311cdb7edb88672b9a51b --- /dev/null +++ b/pool/shard011/JavaScript/0070376_util.js @@ -0,0 +1,49 @@ +/** + * @file General utilities and settings. + * + * It also contains some helper functions to be used in EJS templates. + * + * @module lib/util + */ + +'use strict' + +var path = require('path') + +/** + * Directory with all the fate data. + * @type {string} + */ +module.exports.dir = '/var/www/fateweb' + +/** + * Port to listen on. + * @type {number} + */ +module.exports.port = 8080 + +/** + * Get the Gitweb URL of a piece of history between two commits or from + * one commit back. + * + * @param newer {string} Revision of the newer commit. + * @param [older] {string} Revision of the older commit. + * @return {string} HTML code for a hyperlink to the URL of the history. + */ +module.exports.linkGitHist = function (newer, older) { + var end = older ? ';hp=' + older : '' + return '' + + (older ? older : newer) + + '' +} + +module.exports.formatConfig = function (str) { + if (str == undefined) return '' + return str.replace(/(?!^)--/g, '
    --') +} + +module.exports.log = path.resolve(__dirname, '..', 'logs', 'access.log') + +module.exports.proxy = true + +module.exports.cache = 10 diff --git a/pool/shard011/JavaScript/0070378_find.js b/pool/shard011/JavaScript/0070378_find.js new file mode 100644 index 0000000000000000000000000000000000000000..b1929b729a87be912f1b2f2200ecc3f26d549af5 --- /dev/null +++ b/pool/shard011/JavaScript/0070378_find.js @@ -0,0 +1,47 @@ +module.exports = app => { + class Post extends app.Service { + //新增数据 + * create(post){ + return yield this.ctx.model.Post.create(post); + } + //删除数据 + * delete(id){ + return yield this.ctx.model.Post.destroy({where:{id: id}}); + } + //更新操作 + * update(id,msg){ + return yield this.ctx.model.Post.update(msg,{where:{id: id}}); + } + //关联查询 + * find(id){ + const post = yield this.ctx.model.Post.findById(id,{ + include: [{ + model: this.ctx.model.User, + as: 'user', + attributes: ['id','name','age'], + }], + }); + if(!post){ + this.ctx.throw(404,'post not found'); + } + return post; + }; + //单表查询 + * findSigle(id){ + const post = yield this.ctx.model.Post.findOne({where:{id: id}}); + if(!post){ + this.ctx.throw(404,'post not found'); + } + return post; + } + //单表查询,查询条件为数组 + * findInArray(ids){ + const post = yield this.ctx.model.Post.findAll({where: {id: ids}}); + if(!post){ + this.ctx.throw(404,'post not found'); + } + return post; + } + } + return Post; +} diff --git a/pool/shard011/JavaScript/0070394_mobile_operator.js b/pool/shard011/JavaScript/0070394_mobile_operator.js new file mode 100644 index 0000000000000000000000000000000000000000..edd2b44677a1362a41aed72fbfbf4ac1e97564f5 --- /dev/null +++ b/pool/shard011/JavaScript/0070394_mobile_operator.js @@ -0,0 +1,96 @@ +'use strict'; + +var MobileOperator = { + BRAZIL_MCC: 724, + BRAZIL_CELLBROADCAST_CHANNEL: 50, + + userFacingInfo: function mo_userFacingInfo(mobileConnection) { + var network = mobileConnection.voice.network; + var iccInfo = mobileConnection.iccInfo; + var operator = network.shortName || network.longName; + + if (iccInfo.isDisplaySpnRequired && iccInfo.spn + && !mobileConnection.voice.roaming) { + if (iccInfo.isDisplayNetworkNameRequired) { + operator = operator + ' ' + iccInfo.spn; + } else { + operator = iccInfo.spn; + } + } + + var carrier, region; + if (this.isBrazil(mobileConnection)) { + // We are in Brazil, It is legally required to show local info + // about current registered GSM network in a legally specified way. + var lac = mobileConnection.voice.cell.gsmLocationAreaCode % 100; + var carriers = MobileInfo.brazil.carriers; + var regions = MobileInfo.brazil.regions; + + carrier = carriers[network.mnc] || (this.BRAZIL_MCC.toString() + network.mnc); + region = (regions[lac] ? regions[lac] + ' ' + lac : ''); + } + + return { + 'operator': operator, + 'carrier': carrier, + 'region': region + }; + }, + + isBrazil: function mo_isBrazil(mobileConnection) { + var cell = mobileConnection.voice.cell; + return mobileConnection.voice.network.mcc == this.BRAZIL_MCC && + cell && cell.gsmLocationAreaCode; + } +}; + + +var MobileInfo = { + brazil: { + carriers: { + '0': 'NEXTEL', + '2': 'TIM', '3': 'TIM', '4': 'TIM', + '5': 'CLARO', '6': 'VIVO', '7': 'CTBC', '8': 'TIM', + '10': 'VIVO', '11': 'VIVO', '15': 'SERCOMTEL', + '16': 'OI', '23': 'VIVO', '24': 'OI', '31': 'OI', + '32': 'CTBC', '33': 'CTBC', '34': 'CTBC', '37': 'AEIOU' + }, + regions: { + '11': 'SP', '12': 'SP', '13': 'SP', '14': 'SP', '15': 'SP', '16': 'SP', + '17': 'SP', '18': 'SP', '19': 'SP', + '21': 'RJ', '22': 'RJ', '24': 'RJ', + '27': 'ES', '28': 'ES', + '31': 'MG', '32': 'MG', '33': 'MG', '34': 'MG', '35': 'MG', '37': 'MG', + '38': 'MG', + '41': 'PR', '42': 'PR', '43': 'PR', '44': 'PR', '45': 'PR', '46': 'PR', + '47': 'SC', '48': 'SC', '49': 'SC', + '51': 'RS', '53': 'RS', '54': 'RS', '55': 'RS', + '61': 'DF', + '62': 'GO', + '63': 'TO', + '64': 'GO', + '65': 'MT', '66': 'MT', + '67': 'MS', + '68': 'AC', + '69': 'RO', + '71': 'BA', '73': 'BA', '74': 'BA', '75': 'BA', '77': 'BA', + '79': 'SE', + '81': 'PE', + '82': 'AL', + '83': 'PB', + '84': 'RN', + '85': 'CE', + '86': 'PI', + '87': 'PE', + '88': 'CE', + '89': 'PI', + '91': 'PA', + '92': 'AM', + '93': 'PA', '94': 'PA', + '95': 'RR', + '96': 'AP', + '97': 'AM', + '98': 'MA', '99': 'MA' + } + } +}; diff --git a/pool/shard011/JavaScript/0070396_eachs.js b/pool/shard011/JavaScript/0070396_eachs.js new file mode 100644 index 0000000000000000000000000000000000000000..1d50aedc8f8fcc72615ad94dea099397902eb2f1 --- /dev/null +++ b/pool/shard011/JavaScript/0070396_eachs.js @@ -0,0 +1,102 @@ +/* jshint strict: true, undef: true */ +/* globals spec, _, to_string, is_enumerable, length, keys_or_indexes */ +/* globals exports */ + + +// TODO: spec :eachs does not alter inputs +spec( + ["01", "12"], + function eachs_passes_key_and_val() { + + var v = []; + eachs( [1,2], function (kx, x) { v.push("" + kx + x); }); + return v; + } +); + +spec( + ["1a", "1b", "2a", "2b"], + function eachs_passes_vals_of_multiple_colls() { + + var v = []; + eachs( [1,2], ["a", "b"], function (kx, x, ky, y) { v.push("" + x + y); }); + return v; + } +); + +spec( + ["onea", "twoa"], + function eachs_passes_keys_and_vals_of_arrays_and_plain_objects() { + + var v = []; + eachs({one: 1, two: 2}, ["a"], function (kx, x, ky, y) { v.push("" + kx + y); }); + return v; + } +); + +spec( + ["1a", "1b", "2a", "2b"], + function eachs_passes_vals_of_plain_object_and_array() { + + var v = []; + eachs({one: 1, two: 2}, ["a", "b"], function (kx, x, ky, y) { v.push("" + x + y); }); + return v; + } +); + +spec( [], + function eachs_returns_empty_array_if_one_array_is_empty() { + + var v = []; + eachs({one: 1, two: 2}, [], ["a"], function (kx, x, ky, y, kz, z) { + v.push("" + kx + y); + }); + return v; + } +); + +exports.eachs = eachs; +function eachs() { + + var args = _.toArray(arguments); + + if (args.length < 2) + throw new Error("Not enough args: " + to_string(args)); + var f = args.pop(); + + // === Validate inputs before continuing: + for (var i = 0; i < args.length; i++) { + if (!is_enumerable(args[i])) + throw new Error("Invalid value for eachs: " + to_string(args[i])); + } + + // === Process inputs: + var cols_length = length(args); + + return eachs_row_maker([], 0, _.map(args, keys_or_indexes)); + + function eachs_row_maker(row, col_i, key_cols) { + if (col_i >= cols_length) { + if (row.length !== f.length) + throw new Error("f.length (" + f.length + ") should be " + row.length + " (collection count * 2 )"); + f.apply(null, [].concat(row)); // set reduced value + return; + } + + var keys = key_cols[col_i].slice(0); + var vals = args[col_i]; + ++col_i; + + for(var i = 0; i < keys.length; i++) { + row.push(keys[i]); // key + row.push(vals[keys[i]]); // actual value + + eachs_row_maker(row, col_i, key_cols); + + row.pop(); + row.pop(); + } + + return; + } +} diff --git a/pool/shard011/JavaScript/0070398_fs.js b/pool/shard011/JavaScript/0070398_fs.js new file mode 100644 index 0000000000000000000000000000000000000000..b1baf1f50e89e415b56b29ea858cd80b98ac3aa4 --- /dev/null +++ b/pool/shard011/JavaScript/0070398_fs.js @@ -0,0 +1,17 @@ +'use strict' + +const fs = jest.genMockFromModule(`fs`) + +let mockFiles = {} +function __setMockFiles(newMockFiles) { + mockFiles = Object.assign({}, newMockFiles) +} + +function readFileSync(filePath, parser) { + return mockFiles[filePath] +} + +fs.__setMockFiles = __setMockFiles +fs.readFileSync = readFileSync + +module.exports = fs diff --git a/pool/shard011/JavaScript/0070399_list-elem.js b/pool/shard011/JavaScript/0070399_list-elem.js new file mode 100644 index 0000000000000000000000000000000000000000..7b8cfa0df07c5040aceb633a1c5bcf211c891278 --- /dev/null +++ b/pool/shard011/JavaScript/0070399_list-elem.js @@ -0,0 +1,61 @@ +(function() { + window.daElements.listElem = { + properties: { + localData: { + type: Array, + value: [] + }, + filters: { + type: Array, + notify: true, + value: [] + }, + activeFilterId: { + type: Number, + value: null, + observer: 'filter', + notify: true + }, + user: { + type: String + } + }, + listeners: { + 'cell-tap': 'cellTap' + }, + cellListeners: { + 'Docket': 'docketTap' + }, + ready: function() { + return app.patchDatatable(this.$.datatableList, this); + }, + refresh: function() { + console.log("refreshing case list"); + this.$.datatableList.data = []; + this.filter(); + return this.$.datatableList.data = this.localData; + }, + filter: function() { + var filter; + if (this.activeFilterId !== null) { + filter = this.filters[this.activeFilterId]; + return this.localData = filter.filter(app.cases); + } else { + return this.localData = app.cases; + } + }, + cellTap: function(e) { + if (this.cellListeners[e.detail.column.header] != null) { + return this[this.cellListeners[e.detail.column.header]](e); + } + }, + docketTap: function(e) { + if (e.detail.item["case"] != null) { + return app.displayCase(e.detail.item["case"].id); + } else { + return app.displayCase(e.detail.item.id); + } + } + }; + +}).call(this); diff --git a/pool/shard011/JavaScript/0070400_Provider.js b/pool/shard011/JavaScript/0070400_Provider.js new file mode 100644 index 0000000000000000000000000000000000000000..10fb87b6a006af5f5794e9c8824f23ff67ac3d83 --- /dev/null +++ b/pool/shard011/JavaScript/0070400_Provider.js @@ -0,0 +1,103 @@ +"use strict"; + +angular.module('FullstackApp.Provider',[]) +.factory('ProviderFct', function() { + + var providerFct = { + new: function() { + + var model = { + id: null, + name: "" + }; + + return model; + } + } + + return providerFct; +}) +.service('ProviderSvc',function( $http ) { + this.providers = []; + var That = this; + + this.getAll = function() { + var promise = new Promise( + function( resolve, reject) { + if ( That.providers.length ) { + resolve( That.providers); + } + else { + $http.get('/providers').then(function(res) { + That.providers = res.data; + resolve( res.data) + }).catch(reject); + } + } + ); + return promise; + } + this.delete = function( provider ) { return $http.delete('/providers/' + provider.id) } + this.save = function( provider ) { + var promise = new Promise( + function( resolve, reject ) { + $http.post('/providers/:id', provider).then(resolve, reject); + } + ); + return promise; + } + this.getAll = this.getAll.bind( this ); +}) +.controller('ProviderCtrl',function( $scope, ProviderSvc, ProviderFct ) { + + angular.extend($scope, { + providers: [], + newProvider: ProviderFct.new() + }); + + $scope.saveProvider = function( provider ) { + ProviderSvc.save( provider ).then(function( res ){ + if (!provider.id) { + $scope.providers.push( res.data.model ); + $scope.newProvider.name = ""; + } + $scope.$emit('providersChange', $scope.providers); + }).catch( function( err ) { + $scope.showError( err.data ); + }); + + } + + // Adds a new provider + $scope.addProvider = function() { + if ( $scope.newProvider.name.length ) $scope.saveProvider( $scope.newProvider ); + } + + // Updates a provider's name + $scope.editProvider = function( provider ) { + var name = prompt("Enter the provider's name", provider.name); + if ( angular.isString( name ) && name.length ) { + provider.name = name; + $scope.saveProvider( provider ); + } + } + + // Deletes a provider + $scope.deleteProvider = function( provider ) { + if (confirm("Are you sure you want to delete the provider: ".concat(provider.name,"?"))) { + ProviderSvc.delete( provider ).then(function( res ) { + var i = $scope.providers.indexOf( provider ); + $scope.providers.splice(i, 1); + $scope.$emit('providersChange', $scope.providers); + }); + } + } + + // Loads the provider's list + ProviderSvc.getAll().then(function( providers ) { + $scope.providers = providers; + $scope.$emit('providersChange', providers); + }).catch(function( res ) { + $scope.showError( res.data.err ); + }) +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070407_blip-assistant.js b/pool/shard011/JavaScript/0070407_blip-assistant.js new file mode 100644 index 0000000000000000000000000000000000000000..b9eaaa2039b2ec337a22a73d16720bef8a7a8b74 --- /dev/null +++ b/pool/shard011/JavaScript/0070407_blip-assistant.js @@ -0,0 +1,305 @@ +function BlipAssistant() { + /* this is the creator function for your scene assistant object. It will be passed all the + additional parameters (after the scene name) that were passed to pushScene. The reference + to the scene controller (this.controller) has not be established yet, so any initialization + that needs the scene controller should be done in the setup function below. */ + + // Database object + this.sqlite = new Sqlite("tram2000") + // Number of seconds since beginning of the journey + this.seconds = 0 + // Latest timestamp returned by GPS + this.timestamp = 0 + this.positions_queue = [] + // Keeps active blip object + this.blip = false + // Latest know position +// this.lat_lng = false + // How many stops did we past + this.count = 0 + // + this.last_measure = 0 +} + +// this function is for setup tasks that have to happen when the scene is first created +BlipAssistant.prototype.setup = function() { + + // Timer setup + this.timerRollHandler = this.timerRoll.bind(this) + this.interval = window.setInterval(this.timerRollHandler, 1000) + + // Command menu setup + this.commandMenuModel = {items: [{label: 'Pokaż szczegóły', command: 'show-details'}, {label: 'Reset', icon:'refresh', command:'reset'}]} + this.controller.setupWidget(Mojo.Menu.commandMenu, {}, this.commandMenuModel) + + // Start tracking + this.controller.serviceRequest('palm://com.palm.location', { + method : "startTracking", + parameters: { + accuracy : 1, + responseTime: 1, + subscribe : true + }, + onSuccess : this.onGpsSuccess.bind(this), + onFailure : this.onGpsFailure.bind(this) + }) + + // Require the device to stay awake + this.controller.serviceRequest("palm://com.palm.power/com/palm/power", { + method : "activityStart", + parameters: { + id : "com.palm.app.news.update-1", + duration_ms : "900000" // = 15 minutes (max) + }, + onSuccess : function(){ console.log("Keeping awake for 15 min...") }, + onFailure : function(){ console.log("Keeping awake failure.") } + }) + +} + +BlipAssistant.prototype.onGpsSuccess = function(data) { + + // Time which might be useful if we create new blip + this.timestamp = data.timestamp + this.positions_queue.push({lat: data.latitude, lng: data.longitude, time: data.timestamp}) +// console.log(Object.toJSON(this.positions_queue)) + +} + +BlipAssistant.prototype.onGpsFailure = function(status){ + // console.log("Porażka gps" + Object.toJSON(errorCode)) + window.clearInterval(this.interval) + this.controller.showAlertDialog({ + onChoose: function() { }, + title: 'Błąd GPS ('+ status.errorCode +')', + message: 'Nie mogłem ustalić bieżącego położenia.', + choices: [ + {label: 'Spróbuj ponownie'}, + {label: 'Anuluj'} + ] + }) +} + +// On found nearby stops +BlipAssistant.prototype.dbSuccessHandler = function(transaction, SQLResultSet) { + // Handle successful queries including receiving results + // console.log("SQL success: " + SQLResultSet.rows.length) + var the_nearest_stop + var position = this.positions_queue[this.positions_queue.length - 1] + + if(SQLResultSet.rows.length > 1) { + // Find the closest stop + var first_stop = SQLResultSet.rows.item(0) + // Infinity + var closest_distance = length(decodeGeoHash(first_stop.geo), position) // We can use this.lat_lng because it is the same as current position + the_nearest_stop = first_stop + + for(var i=1; i distance){ + closest_distance = distance + the_nearest_stop = stop + } + } + } else if(SQLResultSet.rows.length == 1) { + the_nearest_stop = SQLResultSet.rows.item(0) + } else { + // Nothing to do here + return + } + + // console.log("Najbliższy przystanek: " + the_nearest_stop.id) + // console.log("Next: " + Object.toJSON(this.blip.next)) + +// if(!this.blip){ +// // The same stop. Nothing do do here +// return +// } + + // Check whether or not we are where we were + if(this.blip && this.blip.beg_id != the_nearest_stop.id) { + + if(this.blip.next.indexOf( the_nearest_stop.id ) == -1) { + var transfer = false + $.each(this.blip.alternate_next, function(id, hash){ + if(hash.next.indexOf( the_nearest_stop.id ) != -1){ + transfer = {id: id, time: hash.time} + return + } + }) + if(transfer) { // There was a transfer (previously) + // Remove redundant data + var transfer_time = Math.round((transfer.time - this.blip.beg_time) / 1000) +// console.log(transfer_time) + this.data = this.blip.data.substring(transfer_time) + + this.blip.beg_id = transfer.id + this.blip.beg_time = transfer.time + } else { + // We may transferred + if(!this.blip.alternate_next[the_nearest_stop.id]) { + this.blip.alternate_next[the_nearest_stop.id] = {next: the_nearest_stop.next.split(","), time: this.timestamp} + + } + return + } + } + // Otherwise we have the simplest scenario + + // Finish and save current blip + // These are common actions for both situations: with and without transfer + this.blip.end_id = the_nearest_stop.id + this.blip.save() + this.blip = false + + } else if(this.blip) { + // Prevent double blip + return + } + + // Begin new blip + this.blip = new Blip(this.sqlite, this.timestamp, the_nearest_stop) + this.controller.get("count").update(this.count++) +} + +BlipAssistant.prototype.timerRoll = function(event){ + + // Update timer + this.seconds++ + var min = Math.floor(this.seconds / 60) + var sec = this.seconds % 60 + if(sec < 10) sec = "0" + sec + this.controller.get("time").update(min + ":" + sec) + + this.last_measure++ + // Calculate speed + var speed = 0 + // If this is not a first call (so we can display current speed) + + if(this.positions_queue.length == 2){ + // Current position + var location = this.positions_queue.pop() + // this will be our reference + var prev_location = this.positions_queue.pop() + + // Estimate current speed (if there is a movement) + if(prev_location.lat != location.lat || prev_location.lng != location.lng) + speed = Math.round(length(prev_location, location) * ((location.time - prev_location.time) * (100/36))) + + } else if(location && this.last_measure == 1) { + // First call or GPS didn't return position + speed = 0 + } else { + // GPS doesn't respond for 3 seconds or more + speed = -1 + } + + console.log("speed: " + speed) + // console.log(Object.toJSON(data)) + if(speed == -1) { + speed = "-" + } else { + + // Only if there is no speed, + // check if we are close enough to a stop (or stops) + if(speed == 0) Stops.findNearby(this.sqlite, location, this.dbSuccessHandler.bind(this)) + + // append new data to blip + if(this.blip) { + this.blip.add( length(location, this.blip) * 1000, this.last_measure ) + this.last_measure = 0 + } + + this.positions_queue = [location] + + speed += " km/h" + } + + this.controller.get("speed").update(speed) + + // We no longer need previous position +// this.lat_lng = p2 + + +} + +BlipAssistant.prototype.activate = function(event) { + /* put in event handlers here that should only be in effect when this scene is active. For + example, key handlers that are observing the document */ +} + + +BlipAssistant.prototype.deactivate = function(event) { + /* remove any event handlers you added in activate and do any other cleanup that should happen before + this scene is popped or another scene is pushed on top */ +} + +BlipAssistant.prototype.cleanup = function(event) { + /* this function should do any cleanup needed before the scene is destroyed as + a result of being popped off the scene stack */ + + clearInterval(this.interval) +} + +BlipAssistant.prototype.toggleDetails = function(){ + // console.log("showing details") + $("#details").toggleClass("hidden") + // Nie mogłem połączyć się z siecią internet. +} + +BlipAssistant.prototype.handleCommand = function(event) { + + if(event.type == Mojo.Event.command) { + switch(event.command) { + case 'show-details': + this.commandMenuModel.temp = this.commandMenuModel.items + this.commandMenuModel.items = [{label: 'Ukryj szczegóły', command: 'hide-details'}, {label: 'Reset', icon:'refresh', command:'reset'}] + this.controller.modelChanged(this.commandMenuModel) + this.toggleDetails() + break + + case 'hide-details': + this.commandMenuModel.items = this.commandMenuModel.temp + this.controller.modelChanged(this.commandMenuModel) + this.toggleDetails() + break + + case 'reset': + Mojo.Controller.stageController.activeScene().showAlertDialog({ + onChoose: function(value) { + if(value){ + this.blip = false + this.count = 0 + this.seconds = -1 + this.controller.get("count").update("-") + } + }, + title: "Restart", + message: "Czy na pewno chcesz na nowo rozpocząć proces monitorowania podróży?", + choices:[ + {label: 'Tak', value: true}, + {label: 'Nie', value: false} + ] + }) + break + } + } +} + +// Converts degrees to radians +Number.prototype.toRad = function() { + return this * Math.PI / 180 +} + +// Returns length between two points in km +function length(p1, p2){ + var R = 6371 // Radius of the earth in km + var dLat = (p2.lat - p1.lat).toRad() // Javascript functions in radians + var dLon = (p2.lng - p1.lng).toRad() + var a = Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(p1.lat.toRad()) * Math.cos(p2.lat.toRad()) * + Math.sin(dLon/2) * Math.sin(dLon/2) + var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) + return R * c // Return distance in km +} diff --git a/pool/shard011/JavaScript/0070410_eserveri.js b/pool/shard011/JavaScript/0070410_eserveri.js new file mode 100644 index 0000000000000000000000000000000000000000..cfeae8cc778f8ca5efefec26cc1a7a65f56849e7 --- /dev/null +++ b/pool/shard011/JavaScript/0070410_eserveri.js @@ -0,0 +1,52 @@ +exports.run = function(bot, msg, args) { + var tag = msg.guild.owner.user; + msg.delete(); + msg.channel.send({ + embed: { + color: 3447003, + author: { + name: msg.guild.name, + icon_url: msg.guild.iconURL + }, + title: 'Statistics', + url: '', + description: 'serverinfo', + fields: [{ + name: 'Owner:', + value: `${tag.username}#${tag.discriminator} (${msg.guild.owner.id})` + }, + { + name: 'Member Count', + value: `${msg.guild.memberCount} (${msg.guild.members.filter(m=>m.user.bot).size} Bots)`, + inline: true + }, + { + name: 'AFK Timeout', + value: `${msg.guild.afkTimeout / 60} minutes`, + inline: true + }, + { + name: 'Location', + value: msg.guild.region, + inline: true + }, + { + name: 'Created', + value: msg.guild.createdAt.toLocaleString(), + inline: true + } + ], + timestamp: new Date(), + footer: { + icon_url: bot.user.avatarURL, + text: '© Jesse / Maxine#8621' + } + } + }); +} + +exports.info = { + name: 'server', + usage: 'server', + description: 'shows the serverinfo in embed' +}; diff --git a/pool/shard011/JavaScript/0070413_js.js b/pool/shard011/JavaScript/0070413_js.js new file mode 100644 index 0000000000000000000000000000000000000000..99c355bd1533190313f8aebc5002c843abb05428 --- /dev/null +++ b/pool/shard011/JavaScript/0070413_js.js @@ -0,0 +1,29 @@ +exports.vargs = function(args, n) { return Array.prototype.slice.call(args, n || 0); } +exports.isArray = function(input) { return Object.prototype.toString.call(input) === '[object Array]'; } + +exports.shallowCopy = function(input) { + if (exports.isArray(input)) { + return input.slice(0); + } else { + var out = {}; + for (var key in input) { + if (input.hasOwnProperty(key)) { + out[key] = input[key]; + } + } + } + + return out; +} + +exports.merge = function(base, extra) { + base = base || {}; + + for (var key in extra) { + if (extra.hasOwnProperty(key) && !base.hasOwnProperty(key)) { + base[key] = extra[key]; + } + } + + return base; +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070414_md023.js b/pool/shard011/JavaScript/0070414_md023.js new file mode 100644 index 0000000000000000000000000000000000000000..c7173c1720a19ca5ec64117f93ef2d7774dc71cc --- /dev/null +++ b/pool/shard011/JavaScript/0070414_md023.js @@ -0,0 +1,38 @@ +// @ts-check + +"use strict"; + +const { addErrorContext, filterTokens } = require("../helpers"); + +const spaceBeforeHeadingRe = /^((?:\s+)|(?:[>\s]+\s\s))[^>\s]/; + +module.exports = { + "names": [ "MD023", "heading-start-left", "header-start-left" ], + "description": "Headings must start at the beginning of the line", + "tags": [ "headings", "headers", "spaces" ], + "function": function MD023(params, onError) { + filterTokens(params, "heading_open", function forToken(token) { + const { lineNumber, line } = token; + const match = line.match(spaceBeforeHeadingRe); + if (match) { + const [ prefixAndFirstChar, prefix ] = match; + let deleteCount = prefix.length; + const prefixLengthNoSpace = prefix.trimEnd().length; + if (prefixLengthNoSpace) { + deleteCount -= prefixLengthNoSpace - 1; + } + addErrorContext( + onError, + lineNumber, + line, + null, + null, + [ 1, prefixAndFirstChar.length ], + { + "editColumn": prefixLengthNoSpace + 1, + "deleteCount": deleteCount + }); + } + }); + } +}; diff --git a/pool/shard011/JavaScript/0070415_tab.js b/pool/shard011/JavaScript/0070415_tab.js new file mode 100644 index 0000000000000000000000000000000000000000..74bd71e9263cca79931302886b845ba14a050b71 --- /dev/null +++ b/pool/shard011/JavaScript/0070415_tab.js @@ -0,0 +1,155 @@ +/* ======================================================================== + * Bootstrap: tab.js v3.3.7 + * http://getbootstrap.com/javascript/#tabs + * ======================================================================== + * Copyright 2011-2016 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * ======================================================================== */ + + ++function ($) { + 'use strict'; + + // TAB CLASS DEFINITION + // ==================== + + var Tab = function (element) { + // jscs:disable requireDollarBeforejQueryAssignment + this.element = $(element); + // jscs:enable requireDollarBeforejQueryAssignment + }; + + Tab.VERSION = '3.3.7'; + + Tab.TRANSITION_DURATION = 150; + + Tab.prototype.show = function () { + var $this = this.element; + var $ul = $this.closest('ul:not(.dropdown-menu)'); + var selector = $this.data('target'); + + if (!selector) { + selector = $this.attr('href'); + selector = selector && selector.replace(/.*(?=#[^\s]*$)/, ''); // strip for ie7 + } + + if ($this.parent('li').hasClass('active')) return; + + var $previous = $ul.find('.active:last a'); + var hideEvent = $.Event('hide.bs.tab', { + relatedTarget: $this[0] + }); + var showEvent = $.Event('show.bs.tab', { + relatedTarget: $previous[0] + }); + + $previous.trigger(hideEvent); + $this.trigger(showEvent); + + if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return; + + var $target = $(selector); + + this.activate($this.closest('li'), $ul); + this.activate($target, $target.parent(), function () { + $previous.trigger({ + type: 'hidden.bs.tab', + relatedTarget: $this[0] + }); + $this.trigger({ + type: 'shown.bs.tab', + relatedTarget: $previous[0] + }) + }) + }; + + Tab.prototype.activate = function (element, container, callback) { + var $active = container.find('> .active'); + var transition = callback + && $.support.transition + && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length); + + function next() { + $active + .removeClass('active') + .find('> .dropdown-menu > .active') + .removeClass('active') + .end() + .find('[data-toggle="tab"]') + .attr('aria-expanded', false); + + element + .addClass('active') + .find('[data-toggle="tab"]') + .attr('aria-expanded', true); + + if (transition) { + element[0].offsetWidth; // reflow for transition + element.addClass('in') + } else { + element.removeClass('fade') + } + + if (element.parent('.dropdown-menu').length) { + element + .closest('li.dropdown') + .addClass('active') + .end() + .find('[data-toggle="tab"]') + .attr('aria-expanded', true) + } + + callback && callback() + } + + $active.length && transition ? + $active + .one('bsTransitionEnd', next) + .emulateTransitionEnd(Tab.TRANSITION_DURATION) : + next(); + + $active.removeClass('in') + }; + + + // TAB PLUGIN DEFINITION + // ===================== + + function Plugin(option) { + return this.each(function () { + var $this = $(this); + var data = $this.data('bs.tab'); + + if (!data) $this.data('bs.tab', (data = new Tab(this))); + if (typeof option == 'string') data[option]() + }) + } + + var old = $.fn.tab; + + $.fn.tab = Plugin; + $.fn.tab.Constructor = Tab; + + + // TAB NO CONFLICT + // =============== + + $.fn.tab.noConflict = function () { + $.fn.tab = old; + return this + }; + + + // TAB DATA-API + // ============ + + var clickHandler = function (e) { + e.preventDefault(); + Plugin.call($(this), 'show') + }; + + $(document) + .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) + .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) + +}(jQuery); diff --git a/pool/shard011/JavaScript/0070416_sigV4Client.js b/pool/shard011/JavaScript/0070416_sigV4Client.js new file mode 100644 index 0000000000000000000000000000000000000000..3dc5a76caf827d60c332b5395f28f47dbd761154 --- /dev/null +++ b/pool/shard011/JavaScript/0070416_sigV4Client.js @@ -0,0 +1,220 @@ +/* + * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ + +/* + * Note: The original sourcecode autogenerated by the Amazon APIGateway has been modified by + * Civic. + */ + +var utils = require("./utils"); +var CryptoJS = require("../CryptoJS/rollups/hmac-sha256"); +var axios = require("../axios/dist/axios.standalone"); + +var sigV4ClientFactory = {}; +sigV4ClientFactory.newClient = function (config) { + var AWS_SHA_256 = 'AWS4-HMAC-SHA256'; + var AWS4_REQUEST = 'aws4_request'; + var AWS4 = 'AWS4'; + var X_AMZ_DATE = 'x-amz-date'; + var X_AMZ_SECURITY_TOKEN = 'x-amz-security-token'; + var HOST = 'host'; + var AUTHORIZATION = 'Authorization'; + + function hash(value) { + return CryptoJS.SHA256(value); + } + + function hexEncode(value) { + return value.toString(CryptoJS.enc.Hex); + } + + function hmac(secret, value) { + return CryptoJS.HmacSHA256(value, secret, {asBytes: true}); + } + + function buildCanonicalRequest(method, path, queryParams, headers, payload) { + return method + '\n' + + buildCanonicalUri(path) + '\n' + + buildCanonicalQueryString(queryParams) + '\n' + + buildCanonicalHeaders(headers) + '\n' + + buildCanonicalSignedHeaders(headers) + '\n' + + hexEncode(hash(payload)); + } + + function hashCanonicalRequest(request) { + return hexEncode(hash(request)); + } + + function buildCanonicalUri(uri) { + return encodeURI(uri); + } + + function buildCanonicalQueryString(queryParams) { + if (Object.keys(queryParams).length < 1) { + return ''; + } + + var sortedQueryParams = []; + for (var property in queryParams) { + if (queryParams.hasOwnProperty(property)) { + sortedQueryParams.push(property); + } + } + sortedQueryParams.sort(); + + var canonicalQueryString = ''; + for (var i = 0; i < sortedQueryParams.length; i++) { + canonicalQueryString += sortedQueryParams[i] + '=' + encodeURIComponent(queryParams[sortedQueryParams[i]]) + '&'; + } + return canonicalQueryString.substr(0, canonicalQueryString.length - 1); + } + + function buildCanonicalHeaders(headers) { + var canonicalHeaders = ''; + var sortedKeys = []; + for (var property in headers) { + if (headers.hasOwnProperty(property)) { + sortedKeys.push(property); + } + } + sortedKeys.sort(); + + for (var i = 0; i < sortedKeys.length; i++) { + canonicalHeaders += sortedKeys[i].toLowerCase() + ':' + headers[sortedKeys[i]] + '\n'; + } + return canonicalHeaders; + } + + function buildCanonicalSignedHeaders(headers) { + var sortedKeys = []; + for (var property in headers) { + if (headers.hasOwnProperty(property)) { + sortedKeys.push(property.toLowerCase()); + } + } + sortedKeys.sort(); + + return sortedKeys.join(';'); + } + + function buildStringToSign(datetime, credentialScope, hashedCanonicalRequest) { + return AWS_SHA_256 + '\n' + + datetime + '\n' + + credentialScope + '\n' + + hashedCanonicalRequest; + } + + function buildCredentialScope(datetime, region, service) { + return datetime.substr(0, 8) + '/' + region + '/' + service + '/' + AWS4_REQUEST + } + + function calculateSigningKey(secretKey, datetime, region, service) { + return hmac(hmac(hmac(hmac(AWS4 + secretKey, datetime.substr(0, 8)), region), service), AWS4_REQUEST); + } + + function calculateSignature(key, stringToSign) { + return hexEncode(hmac(key, stringToSign)); + } + + function buildAuthorizationHeader(accessKey, credentialScope, headers, signature) { + return AWS_SHA_256 + ' Credential=' + accessKey + '/' + credentialScope + ', SignedHeaders=' + buildCanonicalSignedHeaders(headers) + ', Signature=' + signature; + } + + var awsSigV4Client = { }; + if(config.accessKey === undefined || config.secretKey === undefined) { + return awsSigV4Client; + } + awsSigV4Client.accessKey = utils.assertDefined(config.accessKey, 'accessKey'); + awsSigV4Client.secretKey = utils.assertDefined(config.secretKey, 'secretKey'); + awsSigV4Client.sessionToken = config.sessionToken; + awsSigV4Client.serviceName = utils.assertDefined(config.serviceName, 'serviceName'); + awsSigV4Client.region = utils.assertDefined(config.region, 'region'); + awsSigV4Client.endpoint = utils.assertDefined(config.endpoint, 'endpoint'); + awsSigV4Client.host = utils.assertDefined(config.host, 'host'); + + awsSigV4Client.makeRequest = function (request) { + var verb = utils.assertDefined(request.verb, 'verb'); + var path = utils.assertDefined(request.path, 'path'); + var queryParams = utils.copy(request.queryParams); + if (queryParams === undefined) { + queryParams = {}; + } + var headers = utils.copy(request.headers); + if (headers === undefined) { + headers = {}; + } + + //If the user has not specified an override for Content type the use default + if(headers['Content-Type'] === undefined) { + headers['Content-Type'] = config.defaultContentType; + } + + //If the user has not specified an override for Accept type the use default + if(headers['Accept'] === undefined) { + headers['Accept'] = config.defaultAcceptType; + } + + var body = utils.copy(request.body); + if (body === undefined || verb === 'GET') { // override request body and set to empty when signing GET requests + body = ''; + } else { + body = JSON.stringify(body); + } + + //If there is no body remove the content-type header so it is not included in SigV4 calculation + if(body === '' || body === undefined || body === null) { + delete headers['Content-Type']; + } + + var datetime = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z').replace(/[:\-]|\.\d{3}/g, ''); + headers[X_AMZ_DATE] = datetime; + headers[HOST] = awsSigV4Client.host; + var canonicalRequest = buildCanonicalRequest(verb, path, queryParams, headers, body); + + var hashedCanonicalRequest = hashCanonicalRequest(canonicalRequest); + var credentialScope = buildCredentialScope(datetime, awsSigV4Client.region, awsSigV4Client.serviceName); + var stringToSign = buildStringToSign(datetime, credentialScope, hashedCanonicalRequest); + var signingKey = calculateSigningKey(awsSigV4Client.secretKey, datetime, awsSigV4Client.region, awsSigV4Client.serviceName); + var signature = calculateSignature(signingKey, stringToSign); + headers[AUTHORIZATION] = buildAuthorizationHeader(awsSigV4Client.accessKey, credentialScope, headers, signature); + if(awsSigV4Client.sessionToken !== undefined && awsSigV4Client.sessionToken !== '') { + headers[X_AMZ_SECURITY_TOKEN] = awsSigV4Client.sessionToken; + } + delete headers[HOST]; + + var url = config.endpoint + path; + var queryString = buildCanonicalQueryString(queryParams); + if (queryString != '') { + url += '?' + queryString; + } + + //Need to re-attach Content-Type if it is not specified at this point + if(headers['Content-Type'] === undefined) { + headers['Content-Type'] = config.defaultContentType; + } + + var signedRequest = { + method: verb, + url: url, + headers: headers, + data: body + }; + return axios(signedRequest); + }; + + return awsSigV4Client; +}; + +module.exports = sigV4ClientFactory; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070417_app.js b/pool/shard011/JavaScript/0070417_app.js new file mode 100644 index 0000000000000000000000000000000000000000..4aec7b317089b768ddd623c3f7af8833b1c53ef8 --- /dev/null +++ b/pool/shard011/JavaScript/0070417_app.js @@ -0,0 +1,140 @@ +/* + * + * INSPINIA - Responsive Admin Theme + * version 2.7.1 + * + */ + +$(document).ready(function () { + + + // Add body-small class if window less than 768px + if ($(this).width() < 769) { + $('body').addClass('body-small') + } else { + $('body').removeClass('body-small') + } + + // MetsiMenu + $('#side-menu').metisMenu(); + + // Collapse ibox function + $('.collapse-link').on('click', function () { + var ibox = $(this).closest('div.ibox'); + var button = $(this).find('i'); + var content = ibox.children('.ibox-content'); + content.slideToggle(200); + button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down'); + ibox.toggleClass('').toggleClass('border-bottom'); + setTimeout(function () { + ibox.resize(); + ibox.find('[id^=map-]').resize(); + }, 50); + }); + + // Close ibox function + $('.close-link').on('click', function () { + var content = $(this).closest('div.ibox'); + content.remove(); + }); + + // Fullscreen ibox function + $('.fullscreen-link').on('click', function () { + var ibox = $(this).closest('div.ibox'); + var button = $(this).find('i'); + $('body').toggleClass('fullscreen-ibox-mode'); + button.toggleClass('fa-expand').toggleClass('fa-compress'); + ibox.toggleClass('fullscreen'); + setTimeout(function () { + $(window).trigger('resize'); + }, 100); + }); + + // Minimalize menu + $('.navbar-minimalize').on('click', function (event) { + event.preventDefault(); + $("body").toggleClass("mini-navbar"); + SmoothlyMenu(); + + }); + + // Full height of sidebar + function fix_height() { + var heightWithoutNavbar = $("body > #wrapper").height() - 61; + $(".sidebard-panel").css("min-height", heightWithoutNavbar + "px"); + + var navbarHeight = $('nav.navbar-default').height(); + var wrapperHeight = $('#page-wrapper').height(); + + if (navbarHeight > wrapperHeight) { + $('#page-wrapper').css("min-height", navbarHeight + "px"); + } + + if (navbarHeight < wrapperHeight) { + $('#page-wrapper').css("min-height", $(window).height() + "px"); + } + + if ($('body').hasClass('fixed-nav')) { + if (navbarHeight > wrapperHeight) { + $('#page-wrapper').css("min-height", navbarHeight + "px"); + } else { + $('#page-wrapper').css("min-height", $(window).height() - 60 + "px"); + } + } + + } + + fix_height(); + + // Fixed Sidebar + $(window).bind("load", function () { + if ($("body").hasClass('fixed-sidebar')) { + $('.sidebar-collapse').slimScroll({ + height: '100%', + railOpacity: 0.9 + }); + } + }); + + $(window).bind("load resize scroll", function () { + if (!$("body").hasClass('body-small')) { + fix_height(); + } + }); + + // Add slimscroll to element + $('.full-height-scroll').slimscroll({ + height: '100%' + }) +}); + + +// Minimalize menu when screen is less than 768px +$(window).bind("resize", function () { + if ($(this).width() < 769) { + $('body').addClass('body-small') + } else { + $('body').removeClass('body-small') + } +}); + +function SmoothlyMenu() { + if (!$('body').hasClass('mini-navbar') || $('body').hasClass('body-small')) { + // Hide menu in order to smoothly turn on when maximize menu + $('#side-menu').hide(); + // For smoothly turn on menu + setTimeout( + function () { + $('#side-menu').fadeIn(400); + }, 200); + } else if ($('body').hasClass('fixed-sidebar')) { + $('#side-menu').hide(); + setTimeout( + function () { + $('#side-menu').fadeIn(400); + }, 100); + } else { + // Remove all inline style from jquery fadeIn function to reset menu state + $('#side-menu').removeAttr('style'); + } +} diff --git a/pool/shard011/JavaScript/0070418_Cordova.js b/pool/shard011/JavaScript/0070418_Cordova.js new file mode 100644 index 0000000000000000000000000000000000000000..6e466c542cdff8fa17ae58118d0956b308aef1f6 --- /dev/null +++ b/pool/shard011/JavaScript/0070418_Cordova.js @@ -0,0 +1,90 @@ +/** + * @private + */ +Ext.define('Ext.device.notification.Cordova', { + alternateClassName: 'Ext.device.notification.PhoneGap', + extend: 'Ext.device.notification.Abstract', + requires: ['Ext.device.Communicator'], + + show: function(config) { + config = this.callParent(arguments); + this.confirm(config); + }, + + confirm: function(config) { + config = this.callParent(arguments); + + var buttons = config.buttons, + ln = config.buttons.length; + + if (ln && typeof buttons[0] != "string") { + var newButtons = [], + i; + + for (i = 0; i < ln; i++) { + newButtons.push(buttons[i].text); + } + buttons = newButtons; + } + + var callback = function(index) { + if (config.callback) { + config.callback.apply(config.scope, (buttons) ? [buttons[index - 1].toLowerCase()] : []); + } + }; + + + navigator.notification.confirm( + config.message, + callback, + config.title, + buttons + ); + }, + + alert: function(config) { + navigator.notification.alert( + config.message, + config.callback, + config.title, + config.buttonName + ); + }, + + prompt: function(config) { + config = this.callParent(arguments); + var buttons = config.buttons, + ln = config.buttons.length; + + if (ln && typeof buttons[0] != "string") { + var newButtons = [], + i; + + for (i = 0; i < ln; i++) { + newButtons.push(buttons[i].text); + } + buttons = newButtons; + } + + var callback = function(result) { + if (config.callback) { + config.callback.call(config.scope, (buttons) ? buttons[result.buttonIndex - 1].toLowerCase() : null, result.input1); + } + }; + + navigator.notification.prompt( + config.message, + callback, + config.title, + buttons + ); + }, + + vibrate: function(time) { + navigator.notification.vibrate(time); + }, + + beep: function(times) { + navigator.notification.vibrate(times); + } +}); diff --git a/pool/shard011/JavaScript/0070420_auto-location.js b/pool/shard011/JavaScript/0070420_auto-location.js new file mode 100644 index 0000000000000000000000000000000000000000..2dc152ca39ff6bd5bb00d7f78a1ad1ec89094089 --- /dev/null +++ b/pool/shard011/JavaScript/0070420_auto-location.js @@ -0,0 +1,108 @@ +/* eslint-env mocha */ + +const setup = require('../_setup') +const should = require('should') + +const autoLocationField = require('../../server/forms/_fields/autoLocation') +const latitudeField = require('../../server/forms/_fields/latitude') +const longitudeField = require('../../server/forms/_fields/longitude') + +const modelName = 'formTestAutoLocation' +const tableName = 'testAutoLocation' + +describe('Forms:autoLocation', function () { + before(async function () { + await setup.init() + }) + + after(async function () { + await setup.finish() + }) + + const form = { + modelName, + tableName, + fields: { + ...latitudeField.fields, + ...longitudeField.fields, + ...autoLocationField.fields + } + } + + before(async function () { + setup.api.forms.register(form) + setup.api.models.settlement.create({ + latitude: 1, + longitude: 1, + nameEn: 'Settlement 1', + nameLocal: 'Селище 1', + nameLang: 'bg' + }) + + await form.model.sync() + }) // before + + it('form is initialized', async function () { + should.exists(form) + }) + + it('form.model is initialized', async function () { + should.exists(form.model) + }) + + it('can create', async function () { + const response = await setup.runActionAsAdmin(`${modelName}:create`, { + latitude: 1.23, + longitude: 2.34 + }) + should.exists(response) + response.should.not.have.property('error') + response.should.have.property('data') + }) + + it('task fills autoLocation', async function () { + const { data: { id, autoLocation: initialAutoLocation } } = await setup.runActionAsAdmin(`${modelName}:create`, { + latitude: 1, + longitude: 1 + }) + should(initialAutoLocation).equal(null) + + await setup.api.tasks.tasks.autoLocation.run({ form: modelName, id }) + + const { data: { autoLocation } } = await setup.runActionAsAdmin(`${modelName}:view`, { id }) + should(autoLocation).not.equal(null) + }) + + it('resets autoLocation when latitude changes', async function () { + const { data: { id } } = await setup.runActionAsAdmin(`${modelName}:create`, { + latitude: 1, + longitude: 1 + }) + await setup.api.tasks.tasks.autoLocation.run({ form: modelName, id }) + const { data: { autoLocation } } = await setup.runActionAsAdmin(`${modelName}:edit`, { id, latitude: 1.00001 }) + should(autoLocation).equal(null) + }) + + it('resets autoLocation when longitude changes', async function () { + const { data: { id } } = await setup.runActionAsAdmin(`${modelName}:create`, { + latitude: 1, + longitude: 1 + }) + await setup.api.tasks.tasks.autoLocation.run({ form: modelName, id }) + const { data: { autoLocation } } = await setup.runActionAsAdmin(`${modelName}:edit`, { id, longitude: 1.00001 }) + should(autoLocation).equal(null) + }) + + it('task fills autoLocation after reset', async function () { + const { data: { id } } = await setup.runActionAsAdmin(`${modelName}:create`, { + latitude: 1, + longitude: 1 + }) + await setup.api.tasks.tasks.autoLocation.run({ form: modelName, id }) + await setup.runActionAsAdmin(`${modelName}:edit`, { id, latitude: 1.00001, longitude: 1.00001 }) + await setup.api.tasks.tasks.autoLocation.run({ form: modelName, id }) + + const { data: { autoLocation } } = await setup.runActionAsAdmin(`${modelName}:view`, { id }) + should(autoLocation).not.equal(null) + }) +}) diff --git a/pool/shard011/JavaScript/0070425_select.js b/pool/shard011/JavaScript/0070425_select.js new file mode 100644 index 0000000000000000000000000000000000000000..0909cc752830f62c03721a68b163257c88936e94 --- /dev/null +++ b/pool/shard011/JavaScript/0070425_select.js @@ -0,0 +1,63 @@ +define(function (require) { + 'use strict'; + + // foreign modules + + var _ = require('underscore'); + + // local modules + + var ElementModel = require('forms/models/element'); + + // this module + return ElementModel.extend({ + defaults: function () { + return Object.assign(ElementModel.prototype.defaults.call(this), { + mode: 'collapsed', + layout: 'vertical', + other: false, + nativeMenu: false + }); + }, + + initialize: function () { + var attrs; + ElementModel.prototype.initialize.apply(this, arguments); + + attrs = this.attributes; + attrs.nativeMenu = attrs.type === 'select' && attrs.mode === 'collapsed'; + + if (attrs.canSpecifyOther) { + attrs.other = attrs.canSpecifyOther; + attrs.canSpecifyOther = null; + } + }, + initializeView: function () { + var Forms = BMP.Forms; + var View, view, mode; + var attrs = this.attributes; + + if (attrs.readonly) { + this.removeView(); + View = Forms._views.SelectReadOnlyElement; + } else { + mode = attrs.mode || 'collapsed'; + mode = mode[0].toUpperCase() + mode.substring(1); + View = Forms._views['Choice' + mode + 'Element']; + } + + view = new View({model: this}); + this.set('_view', view); + return view; + }, + + isEmpty: function () { + var attrs = this.attributes; + if (ElementModel.prototype.isEmpty.call(this)) { + return true; + } + return attrs.other && attrs.value === 'other' && !_.contains(attrs.options, 'other'); + } + + }); +}); diff --git a/pool/shard011/JavaScript/0070426_user.js b/pool/shard011/JavaScript/0070426_user.js new file mode 100644 index 0000000000000000000000000000000000000000..6f10750dcfc13b8bfe1c5daaab4dfe684a04185b --- /dev/null +++ b/pool/shard011/JavaScript/0070426_user.js @@ -0,0 +1,154 @@ +var bcrypt = require("bcrypt"); +var database = require('../../models'); + +module.exports = { + hash: function( secret, callback ) { + bcrypt.hash( secret, 10, function( error, hash ) { + callback( error, hash ); + }); + }, + + create: function( data, callback ) { + var whitelist = { + username: true, + password: true, + firstname: true, + lastname: true, + role: true + }; + + this.hash( data.password, function( error, hash ) { + data.password = hash; + + database.User.create( data ).then(function( userObj ) { + if ( typeof callback == "function" ) { + callback( false, userObj ); + } + }, function( error ) { + if ( typeof callback == "function" ) { + callback( true, false ); + } + }); + }); + }, + + modify: function( user, data, callback ) { + var whitelist = { + password: true, + firstname: true, + lastname: true, + role: true + }; + + // Apply whitelist for security purposes + this.hash( data.password, function( error, hash ) { + data.password = hash; + + database.User.find({ where: { username: user }}).then(function( userObj ) { + userObj.updateAttributes( data ).then(function() { + if ( typeof callback == "function" ) { + callback( false ); + } + }, function( error ) { + if ( typeof callback == "function" ) { + callback( true ); + } + }); + }, function( error ) { + if ( typeof callback == "function" ) { + callback( true ); + } + }); + }); + }, + + list: function( callback ) { + database.User.findAll().then(function( usersObj ) { + callback( false, usersObj ); + }, function( error ) { + callback( true, false ); + }); + }, + + reset: function( email, callback ) { + var resetHash = ''; + + database.User.findById({ where: { email: email }}).then(function( userObj ) { + if ( userObj === null ) { + + } else { + userObj.updateAttributes({ + + }).then(function() { + // UserObj wouldn't be updated here due to sqlize issue + + callback( false, true ); + }); + } + }, function( error ) { + callback( error, false ); + }); + }, + + // Login Middleware + login: function( username, password, done ) { + database.User.find({ where: { username: username }}).then(function( userObj ) { + if ( userObj === null ) { + done( null, false, { message: 'Invalid username' } ); + } else { + bcrypt.compare( password, userObj.password, function( error, match ) { + if ( match ) { + done( false, userObj.dataValues ); + } else { + done( null, false, { message: 'Invalid password' } ); + } + }); + } + }, function( error ) { + done( error, false ); + }); + }, + + // Store just the User ID when they log in + serialize: function( user, done ) { + done( null, user.id ); + }, + + // Grab user info from DB from every request + unserialize: function( id, done ) { + database.User.findById(id).then(function( user ) { + if ( user !== null ) { + done( false, user.dataValues ); + } else { + done( false, false ); + } + }, function( error ) { + done( error, false ); + }); + }, + + // Check the auth level string passed in via middleware + auth: function( level ) { + return function( req, res, next ) { + if ( req.isAuthenticated() ) { + var role = req.user.role; + + if ( level === 'admin' && role === 'admin' ) { + next(); + } else if ( level === 'campaigns' && ( role === 'admin' || role === 'campaigns' ) ) { + next(); + } else if ( level === 'reporting' && ( role === 'admin' || role === 'campaigns' || role === 'reporting' )) { + next(); + } else if ( !level ) { + next(); + } else { + res.render('errors/401.html'); + } + } else { + req.flash('error', 'You must be logged in to view that page'); + req.session.next = req.originalUrl; + res.redirect( '/admin' ); + } + }; + }, +}; diff --git a/pool/shard011/JavaScript/0070430_start.js b/pool/shard011/JavaScript/0070430_start.js new file mode 100644 index 0000000000000000000000000000000000000000..9486ac89af55be575ab37b02edd4fe764e470f3a --- /dev/null +++ b/pool/shard011/JavaScript/0070430_start.js @@ -0,0 +1,140 @@ +/** + * React Starter Kit (https://www.reactstarterkit.com/) + * + * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE.txt file in the root directory of this source tree. + */ + +import Browsersync from 'browser-sync'; +import webpack from 'webpack'; +import webpackMiddleware from 'webpack-middleware'; +import webpackHotMiddleware from 'webpack-hot-middleware'; +import run from './run'; +import runServer from './runServer'; +import webpackConfig from './webpack.config'; +import clean from './clean'; +import bundle from './bundle'; +import extractMessages from './extractMessages'; +import copy from './copy'; +import opn from 'opn'; + +const DEBUG = !process.argv.includes('--release'); + +/** + * Launches a development web server with "live reload" functionality - + * synchronizing URLs, interactions and code changes across multiple devices. + */ +async function start() { + await run(clean); + await run(extractMessages.bind(undefined, { watch: true })); + if (!DEBUG) { + await run(bundle); + } + await run(copy.bind(undefined, { watch: true })); + await new Promise(resolve => { + + if (DEBUG) { + + // Patch the client-side bundle configurations + // to enable Hot Module Replacement (HMR) and React Transform + webpackConfig.filter(x => x.target !== 'node').forEach(config => { + /* eslint-disable no-param-reassign */ + config.entry = ['webpack-hot-middleware/client'].concat(config.entry); + config.output.filename = config.output.filename.replace('[chunkhash]', '[hash]'); + config.output.chunkFilename = config.output.chunkFilename.replace('[chunkhash]', '[hash]'); + config.plugins.push(new webpack.HotModuleReplacementPlugin()); + config.plugins.push(new webpack.NoErrorsPlugin()); + config + .module + .loaders + .filter(x => x.loader === 'babel-loader') + .forEach(x => (x.query = { + ...x.query, + + // Wraps all React components into arbitrary transforms + // https://github.com/gaearon/babel-plugin-react-transform + plugins: [ + ...(x.query ? x.query.plugins : []), + ['react-transform', { + transforms: [ + { + transform: 'react-transform-hmr', + imports: ['react'], + locals: ['module'], + }, { + transform: 'react-transform-catch-errors', + imports: ['react', 'redbox-react'], + }, + ], + }, + ], + ], + })); + /* eslint-enable no-param-reassign */ + }); + + } + + const bundler = webpack(webpackConfig); + const wpMiddleware = webpackMiddleware(bundler, { + + // IMPORTANT: webpack middleware can't access config, + // so we should provide publicPath by ourselves + publicPath: webpackConfig[0].output.publicPath, + + // Pretty colored output + stats: webpackConfig[0].stats, + + // For other settings see + // https://webpack.github.io/docs/webpack-dev-middleware + }); + const hotMiddlewares = bundler + .compilers + .filter(compiler => compiler.options.target !== 'node') + .map(compiler => webpackHotMiddleware(compiler)); + + let handleServerBundleComplete = () => { + runServer((err, host) => { + if (!err) { + + if (!DEBUG) { + return; + } + const bs = Browsersync.create(); + bs.init({ + ...(DEBUG ? { https: true } : { notify: false, ui: false, https: true }), + + https: { + key: "server.key", + cert: "server.crt" + }, + + proxy: { + target: host, + middleware: [wpMiddleware, ...hotMiddlewares], + }, + + open: false, + + callbacks: { + ready: () => opn("https://local.transitlinks.net") + }, + + // no need to watch '*.js' here, webpack will take care of it for us, + // including full page reloads if HMR won't work + files: ['build/content/**/*.*'], + }, resolve); + + handleServerBundleComplete = runServer; + + } + }); + }; + + bundler.plugin('done', () => handleServerBundleComplete()); + }); +} + +export default start; diff --git a/pool/shard011/JavaScript/0070432_rest.js b/pool/shard011/JavaScript/0070432_rest.js new file mode 100644 index 0000000000000000000000000000000000000000..73fd5ab0bec2deb509bf78b3a83dd95d26e5a6f1 --- /dev/null +++ b/pool/shard011/JavaScript/0070432_rest.js @@ -0,0 +1,118 @@ +require('dotenv').config() + +const request = require('request'), + queryString = require('query-string'), + userManager = require('./UserManager') + +const host = process.env.BPM_SERVER_HOST || 'localhost', + port = process.env.BPM_SERVER_APP_PORT || '', + protocol = process.env.BPM_SERVER_PROTOCOL || 'https', + rest = process.env.BPM_REST_CONTEXT || '/rest/bpm/wle/v1', + + /* istanbul ignore next */ + restUrl = protocol + '://' + host + (port ? ':' + port : '') + rest + +module.exports = { + get, + post, + put, + del, + + __parseJson: parseJson, +} + +// + +function get(path, options = {}) { + options.method = 'get' + + return call(path, options) +} + +function post(path, options = {}) { + options.method = 'post' + + return call(path, options) +} + +function put(path, options = {}) { + options.method = 'put' + + return call(path, options) +} + +function del(path, options = {}) { + options.method = 'delete' + + return call(path, options) +} + +// + +/** + * + * @param {string} path - a URL relative to the base REST API path: /rest/bpm/wle/v1 - leading forward-slash is optional + * @param {object} options + * @param {string} options.method - the HTTP method + * @param {string} [options.username] - alternative username + * @param {string} [options.password] - alternative password + * @param {object} [options.params] - query string parameters + * @param {object} [options.data] - body data + * @returns {Promise} + */ +/* istanbul ignore next */ +function call(path, options = {}) { + path = (path[0] !== '/') ? '/' + path : path + + const currentUser = userManager.current, + method = options.method.toLowerCase() || 'get', + paramMark = path.indexOf('?') > -1 ? '&' : '?', + parameters = paramMark + queryString.stringify(options.params), + url = restUrl + path + parameters + + //console.log('rest', path, options) + + return new Promise((resolve, reject) => { + request[method](url, { + auth: { + user: currentUser.username, + pass: currentUser.password, + sendImmediately: false + }, + form: options.data + }, (err, response, body) => { + if (err) { + console.log(err); + return reject(err) + } + + //console.log('status', response && response.statusCode) + //console.log('body', body) + + if (response && response.statusCode) { + if (response.statusCode >= 400 && response.statusCode < 600) { + + // IBM BPM responds with a JSON error structure + return reject(parseJson(response, body) || response.statusMessage) + } + } + + resolve(parseJson(response, body)) + }) + }) +} + +function parseJson(response, body) { + if (!response || !response.headers) return body + + /* istanbul ignore next */ + if (response.headers['content-type'] === 'application/json') { + try { + return JSON.parse(body) + } catch (err) { + throw err + } + } + + return body +} diff --git a/pool/shard011/JavaScript/0070434_CanvasUtils.js b/pool/shard011/JavaScript/0070434_CanvasUtils.js new file mode 100644 index 0000000000000000000000000000000000000000..e047a57427847dcc0ce30c626254525524b35742 --- /dev/null +++ b/pool/shard011/JavaScript/0070434_CanvasUtils.js @@ -0,0 +1,126 @@ +import { ShapeUtils } from "./ShapeUtils"; +import { ColorUtils } from "./ColorUtils"; +export class CanvasUtils { + static paintBase(context, dimension, baseColor) { + context.save(); + context.fillStyle = baseColor !== null && baseColor !== void 0 ? baseColor : "rgba(255, 255, 255, 0)"; + context.fillRect(0, 0, dimension.width, dimension.height); + context.restore(); + } + static clear(context, dimension) { + context.clearRect(0, 0, dimension.width, dimension.height); + } + static drawPolygonMask(context, rawData, stroke) { + const color = typeof stroke.color === "string" ? + ColorUtils.stringToRgb(stroke.color) : + ColorUtils.colorToRgb(stroke.color); + if (color) { + context.save(); + context.beginPath(); + context.moveTo(rawData[0].x, rawData[0].y); + for (let i = 1; i < rawData.length; i++) { + context.lineTo(rawData[i].x, rawData[i].y); + } + context.closePath(); + context.strokeStyle = ColorUtils.getStyleFromColor(color); + context.lineWidth = stroke.width; + context.stroke(); + context.restore(); + } + } + static drawLineLinked(context, width, begin, end, backgroundMask, colorLine, opacity, shadow) { + context.save(); + if (backgroundMask) { + context.globalCompositeOperation = 'destination-out'; + } + if (colorLine) { + context.strokeStyle = ColorUtils.getStyleFromColor(colorLine, opacity); + ; + } + context.lineWidth = width; + context.beginPath(); + const color = typeof shadow.color === "string" ? + ColorUtils.stringToRgb(shadow.color) : + ColorUtils.colorToRgb(shadow.color); + if (shadow.enable && color) { + context.shadowBlur = shadow.blur; + context.shadowColor = ColorUtils.getStyleFromColor(color); + } + context.moveTo(begin.x, begin.y); + context.lineTo(end.x, end.y); + context.stroke(); + context.closePath(); + context.restore(); + } + static drawConnectLine(context, width, lineStyle, begin, end) { + context.save(); + context.beginPath(); + context.lineWidth = width; + context.strokeStyle = lineStyle; + context.moveTo(begin.x, begin.y); + context.lineTo(end.x, end.y); + context.stroke(); + context.closePath(); + context.restore(); + } + static gradient(context, p1, p2, midColor) { + const gradStop = Math.floor(p2.radius / p1.radius); + if (!p1.color || !p2.color) { + return; + } + const sourcePos = p1.position; + const destPos = p2.position; + const grad = context.createLinearGradient(sourcePos.x, sourcePos.y, destPos.x, destPos.y); + grad.addColorStop(0, ColorUtils.getStyleFromColor(p1.color)); + grad.addColorStop(gradStop > 1 ? 1 : gradStop, midColor); + grad.addColorStop(1, ColorUtils.getStyleFromColor(p2.color)); + return grad; + } + static drawGrabLine(context, width, begin, end, colorLine, opacity) { + context.save(); + context.strokeStyle = `rgba(${colorLine.r},${colorLine.g},${colorLine.b},${opacity})`; + context.lineWidth = width; + context.beginPath(); + context.moveTo(begin.x, begin.y); + context.lineTo(end.x, end.y); + context.stroke(); + context.closePath(); + context.restore(); + } + static drawParticle(context, particle, colorValue, backgroundMask, radius) { + context.save(); + const stroke = particle.stroke; + const strokeColor = particle.strokeColor; + const shadow = particle.container.options.particles.shadow; + const shadowColor = particle.shadowColor; + if (shadow.enable && shadowColor) { + context.shadowBlur = shadow.blur; + context.shadowColor = ColorUtils.getStyleFromColor(shadowColor); + context.shadowOffsetX = shadow.offset.x; + context.shadowOffsetY = shadow.offset.y; + } + context.fillStyle = colorValue; + const pos = { + x: particle.position.x, + y: particle.position.y, + }; + context.translate(pos.x, pos.y); + context.beginPath(); + if (particle.angle !== 0) { + context.rotate(particle.angle * Math.PI / 180); + } + if (backgroundMask) { + context.globalCompositeOperation = 'destination-out'; + } + ShapeUtils.drawShape(context, particle, radius, stroke, strokeColor); + context.closePath(); + if (stroke.width > 0 && particle.strokeColor) { + context.strokeStyle = ColorUtils.getStyleFromColor(particle.strokeColor); + context.lineWidth = stroke.width; + context.stroke(); + } + context.fill(); + context.restore(); + } +} +//# sourceMappingURL=CanvasUtils.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070436_purify.js b/pool/shard011/JavaScript/0070436_purify.js new file mode 100644 index 0000000000000000000000000000000000000000..d0d40a0244031dd5edf28cdd9c19eea65fc71204 --- /dev/null +++ b/pool/shard011/JavaScript/0070436_purify.js @@ -0,0 +1,9 @@ +const gulp = require('gulp') +const config = require('../config') +const purify = require('@pixel2html/pipes').purify + +gulp.task('purify', () => + gulp.src(config.directories.dist.styles + '*.css') + .pipe(purify({paths: config.purify})()) + .pipe(gulp.dest(config.directories.dist.styles)) +) diff --git a/pool/shard011/JavaScript/0070439_index.js b/pool/shard011/JavaScript/0070439_index.js new file mode 100644 index 0000000000000000000000000000000000000000..8250bac4edd6d63886caf6eb1e990350303a5ea2 --- /dev/null +++ b/pool/shard011/JavaScript/0070439_index.js @@ -0,0 +1,49 @@ +import React from 'react' +import cookie from 'cookie' +import { withApollo, compose } from 'react-apollo' + +import withData from '../lib/withData' +import redirect from '../lib/redirect' +import checkLoggedIn from '../lib/checkLoggedIn' + +class Index extends React.Component { + static async getInitialProps (context, apolloClient) { + const { loggedInUser } = await checkLoggedIn(context, apolloClient) + + if (!loggedInUser.user) { + // If not signed in, send them somewhere more useful + redirect(context, '/signin') + } + + return { loggedInUser } + } + + signout = () => { + document.cookie = cookie.serialize('token', '', { + maxAge: -1 // Expire the cookie immediately + }) + + // Force a reload of all the current queries now that the user is + // logged in, so we don't accidentally leave any state around. + this.props.client.resetStore().then(() => { + // Redirect to a more useful page when signed out + redirect({}, '/signin') + }) + } + + render () { + return ( +
    + Hello {this.props.loggedInUser.user.name}!
    + +
    + ) + } +}; + +export default compose( + // withData gives us server-side graphql queries before rendering + withData, + // withApollo exposes `this.props.client` used when logging out + withApollo +)(Index) diff --git a/pool/shard011/JavaScript/0070440_same-timestamp-events-test-def.js b/pool/shard011/JavaScript/0070440_same-timestamp-events-test-def.js new file mode 100644 index 0000000000000000000000000000000000000000..2b5113f16387d04911bdf3376add28dabca19c3e --- /dev/null +++ b/pool/shard011/JavaScript/0070440_same-timestamp-events-test-def.js @@ -0,0 +1,107 @@ +'use strict'; + +const httpStatus = require('http-status-codes'); + +const moment = require('abacus-moment'); + +const { carryOverDb } = require('abacus-test-helper'); +const { serviceMock } = require('abacus-mock-util'); + +let fixture; + +const build = () => { + context('when reading multiple events with same timestamp from Cloud Controller', () => { + let externalSystemsMocks; + let usageEventsTimestamp; + + before(async () => { + externalSystemsMocks = fixture.externalSystemsMocks(); + externalSystemsMocks.startAll(); + + externalSystemsMocks.uaaServer.tokenService + .whenScopesAre(fixture.oauth.abacusCollectorScopes) + .return(fixture.oauth.abacusCollectorToken); + + externalSystemsMocks.uaaServer.tokenService + .whenScopesAre(fixture.oauth.cfAdminScopes) + .return(fixture.oauth.cfAdminToken); + + const now = moment.now(); + usageEventsTimestamp = moment + .utc(now) + .subtract(fixture.env.minimalAgeInMinutes + 1, 'minutes') + .valueOf(); + const firstUsageEvent = fixture + .usageEvent() + .overwriteCreatedAt(usageEventsTimestamp) + .get(); + const secondUsageEvent = fixture + .usageEvent() + .overwriteCreatedAt(usageEventsTimestamp) + .get(); + + externalSystemsMocks.cloudController.usageEvents.return.firstTime([firstUsageEvent, secondUsageEvent]); + + externalSystemsMocks.abacusCollector.collectUsageService.return.always(httpStatus.ACCEPTED); + + await carryOverDb.setup(); + fixture.bridge.start(externalSystemsMocks); + + await eventually(serviceMock(externalSystemsMocks.cloudController.usageEvents).received(2)); + }); + + after((done) => { + fixture.bridge.stop(); + carryOverDb.teardown(); + externalSystemsMocks.stopAll(done); + }); + + context('When abacus collector is called', () => { + it('Two usages are sent', () => { + expect(externalSystemsMocks.abacusCollector.collectUsageService.requests().length).to.equal(2); + }); + + it('First recieved usage is as it was sent', () => { + expect(externalSystemsMocks.abacusCollector.collectUsageService.request(0).usage).to.deep.equal( + fixture.collectorUsage() + .overwriteUsageTime(usageEventsTimestamp) + .overwriteMeasuredUsage(fixture.usageEventStates.default) + .get() + ); + }); + + it('Second recieved usage timestamp is adjusted', () => { + expect(externalSystemsMocks.abacusCollector.collectUsageService.request(1).usage).to.deep.equal( + fixture.collectorUsage() + .overwriteUsageTime(usageEventsTimestamp + 1) + .overwriteMeasuredUsage(fixture.usageEventStates.default) + .get() + ); + }); + }); + + it('Exposes correct statistics', async () => { + const response = await fixture.bridge.readStats.withValidToken(); + expect(response.statusCode).to.equal(httpStatus.OK); + expect(response.body.statistics.usage).to.deep.equal({ + success: { + all: 2, + conflicts: 0, + notsupported: 0, + skips: 0 + }, + failures: 0 + }); + }); + }); +}; + +const testDef = { + fixture: (value) => { + fixture = value; + return testDef; + }, + build +}; + +module.exports = testDef; diff --git a/pool/shard011/JavaScript/0070442_index.js b/pool/shard011/JavaScript/0070442_index.js new file mode 100644 index 0000000000000000000000000000000000000000..489992cb8e18e6a1a49788a23ac44cb24a1024e4 --- /dev/null +++ b/pool/shard011/JavaScript/0070442_index.js @@ -0,0 +1,15 @@ +import mojs from 'mo-js'; + +let identity = s => s; +console.log(identity('Initialized')); +console.log(mojs); + +// var shape = new mojs.Shape({ +// shape: 'circle', +// isShowStart: true +// }); + +const burst = new mojs.Burst(); +document.addEventListener( 'click' , (e) => { + burst.replay(); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070446_requiredExtensionIcon.js b/pool/shard011/JavaScript/0070446_requiredExtensionIcon.js new file mode 100644 index 0000000000000000000000000000000000000000..cefb4cf468d3e481385e545172e36bd062c9eee8 --- /dev/null +++ b/pool/shard011/JavaScript/0070446_requiredExtensionIcon.js @@ -0,0 +1,87 @@ +'use strict'; + +var should = require('should'); + +var lib = require('manifoldjs-lib'); +var validationConstants = lib.constants.validation; + +var constants = require('../../../lib/constants'), + validation = require('../../../lib/validationRules/requiredExtensionIcon'); + +var requiredIconSizes = ['48x48']; +var manifestWithRequiredIconSizes = [{sizes : '48x48'}]; + +describe('Validation - Chrome', function () { + describe('requiredExtensionIcon', function () { + it('Should return a suggestion if manifest does not contains icons', function(done) { + validation({}, function(err, suggestion) { + should.not.exist(err); + should.exist(suggestion); + suggestion.should.have.property('platform', constants.platform.id); + suggestion.should.have.property('level', validationConstants.levels.suggestion); + suggestion.should.have.property('member', validationConstants.manifestMembers.icons); + suggestion.should.have.property('code', validationConstants.codes.missingImage); + suggestion.should.have.property('data', requiredIconSizes); + done(); + }); + }); + + it('Should return a suggestion if manifest icons is empty', function(done) { + validation({ icons: [] }, function(err, suggestion) { + should.not.exist(err); + should.exist(suggestion); + suggestion.should.have.property('platform', constants.platform.id); + suggestion.should.have.property('level', validationConstants.levels.suggestion); + suggestion.should.have.property('member', validationConstants.manifestMembers.icons); + suggestion.should.have.property('code', validationConstants.codes.missingImage); + suggestion.should.have.property('data', requiredIconSizes); + done(); + }); + }); + + it('Should return a suggestion if manifest icons does not contains the required sizes', function(done) { + validation({ icons: [{sizes : '1x1'}] }, function(err, suggestion) { + should.not.exist(err); + should.exist(suggestion); + suggestion.should.have.property('platform', constants.platform.id); + suggestion.should.have.property('level', validationConstants.levels.suggestion); + suggestion.should.have.property('member', validationConstants.manifestMembers.icons); + suggestion.should.have.property('code', validationConstants.codes.missingImage); + suggestion.should.have.property('data', requiredIconSizes); + done(); + }); + }); + + it('Should not return a suggestion if manifest icons contains all of the required sizes', function(done) { + validation({ icons: manifestWithRequiredIconSizes }, function(err, suggestion) { + should.not.exist(err); + should.not.exist(suggestion); + done(); + }); + }); + + it('Should not return a suggestion if manifest icons contains all the required sizes and others at the end', function(done) { + var icons = manifestWithRequiredIconSizes.slice(); + icons.push({sizes : '1x1'}); + validation({ icons: icons }, function(err, suggestion) { + should.not.exist(err); + should.not.exist(suggestion); + done(); + }); + }); + + it('Should not return a suggestion if manifest icons contains all the required sizes and others at the begining', function(done) { + var icons = [{sizes : '1x1'}]; + + for (var i = 0; i < manifestWithRequiredIconSizes.length; i++) { + icons.push(manifestWithRequiredIconSizes[i]); + } + + validation({ icons: icons }, function(err, suggestion) { + should.not.exist(err); + should.not.exist(suggestion); + done(); + }); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0070447_validacionesUsuarios.js b/pool/shard011/JavaScript/0070447_validacionesUsuarios.js new file mode 100644 index 0000000000000000000000000000000000000000..0ee476ddc130b47abac894bb8d565f2e22f8fc66 --- /dev/null +++ b/pool/shard011/JavaScript/0070447_validacionesUsuarios.js @@ -0,0 +1,127 @@ +function validarDatos(){ + + valor = document.getElementById("documentoUsuarioSolicitado").value; + if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) { + alert("Debe diligenciar el campo documento de identidad"); + document.getElementById("documentoUsuarioSolicitado").focus(); + return false; + } + + + indice = document.getElementById("paisSolicitado").selectedIndex; + if( indice == null || indice == 0 ) { + alert("Debe seleccionar el país de expedición"); + document.getElementById("paisSolicitado").focus(); + return false; + } + + indice = document.getElementById("departamentoSolicitado").selectedIndex; + if( indice == null || indice == 0 ) { + alert("Debe seleccionar el departamento de expedición"); + document.getElementById("departamentoSolicitado").focus(); + return false; + } + + + indice = document.getElementById("ciudadSolicitado").selectedIndex; + if( indice == null || indice == 0 ) { + alert("Debe seleccionar la ciudad de expedición"); + document.getElementById("ciudadSolicitado").focus(); + return false; + } + + + indice = document.getElementById("tipoDocumentoUsuarioSolicitado").selectedIndex; + if( indice == null || indice == 0 ) { + alert("Debe seleccionar un tipo de documento de indentidad"); + document.getElementById("tipoDocumentoUsuarioSolicitado").focus(); + return false; + } + + + valor = document.getElementById("nombresUsuarioSolicitado").value; + if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) { + alert("Debe diligenciar el campo nombres completos"); + document.getElementById("nombresUsuarioSolicitado").focus(); + return false; + } + + + valor = document.getElementById("apellidoUsuarioSolicitado").value; + if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) { + alert("Debe diligenciar el campo apellidos completos"); + document.getElementById("apellidoUsuarioSolicitado").focus(); + return false; + } + + + + valor = document.getElementById("mailUsuarioSolicitado").value; + if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) { + alert("Debe diligenciar el campo correo electrónico"); + document.getElementById("mailUsuarioSolicitado").focus(); + return false; + } + + /* Este código si funciona: Valida la estructura del Correo Electrónico */ + valor = document.getElementById("mailUsuarioSolicitado").value; + if( !(/^[\w-\.]+[@]+[\w-\.]+[.]+[\w-\.]{2,4}$/.test(valor)) ){ + alert("El formato de correo electrónico es incorrecto"); + document.getElementById("mailUsuarioSolicitado").focus(); + return false; + } + + + + /* + valor = document.getElementById("mailUsuarioSolicitado").value; + if( !(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)/.test(valor)) ) { + alert("El formato de correo electrónico es incorrecto") + return false; + } + */ + + + valor = document.getElementById("telefonoUsuarioSolicitado").value; + if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) { + alert("Debe diligenciar el campo teléfono "); + document,getElementById("telefonoUsuarioSolicitado").focus(); + return false; + } + + /* + + Esta validación significa que se debe ingresar y número de 10 cifras, + si ingresa menos de 10 o mayores que 10 no permite continuar con el formulario + + valor = document.getElementById("telefonoUsuarioSolicitado").value; + if( !(/^\d{10}$/.test(valor)) ) { + alert("El formato del campo teléfono/celular es incorrecto") + return false; + } + */ + + indice = document.getElementById("tipoUsuarioSolicitado").selectedIndex; + if( indice == null || indice == 0 ) { + alert("Debe seleccionar un tipo de usuario"); + document.getElementById("tipoDocumentoUsuarioSolicitado").focus(); + return false; + } + + indice = document.getElementById("estadoUsuarioSolicitado").selectedIndex; + if( indice == null || indice == 0 ) { + alert("Debe seleccionar un tipo de estado"); + document.getElementById("estadoUsuarioSolicitado").focus(); + return false; + } + + valor = document.getElementById("contraseniaUsuarioSolicitado").value; + if( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) { + alert("Debe diligenciar el campo contraseña"); + document.getElementById("contraseniaUsuarioSolicitado") + return false; + } + + + + } \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070448_withChannel.js b/pool/shard011/JavaScript/0070448_withChannel.js new file mode 100644 index 0000000000000000000000000000000000000000..549b6c33c2946fe4e0d6edee14c0afc0bcdda9dd --- /dev/null +++ b/pool/shard011/JavaScript/0070448_withChannel.js @@ -0,0 +1,65 @@ +const fp = require('lodash/fp') +const HttpStatus = require('http-status-codes') + +const store = require('../../store') + +const withChannel = (ctx, next) => { + const state = store.getState() + + const channelId = ctx.request.body.channelId || ctx.request.query.channelId + const serverId = ctx.request.body.serverId || ctx.request.query.serverId + let channelName = + ctx.request.body.channelName || ctx.request.query.channelName + + if (!channelId && !(serverId && channelName)) { + ctx.body = { + error: 'Param channelId or params serverId & channelName are required!', + } + ctx.status = HttpStatus.BAD_REQUEST + return + } + + let channel + + if (channelId) { + channel = state.channels[channelId] + } else if (serverId && channelName) { + channelName = channelName.replace(/~/g, '#') + + channel = fp.find( + channel => + channel.isPublic && + channel.name === channelName && + state.connections[channel.connectionId].serverId === serverId, + state.channels, + ) + } + + if (!channel) { + ctx.body = { error: 'Channel not found!' } + ctx.status = HttpStatus.NOT_FOUND + return + } + + const connection = state.connections[channel.connectionId] + + if (!channel.isPublic) { + if (!ctx.session) { + ctx.body = { error: 'Session required!' } + ctx.status = HttpStatus.UNAUTHORIZED + return + } + + if (connection.accountId !== ctx.session.accountId) { + ctx.body = { error: 'Connection forbidden for session!' } + ctx.status = HttpStatus.FORBIDDEN + return + } + } + + ctx.channel = channel + ctx.connection = connection + return next() +} + +module.exports = withChannel diff --git a/pool/shard011/JavaScript/0070450_ext.centralNotice.legacySupport.js b/pool/shard011/JavaScript/0070450_ext.centralNotice.legacySupport.js new file mode 100644 index 0000000000000000000000000000000000000000..c36f0221252b98defda46797eb97138d43dbee68 --- /dev/null +++ b/pool/shard011/JavaScript/0070450_ext.centralNotice.legacySupport.js @@ -0,0 +1,25 @@ +/** + * Provides features to support legacy campaigns. With this mixin, campaigns may: + * - set a rate for Special:RecordImpression that's different from the default; and + * - signal that banners are not guaranteed to display. + */ +( function () { + + var cn = mw.centralNotice, + mixin = new cn.Mixin( 'legacySupport' ); + + mixin.setPreBannerHandler( function ( mixinParams ) { + + if ( mixinParams.setSRISampleRate ) { + cn.setMinRecordImpressionSampleRate( mixinParams.sriSampleRate ); + } + + if ( mixinParams.bannersNotGuaranteedToDisplay ) { + cn.setBannersNotGuaranteedToDisplay(); + } + } ); + + // Register the mixin + cn.registerCampaignMixin( mixin ); + +}() ); diff --git a/pool/shard011/JavaScript/0070451_usw.fileselect.js b/pool/shard011/JavaScript/0070451_usw.fileselect.js new file mode 100644 index 0000000000000000000000000000000000000000..104e3747f2c358a9d951dbc87ef07d3cad02ea22 --- /dev/null +++ b/pool/shard011/JavaScript/0070451_usw.fileselect.js @@ -0,0 +1,55 @@ +/*jslint nomen: true, vars: true, white: true */ +/*global $, jQuery, alert*/ +/* +=============================================================================== +Creator : Ceri Binding, University of South Wales ceri.binding@southwales.ac.uk +Project : ARIADNE +Classes : usw.fileselect +Version : 20150205 +Summary : but styled as a button (hides the file path) +Require : jquery, jquery-ui +Example :
    +License : http://creativecommons.org/publicdomain/zero/1.0/ +=============================================================================== +History : +05/03/2015 CFB created script +=============================================================================== +*/ +(function ($) { //start of main jQuery closure + "use strict"; // strict mode pragma + + $.widget('usw.fileselect', { + + // stateful defaults + options: {}, + + _create: function (options) { + var self = this; + self.options = $.extend(self.options, options); + + var label = $(self.element).data("label") || "File"; + + $(self.element).html(""); + // hide the file control and notify when a file is selected + $("input[type='file']:first", self.element) + .css({ "display": "none" }) + .bind('change', function () { + var fileName = ""; + fileName = $(this).val(); + $(self.element).trigger("selected", { "fileName": fileName }); + + //replace the input with a new clone to ensure the change event + // fires again if the same file is selected twice in succession + var control = $("input#file-select:first"); + control.replaceWith(control = control.clone(true)); + }); + } + + }); // end widget usw.fileselect + + // any elements of class usw-fileselect automatically become one... + $(window).load(function () { + $(".usw-fileselect").fileselect(); + }); + +}(jQuery)); //end of main jQuery closure diff --git a/pool/shard011/JavaScript/0070455_server.js b/pool/shard011/JavaScript/0070455_server.js new file mode 100644 index 0000000000000000000000000000000000000000..a7066106af4e628681d090e410458c4d7f9d146a --- /dev/null +++ b/pool/shard011/JavaScript/0070455_server.js @@ -0,0 +1,10 @@ +var express = require('express'); +var path = require('path'); +var app = express(); + +app.set('port', (process.env.PORT || 3000)); +app.use('/', express.static(path.join(__dirname, 'public'))); + +app.listen(app.get('port'), function() { + console.log('Server started: http://localhost:' + app.get('port') + '/'); +}); diff --git a/pool/shard011/JavaScript/0070456_app.js b/pool/shard011/JavaScript/0070456_app.js new file mode 100644 index 0000000000000000000000000000000000000000..693fe590b735c34430457253fac282ff9f8a9ed4 --- /dev/null +++ b/pool/shard011/JavaScript/0070456_app.js @@ -0,0 +1,78 @@ +/// +var express = require('express'); +var path = require('path'); +var favicon = require('serve-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); +var config = require('./config'); + + +require('./models/user'); +require('./models/post'); +var mongoose = require('mongoose'); +mongoose.connect(config.dbConnection); +var session = require('express-session'); +var passport = require('passport'); +var api = require('./routes/api'); +var authenticate = require('./routes/authenticate')(passport); + +var app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs'); + +// uncomment after placing your favicon in /public +//app.use(favicon(__dirname + '/public/favicon.ico')); +app.use(logger('dev')); +app.use(session({ + secret: config.secretHash +})); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: false })); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); +app.use(passport.initialize()); +app.use(passport.session()); + +app.use('/auth', authenticate); +app.use('/api', api); + +// catch 404 and forward to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// Initialize Passport +var initPassport = require('./passport-init'); +initPassport(passport); + +// error handlers + +// development error handler +// will print stacktrace +if (app.get('env') === 'development') { + app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); +}); + + +module.exports = app; diff --git a/pool/shard011/JavaScript/0070457_state0.js b/pool/shard011/JavaScript/0070457_state0.js new file mode 100644 index 0000000000000000000000000000000000000000..c2adda7de3ce9564523b26ee380172b64a2122be --- /dev/null +++ b/pool/shard011/JavaScript/0070457_state0.js @@ -0,0 +1,72 @@ +demo.state0 = function(){}; +demo.state0.prototype = { + preload: function(){ + // Add this in every preload function. All necessary images for the stage should be in loadImages() + loadImages(); + loadCatBoss(); + game.load.image('platform', 'assets/sprites/platform.png'); + + }, + create: function(){ + game.physics.startSystem(Phaser.Physics.ARCADE); + game.stage.backgroundColor = '#FFFFFF'; + addChangeStateEventListeners(); + + createChameleon(200,game.world.height); + cursors = game.input.keyboard.createCursorKeys(); + + // Init Stomach, args are x&y of top left corner of inventory + createInventory(400,25); + + make_fruit_groups(); + make_enemy_groups(); + + placeFruit(500,500, "redfruit"); + placeBird(200, 100, "red"); + place_cat_boss(400, 100); + + addMovingPlatforms(); + placeMP(200, 200, 2, 2, 4, 4, 4000); + + + // load in sound + jump1 = game.add.audio('jump'); + guitar1 = game.add.audio('guitar'); + + + // loops guitar music + guitar1.loopFull(); + + + + }, + update: function(){ + chameleonmove(); + moveBird(); + cat_boss_move(); + /* + for (fruit in fruit_colors){ + clr = fruit_colors[fruit]; + stomach_icons[clr].events.onInputDown.add(chameleon_change_color, {color:clr}); + } */ + }, + preRender: function () { + if (this.game.paused) + { + // Because preRender still runs even if your game pauses! + return; + } + + if (this.locked || this.wasLocked) + { + this.player.x += this.lockedTo.deltaX; + this.player.y = this.lockedTo.y - 48; + + if (this.player.body.velocity.x !== 0) + { + this.player.body.velocity.y = 0; + } + } + } +}; + diff --git a/pool/shard011/JavaScript/0070458_math.js b/pool/shard011/JavaScript/0070458_math.js new file mode 100644 index 0000000000000000000000000000000000000000..3ee2159d1b77f9127fa37f6e7e593b6fa3c06a9e --- /dev/null +++ b/pool/shard011/JavaScript/0070458_math.js @@ -0,0 +1,117 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * and 2014 Massachusetts Institute of Technology + * http://zerorobotics.org/ + * + * 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. + */ + +/** + * @fileoverview Generating C++ for math blocks. Modified from the standard Blockly JavaScript generator. + * @author q.neutron@gmail.com (Quynh Neutron), dininno@mit.edu (Ethan DiNinno) + */ +'use strict'; + +goog.provide('Blockly.zr_cpp.math'); + +goog.require('Blockly.zr_cpp'); + +Blockly.zr_cpp['math_number'] = function(block) { + // Numeric value. + var code = block.getFieldValue('NUM'); + //Validate that the input starts with a number. parseFloat will correctly ignore the trailing f on single-precision floats. + //TODO: better validation to make sure there isn't other crud after the number + if(isNaN(parseFloat(code))) { + code = '0'; + } + return [code, Blockly.zr_cpp.ORDER_ATOMIC]; +}; + +Blockly.zr_cpp['math_arithmetic'] = function(block) { + // Basic arithmetic operators, and power. + var OPERATORS = { + ADD: [' + ', Blockly.zr_cpp.ORDER_ADDITION], + MINUS: [' - ', Blockly.zr_cpp.ORDER_SUBTRACTION], + MULTIPLY: [' * ', Blockly.zr_cpp.ORDER_MULTIPLICATION], + DIVIDE: [' / ', Blockly.zr_cpp.ORDER_DIVISION], + POWER: [null, Blockly.zr_cpp.ORDER_COMMA] // Handle power separately. + }; + var tuple = OPERATORS[block.getFieldValue('OP')]; + var operator = tuple[0]; + var order = tuple[1]; + var argument0 = Blockly.zr_cpp.valueToCode(block, 'A', order) || '0'; + var argument1 = Blockly.zr_cpp.valueToCode(block, 'B', order) || '0'; + var code; + // Power requires a special case since it has no operator. The ZR libraries use all single-precision floats. + if (!operator) { + code = 'powf(' + argument0 + ', ' + argument1 + ')'; + return [code, Blockly.zr_cpp.ORDER_FUNCTION_CALL]; + } + code = argument0 + operator + argument1; + return [code, order]; +}; + +Blockly.zr_cpp['math_single'] = function(block) { + // Math operators with single operand. + var operator = block.getFieldValue('OP'); + var code; + var arg; + if (operator == '-') { + // Negation is a special case given its different operator precedence. + arg = Blockly.zr_cpp.valueToCode(block, 'NUM', + Blockly.zr_cpp.ORDER_UNARY_NEGATION) || '0'; + if (arg[0] == '-') { + // --3 is not legal + arg = ' ' + arg; + } + code = '-' + arg; + return [code, Blockly.zr_cpp.ORDER_UNARY_NEGATION]; + } + arg = Blockly.zr_cpp.valueToCode(block, 'NUM', + Blockly.zr_cpp.ORDER_NONE) || '0'; + // All ZR trig functions are single-precision and handled in radians, which makes most of the JS version of this unnecessary + code = operator + '(' + arg + ')'; + return [code, Blockly.zr_cpp.ORDER_FUNCTION_CALL]; +}; + +Blockly.zr_cpp['math_constant'] = function(block) { + return [block.getFieldValue('CONSTANT'), Blockly.zr_cpp.ORDER_ATOMIC]; +}; + +Blockly.zr_cpp['math_change'] = function(block) { + // Add to a variable in place. + var argument0 = Blockly.zr_cpp.valueToCode(block, 'DELTA', + Blockly.zr_cpp.ORDER_ADDITION) || '0'; + var varName = Blockly.zr_cpp.variableDB_.getName( + block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE); + return varName + ' += ' + argument0 + ';\n'; +}; + +// Rounding functions have a single operand. +Blockly.zr_cpp['math_round'] = Blockly.zr_cpp['math_single']; +// Trigonometry functions have a single operand. +Blockly.zr_cpp['math_trig'] = Blockly.zr_cpp['math_single']; + + +Blockly.zr_cpp['math_modulo'] = function(block) { + // Remainder computation. + var argument0 = Blockly.zr_cpp.valueToCode(block, 'DIVIDEND', + Blockly.zr_cpp.ORDER_MODULUS) || '0'; + var argument1 = Blockly.zr_cpp.valueToCode(block, 'DIVISOR', + Blockly.zr_cpp.ORDER_MODULUS) || '0'; + var code = argument0 + ' % ' + argument1; + return [code, Blockly.zr_cpp.ORDER_MODULUS]; +}; diff --git a/pool/shard011/JavaScript/0070459_html-id-href.test.js b/pool/shard011/JavaScript/0070459_html-id-href.test.js new file mode 100644 index 0000000000000000000000000000000000000000..506357b7dbec3e9a69d785b2f94edae020d2855a --- /dev/null +++ b/pool/shard011/JavaScript/0070459_html-id-href.test.js @@ -0,0 +1,63 @@ +var should = require('should'); +var nock = require('nock'); +var fs = require('fs-extra'); +var scrape = require('../../../index'); + +var testDirname = __dirname + '/.tmp'; +var mockDirname = __dirname + '/mocks'; + +describe('Functional html id href', function() { + + beforeEach(function() { + nock.cleanAll(); + nock.disableNetConnect(); + }); + + afterEach(function() { + nock.cleanAll(); + nock.enableNetConnect(); + fs.removeSync(testDirname); + }); + + it('should ignore same-file paths and update other-file paths', function() { + nock('http://example.com/').get('/').replyWithFile(200, mockDirname + '/index.html'); + nock('http://example.com/').get('/sprite.svg').reply(200, 'sprite.svg'); + nock('https://mdn.mozillademos.org/').get('/files/6457/mdn_logo_only_color.png').reply(200, 'mdn_logo_only_color.png'); + nock('http://example.com/').get('/some/other.html').reply(200, 'other.html'); + + var options = { + urls: [ 'http://example.com/' ], + directory: testDirname, + recursive: true, + maxDepth: 2, + sources: [ + { selector: 'svg *[xlink\\:href]', attr: 'xlink:href' }, + { selector: 'svg *[href]', attr: 'href' }, + { selector: 'a', attr: 'href' } + ], + subdirectories: [ + { directory: 'local', extensions: ['.png', '.svg'] } + ] + }; + + return scrape(options).then(function() { + fs.existsSync(testDirname + '/index.html').should.be.eql(true); + fs.existsSync(testDirname + '/other.html').should.be.eql(true); + fs.existsSync(testDirname + '/local/sprite.svg').should.be.eql(true); + fs.existsSync(testDirname + '/local/mdn_logo_only_color.png').should.be.eql(true); + + var indexHtml = fs.readFileSync(testDirname + '/index.html').toString(); + + // should update path to external svgs + should(indexHtml).containEql('xlink:href="local/sprite.svg#icon-undo"'); + should(indexHtml).containEql('href="local/sprite.svg#icon-redo"'); + // should keep links to local svgs + should(indexHtml).containEql('xlink:href="#codrops" class="codrops-1"'); + should(indexHtml).containEql('xlink:href="#codrops" class="codrops-2"'); + should(indexHtml).containEql('xlink:href="#codrops" class="codrops-3"'); + + should(indexHtml).containEql('Go to top (this page)'); + should(indexHtml).containEql('Go to top (other page)'); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0070466_webpack.config.js b/pool/shard011/JavaScript/0070466_webpack.config.js new file mode 100644 index 0000000000000000000000000000000000000000..7e0f27cc8c993be3bfb123a3901d70343dd51eda --- /dev/null +++ b/pool/shard011/JavaScript/0070466_webpack.config.js @@ -0,0 +1,89 @@ +/** + * Configs file for bundling + * @author NHN. FE Development Lab + */ + +'use strict'; + +var path = require('path'); +var pkg = require('./package.json'); +var webpack = require('webpack'); +var MiniCssExtractPlugin = require('mini-css-extract-plugin'); +var TerserPlugin = require('terser-webpack-plugin'); +var OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); + +function getOptimization(isMinified) { + if (isMinified) { + return { + minimizer: [ + new TerserPlugin({ + cache: true, + parallel: true, + sourceMap: false, + extractComments: false + }), + new OptimizeCSSAssetsPlugin() + ] + }; + } + + return { + minimize: false + }; +} + +module.exports = function(env, argv) { + var isProduction = argv.mode === 'production'; + var isMinified = !!argv.minify; + var FILENAME = pkg.name + (isMinified ? '.min' : ''); + var BANNER = [ + 'TOAST UI Pagination', + '@version ' + pkg.version, + '@author ' + pkg.author, + '@license ' + pkg.license + ].join('\n'); + + return { + mode: 'development', + entry: './src/js/index.js', + output: { + library: ['tui', 'Pagination'], + libraryTarget: 'umd', + path: path.resolve(__dirname, 'dist'), + publicPath: 'dist', + filename: FILENAME + '.js' + }, + module: { + rules: [ + { + test: /\.js$/, + exclude: /(test|node_modules)/, + loader: 'eslint-loader', + enforce: 'pre', + options: { + failOnError: isProduction + } + }, + { + test: /\.css$/, + use: [MiniCssExtractPlugin.loader, 'css-loader'] + }, + { + test: /\.png$/, + loader: 'url-loader' + } + ] + }, + plugins: [ + new webpack.BannerPlugin(BANNER), + new MiniCssExtractPlugin({ filename: FILENAME + '.css' }) + ], + optimization: getOptimization(isMinified), + devServer: { + historyApiFallback: false, + progress: true, + host: '0.0.0.0', + disableHostCheck: true + } + }; +}; diff --git a/pool/shard011/JavaScript/0070468_ummon.task-inheritance.test.js b/pool/shard011/JavaScript/0070468_ummon.task-inheritance.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d65182192d1aacdf8f93b99026c2f57f5ba26ffd --- /dev/null +++ b/pool/shard011/JavaScript/0070468_ummon.task-inheritance.test.js @@ -0,0 +1,43 @@ +'use strict'; + +var test = require("tap").test; +var async = require("async"); + +var ummon = require('..')({pause:true, autoSave:false}); + +test('Create collections default values and retrieve a task that inherits them', function(t){ + t.plan(2); + ummon.defaults.science = { 'cwd': '/user/bill' }; + + async.series([ + function(callback){ ummon.createTask({"collection":"science", "name":"nye","command": "echo \"The science guy!\"" }, callback); }, + function(callback){ ummon.createTask({"collection":"science", "cwd":"/user/neil","name":"tyson","command": "echo \"The space guy!\"" }, callback); }, + ], function(err, results) { + t.notOk(results[0].cwd, 'The nye task shouldn\'t have its cwd set. It\'s in the collection defaults'); + t.equal(results[1].cwd, '/user/neil', 'The tyson task should override the collection defaults'); + }); + +}); + + +test('Test getting a task that inherits global task settings', function(t){ + t.plan(6); + + ummon.config.globalTaskDefaults = { env: {"NODE_ENV":"TEST" }}; + + ummon.getTask('science.nye', function(err, task){ + t.notOk(err, 'There is no error'); + t.ok(task, 'There is a task'); + t.equal(task.cwd, '/user/bill', 'Defaults are not set on the master task'); + t.notOk(ummon.tasks['science.nye'].env, 'The task is truly inheriting from globals'); + t.notOk(ummon.tasks['science.nye'].cwd, 'The task is truly inheriting from globals'); + t.equal(task.env.NODE_ENV, 'TEST', 'Global default are attached to the retrieved'); + }) +}) + +test('teardown', function(t){ + setImmediate(function() { + process.exit(); + }); + t.end(); +}); diff --git a/pool/shard011/JavaScript/0070469_writable-as-promise.js b/pool/shard011/JavaScript/0070469_writable-as-promise.js new file mode 100644 index 0000000000000000000000000000000000000000..c2aa74561b895427c7bc0b186c4b105c180fa327 --- /dev/null +++ b/pool/shard011/JavaScript/0070469_writable-as-promise.js @@ -0,0 +1,35 @@ +import { Writable } from "stream" + +export class WritableAsPromise extends Writable { + constructor() { + super() + + this._output = `` + this._deferred = { + promise: null, + resolve: null, + reject: null, + } + this._deferred.promise = new Promise((resolve, reject) => { + this._deferred.resolve = resolve + this._deferred.reject = reject + }) + } + + _write(chunk, enc, cb) { + this._output += chunk.toString() + + cb() + } + + end() { + this._deferred.resolve(this._output) + + this.destroy() + } + + // disguise us as a promise + then(resolve, reject) { + return this._deferred.promise.then(resolve, reject) + } +} diff --git a/pool/shard011/JavaScript/0070474_inheritance.js b/pool/shard011/JavaScript/0070474_inheritance.js new file mode 100644 index 0000000000000000000000000000000000000000..d189ad7e573118ef1eb09a0e298bb42ac0964790 --- /dev/null +++ b/pool/shard011/JavaScript/0070474_inheritance.js @@ -0,0 +1,71 @@ +// By John Resig, http://ejohn.org/blog/simple-javascript-inheritance/ + +// Inspired by base2 and Prototype +(function(){ + var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; + // The base Class implementation (does nothing) + this.Class = function(){}; + + // Create a new Class that inherits from this class + Class.extend = function(prop) { + var _super = this.prototype; + + // Instantiate a base class (but only create the instance, + // don't run the init constructor) + initializing = true; + var prototype = new this(); + initializing = false; + + // Copy the properties over onto the new prototype + for (var name in prop) { + // Check if we're overwriting an existing function + prototype[name] = typeof prop[name] == "function" && + typeof _super[name] == "function" && fnTest.test(prop[name]) ? + (function(name, fn){ + return function() { + var tmp = this._super; + + // Add a new ._super() method that is the same method + // but on the super-class + this._super = _super[name]; + + // The method only need to be bound temporarily, so we + // remove it when we're done executing + var ret = fn.apply(this, arguments); + this._super = tmp; + + return ret; + }; + })(name, prop[name]) : + prop[name]; + } + + // The dummy class constructor + function Class() { + // All construction is actually done in the init method + if ( !initializing && this.init ) + this.init.apply(this, arguments); + } + + // Populate our constructed prototype object + Class.prototype = prototype; + + // Enforce the constructor to be what we expect + Class.constructor = Class; + + // And make this class extendable + Class.extend = arguments.callee; + + return Class; + }; +})(); + +// TODO: move somewhere else +Function.prototype.bind = function(scope) { + var proxied = this; + return function() { + var args = Array.prototype.slice.call(arguments); + args.push(this); + return proxied.apply(scope, args); + }; +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070480_crawlStations.js b/pool/shard011/JavaScript/0070480_crawlStations.js new file mode 100644 index 0000000000000000000000000000000000000000..da8b64abbfafdaac721f8cf0365b7aa650bad5d5 --- /dev/null +++ b/pool/shard011/JavaScript/0070480_crawlStations.js @@ -0,0 +1,134 @@ +// util +var _ = require('lodash'); +var Promise = require('bluebird'); + +// request and parser +var cheerio = require('cheerio'); +var request = Promise.promisify(require('request')); + +// debug messages +var debug = require('debug'); + +// db +var db = require('../db'); +var Cities = db.models.Cities; +var Stations = db.models.Stations; + +/** + * Crawl the last level of ANP Fuels' page, collecting the stations and its prices + * It scraps the page to find the stations info and prices for the fuel(parameter). + * Then on one hand it verifies if the station already exist, if not a new station + * is created with the prices found. On the other hand, if the station already + * exists the algorithm just push prices on the array of prices of that station + * document. + * @param {String} selSemana week identification + * @param {[type]} fuel collect info of this kind of fuel + * @param {[type]} city city that contains the stations + * @return {Promise} return all the stations found + */ +var crawlStations = function(selSemana, fuel, city){ + + var semana = selSemana.split(' '); + var dates = { + from: new Date(semana[1]), + to: new Date(semana[3]) + }; + + var crawlmenssage = [selSemana,city.document.name,fuel.fuelType].join() + debug('crawler:min:crawlStations')(crawlmenssage, 'request'); + + return request({ + url: 'http://www.anp.gov.br/preco/prc/Resumo_Semanal_Posto.asp', + method: 'POST', + encoding: 'binary', + form: { + 'cod_semana': selSemana.split('*')[0], + 'selMunicipio': city.selMunicipio, + 'cod_combustivel': fuel.selCombustivel.split('*')[0] + } + }).then(function(html){ + + debug('crawler:min:crawlStations')(crawlmenssage, 'parsing'); + + // parsing ..... + var $ = cheerio.load(html.toString()); + + // get all rows from table of cities stats + var rows = $('div.multi_box3 table.table_padrao tr'); + + var stations = {}; + var allInsertions = []; // keep all insertions promised + rows.slice(1, rows.length).each(function(i, row){ + var cols = $(row).children(); // all columns + + // get stations + var name = cols.eq(0).text() + stations[name] = { + name: name, + address: cols.eq(1).text(), + area: cols.eq(2).children().text(), + flag: cols.eq(3).text(), + city: city.document._id + }; + + // get prices + var prices = { + fuelType: fuel.fuelType, + sellPrice: parseFloat(cols.eq(4).html().replace(',', '.')) || null, + buyPrice: parseFloat(cols.eq(5).html().replace(',', '.')) || null, + saleMode: cols.eq(6).html() || null, + provider: cols.eq(7).html() ? new Date(cols.eq(7).html()) : null, + date: cols.eq(8).html() ? new Date(cols.eq(8).html()) : null + }; + + // push to sincronize with allInsertions + allInsertions.push( + Stations.findOne({ + name: stations[name].name, + address: stations[name].address, + area: stations[name].area + }) // verify if the station already exists + .then(function(stationFound){ + + if(!stationFound){ // if doesnt exists create a new station + var newStation = new Stations(stations[name]); + newStation.dates = dates; + return newStation.save() + .then(function(stationInserted){ + Cities.findByIdAndUpdate( + city.document._id, + {$push: {'stations': stationInserted}}, + {safe: true, upsert: true}, + function(err, model) { + debug('crawler:min:crawlStations')(crawlmenssage+' -> '+stationInserted.name, 'inserted'); + } + ); + return Promise.resolve(stationInserted); + }); + }else{ // if exists, just return the station + return Promise.resolve(stationFound); + } + }).then(function(stationDoc){ + stationDoc.prices.push(prices); // add prices for this fuel + return stationDoc.save() + .then(function(){ + return Promise.resolve(); + }); + }).catch(function(err){ + console.log(dates, semana, stations[name]); + return Promise.reject(err); + }) + ); + }); + + return Promise.all(allInsertions) // sincronize all insertions + .then(function(){ + debug('crawler:min:crawlStations')(crawlmenssage, 'finish'); + debug('crawler:extra:crawlStations')([selSemana, stations]); + + return Promise.resolve([selSemana, stations]); + }); + }); +} + +module.exports = crawlStations; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070481_version.js b/pool/shard011/JavaScript/0070481_version.js new file mode 100644 index 0000000000000000000000000000000000000000..a547a841a43ad89a0f09f32f5264efbc41305bb2 --- /dev/null +++ b/pool/shard011/JavaScript/0070481_version.js @@ -0,0 +1,127 @@ +'use strict'; + +var semver = require('semver'); + +/** + * Assert that a version number is both a Semantic Version number and ends in + * "-dev" (or some other approved suffix). + * @param {string} version + * @returns {undefined} + * @throws {Error} + */ +function assertValidDevelopmentVersion(version) { + assertValidSemanticVersion(version); + var prerelease = getPrerelease(version); + if (prerelease !== 'dev' && + prerelease !== 'snapshot' && + prerelease !== 'SNAPSHOT') + { + throw new Error("Not a recognized Development Version '" + version + "'"); + } +} + +/** + * Assert that a version number is both a Semantic Version number and not a + * prerelease version. + * @private + * @param {string} version + * @returns {undefined} + * @throws {Error} + */ +function assertValidReleaseVersion(version) { + assertValidSemanticVersion(version); + var prerelease = getPrerelease(version); + if (prerelease) { + throw new Error("A Release cannot include a prerelease version '" + version + "'"); + } +} + +/** + * Assert that a version number is both a Semantic Version number and ends in + * "-rc" (or some other approvded suffix). + * @private + * @param {string} version + * @returns {undefined} + * @throws {Error} + */ +function assertValidReleaseCandidateVersion(version) { + assertValidSemanticVersion(version); + var prerelease = getPrerelease(version); + if (!prerelease.match(/^alpha\.?[0-9]*$/) && + !prerelease.match(/^beta\.?[0-9]*$/) && + !prerelease.match(/^rc\.?[0-9]*$/)) + { + throw new Error("Not a recognized Release Candidate version '" + version + "'"); + } +} + +/** + * Assert that a version number is either a Release or Releae Candidate version + * number. + * @param {string} version + * @returns {undefined} + * @throws {Error} + */ +function assertValidReleaseOrReleaseCandidateVersion(version) { + try { + assertValidReleaseVersion(version); + } catch (error) { + try { + return assertValidReleaseCandidateVersion(version); + } catch (error) { + throw new Error("Not a recognized Release or Release Candidate version '" + + version + "'"); + } + } +} + +/** + * Assert that a version number is a Semantic Version number. + * @param {string} version + * @returns {undefined} + * @throws {Error} + */ +function assertValidSemanticVersion(version) { + if (!semver.valid(version)) { + throw new Error("Not a Semantic Version '" + version + "'"); + } +} + +/** + * Get the prerelease portion of a Semantic Version number. + * @private + * @param {string} version + * @returns {?string} + * @throws {Error} + */ +function getPrerelease(version) { + assertValidSemanticVersion(version); + version = version.split('-')[1] + if (version) { + return version.split('+')[0]; + } + return null; +} + +/* + * Check if a Semantic Version number is a Release Candidate version. + * @private + * @param {string} version + * @returns {boolean} + * @throws {Error} + */ +function isReleaseCandidateVersion(version) { + assertValidSemanticVersion(version); + try { + assertValidReleaseCandidateVersion(version); + } catch (error) { + return false; + } + return true; +} + +module.exports.assertValidDevelopmentVersion = assertValidDevelopmentVersion; +module.exports.assertValidReleaseOrReleaseCandidateVersion = + assertValidReleaseOrReleaseCandidateVersion; +module.exports.assertValidSemanticVersion = assertValidSemanticVersion; +module.exports.isReleaseCandidateVersion = isReleaseCandidateVersion; diff --git a/pool/shard011/JavaScript/0070482_helium.config.js b/pool/shard011/JavaScript/0070482_helium.config.js new file mode 100644 index 0000000000000000000000000000000000000000..e21fe198c8ab702bd268acc9d574289e9b7df829 --- /dev/null +++ b/pool/shard011/JavaScript/0070482_helium.config.js @@ -0,0 +1,100 @@ +/* + * 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. + */ + +export const HeliumConfFieldType = { + NUMBER: 'number', + JSON: 'json', + STRING: 'string', +}; + +/** + * @param persisted including `type`, `description`, `defaultValue` for each conf key + * @param spec including `value` for each conf key + */ +export function mergePersistedConfWithSpec(persisted, spec) { + const confs = []; + + for(let name in spec) { + const specField = spec[name]; + const persistedValue = persisted[name]; + + const value = (persistedValue) ? persistedValue : specField.defaultValue; + const merged = { + name: name, type: specField.type, description: specField.description, + value: value, defaultValue: specField.defaultValue, + }; + + confs.push(merged); + } + + return confs; +} + +export function createPackageConf(defaultPackages, persistedPackacgeConfs) { + let packageConfs = {}; + + for (let name in defaultPackages) { + const pkgInfo = defaultPackages[name]; + + const configSpec = pkgInfo.pkg.config; + if (!configSpec) { continue; } + + const version = pkgInfo.pkg.version; + if (!version) { continue; } + + let config = {}; + if (persistedPackacgeConfs[name] && persistedPackacgeConfs[name][version]) { + config = persistedPackacgeConfs[name][version]; + } + + const confs = mergePersistedConfWithSpec(config, configSpec); + packageConfs[name] = confs; + } + + return packageConfs; +} + +export function parseConfigValue(type, stringified) { + let value = stringified; + + try { + if (HeliumConfFieldType.NUMBER === type) { + value = parseFloat(stringified); + } else if (HeliumConfFieldType.JSON === type) { + value = JSON.parse(stringified); + } + } catch(error) { + // return just the stringified one + console.error(`Failed to parse conf type ${type}, value ${value}`); + } + + return value; +} + +/** + * create persistable config object + */ +export function createPersistableConfig(currentConf) { + // persist key-value only + // since other info (e.g type, desc) can be provided by default config + const filtered = currentConf.reduce((acc, c) => { + let value = parseConfigValue(c.type, c.value); + acc[c.name] = value; + return acc; + }, {}); + + return filtered; +} + + diff --git a/pool/shard011/JavaScript/0070486_device-controller.js b/pool/shard011/JavaScript/0070486_device-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..6f9554d3a28e05d62c5e75e836a5fb5c9bffbaa9 --- /dev/null +++ b/pool/shard011/JavaScript/0070486_device-controller.js @@ -0,0 +1,76 @@ +'use strict'; +angular.module('backend-module.device') + .config(['$stateProvider', function ($stateProvider) { + $stateProvider.state('backend.device.list', { + url: '/list', + templateUrl: 'backend/device/device-list/device.html', + controller: 'DeviceListController', + authenticate: true, + role: "admin", + resolve: { + _devices: [ + 'DeviceDevices', '$stateParams', + function (DeviceDevices, $stateParams) { + var page = $stateParams.page ? $stateParams.page : 1; + var perPage = $stateParams.perPage ? $stateParams.perPage : 4; + + var FiltersDevices = { + 'sort': '-updatedAt', + expand: 'product', + 'per-page': perPage, + page: page + }; + return DeviceDevices.getList(FiltersDevices); + } + ] + } + }); + }]) + .controller('DeviceListController', + ['$scope', '$modal', '$timeout', '_devices', 'DeviceDevices', + function ($scope, $modal, $timeout, _devices, DeviceDevices) { + $scope.devices = _devices.data; + $scope.search = {}; + + $scope.search.totalItems = _devices.headers('x-pagination-total-count'); + $scope.search.currentPage = _devices.headers('x-pagination-current-page'); + $scope.search.itemsPerPage = _devices.headers('x-pagination-per-page'); + $scope.search.maxPageSize = 4; + $scope.setPerPage = function (perPage) { + $scope.search.itemsPerPage = perPage; + goToDevicesList(); + + }; + $scope.pageChanged = function () { + + goToDevicesList() + }; + function goToDevicesList() { + + var page = $scope.search.currentPage; + var perPage = $scope.search.itemsPerPage; + + var FiltersDevices = { + 'sort': '-updatedAt', + expand: '', + 'per-page': perPage, + page: page + }; + + + DeviceDevices.getList( + FiltersDevices + ).then(function (result) { + + $scope.devices = result.data; + + $scope.search.totalItems = result.headers('x-pagination-total-count'); + $scope.search.currentPage = result.headers('x-pagination-current-page'); + $scope.search.itemsPerPage = result.headers('x-pagination-per-page'); + $scope.displayPageBoundaryLinks = Math.ceil($scope.search.totalItems / $scope.search.itemsPerPage) > $scope.search.maxPageSize; + + }); + + } + + }]); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070487_util.js b/pool/shard011/JavaScript/0070487_util.js new file mode 100644 index 0000000000000000000000000000000000000000..5610737f60adeb4fae120cfb63cd6f86ee68391b --- /dev/null +++ b/pool/shard011/JavaScript/0070487_util.js @@ -0,0 +1,92 @@ +module.exports = (function() { + var $$ = window.mvue; + + /** + * 根据参数判断是否需要渲染 header 部分 + * + * 先根据 页面 实例配置信息判断,没找到则尝试 + * 根据 全局 配置信息判断,默认为 true 显示 + */ + $$.needHeader = function(match) { + var $config = $$.config.common, + item = match.item, value; + + value = item.loadHead !== undefined ? item.loadHead : + ($config.loadHead !== undefined ? $config.loadHead : undefined); + + if (value !== undefined) { + if (value === false) { + return false; + } else if ($.isFun(value)) { + return value(); + } else { + return true; + } + } else { + return true; // 默认显示 header 部分 + } + }; + + // 检测对象当前是否运行在页面层级 + $$.isRunPage = function(scope) { + var $tpar = $(scope.$el).parent().parent(); + + return $tpar.tag() == "mg-view"; + } + + /** + * 手动调用 VM对象 的绑定方法 + */ + $$.vmCall = function(scope, evename) { + var mixins = scope.$options.mixins, arrs; + + for(var i=0; i { + if (typeof extensionSchema === 'string') { + extensionSchema = parse(extensionSchema); + } + return extendSchema(updatedSchema, extensionSchema); + }, outputSchema); + if (resolvers) { + outputSchema = addResolversToSchema({ + schema: outputSchema, + resolvers, + }); + } + } else if (typeof extension.extendSchema === 'function') { + debug( + `Extending schema via a function from the “${extension.name}” extension.` + ); + outputSchema = extension.extendSchema(schema, options); + } else { + throw new Error( + `The “${extension.name}” extension contains an invalid ` + + `\`extendSchema\` value: ${extension.extendSchema}` + ); + } + } + + // Fix for `graphql-tools` creating a new Query type with no description. + if (outputSchema._queryType.description === undefined) { + outputSchema._queryType.description = schema._queryType.description; + } + return outputSchema; +} + +export function createSchema(schema, options = {}) { + const { extensions = [] } = options; + return extensions.reduce((updatedSchema, extension) => { + return applyExtension(extension, updatedSchema, options); + }, schema); +} + +export const baseSchema = new GraphQLSchema({ + query: new GraphQLObjectType({ + name: 'Query', + description: `The query root, from which multiple types of MusicBrainz +requests can be made.`, + fields: () => ({ + lookup, + browse, + search, + node: nodeField, + }), + }), +}); diff --git a/pool/shard011/JavaScript/0070500_HttpPostTestClient.js b/pool/shard011/JavaScript/0070500_HttpPostTestClient.js new file mode 100644 index 0000000000000000000000000000000000000000..8b388a756deedf2ba7b2731b7c328c9374c0b8e7 --- /dev/null +++ b/pool/shard011/JavaScript/0070500_HttpPostTestClient.js @@ -0,0 +1,125 @@ +/** + * + * @author Andrew, Alexey + */ +function HttpPostTestClient() { + var self = this + , model = P.loadModel(this.constructor.name) + , form = P.loadForm(this.constructor.name, model); + + self.show = function () { + form.show(); + }; + + model.requery(function () { + }); + + form.button.onActionPerformed = function (event) { + self.execute(function () { + alert('All tests passed.'); + }); + }; + + self.execute = function (aOnComplete) { + var jCount = 0; + function finished() { + jCount++; + if (jCount === 6) + aOnComplete(); + } + + var req0 = new HTTPRequest(); + req0.module = 'HttpPostTestServer'; + req0.method = 'simplePostTest'; + req0.post("111", function (aRes) { + if (aRes !== "ok!") + throw "simplePostTest. Error! Response is wrong!"; + else { + P.Logger.info("simplePostTest - passed"); + finished(); + } + }, function (e) { + throw "simplePostTest. Error in post query. Server response: " + e; + }); + var req1 = new HTTPRequest(); + req1.module = 'HttpPostTestServer'; + req1.method = 'testBody'; + req1.contentType = 'text/plain;charset=utf-8'; + req1.post("111", function (aRes) { + if (aRes !== "111") + throw "testBody. Error! Response is not equal to request"; + else { + P.Logger.info("testBody - passed"); + finished(); + } + }, function (e) { + throw "testBody. Error in post query. Server response: " + e; + }); + + var req2 = new HTTPRequest(); + req2.restMethod = 'restSimpleTest'; + req2.post('', function (aRes) { + if (aRes !== "ok!") + throw "restSimpleTest. Error! Wrong response from server."; + else { + P.Logger.info("restSimpleTest - passed"); + finished(); + } + }, function (e) { + throw "restSimpleTest. Error in rest POST query. Server response: " + e; + }); + + var req3 = new HTTPRequest(); + req3.restMethod = 'restUPCASETest'; + req3.post('', function (aRes) { + if (aRes !== "ok!") + throw "restUPCASETest. Error! Wrong response from server."; + else { + P.Logger.info("restUPCASETest - passed"); + finished(); + } + }, function (e) { + throw "restUPCASETest. Error in rest POST query. Server response: " + e; + }); + // + var req4 = new HTTPRequest(); + req4.restMethod = 'restGetObjTest'; + req4.post("", function (aRes) { + if (aRes.result !== "ok!") + throw "restGetObjTest. Error! Wrong response from server."; + else { + P.Logger.info("restGetObjTest - passed"); + finished(); + } + }, function (e) { + throw "restGetObjTest. Error in rest POST query. Server response: " + e; + }); + var bd = document.getElementsByTagName('body')[0]; + var dv = document.createElement("div"); + dv.innerHTML = '' + + '' + + '
    ' + + ' ' + + ' ' + + '
    " + + message + + "" + ); +}; + +$.fn.inlineTouchform = function (options) { + var $target = $($(this).get(0)); + options.onerror = options.onerror || function () {}; + options.onload = options.onload || function () {}; + options.lang = options.lang || 'en'; + + $.ajax({ + url: options.formUrl, + dataType: "json", + success: function (data) { + var loading = $('.hq-loading'); + var onLoading = function () { + loading.show(); + }; + var onLoadingComplete = function () { + loading.hide(); + }; + $target.show(); + + data.session_data = $.extend(data.session_data, options.sessionData); + + data = $.extend(data, { + onsubmit: function (xml) { + // post to receiver + $.ajax({ + type: 'POST', + url: options.submitUrl, + data: xml, + success: function () { + $target.html(alertHtml('Form successfully submitted!', 'alert-success')); + options.onsubmit(); + } + }); + }, + onerror: function (resp) { + $target.html(alertHtml(resp.message, 'alert-error')); + }, + onload: function (adapter, resp) { + options.onload(); + } + }); + var sess = new WebFormSession(data); + sess.load($target, options.lang, { + onLoading: onLoading, + onLoadingComplete: onLoadingComplete + }); + } + }); +}; + +$("body").on('click', '.touchforms-link', function () { + var $this = $(this), + $target = $($this.data('target')), + appId = $this.data('app-id'), + moduleId = $this.data('module-id'), + formId = $this.data('form-id'), + formUrl = getFormUrl($this.data('form-url-root'), appId, moduleId, formId), + submitUrl = getSubmitUrl($this.data('submit-url-root'), appId), + sessionData = $this.data('session-data') || {}; + + $this.data('original-html', $this.data('original-html') || $this.html()); + + if ($this.data('state') === 'disabled') { + return false; + } + + // can't use individual off('click') because of event delegation + if (!$this.data('state') || ($this.data('state') === 'closed')) { + $this.data('state', 'disabled'); + $target.inlineTouchform({ + formUrl: formUrl, + submitUrl: submitUrl, + sessionData: sessionData, + onsubmit: function () { + $this.html($this.data('original-html')); + $this.click(); + $this.data('state', 'closed'); + window.location.reload(); + }, + onload: function () { + $this.html(" Cancel") + .data('state', 'open'); + } + }); + } else { + $this.html($this.data('original-html')); + $target.hide().html(""); + $this.data('state', 'closed'); + } + + return false; +}); diff --git a/pool/shard011/JavaScript/0070594_arraybuffer.js b/pool/shard011/JavaScript/0070594_arraybuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..3e6e084a7bee0559c5080ca7a5239af49bd8fb17 --- /dev/null +++ b/pool/shard011/JavaScript/0070594_arraybuffer.js @@ -0,0 +1,96 @@ +// Copyright 2013 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(function(global, shared, exports) { + +"use strict"; + +%CheckIsBootstrapping(); + +var GlobalArrayBuffer = global.ArrayBuffer; +var GlobalObject = global.Object; + +// ------------------------------------------------------------------- + +function ArrayBufferConstructor(length) { // length = 1 + if (%_IsConstructCall()) { + var byteLength = $toPositiveInteger(length, kInvalidArrayBufferLength); + %ArrayBufferInitialize(this, byteLength); + } else { + throw MakeTypeError(kConstructorNotFunction, "ArrayBuffer"); + } +} + +function ArrayBufferGetByteLen() { + if (!IS_ARRAYBUFFER(this)) { + throw MakeTypeError(kIncompatibleMethodReceiver, + 'ArrayBuffer.prototype.byteLength', this); + } + return %_ArrayBufferGetByteLength(this); +} + +// ES6 Draft 15.13.5.5.3 +function ArrayBufferSlice(start, end) { + if (!IS_ARRAYBUFFER(this)) { + throw MakeTypeError(kIncompatibleMethodReceiver, + 'ArrayBuffer.prototype.slice', this); + } + + var relativeStart = TO_INTEGER(start); + if (!IS_UNDEFINED(end)) { + end = TO_INTEGER(end); + } + var first; + var byte_length = %_ArrayBufferGetByteLength(this); + if (relativeStart < 0) { + first = $max(byte_length + relativeStart, 0); + } else { + first = $min(relativeStart, byte_length); + } + var relativeEnd = IS_UNDEFINED(end) ? byte_length : end; + var fin; + if (relativeEnd < 0) { + fin = $max(byte_length + relativeEnd, 0); + } else { + fin = $min(relativeEnd, byte_length); + } + + if (fin < first) { + fin = first; + } + var newLen = fin - first; + // TODO(dslomov): implement inheritance + var result = new GlobalArrayBuffer(newLen); + + %ArrayBufferSliceImpl(this, result, first); + return result; +} + +function ArrayBufferIsViewJS(obj) { + return %ArrayBufferIsView(obj); +} + + +// Set up the ArrayBuffer constructor function. +%SetCode(GlobalArrayBuffer, ArrayBufferConstructor); +%FunctionSetPrototype(GlobalArrayBuffer, new GlobalObject()); + +// Set up the constructor property on the ArrayBuffer prototype object. +%AddNamedProperty( + GlobalArrayBuffer.prototype, "constructor", GlobalArrayBuffer, DONT_ENUM); + +%AddNamedProperty(GlobalArrayBuffer.prototype, + symbolToStringTag, "ArrayBuffer", DONT_ENUM | READ_ONLY); + +$installGetter(GlobalArrayBuffer.prototype, "byteLength", ArrayBufferGetByteLen); + +$installFunctions(GlobalArrayBuffer, DONT_ENUM, [ + "isView", ArrayBufferIsViewJS +]); + +$installFunctions(GlobalArrayBuffer.prototype, DONT_ENUM, [ + "slice", ArrayBufferSlice +]); + +}) diff --git a/pool/shard011/JavaScript/0070596_zooming.js b/pool/shard011/JavaScript/0070596_zooming.js new file mode 100644 index 0000000000000000000000000000000000000000..edebde0e40294a64aeb94681e4485af4113ac2da --- /dev/null +++ b/pool/shard011/JavaScript/0070596_zooming.js @@ -0,0 +1,309 @@ +/** + * zooming - Image zooming with pure JavaScript. + * @version v0.2.2 + * @link https://github.com/kingdido999/zooming + * @license MIT + */ + ++function() { 'use strict' + + function Zooming() { + this._scaleBase = 1.0 + this._target = null // Zoomable target + this._body = document.body + this._lastScrollPosition = null + this._scrollThreshold = 40 + + this._handleClick = this._handleClick.bind(this) + this._handleKeyDown = this._handleKeyDown.bind(this) + this._handleScroll = this._handleScroll.bind(this) + } + + Zooming.prototype = { + init: function() { + this._body.addEventListener('click', this._handleClick) + + var zoomableImages = document.querySelectorAll('img[data-action="zoom"]') + for (var i = 0; i < zoomableImages.length; i++) { + setCursorStyle(zoomableImages[i], 'zoom-in') + } + }, + + _handleClick: function(event) { + var target = event.target + + if (!target) return + + if (target.tagName !== 'IMG') this._close() + + if (!target.hasAttribute('data-action')) return + + switch (target.getAttribute('data-action')) { + case 'zoom': + this._zoom(target) + break + case 'close': + this._close() + break + default: + break + } + }, + + _handleKeyDown: function(event) { + if (event.keyCode === 27) this._close() // Esc + }, + + _handleScroll: function() { + var scrollTop = window.pageYOffset || + (document.documentElement || this._body.parentNode || this._body).scrollTop + + if (this._lastScrollPosition === null) this._lastScrollPosition = scrollTop + + var deltaY = this._lastScrollPosition - scrollTop + + if (Math.abs(deltaY) >= this._scrollThreshold) { + this._lastScrollPosition = null + this._close() + } + }, + + _zoom: function(target) { + // Avoid zooming multiple times + if (this._target) return + + this._target = new Zoomable(target) + this._target.zoomIn() + + document.addEventListener('keydown', this._handleKeyDown) + document.addEventListener('scroll', this._handleScroll) + }, + + _close: function() { + if (!this._target) return + + this._target.zoomOut() + this._target = null + + document.removeEventListener('keydown', this._handleKeyDown) + document.removeEventListener('scroll', this._handleScroll) + } + } + + /** + * The zoomable image. + */ + function Zoomable(img) { + this._scaleBase = 1.0 + this._image = img + this._src = img.getAttribute('src') + this._dataOriginal = img.getAttribute('data-original') + this._overlay = null // An overlay that whites out the body + this._body = document.body + this._handleTransitionEnd = this._handleTransitionEnd.bind(this) + + this._styles = { + image: { + width: '', + height: '', + transform: '', + zoomIn: { + 'position': 'relative', + 'z-index': 666, + '-webkit-transition': 'all 300ms', + '-o-transition': 'all 300ms', + 'transition': 'all 300ms' + }, + zoomOut: { + 'position': '', + 'z-index': '', + '-webkit-transition': '', + '-o-transition': '', + 'transition': '' + } + }, + overlay: { + 'z-index': 233, + 'background': '#fff', + 'position': 'fixed', + 'top': 0, + 'left': 0, + 'right': 0, + 'bottom': 0, + 'filter': 'alpha(opacity=0)', + 'opacity': 0, + '-webkit-transition': 'opacity 300ms', + '-o-transition': 'opacity 300ms', + 'transition': 'opacity 300ms' + } + } + } + + Zoomable.prototype = { + zoomIn: function() { + this._image.addEventListener('transitionend', this._handleTransitionEnd) + var img = new Image() + + img.onload = (function() { + if (this._dataOriginal) this._upgradeSource() + + this._createOverlay() + this._calculateZoom() + + // Repaint before animating, fix Safari image flickering issue + this._image.offsetWidth + + // Zoom image + setStyles(this._image, this._styles.image.zoomIn) + this._transform() + }).bind(this) + + img.src = this._src + }, + + zoomOut: function() { + this._image.addEventListener('transitionend', this._handleTransitionEnd) + this._removeOverlay() + this._styles.image.transform = '' + this._transform() + }, + + _upgradeSource: function() { + // Save the original image width and height styles if present + this._styles.image.width = this._image.style.width + this._styles.image.height = this._image.style.height + + var rect = this._image.getBoundingClientRect() + + // Set image css width and height explicitly so the transformed + // image is correctly displayed + setStyles(this._image, { + 'width': rect.width + 'px', + 'height': rect.height + 'px' + }) + + // Use data-original as image src + this._image.setAttribute('src', this._dataOriginal) + }, + + _downgradeSource: function() { + // Restore the old image width and height + setStyles(this._image, { + 'width': this._styles.image.width, + 'height': this._styles.image.height + }) + + // Restore the image src + this._image.setAttribute('src', this._src) + }, + + _calculateZoom: function() { + var rect = this._image.getBoundingClientRect() + + var windowCenter = { + x: window.innerWidth / 2, + y: window.innerHeight / 2 + } + + var imgHalfWidth = rect.width / 2 + var imgHalfHeight = rect.height / 2 + + var imgCenter = { + x: rect.left + imgHalfWidth, + y: rect.top + imgHalfHeight + } + + // The vector to translate image to the window center + var translate = { + x: windowCenter.x - imgCenter.x, + y: windowCenter.y - imgCenter.y + } + + // The distance between image edge and window edge + var distFromImageEdgeToWindowEdge = { + x: windowCenter.x - imgHalfWidth, + y: windowCenter.y - imgHalfHeight + } + + // The additional scale is based on the smaller value of + // scaling horizontally and scaling vertically + var scaleHorizontally = distFromImageEdgeToWindowEdge.x / imgHalfWidth + var scaleVertically = distFromImageEdgeToWindowEdge.y / imgHalfHeight + var scale = this._scaleBase + Math.min(scaleHorizontally, scaleVertically) + + // Translate the image to window center, then scale the image + this._styles.image.transform = + 'translate(' + translate.x + 'px,' + translate.y + 'px) ' + + 'scale(' + scale + ',' + scale + ')' + }, + + _createOverlay: function() { + // Create an overlay, it does not white out at this point + this._overlay = document.createElement('div') + setStyles(this._overlay, this._styles.overlay) + this._body.appendChild(this._overlay) + + // Use setTimeout to apply correct overlay opacity transition when + // zooming in, otherwise the transition effect won't trigger. + window.setTimeout((function() { + // Now whites out the overlay + setStyles(this._overlay, { + 'filter': "alpha(opacity=100)", + 'opacity': 1 + }) + }).bind(this), 30) + }, + + _removeOverlay: function() { + setStyles(this._overlay, { + 'filter': "alpha(opacity=0)", + 'opacity': 0 + }) + }, + + _transform: function() { + setStyles(this._image, { + '-webkit-transform': this._styles.image.transform, + '-ms-transform': this._styles.image.transform, + 'transform': this._styles.image.transform, + }) + }, + + _handleTransitionEnd: function(event) { + switch (this._image.getAttribute('data-action')) { + case 'close': + this._body.removeChild(this._overlay) + + if (this._dataOriginal) this._downgradeSource() + + setStyles(this._image, this._styles.image.zoomOut) + setCursorStyle(this._image, 'zoom-in') + this._image.setAttribute('data-action', 'zoom') + break + case 'zoom': + setCursorStyle(this._image, 'zoom-out') + this._image.setAttribute('data-action', 'close') + break + default: + break + } + this._image.removeEventListener('transitionend', this._handleTransitionEnd) + } + } + + function setStyles(element, styles) { + for (var prop in styles) { + element.style[prop] = styles[prop] + } + } + + function setCursorStyle(element, style) { + element.style.cursor = style + element.style.cursor = '-webkit-' + style + element.style.cursor = '-moz-' + style + } + + document.addEventListener('DOMContentLoaded', function() { + new Zooming().init() + }) +}() diff --git a/pool/shard011/JavaScript/0070598_Composite.js b/pool/shard011/JavaScript/0070598_Composite.js new file mode 100644 index 0000000000000000000000000000000000000000..0c7f27878b5c869819149f42b9c857d605fd4b9b --- /dev/null +++ b/pool/shard011/JavaScript/0070598_Composite.js @@ -0,0 +1,53 @@ +/** + * Composite pattern. + * @class Composite + * @constructor + * + */ +module.exports = function Composite() { + + this._members = []; + /** + * add an Object to the internal list. + * + * @method add + * @param {Object} o + * @return Composite + * + */ + this.add = function(o) { + + this._members.push(o); + + return this; + + }; + + /** + * _callEach will call a method for each member of this composition. + * + * @method _callEach + * @param {String} method + * @return + * + */ + this._callEach = function(method) { + + var args = Array.prototype.slice.call(arguments, 1); + + this._members.forEach(function(member, key) { + + var f = member[method]; + if (!f) throw new Error("Method '" + method + "' not found on " + member.constructor + "!"); + f.apply(member, args); + + }); + + + }; + + + + + +}; diff --git a/pool/shard011/JavaScript/0070601_section.model.js b/pool/shard011/JavaScript/0070601_section.model.js new file mode 100644 index 0000000000000000000000000000000000000000..7cc2cf6cb7c59b427489c829d956e81f9f74a7ff --- /dev/null +++ b/pool/shard011/JavaScript/0070601_section.model.js @@ -0,0 +1,124 @@ +import mongoose from 'mongoose'; +import Document from './document.model'; +import Input from './input.model'; +import Promise from 'bluebird'; + +let sectionSchema = new mongoose.Schema({ + title: { type: String }, + description: { type: String }, + repeatable: { + type: Boolean, + default: false + }, + position: { + type: Number, + required: true, + get: v => Math.round(v), + set: v => Math.round(v) + }, + document: {type: mongoose.Schema.Types.ObjectId, ref: 'Document'}, + master: {type: mongoose.Schema.Types.ObjectId, ref: 'Section'}, + children: [{type: mongoose.Schema.Types.ObjectId, ref:'Section'}], + inputs: [{type: mongoose.Schema.Types.ObjectId, ref:'Input'}] +}); + +sectionSchema.pre('save', function (next) { + var Section = mongoose.model('Section', sectionSchema); + ( + this.master + ? Section.update( {_id: this.master}, { $addToSet: {children: this._id } } ) + : Document.update( {_id: this.document}, { $addToSet: {sections: this._id } } ) + ) + .then(( (documents) => next() )) + .error(( (err) => next(err) )); +}); + +sectionSchema.post('save', function (section) { + if(section.repeatable && section.children.length < 50) { + var Section = mongoose.model('Section', sectionSchema); + for(var i=1; i<=50; i++) { + var newSection = new Section(); + newSection.master = section._id; + newSection.position = i; + newSection.title = section.title; + newSection.description = section.description; + + newSection.save(); + } + } +}); + +sectionSchema.post('save', function (section) { //sync all the sections inputs + if(section.master) { + var Section = mongoose.model('Section', sectionSchema); + Section.findById(section.master).populate('inputs') + .then(function(section) { + section.inputs.forEach(function(input) { + Input.findOne({clonedFrom: input._id, section: section._id}) + .then((clonedInput) => { + clonedInput = clonedInput || new Input(); + if(clonedInput.syncWith(input)) { + clonedInput.save(); + } + }); + }); + }); + } +}); + +sectionSchema.post('save', function (section) { + var Section = mongoose.model('Section', sectionSchema); + if(section.children) { + Section.find({_id: {$in: section.children } }) + .then(function(children) { + children.forEach((child) => { + if(child.syncWith(section)) { + child.save(); + } + }); + }); + } +}); + +sectionSchema.pre('remove', function (next) { + var Section = mongoose.model('Section', sectionSchema); + ( + this.master + ? Section.update( {_id: this.master}, { $pullAll: {children: [this._id] } } ) + : Document.update( {_id: this.document}, { $pullAll: {sections: [this._id] } } ) + ) + .then(( (documents) => next() )) + .error(( (err) => next(err) )); +}); + +sectionSchema.post('save', function (section) { + var query = { position: section.position, _id: { $ne: section._id } }; + var Section = mongoose.model('Section', sectionSchema); + query[(section.master ? 'master' : 'document')] = (section.master || section.document); + + + Section.find(query) + .then( function(sections) { + return Promise.each(sections, function(section) { + section.position++; + return section.save(); + }) + }) + .error(( (err) => console.log(err) )); +}); + +sectionSchema.methods.syncWith = function(section) { + let self = this; + var didChange = false; + + ['title','description'].forEach((prop) => { + if(self[prop] != section[prop]) { + didChange = true; + self[prop] = section[prop]; + } + }); + + return didChange; +} + +export default mongoose.model('Section', sectionSchema); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070603_log.js b/pool/shard011/JavaScript/0070603_log.js new file mode 100644 index 0000000000000000000000000000000000000000..bf1fa61e4588ee788fd75f858214fef70c1b4b70 --- /dev/null +++ b/pool/shard011/JavaScript/0070603_log.js @@ -0,0 +1,50 @@ +/* */ +(function(process) { + var assert = require('assert'); + var util = require('../../util'); + assert.ok(process.stdout.writable); + assert.ok(process.stderr.writable); + var stdout_write = global.process.stdout.write; + var strings = []; + global.process.stdout.write = function(string) { + strings.push(string); + }; + console._stderr = process.stdout; + var tests = [{ + input: 'foo', + output: 'foo' + }, { + input: undefined, + output: 'undefined' + }, { + input: null, + output: 'null' + }, { + input: false, + output: 'false' + }, { + input: 42, + output: '42' + }, { + input: function() {}, + output: '[Function]' + }, { + input: parseInt('not a number', 10), + output: 'NaN' + }, { + input: {answer: 42}, + output: '{ answer: 42 }' + }, { + input: [1, 2, 3], + output: '[ 1, 2, 3 ]' + }]; + tests.forEach(function(test) { + util.log(test.input); + var result = strings.shift().trim(), + re = (/[0-9]{1,2} [A-Z][a-z]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} - (.+)$/), + match = re.exec(result); + assert.ok(match); + assert.equal(match[1], test.output); + }); + global.process.stdout.write = stdout_write; +})(require('process')); diff --git a/pool/shard011/JavaScript/0070606_ModelService.js b/pool/shard011/JavaScript/0070606_ModelService.js new file mode 100644 index 0000000000000000000000000000000000000000..673a5a9ab96bf6f44feb4d2134a50b304bab78ac --- /dev/null +++ b/pool/shard011/JavaScript/0070606_ModelService.js @@ -0,0 +1,122 @@ +var extend = require('node.extend'); + +// warn this creates each time a new id +var updateOrCreateResponse = function (modelName, findBy, req, res, next) { + + // Locate and validate name parameter + var id = req.param(findBy); + var data = req.params.all(); + if (!name) { + return res.badRequest('No id provided.', findBy, name); + } + + updateOrCreate(modelName, data, id, function (err, result) { + if (err) return res.serverError(err); + res.status(201); + return res.json(result.toJson()); + }); + +} + +var updateOrCreate = function (modelName, data, query, callback, extendFound) { + // sails.log.debug("updateOrCreate", modelName, data, id); + // sails.log.debug("global[modelName]", global[modelName]); + + if (typeof query == 'undefined') { + return callback('No query provided.'); + } + if (!data) { + return callback('No data provided.'); + } + + // Otherwise, find and destroy the global[modelName] in question + global[modelName].find(query).exec(function found(err, found) { + if (err) return callback(err); + if (found instanceof Array) found = found[0]; + // not found + if (!found) { + global[modelName].create(data).exec(function created (err, data) { + if (err) return callback(err); + // sails.log.debug("created", err, data); + global[modelName].publishCreate(data); + return callback(null, data); + }); + } else { + // sails.log.debug("found", found); + if(extendFound) { + sails.log.error("found", found); + sails.log.error("data", data); + data = extend(found, data); + sails.log.error("extended", data); + } + + global[modelName].update(found.id, data).exec(function updated (err, data) { + if (err) return callback(err); + if (data instanceof Array) data = data[0]; + // sails.log.debug("update", err, data); + global[modelName].publishUpdate(found.id, data); + return callback(null, data); + }); + } + }); +} + +var replace = function (modelName, data, callback) { + + if (!data) { + return callback('No data provided.'); + } + + global[modelName].destroy({}).exec(function destroyed (err, destroyResult) { + if (err) return callback(err); + global[modelName].create(data).exec(function created (err, data) { + if (err) return callback(err); + global[modelName].publishCreate(data); + return callback(null, data); + }); + }); +} + +var updateEach = function (modelName, datas, callback) { + if (!datas) { + return callback('No data provided.'); + } + var iterator = function (data, callback) { + if (!data.id) { + return callback('No data provided.'); + } + global[modelName].update(data.id, data).exec(function updated (err, data) { + if (err) return callback(err); + if (data instanceof Array) data = data[0]; + global[modelName].publishUpdate(data.id, data); + return callback(null, data); + }); + } + async.map(datas, iterator, callback); +} + +var updateOrCreateEach = function (modelName, datas, propertyName, callback, extendFound) { + if (!modelName) { + return callback('No model name provided.'); + } + if (!datas) { + return callback('No data provided.'); + } + if (!propertyName) { + return callback('No property name provided.'); + } + var iterator = function (data, callback) { + var query = {}; + query[propertyName] = data[propertyName]; + updateOrCreate(modelName, data, query, callback, extendFound) + } + async.mapSeries(datas, iterator, callback); +} + +module.exports = { + updateOrCreate: updateOrCreate, + updateOrCreateResponse: updateOrCreateResponse, + replace: replace, + updateEach: updateEach, + updateOrCreateEach: updateOrCreateEach +} diff --git a/pool/shard011/JavaScript/0070609_axurerp_pagespecificscript.js b/pool/shard011/JavaScript/0070609_axurerp_pagespecificscript.js new file mode 100644 index 0000000000000000000000000000000000000000..08681339f07698423ba813bf253cfe7984f487f5 --- /dev/null +++ b/pool/shard011/JavaScript/0070609_axurerp_pagespecificscript.js @@ -0,0 +1,94 @@ +for(var i = 0; i < 29; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); } + +$axure.eventManager.pageLoad( +function (e) { + +}); +gv_vAlignTable['u20'] = 'center';document.getElementById('u21_img').tabIndex = 0; + +u21.style.cursor = 'pointer'; +$axure.eventManager.click('u21', function(e) { + +if (true) { + + self.location.href=$axure.globalVariableProvider.getLinkUrl('学员管理列表.html'); + +} +}); +gv_vAlignTable['u22'] = 'center';document.getElementById('u23_img').tabIndex = 0; + +u23.style.cursor = 'pointer'; +$axure.eventManager.click('u23', function(e) { + +if (true) { + + self.location.href=$axure.globalVariableProvider.getLinkUrl('课程列表.html'); + +} +}); +gv_vAlignTable['u24'] = 'center';document.getElementById('u25_img').tabIndex = 0; + +u25.style.cursor = 'pointer'; +$axure.eventManager.click('u25', function(e) { + +if (true) { + + self.location.href=$axure.globalVariableProvider.getLinkUrl('卡片库.html'); + +} +}); +gv_vAlignTable['u26'] = 'center';document.getElementById('u27_img').tabIndex = 0; + +u27.style.cursor = 'pointer'; +$axure.eventManager.click('u27', function(e) { + +if (true) { + + self.location.href=$axure.globalVariableProvider.getLinkUrl('统计.html'); + +} +}); +gv_vAlignTable['u28'] = 'center';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u3'] = 'center';gv_vAlignTable['u5'] = 'top';document.getElementById('u6_img').tabIndex = 0; + +u6.style.cursor = 'pointer'; +$axure.eventManager.click('u6', function(e) { + +if (true) { + + self.location.href=$axure.globalVariableProvider.getLinkUrl('学员列表.html'); + +} +}); +gv_vAlignTable['u7'] = 'center';gv_vAlignTable['u9'] = 'center';gv_vAlignTable['u11'] = 'center';gv_vAlignTable['u13'] = 'center';gv_vAlignTable['u15'] = 'center';document.getElementById('u16_img').tabIndex = 0; + +u16.style.cursor = 'pointer'; +$axure.eventManager.click('u16', function(e) { + +if (true) { + + self.location.href=$axure.globalVariableProvider.getLinkUrl('学员列表.html'); + +} +}); +gv_vAlignTable['u17'] = 'center';u18.tabIndex = 0; + +u18.style.cursor = 'pointer'; +$axure.eventManager.click('u18', function(e) { + +if (true) { + + self.location.href=$axure.globalVariableProvider.getLinkUrl('学员列表.html'); + +} +}); +gv_vAlignTable['u18'] = 'top';document.getElementById('u19_img').tabIndex = 0; + +u19.style.cursor = 'pointer'; +$axure.eventManager.click('u19', function(e) { + +if (true) { + + self.location.href=$axure.globalVariableProvider.getLinkUrl('用户管理列表.html'); + +} +}); diff --git a/pool/shard011/JavaScript/0070615_webpack.config.js b/pool/shard011/JavaScript/0070615_webpack.config.js new file mode 100644 index 0000000000000000000000000000000000000000..bf37bc5345c0df288ff3d0170334f6f7029ff084 --- /dev/null +++ b/pool/shard011/JavaScript/0070615_webpack.config.js @@ -0,0 +1,17 @@ +const merge = require('lodash/merge'); +const path = require('path'); + +const { decorateStorybookConfig } = require('@wix/yoshi-flow-library/storybook'); + +module.exports = ({ config }) => { + const srcPath = path.resolve(__dirname, '../..', 'src'); + + return merge(decorateStorybookConfig(config), { + context: srcPath, + resolve: { + alias: { + 'wix-style-react': srcPath, + }, + }, + }); +}; diff --git a/pool/shard011/JavaScript/0070616_Config.js b/pool/shard011/JavaScript/0070616_Config.js new file mode 100644 index 0000000000000000000000000000000000000000..3bb10a06d55ff188aaf36bdd7a152d1004960958 --- /dev/null +++ b/pool/shard011/JavaScript/0070616_Config.js @@ -0,0 +1,30 @@ +function Config (conf) { + /* + * This class is just a wrapper, see Ubui/Configuration + * for the class that loads the configuration + */ + if (!conf || !(typeof conf === 'object')) { + throw TypeError('The configuration passed is the incorrect format'); + } + + this.propertyObjectLoop = function (property) { + var prop, returnObj = false; + + for (prop in property) { + if (property.hasOwnProperty(prop)) { + this[prop] = property[prop]; + } + } + }; + + /* + * Loop over the configuration and + * create the config object out of + * this class. + */ + this.propertyObjectLoop(conf); + + return this; +}; + +module.exports.Config = Config; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070620_page-title-directive.js b/pool/shard011/JavaScript/0070620_page-title-directive.js new file mode 100644 index 0000000000000000000000000000000000000000..c549328eb78688ee12a318314b30a1e9d7bf84e7 --- /dev/null +++ b/pool/shard011/JavaScript/0070620_page-title-directive.js @@ -0,0 +1,26 @@ +/** + * pageTitle - Directive for set Page title - meta title + */ + +(function () { + 'use strict'; + angular.module('core.directives').directive('dirPageTitle', ['$rootScope','$timeout', function ($rootScope, $timeout) { + + return { + restrict: 'A', + link: function(scope, element) { + var listener = function(event, toState, toParams, fromState, fromParams) { + // Default title - load on Dashboard 1 + var title = '**'; + // Create your own title pattern + if (toState.data && toState.data.pageTitle) title = ' ** ' + toState.data.pageTitle; + $timeout(function() { + element.text(title); + }); + }; + $rootScope.$on('$stateChangeStart', listener); + } + } + + }]); +})(); diff --git a/pool/shard011/JavaScript/0070622_routes.js b/pool/shard011/JavaScript/0070622_routes.js new file mode 100644 index 0000000000000000000000000000000000000000..a28ec16953b4e9c0300645eb4eaee923df45830f --- /dev/null +++ b/pool/shard011/JavaScript/0070622_routes.js @@ -0,0 +1,39 @@ +var Q = require('q'), + path = require('path'), + fs = require('fs'), + + bobble = require('./bobble.js'); + +var IS_NYAN = false; + +exports.getIndex = function (req, res) { + var url = req.protocol + '://' + req.get('host') + req.originalUrl; + res.redirect((IS_NYAN ? 'http://nyanit.com/' : '') + url + 'bobble'); +} + +exports.generateBobble = function (req, res) { + var imgSrc = req.file.path; + bobble.detectFace(req.file.path) + .then(bobble.generateBobblePermutations) + .then(bobble.generateGif) + .then(function () { + console.log('generate'); + res.redirect(301, '/bobble/' + path.basename(imgSrc, path.extname(imgSrc))); + }) +} + +exports.displayBobble = function (req, res) { + var myImg = 'myanimated.gif'; + console.log(req.params['bobbleId']) + if (typeof req.params['bobbleId'] !== 'undefined') { + myImg = req.params['bobbleId'] + '.gif'; + } + console.log('my image:', myImg); + // res.end('hello'); + res.render('index', { + title: 'Bobblehead Generator', + location: "http://nyanit.com/" + req.get('host') + '/bobble/' + path.basename(myImg, path.extname(myImg)), + imgs: [myImg] + }); + // res.end('hello'); +} diff --git a/pool/shard011/JavaScript/0070623_element_observer.js b/pool/shard011/JavaScript/0070623_element_observer.js new file mode 100644 index 0000000000000000000000000000000000000000..c52a5b706597f10c53ffa18fbf1f790b9a06c857 --- /dev/null +++ b/pool/shard011/JavaScript/0070623_element_observer.js @@ -0,0 +1,57 @@ +const ELEMENT_HANDLER_CLASS_PREFIX = 'tf__observer-element-'; +const TEXT_HANDLER_CLASS_PREFIX = 'tf__observer-text-'; + +class ElementObserver { + static _invokeHandlers(handlers, classPrefix, matchedElement, passedNode) { + handlers.forEach(({ selector, handler }, i) => { + if (matchedElement.matches(selector) && + !matchedElement.classList.contains(classPrefix + i)) { + handler(passedNode); + } + }); + } + + constructor() { + this._elementHandlers = []; + this._textHandlers = []; + new MutationObserver(mutations => { + mutations.forEach(mutation => { + Array.from(mutation.addedNodes).forEach(node => { + if (node instanceof Element) { + ElementObserver._invokeHandlers(this._elementHandlers, + ELEMENT_HANDLER_CLASS_PREFIX, node, node); + } else + if (node instanceof Text && node.parentElement !== null) { + ElementObserver._invokeHandlers(this._textHandlers, + TEXT_HANDLER_CLASS_PREFIX, node.parentElement, node); + } + }); + }); + }).observe(document.documentElement, { + childList: true, + subtree: true, + }); + } + + forEach(selector, handler) { + const handlerId = this._elementHandlers.length; + for (const el of Array.from(document.querySelectorAll(selector))) { + handler(el); + el.classList.add(ELEMENT_HANDLER_CLASS_PREFIX + handlerId); + } + this._elementHandlers.push({ selector, handler }); + } + + forEachTextIn(selector, handler) { + const handlerId = this._textHandlers.length; + for (const el of Array.from(document.querySelectorAll(selector))) { + for (const node of el.childNodes) { + if (node instanceof Text) { + handler(node); + } + } + el.classList.add(TEXT_HANDLER_CLASS_PREFIX + handlerId); + } + this._textHandlers.push({ selector, handler }); + } +} diff --git a/pool/shard011/JavaScript/0070628_gulpfile.js b/pool/shard011/JavaScript/0070628_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..37493974f9f6a2a1fc2e3091f92817777db329d2 --- /dev/null +++ b/pool/shard011/JavaScript/0070628_gulpfile.js @@ -0,0 +1,216 @@ +'use strict'; + +// Include gulp +var gulp = require('gulp'); + +// Include Our Plugins +var jshint = require('gulp-jshint'); +var sass = require('gulp-sass'); +var concat = require('gulp-concat'); +var uglify = require('gulp-uglify'); +var rename = require('gulp-rename'); +var htmlmin = require('gulp-htmlmin'); +var imagemin = require('gulp-imagemin'); +var del = require('del'); +var ejs = require("gulp-ejs"); +var pngquant = require('imagemin-pngquant'); +var browserSync = require('browser-sync'); +var runSequence = require('run-sequence'); +var bundle = require('gulp-bundle-assets'); +var sitemap = require('gulp-sitemap'); +var sitemapPages = require('./src/sitemap-pages.json'); + +//Added for Sitemap +var fs = require('fs'); +var path = require('path'); +var map = require('map-stream'); +var vfs = require('vinyl-fs'); +var extraSitemap = require('./src/sitemap-pages.json'); +var pagesArr = []; + +//add pages from json to array +gulp.task('extra-sitemap',function(){ + extraSitemap.extraPagesArr.forEach(function(args) { + pagesArr.push(args); + }); +}); + +//add all build html files we want to log function +gulp.task('no-index',['extra-sitemap'], function(done) { + vfs.src(['build/**/*.html', '!build/partials/**', '!build/controllers/**']) + .pipe(map(log)) + .on('end', done);; +}); + +//get the file path and check contents for noindex nofollow +function log(file, cb) { + fs.readFile(file.path, 'utf-8', function(err, contents) { + if (contents.indexOf('noindex') != -1) { + var x = file.path; + pagesArr.push('!' + path.relative(process.cwd(),x)); + } + }); + cb(null, file); +}; + +//build sitemap +gulp.task('sitemap',['no-index'], function () { + //console.log(pagesArr); + gulp.src(pagesArr) + .pipe(sitemap({ + siteUrl: 'https://www.thecapcitycollective.com' + })) + .pipe(gulp.dest('./build')); +}); +//////end sitemap///////////////////////////////////////////////// + + +////////////////////////////////////////////////////////////////// +// Delete Build folder +gulp.task('clean', function() { + return del(['./build']); +}); + +gulp.task('generate',function(){ + gulp.src("./src/**/*.html") + .pipe(ejs()) + .pipe(gulp.dest("./build")); +}); + +////////////////////////////////////////////////////////////////// +// Browser-Sync +gulp.task('browser-sync', function() { + browserSync.init({ + reloadDebounce: 5000, + server: { + baseDir: './build' + }, + port: 8000, + tunnel: false // only need to enable this if with a device not on the same wifi - crashes often so off by default + }); + + gulp.watch(['src/**/*.html'], function () { + runSequence( + 'generate', + browserSync.reload + ); + }); +}); + +// Minify Images +gulp.task('imagemin', function() { + return gulp.src(['./src/assets/images/*','./src/assets/images/**/*']) + .pipe(imagemin({ + progressive: true, + svgoPlugins: [{removeViewBox: false}], + use: [pngquant()] + })) + .pipe(gulp.dest('./build/assets/images/')); +}); + +// minify html +gulp.task('minify-html', function() { + return gulp.src(['build/**/*.html', '!build/partials/**']) + .pipe(htmlmin({collapseWhitespace: true, minifyJS : true, minifyCSS: true , removeComments: true})) + .pipe(gulp.dest('build')); +}); + + +// Lint Task +gulp.task('lint', function() { + return gulp.src('src/assets/js/*.js') + .pipe(jshint()) + .pipe(jshint.reporter('default')); +}); + +// Compile Our Sass +gulp.task('sass', function () { + return gulp.src('src/assets/sass/**/*.scss') + .pipe(sass({includePaths: ['./node_modules'], outputStyle: 'compressed'}).on('error', sass.logError)) + .pipe(gulp.dest('build/assets/stylesheets/')) + .pipe(browserSync.stream({match: '**/*.scss'})); + +}); + +////////////////////////////////////////////////////////////////// +// videoCopy +gulp.task('videoCopy', function() { + return gulp.src('./src/assets/videos/*') + .pipe(gulp.dest('./build/assets/videos/')) + .pipe(browserSync.stream({match: 'assets/videos/**'})); +}); + +////////////////////////////////////////////////////////////////// +// Concatenate & Minify JS + +// Ignores files used for bundle task +gulp.task('globalScripts', function() { + return gulp.src(['src/assets/js/global-scripts/*.js']) + .pipe(concat('global.js')) + .pipe(gulp.dest('build/assets/javascript')) + .pipe(rename('global.min.js')) + .pipe(uglify()) + .pipe(gulp.dest('build/assets/javascript')) + .pipe(browserSync.stream({match: '**/**/*.js'})); +}); + +// Uses bundle.config.js to find npm js files and bundles/uglifys them +gulp.task('bundleScripts', function() { + return gulp.src('src/assets/js/global-admin/bundle.config.js') + .pipe(bundle()) + .pipe(rename('global-admin.js')) + .pipe(gulp.dest('build/assets/javascript')); +}); + +//Make single script files that will be used on a case by case basis +gulp.task('localScripts',function() { + return gulp.src('src/assets/js/local-scripts/**/*.js') + .pipe(uglify()) + .pipe(gulp.dest('build/assets/javascript/local-scripts')); +}); + +gulp.task('scripts', ['globalScripts', 'bundleScripts','localScripts']); + +////////////////////////////////////////////////////////////////// +// Master Tasks +// Default Task <-- Make into Dev build vs. Prod build +gulp.task('default', function(callback) { + runSequence('clean', + ['lint', 'sass', 'scripts', 'imagemin', 'videoCopy', 'generate'], + 'minify-html', + 'sitemap', + callback); +}); + +gulp.task('netlify', function(callback) { + runSequence('clean', + ['lint', 'sass', 'scripts', 'imagemin', 'videoCopy', 'generate'], + 'minify-html', + 'sitemap', + callback); +}); + + +////////////////////////////////////////////////////////////////// +// Watch & Serve +// Watch Files For Changes +gulp.task('watch', function() { + gulp.watch('src/assets/js/**/*.js', ['lint', 'scripts']); + gulp.watch('src/assets/sass/**/*.scss', ['sass']); + //gulp.watch('src/assets/js/search/*.js', ['webpack:dev']); + gulp.watch('src/**/*.html'); + gulp.watch('src/**/*.js'); + gulp.watch('node_modules/capbox/js/bin/*.js', ['scripts']); + gulp.watch('node_modules/capbox/sass/**/*.scss', ['sass']); +}); + +gulp.task('serve', function(callback) { + runSequence('clean', + ['lint', 'sass', 'scripts', 'imagemin', 'videoCopy', 'generate', 'watch'], + 'browser-sync', + 'minify-html', + 'sitemap', + callback); +}); + + diff --git a/pool/shard011/JavaScript/0070629_scroller.js b/pool/shard011/JavaScript/0070629_scroller.js new file mode 100644 index 0000000000000000000000000000000000000000..7e715a8870679d583d114610df3de71c8d9b99e1 --- /dev/null +++ b/pool/shard011/JavaScript/0070629_scroller.js @@ -0,0 +1,67 @@ +import Em from 'ember'; + +const DURATION = 750; +const EASING = 'swing'; +const OFFSET = 0; + +const { RSVP } = Em; + +export default Em.Service.extend({ + + // ----- Static properties ----- + duration: DURATION, + easing: EASING, + offset: OFFSET, + + + // ----- Computed properties ----- + scrollable: Em.computed(function() { + return Em.$('html, body'); + }), + + + // ----- Methods ----- + getJQueryElement (target) { + const jQueryElement = Em.$(target); + + if (!jQueryElement) { + Em.Logger.warn("element couldn't be found:", target); + return; + } + + return jQueryElement; + }, + + getScrollableTop () { + // because the target elements top is calculated relative to the document, + // and if the scrollable container is not the document, + // we need to normalize the target elements top based on the top and current scrolled position of the scrollable + if (this.get('scrollable').offset().top) { + return this.get('scrollable').scrollTop() - this.get('scrollable').offset().top; + } else { + return 0; + } + }, + + getVerticalCoord (target, offset = 0) { + const jQueryElement = this.getJQueryElement(target); + return this.getScrollableTop() + jQueryElement.offset().top + offset; + }, + + scrollVertical (target, opts = {}) { + return new RSVP.Promise((resolve, reject) => { + + this.get('scrollable') + .animate( + { + scrollTop: this.getVerticalCoord(target, opts.offset) + }, + opts.duration || this.get('duration'), + opts.easing || this.get('easing'), + opts.complete + ) + .promise() + .then(resolve, reject); + }); + } +}); diff --git a/pool/shard011/JavaScript/0070630_app.js b/pool/shard011/JavaScript/0070630_app.js new file mode 100644 index 0000000000000000000000000000000000000000..4005c46a01b8527f185d651e3ce1c3d0d4bccc36 --- /dev/null +++ b/pool/shard011/JavaScript/0070630_app.js @@ -0,0 +1,136 @@ +import React from 'react' +import { render } from 'react-dom' +import { Router, Route, Link, History } from 'react-router' +import { createHistory, useBasename } from 'history' +import auth from './auth' + +const history = useBasename(createHistory)({ + basename: '/auth-flow' +}) + +const App = React.createClass({ + getInitialState() { + return { + loggedIn: auth.loggedIn() + } + }, + + updateAuth(loggedIn) { + this.setState({ + loggedIn: loggedIn + }) + }, + + componentWillMount() { + auth.onChange = this.updateAuth + auth.login() + }, + + render() { + return ( +
    +
      +
    • + {this.state.loggedIn ? ( + Log out + ) : ( + Sign in + )} +
    • +
    • About
    • +
    • Dashboard (authenticated)
    • +
    + {this.props.children} +
    + ) + } +}) + +const Dashboard = React.createClass({ + render() { + const token = auth.getToken() + + return ( +
    +

    Dashboard

    +

    You made it!

    +

    {token}

    +
    + ) + } +}) + +const Login = React.createClass({ + mixins: [ History ], + + getInitialState() { + return { + error: false + } + }, + + handleSubmit(event) { + event.preventDefault() + + const email = this.refs.email.value + const pass = this.refs.pass.value + + auth.login(email, pass, (loggedIn) => { + if (!loggedIn) + return this.setState({ error: true }) + + const { location } = this.props + + if (location.state && location.state.nextPathname) { + this.history.replaceState(null, location.state.nextPathname) + } else { + this.history.replaceState(null, '/about') + } + }) + }, + + render() { + return ( +
    + + (hint: password1)
    + + {this.state.error && ( +

    Bad login information

    + )} +
    + ) + } +}) + +const About = React.createClass({ + render() { + return

    About

    + } +}) + +const Logout = React.createClass({ + componentDidMount() { + auth.logout() + }, + + render() { + return

    You are now logged out

    + } +}) + +function requireAuth(nextState, replaceState) { + if (!auth.loggedIn()) + replaceState({ nextPathname: nextState.location.pathname }, '/login') +} + +render(( + + + + + + + + +), document.getElementById('example')) diff --git a/pool/shard011/JavaScript/0070633_ds1307.js b/pool/shard011/JavaScript/0070633_ds1307.js new file mode 100644 index 0000000000000000000000000000000000000000..9d11319aa2219c7e8396af76fa0afc44b8454e51 --- /dev/null +++ b/pool/shard011/JavaScript/0070633_ds1307.js @@ -0,0 +1,68 @@ +/*jslint node:true, vars:true, bitwise:true, unparam:true */ +/*jshint unused:true */ +/*global */ +/* +* Author: Zion Orent +* Copyright (c) 2014 Intel Corporation. +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +// Load RTC Clock module for Grove - RTC clock +var ds1307 = require('jsupm_ds1307'); +// load this on i2c bus 0 +var myRTCClockObj = new ds1307.DS1307(0); + +// always do this first +console.log("Loading the current time... "); + +var result = myRTCClockObj.loadTime(); +if (!result) +{ + console.log("myRTCClockObj.loadTime() failed."); + process.exit(1); +} + +printTime(myRTCClockObj); + +// set the year as an example +console.log("setting the year to 50"); +myRTCClockObj.year = 50; +myRTCClockObj.setTime(); + +// reload the time and print it +myRTCClockObj.loadTime(); +printTime(myRTCClockObj); + +function printTime(RTCObj) +{ + var timeStr = "The time is: " + + RTCObj.month + "/" + RTCObj.dayOfMonth + "/" + RTCObj.year + " " + + RTCObj.hours + ":" + RTCObj.minutes + ":" + RTCObj.seconds; + + if (RTCObj.amPmMode) + timeStr += (RTCObj.pm ? " PM " : " AM "); + + console.log(timeStr); + + console.log("Clock is in " + + (RTCObj.amPmMode ? "AM/PM mode" : "24hr mode")); +} + diff --git a/pool/shard011/JavaScript/0070635_weather.js b/pool/shard011/JavaScript/0070635_weather.js new file mode 100644 index 0000000000000000000000000000000000000000..d346eec771f882947a40fbafaa3635227817f8a3 --- /dev/null +++ b/pool/shard011/JavaScript/0070635_weather.js @@ -0,0 +1,139 @@ +$(document).ready(function() { + getLatLon(); +}); + +//1.get current lan & lon +var lat = ""; +var lon = ""; +var tempunit = "°C"; +var current_temp = 0; + +function getLatLon() { + var startPos; + var geoOptions = { + enableHighAccuracy: true + } + + var geoSuccess = function(position) { + startPos = position; + lat = startPos.coords.latitude; + lon = startPos.coords.longitude; + doAjax(); + }; + var geoError = function(error) { + console.log('Error occurred. Error code: ' + error.code); + }; + + navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions); +} + +//get weather file(json type) based on lan&lon +function doAjax() { + $.ajax({ + type: 'GET', + url: 'https://openweathermap.org/data/2.5/weather?appid=15a738dd59be0f288da09d8fa0ac6b37', + data: { + 'lat': lat, + 'lon': lon + }, + dataType: "json", + async: true, + success: function(data) { + //get city name + $(".city").text(data.name); + //get country + $.each(data.sys, function(key, value) { + if (key == "country") { + $(".city").append(", " + value + ""); + } + }); + //get current temp + $.each(data.main, function(key, value) { + if (key == "temp") { + current_temp = Math.round(value - 273.15); + + $(".temp").text(current_temp).append(" " + tempunit + ""); + } + }); + + //get main weather:sunny clouds rain and so on + $.each(data.weather, function(i, item) { + $(".weather").text(item.main); + //set weather icon + weather = item.main; + $("#wi-icon").removeClass(); + switch (weather) { + case "Clouds": + $("#wi-icon").addClass("wi wi-cloudy"); + break; + case "Clear": + $("#wi-icon").addClass("wi wi-day-sunny"); + break; + case "Rain": + $("#wi-icon").addClass("wi wi-sprinkle"); + break; + case "Snow": + $("#wi-icon").addClass("wi wi-snow"); + break; + case "Fog": + $("#wi-icon").addClass("wi wi-fog"); + break; + case "Haze": + $("#wi-icon").addClass("wi wi-day-haze"); + break; + case "Mist": + $("#wi-icon").addClass("wi wi-cloudy"); + break; + default: + $("#wi-icon").addClass("wi wi-fog"); + break; + } + + }); + } //success end + }); +} + +//change temperature unit +var boo_tempunit = true; +$(".temp").click(function() { + if (boo_tempunit) { + $(".temp").text(Math.round(current_temp + 32)).append(" " + "℉" + ""); + current_temp += 32; + return boo_tempunit = false; + } else { + $(".temp").text(Math.round(current_temp - 32)).append(" " + "°C" + ""); + current_temp -= 32; + return boo_tempunit = true; + } +}); + +//get current date +var d = new Date(); +var date = d.getDate(); +var month = d.getMonth(); +var day = d.getDay(); +var weekday = new Array(7); +weekday[0] = "Sunday"; +weekday[1] = "Monday"; +weekday[2] = "Tuesday"; +weekday[3] = "Wednesday"; +weekday[4] = "Thursday"; +weekday[5] = "Friday"; +weekday[6] = "Saturday"; +var months = new Array(12); +months[0] = "Jan. "; +months[1] = "Feb. "; +months[2] = "Mar. "; +months[3] = "Apr. "; +months[4] = "May. "; +months[5] = "Jun. "; +months[6] = "Jul. "; +months[7] = "Aug. "; +months[8] = "Sep. "; +months[9] = "Oct. "; +months[10] = "Nov. "; +months[11] = "Dec. "; + +var daytime = date + " " + months[month] + weekday[day]; +$(".daytime").text(daytime); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070636_tools.js b/pool/shard011/JavaScript/0070636_tools.js new file mode 100644 index 0000000000000000000000000000000000000000..c1de539432ff53f57395d91196c65a85995e4fb5 --- /dev/null +++ b/pool/shard011/JavaScript/0070636_tools.js @@ -0,0 +1,17 @@ +import authSelectors from 'template-ui/lib/plugins2/auth/selectors' +import config from '../config' +export const url = (path = '') => config.api + path + +const BASE_URL = url() + +const installationWrapper = (SUB_URL) => (state) => { + const installationid = authSelectors.activeInstallationId(state) + return `${BASE_URL}/installation/${installationid}${SUB_URL}` +} + +const tools = { + url, + installationWrapper, +} + +export default tools \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070638_game.js b/pool/shard011/JavaScript/0070638_game.js new file mode 100644 index 0000000000000000000000000000000000000000..7212ec1a1d0259088e83cb9ff303a88ed6f95c5e --- /dev/null +++ b/pool/shard011/JavaScript/0070638_game.js @@ -0,0 +1,41 @@ +// Constructor +function Game(socket) { + this.socket = socket; + this.updateState({ + players: [], + obstacles: [], + projectiles: [], + queue: [] + }) +}; + +// Class methods +Game.prototype.updateState = function(state) { + this.state = state; + var player = this.getPlayer(this.id); + if(this.state.queue.indexOf(this.id) >= 0){ + this.state.phase = 'queue'; + }else{ + var player = this.getPlayer(this.id); + if(player !== undefined) + this.state.ammo = player.ammo; + else + this.state.phase = 'join'; + } +} +Game.prototype.updatePlayerAcceleration = function(x, y) { + if(x !== 0 || y !== 0) this.socket.emit('updatePlayerAcceleration', x, y); +} +Game.prototype.shootProjectile = function(x, y) { + this.socket.emit('shootProjectile', x, y); +} +Game.prototype.addPlayer = function(avatar) { + this.socket.emit('addPlayer', avatar); +} +Game.prototype.getPlayer = function(id) { + var matches = this.state.players.filter(function(player) { + return player.id == id; + }); + if(matches.length > 0) + return matches[0]; +}; diff --git a/pool/shard011/JavaScript/0070641_karma.conf.js b/pool/shard011/JavaScript/0070641_karma.conf.js new file mode 100644 index 0000000000000000000000000000000000000000..09a62aec3ec094f8324c191cb697a2d7f36ad244 --- /dev/null +++ b/pool/shard011/JavaScript/0070641_karma.conf.js @@ -0,0 +1,86 @@ +// Karma configuration file +var karma = require("karma"); +var DEFAULT_NG_VERSION = "1.5"; + +/** + * This returns a Karma 'files configuration'. + * http://karma-runner.github.io/0.8/config/files.html + * + * Specifies which files can be served by the Karma web server + * + * included: true -- files that are always served to the browser (like + * + * @param {Object} options An object with the options for HelloWorld component. + * + * @option {string} target + * Identifier of the DIV tag where the component should be displayed. + * + * @option {string} [fontFamily='"Andale mono", courier, monospace'] + * Font list to be applied to the component content. + * + * @option {string} [fontColor="white"] + * HTML color code for the font. + * + * @option {string} [backgroundColor="#7BBFE9"] + * Background color for the entire div content. + * + * @option {Object} [selectionFontColor="white"] + * This color will be used to change the font color of selected text. + * + * @option {Object} [ selectionBackgroundColor="yellow"] + * This color will be used to change the background of selected text. + * + * @example + * var instance = new Biojs.HelloWorld({ + * target : "YourOwnDivId", + * selectionBackgroundColor : '#99FF00' + * }); + * + */ +Biojs.HelloWorld = Biojs.extend ( +/** @lends Biojs.HelloWorld# */ +{ + constructor: function (options) { + // In JavaScript ÒthisÓ always refers to the ÒownerÓ of the function we're executing (http://www.quirksmode.org/js/this.html) + // Let's preserve the reference to 'this' through the variable self. In this way, we can invoke/execute + // our component instead of the object where 'this' is being invoked/executed. + var self = this; + + // For practical use, create an object with the main DIV container + // to be used in all of the code of our component + this._container = jQuery("#"+self.opt.target); + + // Apply options values + this._container.css({ + 'font-family': self.opt.fontFamily, // this is one example of the use of self instead of this + 'background-color': self.opt.backgroundColor, + 'color': self.opt.fontColor, + 'font-size': '36px', + 'text-align': 'center', + 'vertical-align':'middle', + 'display': 'table-cell', + 'width': '597px', + 'height': '300px' + }); + + // Disable text selection and + // Change the selection mouse pointer + // from text to hand. + this._container.css({ + '-moz-user-select':'none', + '-webkit-user-select':'none', + 'user-select':'none' + }); + + // Set the content + text = 'Hello World!'; + + for( i=0; i< text.length; i++ ) { + this._container.append('' + text[i] + ''); + } + + // Internal method to initialize the event of select 'Hello' + this._addSelectionTrigger(); + + // Internal method to set the onClick event + this._addSimpleClickTrigger(); + }, + + /** + * Default values for the options + * @name Biojs.HelloWorld-opt + */ + opt: { + target: "YourOwnDivId", + fontFamily: '"Andale mono", courier, monospace', + fontColor: "white", + backgroundColor: "#7BBFE9", + selectionFontColor: "black", + selectionBackgroundColor: "yellow" + }, + + /** + * Array containing the supported event names + * @name Biojs.HelloWorld-eventTypes + */ + eventTypes : [ + /** + * @name Biojs.HelloWorld#onClick + * @event + * @param {function} actionPerformed A function which receives an {@link Biojs.Event} object as argument. + * @eventData {Object} source The component which did triggered the event. + * @eventData {string} type The name of the event. + * @eventData {int} selected Selected character. + * @example + * instance.onClick( + * function( objEvent ) { + * alert("The character " + objEvent.selected + " was clicked."); + * } + * ); + * + * */ + "onClick", + + /** + * @name Biojs.HelloWorld#onHelloSelected + * @event + * @param {function} actionPerformed A function which receives an {@link Biojs.Event} object as argument. + * @eventData {Object} source The component which did triggered the event. + * @eventData {string} type The name of the event. + * @eventData {int} textSelected Selected text, will be 'Hello' obviously. + * @example + * instance.onHelloSelected( + * function( objEvent ) { + * alert("The word " + objEvent.textSelected + " was selected."); + * } + * ); + * + * */ + "onHelloSelected" + ], + + /** + * Change the font size. Do nothing it no value is provided. + * + * @param {string} [size] The new font size in pixels. + * + * @example + * instance.setSize("72px"); + */ + setSize: function(size) { + if ( size != undefined ){ + jQuery("#"+this.opt.target).css('font-size', size); + } + }, + + _addSelectionTrigger: function() { + + var self = this; + var isMouseDown = false; + + // Create the CSS class called selected to change both background and color + + jQuery('' + ).appendTo('head'); + + // + // Add the click event to each character in the content + // But remember, we must to figure out when 'Hello' is selected only + this._container.find('span') + .mousedown(function() { + + // Turn on the flag + isMouseDown = true; + + // A new selection is starting + // Reset all by removing the CSS "selected" class if already applied + self._container.children('span').removeClass('selected') + + // Apply the class for this span/character + // NOTE: "this" refers to the internal object 'span' + // NOT to the component's instance + jQuery(this).addClass('selected'); + + }).mouseover(function() { + // Check if the mouse is being dragged + if (isMouseDown) { + jQuery(this).addClass('selected'); + } + }) + .mouseup(function() { + + /// Turn off the flag + isMouseDown = false; + + var textSelected = ''; + + // Get the entire selected word + self._container.children('span.selected') + .each(function(){ + textSelected += jQuery(this).text(); + }); + + // Since requirements, only "Hello" word should be selected + // to raise the event + if (textSelected == 'Hello') { + self.raiseEvent('onHelloSelected', { + textSelected : textSelected + }) + } + }); + }, + + _addSimpleClickTrigger: function () { + + var self = this; + + // Add the click event to each character in the content + this._container.find('span') + .click( function(e) { + // A letter was clicked! + // Let's discover which one was it + // TIP: e.target contains the clicked DOM node + var selected = jQuery(e.target).text(); + + // Create an event object + var evtObject = { "selected": selected }; + + // We're ready to raise the event onClick of our component + self.raiseEvent('onClick', evtObject); + }); + } + +}); + + + + + + + diff --git a/pool/shard011/JavaScript/0070853_GeneratorsDataTable.js b/pool/shard011/JavaScript/0070853_GeneratorsDataTable.js new file mode 100644 index 0000000000000000000000000000000000000000..de939ae33f5712e3219a32dd9140e55637129788 --- /dev/null +++ b/pool/shard011/JavaScript/0070853_GeneratorsDataTable.js @@ -0,0 +1,56 @@ + + + + + +// +// A wrapper for the table listing of generators +// + +function GeneratorsDataTable(generators) { + this.generators = generators; + this.selection = d3.select("#generators").select("table"); + this.numberFormatFn = function(d){return (Number(d).toPrecision(4));}; + + if ( generators[0].z === undefined ) { + this.tableHeaderData = ["x", "y", "length"]; + this.generatorsDataFn = function(d) { return [d.x, d.y, Geom2.norm(d)]; }; + } else { + this.tableHeaderData = ["x", "y", "z", "length"]; + this.generatorsDataFn = function(d) { return [d.x, d.y, d.z, Geom3.norm(d)]; }; + } + +} + +GeneratorsDataTable.prototype.init = function() { + this.selection + .append("tr") + .attr("class", "header") + .selectAll("th") + .data(this.tableHeaderData) + .enter() + .append("th") + .text(function(d) {return d;}); + + this.selection + .selectAll("tr.data") + .data(this.generators) + .enter() + .append("tr") + .attr("class", "data") + .attr("id", function(d) {return "generator-tr-"+d.k;}) + .selectAll("td") + .data(this.generatorsDataFn) + .enter() + .append("td") + .text(this.numberFormatFn); +}; + +GeneratorsDataTable.prototype.update = function() { + this.selection + .selectAll("tr.data") + .data(this.generators) + .selectAll("td") + .data(this.generatorsDataFn) + .text(this.numberFormatFn); +}; diff --git a/pool/shard011/JavaScript/0070854_labels-resource.js b/pool/shard011/JavaScript/0070854_labels-resource.js new file mode 100644 index 0000000000000000000000000000000000000000..e12a31012d4a3021ea6615c51906ee56808b7189 --- /dev/null +++ b/pool/shard011/JavaScript/0070854_labels-resource.js @@ -0,0 +1,77 @@ +var Label = require('./label'); +var _ = require('underscore'); +var resourceErrorsFactory = require('perspective-core-rest').error.factory; + +var labelsResource = function(server, labelsService) { + + server.route('get', '/labels', function(req, res, next) { + + var respond = function(labels) { + + var response = _.map(labels, function(label) { + return label.toJSON(); + }); + + res.send(200, response); + next(); + }; + + labelsService.all(). + then(respond). + fail(resourceErrorsFactory); + + }); + + server.route('get', '/labels/:id', function(req, res, next) { + + var respond = function(label) { + res.send(200, label); + next(); + }; + + labelsService.get(req.params.id). + then(respond). + fail(resourceErrorsFactory); + + }); + + server.route('post', '/labels', function(req, res, next) { + + var respond = function(label) { + res.send(201, label); + next(); + }; + + labelsService.insert(new Label(req.body)). + then(respond). + fail(resourceErrorsFactory); + + }); + + server.route('del', '/labels/:id', function(req, res, next) { + + var respond = function() { + res.send(200); + next(); + }; + + labelsService.delete(req.params.id). + then(respond). + fail(resourceErrorsFactory); + }); + + server.route('put', '/labels/:id', function(req, res, next) { + + var respond = function(task) { + res.send(200, task); + next(); + }; + + labelsService.update(new Label(req.body)). + then(respond). + fail(resourceErrorsFactory); + }); + +}; + +module.exports = labelsResource; diff --git a/pool/shard011/JavaScript/0070856_Mentor.js b/pool/shard011/JavaScript/0070856_Mentor.js new file mode 100644 index 0000000000000000000000000000000000000000..07eacf091a4e92a7d5b0c94ed90277fca265d746 --- /dev/null +++ b/pool/shard011/JavaScript/0070856_Mentor.js @@ -0,0 +1,48 @@ +/* global sap */ + +sap.ui.define([ + "sap/ui/test/Opa5", + "test/integration/pages/Common", + "sap/ui/test/matchers/BindingPath", + "sap/ui/test/matchers/PropertyStrictEquals", + "sap/ui/test/actions/Press" + ], + function(Opa5, Common, BindingPath, PropertyStrictEquals, Press) { + "use strict"; + var sViewName = "Mentor"; + + Opa5.createPageObjects({ + onTheMentorPage: { + baseClass: Common, + actions: { + iPressTheBackButton: function() { + return this.waitFor({ + controlType: "sap.m.Button", + viewName: sViewName, + matchers: new PropertyStrictEquals({ name: "type", value: "Back" }), + actions: new Press(), + errorMessage: "Did not find the nav button on Mentor Detail page" + }); + } + }, + assertions: { + iShouldSeeTheFirstMentorSelected: function() { + return this.waitFor({ + id: "ObjectPageLayout", + viewName: sViewName, + matchers: function(oObjectPageLayout) { + // the path to the First mentor is stored in the shared context + var sPath = this.getContext().sFirstMentorPath; + return new BindingPath({ path: sPath }); + }.bind(this), + success: function() { + this.getContext().sFirstMentorPath = undefined; + Opa5.assert.ok(true, "Selected Mentor bound"); + }, + errorMessage: "Selected Mentor not bound" + }); + } + } + } + }); + }); diff --git a/pool/shard011/JavaScript/0070858_card.js b/pool/shard011/JavaScript/0070858_card.js new file mode 100644 index 0000000000000000000000000000000000000000..984703e3f896231a204ddd3ece8bf2f960baa7bf --- /dev/null +++ b/pool/shard011/JavaScript/0070858_card.js @@ -0,0 +1,48 @@ +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports", "@angular/core", "../../config/config", "../ion"], factory); + } +})(function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require("@angular/core"); + var config_1 = require("../../config/config"); + var ion_1 = require("../ion"); + /** + * @hidden + */ + var Card = (function (_super) { + __extends(Card, _super); + function Card(config, elementRef, renderer) { + return _super.call(this, config, elementRef, renderer, 'card') || this; + } + Card.decorators = [ + { type: core_1.Directive, args: [{ + selector: 'ion-card' + },] }, + ]; + /** @nocollapse */ + Card.ctorParameters = function () { return [ + { type: config_1.Config, }, + { type: core_1.ElementRef, }, + { type: core_1.Renderer, }, + ]; }; + return Card; + }(ion_1.Ion)); + exports.Card = Card; +}); +//# sourceMappingURL=card.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070859_exportRoutes.js b/pool/shard011/JavaScript/0070859_exportRoutes.js new file mode 100644 index 0000000000000000000000000000000000000000..71fe1d9b6396b9cde60d99f2b05b575a2478988a --- /dev/null +++ b/pool/shard011/JavaScript/0070859_exportRoutes.js @@ -0,0 +1,95 @@ +import OS from 'os' +import { fork } from 'child_process' +import chalk from 'chalk' + +import { progress, time, timeEnd } from '../utils' +import fetchSiteData from './fetchSiteData' +import fetchRoutes from './fetchRoutes' +import plugins from './plugins' + +const cores = Math.max(OS.cpus().length, 1) + +export default (async function exportRoutes(state) { + state = await fetchSiteData(state) + state = await fetchRoutes(state) + state = await buildHTML(state) + state = await plugins.afterExport(state) + return state +}) + +async function buildHTML(state) { + const { + routes, + config: { paths, maxThreads }, + } = state + + time(chalk.green('[\u2713] HTML Exported')) + + // in case of an absolute path for DIST we must tell node to load the modules + // from our project root + if (!paths.DIST.startsWith(paths.ROOT)) { + process.env.NODE_PATH = paths.NODE_MODULES + require('module').Module._initPaths() + } + + // Single threaded export + if (maxThreads <= 1) { + console.log('Exporting HTML...') + await require('./exportRoutes.sync').default(state) + } else { + // Multi-threaded export + const threads = Math.min(cores, maxThreads) + const htmlProgress = progress(routes.length) + + console.log(`Exporting HTML across ${threads} threads...`) + + const exporters = [] + for (let i = 0; i < threads; i++) { + exporters.push( + fork(require.resolve('./exportRoutes.threaded'), [], { + env: { + ...process.env, + REACT_STATIC_THREAD: 'true', + }, + stdio: 'inherit', + }) + ) + } + + const exporterRoutes = exporters.map(() => []) + + routes.forEach((route, i) => { + exporterRoutes[i % exporterRoutes.length].push(route) + }) + + await Promise.all( + exporters.map((exporter, i) => { + const routes = exporterRoutes[i] + return new Promise((resolve, reject) => { + exporter.send({ + ...state, + routes, + }) + exporter.on('message', ({ type, payload }) => { + if (type === 'error') { + reject(payload) + } + if (type === 'log') { + console.log(...payload) + } + if (type === 'tick') { + htmlProgress.tick() + } + if (type === 'done') { + resolve() + } + }) + }) + }) + ) + } + + timeEnd(chalk.green('[\u2713] HTML Exported')) + + return state +} diff --git a/pool/shard011/JavaScript/0070861_parallelize_test.js b/pool/shard011/JavaScript/0070861_parallelize_test.js new file mode 100644 index 0000000000000000000000000000000000000000..60c30f5d5f1d0abf224e8075525bb3a7649a746c --- /dev/null +++ b/pool/shard011/JavaScript/0070861_parallelize_test.js @@ -0,0 +1,84 @@ +'use strict'; + +require('mocha'); +var expect = require('expect.js'); +var exec = require('child_process').exec; +var fs = require('fs'); + +describe('grunt-parallelize', function() { + describe('grunt parallelize:task:target', function() { + it('supports "Compact Format"', function(done) { + testGruntfile('compactFormat', done); + }); + + it('supports "Files Array Format"', function(done) { + testGruntfile('filesArrayFormat', done); + }); + + it('runs and displays all child tasks if some task has error"', function(done) { + testGruntfile('containsError', done); + }); + }); + + describe('grunt parallelize:task', function() { + this.timeout(5000); + it('runs all targets', function(done) { + testGruntfile('runAllTargets', done); + }); + + it('runs and displays all targets if some target has error"', function(done) { + testGruntfile('someTargetContainsError', done); + }); + }); + + describe('grunt parallelize', function() { + this.timeout(5000); + it('runs all tasks', function(done) { + testGruntfile('runAllTasks', done); + }); + }); + + describe('detect processes', function() { + it('detects from target options', function(done) { + testGruntfile('targetOption', done); + }); + + it('detects from task options', function(done) { + testGruntfile('taskOption', done); + }); + }); + +}); + +function testGruntfile(name, callback) { + var prefix = __dirname + '/cases/' + name; + var gruntfile = prefix + '.Gruntfile.js'; + runGruntfile(gruntfile, function(err, stdout, stderr) { + var expectedFile = prefix + (err ? '.ng.txt' : '.ok.txt'); + var expected; + try { + expected = fs.readFileSync(expectedFile, {encoding: 'utf8'}); + } catch (e) { + // ng is unexpected. + console.log('stdout: ' + stdout); + callback(err || stderr || stdout || true); + return; + } + try { + expect(stdout).to.be(expected); + } catch (e) { + console.log('expected:'); + console.log(expected); + console.log('actual:'); + console.log(stdout); + throw e; + } + callback(); + }); +} + +function runGruntfile(gruntfile, callback) { + var cmd = ['grunt', '--no-color', '--gruntfile', gruntfile].join(' '); + var options = {}; + exec(cmd, options, callback); +} diff --git a/pool/shard011/JavaScript/0070863_component.js b/pool/shard011/JavaScript/0070863_component.js new file mode 100644 index 0000000000000000000000000000000000000000..0e4ef03100a3a82b7e327ba0728faaa36d6a9cbd --- /dev/null +++ b/pool/shard011/JavaScript/0070863_component.js @@ -0,0 +1,180 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// define the namespaces +jmaki.namespace("jmaki.widgets.yahoo.simpledlg"); + +/** + * Yahoo UI Simple Dialog Widget + * @author Ahmad M. Zawawi + * @constructor + * @see http://developer.yahoo.com/yui/container/simpledialog/ + */ +jmaki.widgets.yahoo.simpledlg.Widget = function(wargs) { + + var topic = "/yahoo/simpledlg"; + var dlg; + var uuid = wargs.uuid; + var dlgId = uuid + "_simpledlg"; + YAHOO.log("dlgId = " + dlgId); + + //dialog default event handlers + function onClick(evt) { + var el = YAHOO.util.Event.getTarget(evt); + var v = { label:el.innerHTML }; + jmaki.publish(topic + "/onClick", {id:uuid,value:v}); + this.hide(); + }; + + //Configuration + var cfg = { + width: "300px", + fixedcenter: true, + header: "Header Text", + text: "Body Text", + draggable: true, + close: true, + visible: true, + modal: false, + icon: YAHOO.widget.SimpleDialog.ICON_INFO, + constraintoviewport: true, + buttons: [ + { label:"Yes" }, + { label:'No', isDefault:true } + ] + }; + + + //read the widget configuration arguments + if (typeof wargs.args != 'undefined') { + + //overide topic name if needed + if (typeof wargs.args.topic != 'undefined') { + topic = wargs.args.topic; + jmaki.log("Yahoo simpledlg: widget uses deprecated topic. Use publish instead."); + } + if (typeof wargs.args.width != 'undefined') { + cfg.width = wargs.args.width; + } + if (typeof wargs.args.fixedcenter != 'undefined') { + cfg.fixedcenter = wargs.args.fixedcenter; + } + if (typeof wargs.args.header != 'undefined') { + cfg.header = wargs.args.header; + } + if (typeof wargs.args.text != 'undefined') { + cfg.text = wargs.args.text; + } + if (typeof wargs.args.draggable != 'undefined') { + cfg.draggable = wargs.args.draggable; + } + if (typeof wargs.args.close != 'undefined') { + cfg.close = wargs.args.close; + } + if (typeof wargs.args.visible != 'undefined') { + cfg.visible = wargs.args.visible; + } + if (typeof wargs.args.modal != 'undefined') { + cfg.modal = wargs.args.modal; + } + if (typeof wargs.args.constraintoviewport != 'undefined') { + cfg.constraintoviewport = wargs.args.constraintoviewport; + } + if (typeof wargs.args.icon != 'undefined') { + var icTypes = { + 'ALARM':YAHOO.widget.SimpleDialog.ICON_ALARM, + 'BLOCK':YAHOO.widget.SimpleDialog.ICON_BLOCK, + 'HELP':YAHOO.widget.SimpleDialog.ICON_HELP, + 'INFO':YAHOO.widget.SimpleDialog.ICON_INFO, + 'TIP':YAHOO.widget.SimpleDialog.ICON_TIP, + 'WARN':YAHOO.widget.SimpleDialog.ICON_WARN + }; + var t = icTypes[wargs.args.icon]; + cfg.icon = (typeof t != 'undefined') ? t : YAHOO.widget.SimpleDialog.ICON_INFO; + } + if (wargs.publish) topic = wargs.publish; + + } + if (typeof wargs.value != 'undefined') { + var v = wargs.value; + if(typeof v.buttons != 'undefined') { + cfg.buttons = v.buttons; + } + } + + YAHOO.log("width = " + cfg.width); + YAHOO.log("fixedcenter = " + cfg.fixedcenter); + YAHOO.log("header = " + cfg.header); + YAHOO.log("text = " + cfg.text); + YAHOO.log("draggable = " + cfg.draggable); + YAHOO.log("close = " + cfg.close); + YAHOO.log("visible = " + cfg.visible); + YAHOO.log("icon = " + cfg.icon); + YAHOO.log("modal = " + cfg.modal); + + /** + * Create Yahoo Buttons + */ + function createYButtons(buttons) { + var ybs = []; + for(var i = 0; i < buttons.length; i++) { + var btn = buttons[i]; + if(typeof btn != 'undefined') { + var yb = {}; + if(typeof btn.label != 'undefined' ) { + yb.text = btn.label; + } + if(typeof btn.isDefault != 'undefined') { + yb.isDefault = btn.isDefault; + } + yb.handler = onClick; + ybs.push(yb); + } else { + YAHOO.log('Found an empty button defintion',"warn"); + } + } + return ybs; + } + + /** + * initialize the simple dialog + */ + this.init = function() { + //override our simple button data format + //with new yahoo data button format + cfg.buttons = createYButtons(cfg.buttons); + + // Create the Simple Dialog + dlg = new YAHOO.widget.SimpleDialog("dlg" + uuid, cfg); + dlg.setHeader(cfg.header); + dlg.render(document.body); + } + + /** + * shows or hides the dialog depending on the visible flag + */ + this.setVisible = function(visible) { + if(visible) { + dlg.show(); + } else { + dlg.hide(); + } + } + + this.init(); + +} diff --git a/pool/shard011/JavaScript/0070865_purge.js b/pool/shard011/JavaScript/0070865_purge.js new file mode 100644 index 0000000000000000000000000000000000000000..1e541aa28ffde6c31f2d410c79e4c1c1ffbbca75 --- /dev/null +++ b/pool/shard011/JavaScript/0070865_purge.js @@ -0,0 +1,70 @@ +'use strict'; + +require('dotenv').config({silent: true}); + +const argv = require('minimist')(process.argv.slice(2)); + +const DRY_RUN = argv.dryRun; +const PRODUCTION = argv.env === 'prod'; + +const FASTLY_API_KEY = process.env.FASTLY_API_KEY; + +if (!FASTLY_API_KEY) { + console.error('In order to purge assets from Fastly, you need to have set the environment variable "FASTLY_API_KEY". This can be done by creating a file named ".env" in the root of this repository with the contents "FASTLY_API_KEY=XXXXXX", where XXXXXX is your Fastly API key.'); + process.exit(1); +} + +const flatten = require('lodash').flattenDeep; +const qaHostNames = [ + 'http://qa.polyfill.io' +]; +const productionHostNames = [ + 'https://polyfill.io', + 'https://polyfill.webservices.ft.com', + 'https://cdn.polyfill.io' +]; +const hostnames = PRODUCTION ? productionHostNames : qaHostNames; +const paths = [ + '/v2/', + '/v2/assets/css/style.css', + '/v2/assets/images/fastly-logo.png', + '/v2/assets/images/logo.svg', + '/v2/assets/js/ui.js', + '/v2/docs/', + '/v2/docs/api', + '/v2/docs/contributing', + '/v2/docs/contributing/authoring-polyfills', + '/v2/docs/contributing/common-scenarios', + '/v2/docs/contributing/docs/assets/compat.json', + '/v2/docs/contributing/testing', + '/v2/docs/examples', + '/v2/docs/features/', + '/v2/docs/usage' +]; +const endpoints = flatten(paths.map(path => hostnames.map(host => host + path))); + +if (!DRY_RUN) { + console.log(); + const fetch = require('node-fetch'); + Promise.all(endpoints.map(endpoint => { + return fetch(endpoint, { + method: 'PURGE', + headers: {"Fastly-Key": process.env.FASTLY_API_KEY}, + mode: 'no-cors', + cache: 'default' + }) + .then(function(res) { + if (res.ok) { + console.log(`Purged ${endpoint}`); + } else if (res.status === 401){ + throw Error('It seems you may not be authorised to purge the resources. Have you set the environment variable "FASTLY_API_KEY"?'); + } + }); + })) + .then(() => console.log('\nPurged all endpoints successfully.')) + .catch((e) => console.error(`Failed to purge endpoints. ${e}`)); +} else { + console.log('\nThis is a dry run. No assets were purged from the cache.\n'); + console.log('If this were not a dry run, these are the assets which would have been purged from the cache:\n'); + endpoints.forEach(endpoint => console.log(endpoint)); +} diff --git a/pool/shard011/JavaScript/0070868_action.js b/pool/shard011/JavaScript/0070868_action.js new file mode 100644 index 0000000000000000000000000000000000000000..638daebb14fdc0fd60ae1860e8d213d1d85eed2e --- /dev/null +++ b/pool/shard011/JavaScript/0070868_action.js @@ -0,0 +1,242 @@ +/* + This file is part of Cuidando Bem. + + Cuidando Bem is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Cuidando Bem is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Cuidando Bem. If not, see . + */ +define([], function() { + + var counter = -1; + + /** + * A class that defines actions and its behaviour + * @class + * @name Action + * @param {string} _id + * @param {string} _name + * @return ObjectExpression + * + * @author Otho - Marcelo Lopes Lotufo + */ + "use strict"; + function Action( _id, _name ) { + counter++; + // Attributes + + if ( _id == null ) { + _id = "action_" + counter; + } + + if ( _name == null ) { + _name = ""; + } + + var id = _id; + /** + * @type {string} + * @private + * + * @memberOf Action# + */ + var name = _name; + /** + * @type {string} + * @private + * + * @memberOf Action# + */ + var cssClass = "noTexture"; + /** + * @type {boolean} + * @private + * + * @memberOf Action# + */ + var visible = true; + /** + * @type {function} + * @private + * + * @memberOf Action# + */ + var onClickFunction = function() { + }; + /** + * @type {boolean} + * @private + * + * @memberOf Action# + */ + var enable = true; + + // Methods + + /** + * It runs this class actionFunction + * @method + * @method execute + * @public + * + * @memberOf Action# + */ + function execute() { + onClickFunction(); + } + + // Getters + + /** + * @method + * @method getFunction + * @return actionFunction + * @public + * + * @memberOf Action# + */ + + function getFunction() { + return onClickFunction; + } + + function getClone() { + return new Action( id, name ) + .setCssClass( cssClass ) + .setVisibility( visible ) + .onClick( onClickFunction ) + .setEnable( enable ); + } + + function getId() { + return id; + } + + /** + * @method + * @method getName + * @return name + * @public + * + * @memberOf Action# + */ + function getName() { + return name; + } + + /** + * @method + * @method getCssClass + * @return cssClass + * @public + * + * @memberOf Action# + */ + function getCssClass() { + return cssClass; + } + + /** + * @method + * @method isEnabled + * @return enable + * @public + * + * @memberOf Action# + */ + function isEnabled() { + return enable; + } + + /** + * @method + * @method isVisible + * @return visible + * @public + * + * @memberOf Action# + */ + function isVisible() { + return visible; + } + + // Setters + /** + * @method + * @method setEnable + * @param {boolean} _enable + * @public + * + * @memberOf Action# + */ + function setEnable( _enable ) { + enable = _enable; + return this; + } + + /** + * @method + * @method setVisibility + * @param {boolean} _visible + * @public + * + * @memberOf Action# + */ + function setVisibility( _visible ) { + visible = _visible; + return this; + } + + function setCssClass( _cssClass ) { + cssClass = _cssClass; + return this; + } + + function setId( _id ) { + id = _id; + return this; + } + + function setName( _name ) { + name = _name; + return this; + } + + function onClick( _function ) { + onClickFunction = _function; + return this; + } + + // Public interface + + return { + execute: execute, + + getClone: getClone, + getFunction: getFunction, + getId: getId, + getName: getName, + getCssClass: getCssClass, + isEnabled: isEnabled, + isVisible: isVisible, + + setId: setId, + setName: setName, + setCssClass: setCssClass, + setEnable: setEnable, + setVisibility: setVisibility, + onClick: onClick + }; + } + + + return Action; +}); diff --git a/pool/shard011/JavaScript/0070870_index.js b/pool/shard011/JavaScript/0070870_index.js new file mode 100644 index 0000000000000000000000000000000000000000..9a7e66f6174b88acd9410e137a97902b34c95def --- /dev/null +++ b/pool/shard011/JavaScript/0070870_index.js @@ -0,0 +1,202 @@ +'use strict'; + +var fs = require('fs'); +var path = require('path'); +var log = require('gulplog'); +var yargs = require('yargs'); +var Liftoff = require('liftoff'); +var interpret = require('interpret'); +var v8flags = require('v8flags'); +var findRange = require('semver-greatest-satisfied-range'); +var ansi = require('./lib/shared/ansi'); +var exit = require('./lib/shared/exit'); +var tildify = require('./lib/shared/tildify'); +var makeTitle = require('./lib/shared/make-title'); +var cliOptions = require('./lib/shared/cli-options'); +var completion = require('./lib/shared/completion'); +var verifyDeps = require('./lib/shared/verify-dependencies'); +var cliVersion = require('./package.json').version; +var getBlacklist = require('./lib/shared/get-blacklist'); +var toConsole = require('./lib/shared/log/to-console'); + +var loadConfigFiles = require('./lib/shared/config/load-files'); +var mergeConfigToCliFlags = require('./lib/shared/config/cli-flags'); +var mergeConfigToEnvFlags = require('./lib/shared/config/env-flags'); + +// Logging functions +var logVerify = require('./lib/shared/log/verify'); +var logBlacklistError = require('./lib/shared/log/blacklist-error'); + +// Get supported ranges +var ranges = fs.readdirSync(__dirname + '/lib/versioned/'); + +// Set env var for ORIGINAL cwd +// before anything touches it +process.env.INIT_CWD = process.cwd(); + +var cli = new Liftoff({ + name: 'gulp', + processTitle: makeTitle('gulp', process.argv.slice(2)), + completions: completion, + extensions: interpret.jsVariants, + v8flags: v8flags, + configFiles: { + '.gulp': { + home: { + path: '~', + extensions: interpret.extensions, + }, + cwd: { + path: '.', + extensions: interpret.extensions, + }, + }, + }, +}); + +var usage = + '\n' + ansi.bold('Usage:') + + ' gulp ' + ansi.blue('[options]') + ' tasks'; + +var parser = yargs.usage(usage, cliOptions); +var opts = parser.argv; + +cli.on('require', function(name) { + log.info('Requiring external module', ansi.magenta(name)); +}); + +cli.on('requireFail', function(name, error) { + log.warn( + ansi.yellow('Failed to load external module'), + ansi.magenta(name) + ); + /* istanbul ignore else */ + if (error) { + log.warn(ansi.yellow(error.toString())); + } +}); + +cli.on('respawn', function(flags, child) { + var nodeFlags = ansi.magenta(flags.join(', ')); + var pid = ansi.magenta(child.pid); + log.info('Node flags detected:', nodeFlags); + log.info('Respawned to PID:', pid); +}); + +function run() { + cli.prepare({ + cwd: opts.cwd, + configPath: opts.gulpfile, + require: opts.require, + completion: opts.completion, + }, function(env) { + var cfgLoadOrder = ['home', 'cwd']; + var cfg = loadConfigFiles(env.configFiles['.gulp'], cfgLoadOrder); + opts = mergeConfigToCliFlags(opts, cfg); + env = mergeConfigToEnvFlags(env, cfg, opts); + env.configProps = cfg; + + // Set up event listeners for logging again after configuring. + toConsole(log, opts); + + cli.execute(env, env.nodeFlags, handleArguments); + }); +} + +module.exports = run; + +// The actual logic +function handleArguments(env) { + + // This translates the --continue flag in gulp + // To the settle env variable for undertaker + // We use the process.env so the user's gulpfile + // Can know about the flag + if (opts.continue) { + process.env.UNDERTAKER_SETTLE = 'true'; + } + + if (opts.help) { + parser.showHelp(console.log); + exit(0); + } + + // Anything that needs to print outside of the logging mechanism should use console.log + if (opts.version) { + console.log('CLI version:', cliVersion); + console.log('Local version:', env.modulePackage.version || 'Unknown'); + exit(0); + } + + if (opts.verify) { + var pkgPath = opts.verify !== true ? opts.verify : 'package.json'; + /* istanbul ignore else */ + if (path.resolve(pkgPath) !== path.normalize(pkgPath)) { + pkgPath = path.join(env.cwd, pkgPath); + } + log.info('Verifying plugins in ' + pkgPath); + return getBlacklist(function(err, blacklist) { + /* istanbul ignore if */ + if (err) { + return logBlacklistError(err); + } + + var blacklisted = verifyDeps(require(pkgPath), blacklist); + + logVerify(blacklisted); + }); + } + + if (!env.modulePath) { + /* istanbul ignore next */ + var missingNodeModules = + fs.existsSync(path.join(env.cwd, 'package.json')) + && !fs.existsSync(path.join(env.cwd, 'node_modules')); + + /* istanbul ignore next */ + var missingGulpMessage = + missingNodeModules + ? 'Local modules not found in' + : 'Local gulp not found in'; + log.error( + ansi.red(missingGulpMessage), + ansi.magenta(tildify(env.cwd)) + ); + /* istanbul ignore next */ + var installCommand = + missingNodeModules + ? 'npm install' + : 'npm install gulp'; + log.error(ansi.red('Try running: ' + installCommand)); + exit(1); + } + + if (!env.configPath) { + log.error(ansi.red('No gulpfile found')); + exit(1); + } + + // Chdir before requiring gulpfile to make sure + // we let them chdir as needed + if (process.cwd() !== env.cwd) { + process.chdir(env.cwd); + log.info( + 'Working directory changed to', + ansi.magenta(tildify(env.cwd)) + ); + } + + // Find the correct CLI version to run + var range = findRange(env.modulePackage.version, ranges); + + if (!range) { + log.error( + ansi.red('Unsupported gulp version', env.modulePackage.version) + ); + exit(1); + } + + // Load and execute the CLI version + var versionedDir = path.join(__dirname, '/lib/versioned/', range, '/'); + require(versionedDir)(opts, env, env.configProps); +} diff --git a/pool/shard011/JavaScript/0070872_editor_plugin_src.js b/pool/shard011/JavaScript/0070872_editor_plugin_src.js new file mode 100644 index 0000000000000000000000000000000000000000..8bf76fa389ed2a118b6a4cac08de5d5080c7a6c7 --- /dev/null +++ b/pool/shard011/JavaScript/0070872_editor_plugin_src.js @@ -0,0 +1,38 @@ +(function(tinymce, $) { + tinymce.create('tinymce.plugins.epifloatingtoolbar', { + /** + * Initializes of epifloatingtool plugin. + * + * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. + * @param {string} url Absolute URL to where the plugin is located. + */ + init: function (ed, url) { + ed.isFullscreen = false; + ed.onInit.add(function (ed, cm) { + if (!ed.isFullscreen) { + var d = tinymce.DOM, toolbar = d.get(ed.id + '_external').parentNode; + d.addClass(toolbar, "mceEditor epi-lightSkin epi-lightSkinOpe"); + d.setAttrib(toolbar, "style", ""); + d.add('epi-opeToolbar', toolbar); + } + }); + }, + + /** + * Returns information about the plugin as a name/value array. + * + * @return {Object} Name/value array containing information about the plugin. + */ + getInfo: function () { + return { + longname: 'Floating Toolbar plugin', + author: 'EPiServer AB', + authorurl: 'http://www.episerver.com', + infourl: 'http://www.episerver.com', + version: 1.0 + }; + } + }); + // Register plugin + tinymce.PluginManager.add('epifloatingtoolbar', tinymce.plugins.epifloatingtoolbar); +} (tinymce, epiJQuery)); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070882_calendar.view.js b/pool/shard011/JavaScript/0070882_calendar.view.js new file mode 100644 index 0000000000000000000000000000000000000000..f5502a4918f995b10e5a8ff3006966b7b9f3fb95 --- /dev/null +++ b/pool/shard011/JavaScript/0070882_calendar.view.js @@ -0,0 +1,226 @@ +require(['js/meta.js', 'aps/load'], function(meta, load) { + function suwizardOverview() { + var calendar = aps.context.params.objects[0]; + layout[2][0][2][0][1].value = calendar.name; + layout[2][0][2][1][1].value = calendar.description; + layout[2][0][2][2][1].value = meta.timezoneInfo(calendar.timezone, dt); + load(layout); + } + + function suserviceView(Store, eventBlock) { + (new Store({ + target: '/aps/2/resources', + apsType: 'http://aps.google.com/gcalendar/calendar/1.0' + })).query().then(meta.getFull).then(function(calendars) { + var calendar; + calendars.some(function(v) { + if (v.owner.aps.id === aps.context.params.user.aps.id) { + calendar = v; + return true; + } + }); + layout[2][0][2][0][1].value = calendar.name; + layout[2][0][2][1][1].value = calendar.description; + layout[2][0][2][2][1].value = meta.timezoneInfo(calendar.timezone, dt); + layout[2].push(eventBlock({ + calendarId: calendar.aps.id, + hideControls: true + })); + load(layout); + }); + } + + function calendarView(Store, eventBlock) { + var calendar; + meta.getFull(aps.context.vars.target).then(function(resource) { + calendar = resource; + return meta.getFull(resource.owner); + }).then(function(owner) { + layout[2].unshift(['aps/FieldSet', { + id: 'fs-owner', + title: 'Calendar owner' + }, + [ + ['aps/Output', { + id: 'ou-owner', + label: 'Service user', + value: meta.userInfo(owner) + }] + ] + ]); + layout[2].push(eventBlock({ + calendarId: calendar.aps.id, + hideControls: true + })); + layout[2][1][2][0][1].value = calendar.name; + layout[2][1][2][1][1].value = calendar.description; + layout[2][1][2][2][1].value = meta.timezoneInfo(calendar.timezone, dt); + load(layout).then(function() { + var data = meta.wizard(); + if (data) + meta.showMsg.apply(this, data); + aps.app.onSubmit = function() { + if (confirm('Are you sure that you want to delete this calendar and all its events?')) { + (new Store({ + target: '/aps/2/resources' + })).remove(calendar.aps.id).then(function() { + meta.wizard(['Calendar \'' + calendar.name + '\' was successfully deleted!', 'info', true]); + aps.apsc.gotoView('calendars'); + }, meta.showMsg); + } else { + aps.apsc.cancelProcessing(); + } + }; + aps.app.onPrev = function() { + aps.apsc.gotoView('calendars'); + }; + aps.app.onNext = function() { + aps.apsc.gotoView('calendar.edit', calendar.aps.id); + }; + }); + }); + } + + + function calendarNew(newCalendarWizard, Store) { + var data = meta.wizard(); + if (!data) { + aps.apsc.gotoView('calendar.new0'); + return; + } + var model = data.model, + steps = JSON.parse(newCalendarWizard); + steps[1].active = true; + layout[2].unshift(['aps/WizardControl', { + id: 'wc-wizard', + steps: steps + }], ['aps/FieldSet', { + id: 'fs-owner', + title: 'Calendar owner' + }, + [ + ['aps/Output', { + id: 'ou-owner', + label: 'Service user', + value: data.user + }] + ] + ]); + layout[2][2][2][0][1].value = model.name; + layout[2][2][2][1][1].value = model.description; + layout[2][2][2][2][1].value = meta.timezoneInfo(model.timezone, dt); + load(layout).then(function() { + aps.app.onPrev = function() { + meta.wizard(data); + aps.apsc.gotoView('calendar.new0'); + }; + aps.app.onSubmit = function() { + (new Store({ + target: '/aps/2/resources/' + aps.context.vars.context.aps.id + '/calendars' + })).put(model).then(function() { + aps.apsc.gotoView('calendars'); + }, meta.showMsg); + }; + aps.app.onCancel = function() { + meta.wizard(); + aps.apsc.gotoView('calendars'); + }; + }); + } + + function myCPView(registry, eventBlock, xhr) { + var calendar = aps.context.vars.calendar, + data = meta.wizard(); + layout[2][0][2][0][1].value = calendar.name; + layout[2][0][2][1][1].value = calendar.description; + layout[2][0][2][2][1].value = meta.timezoneInfo(calendar.timezone, dt); + layout[2].push(eventBlock({ + dateTime: dt, + storeTarget: '/aps/2/resources/' + calendar.aps.id + '/listEvents', + hideFilters: true, + overrideMasterDetail: true + })); + load(layout).then(function() { + if (data) + meta.showMsg.apply(this, data); + registry.byId('btn-schedule').on('click', function() { + aps.apsc.gotoView('event.new0'); + }); + registry.byId('btn-cancel').on('click', function() { + if (!confirm('Are you sure that you want to cancel all selected events (notifications will be sent to attendees)?')) { + this.cancel(); + return; + } + aps.apsc.showLoading(); + var button = this, + grid = registry.byId('gr-events'), + selectionArray = grid.get('selectionArray'), + count = selectionArray.length; + selectionArray.forEach(function(v) { + xhr.post('/aps/2/resources/' + calendar.aps.id + '/cancelEvent', { + data: v + }).then(function() { + selectionArray.splice(selectionArray.indexOf(v), 1); + grid.refresh(); + }, meta.showMsg).always(function() { + if (--count === 0) { + aps.apsc.hideLoading(); + button.cancel(); + } + }); + }); + }); + }); + } + + if (!meta.check({ + 'suwizard.overview': [ + [], + suwizardOverview + ], + 'suservice.view': [ + ['aps/ResourceStore', 'js/eventBlock.js'], + suserviceView + ], + 'calendar.view': [ + ['aps/ResourceStore', 'js/eventBlock.js'], + calendarView + ], + 'calendar.new1': [ + ['dojo/text!./js/newCalendarWizard.json', 'aps/ResourceStore'], + calendarNew + ], + 'mycp.view': [ + ['dijit/registry', 'js/eventBlock.js', 'aps/xhr'], + myCPView + ] + })) + return; + var dt = meta.dt, + layout = ['aps/PageContainer', { + id: 'page-container' + }, + [ + ['aps/FieldSet', { + id: 'fs-params', + title: 'Calendar parameters' + }, + [ + ['aps/Output', { + id: 'ou-name', + label: 'Name' + }], + ['aps/Output', { + id: 'ou-description', + label: 'Description' + }], + ['aps/Output', { + id: 'ou-timezone', + label: 'Timezone' + }] + ] + ] + ] + ]; + return meta.run(); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070884_context.js b/pool/shard011/JavaScript/0070884_context.js new file mode 100644 index 0000000000000000000000000000000000000000..e69fc66810e6de7cf9309c7987daf3033715a75f --- /dev/null +++ b/pool/shard011/JavaScript/0070884_context.js @@ -0,0 +1,29 @@ +/* + * This file is part of the nivo project. + * + * Copyright 2016-present, Raphaël Benitte. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +import { createContext, useContext } from 'react' +import PropTypes from 'prop-types' +import { usePartialTheme } from '../hooks' + +export const themeContext = createContext() + +// required to preserve equality +const defaultPartialTheme = {} + +export const ThemeProvider = ({ theme: partialTheme = defaultPartialTheme, children }) => { + const theme = usePartialTheme(partialTheme) + + return {children} +} + +ThemeProvider.propTypes = { + children: PropTypes.node.isRequired, + theme: PropTypes.object, +} + +export const useTheme = () => useContext(themeContext) diff --git a/pool/shard011/JavaScript/0070885_jquery.calendars-is.js b/pool/shard011/JavaScript/0070885_jquery.calendars-is.js new file mode 100644 index 0000000000000000000000000000000000000000..8b1f1d798a65c361e3fcb1c9a57d57375fdb15e6 --- /dev/null +++ b/pool/shard011/JavaScript/0070885_jquery.calendars-is.js @@ -0,0 +1,23 @@ +/* http://keith-wood.name/calendars.html + Icelandic localisation for Gregorian/Julian calendars for jQuery. + Written by Haukur H. Thorsson (haukur@eskill.is). */ +(function($) { + $.calendars.calendars.gregorian.prototype.regional['is'] = { + name: 'Gregorian', + epochs: ['BCE', 'CE'], + monthNames: ['Janúar','Febrúar','Mars','Apríl','Maí','Júní', + 'Júlí','Ágúst','September','Október','Nóvember','Desember'], + monthNamesShort: ['Jan','Feb','Mar','Apr','Maí','Jún', + 'Júl','Ágú','Sep','Okt','Nóv','Des'], + dayNames: ['Sunnudagur','Mánudagur','Þriðjudagur','Miðvikudagur','Fimmtudagur','Föstudagur','Laugardagur'], + dayNamesShort: ['Sun','Mán','Þri','Mið','Fim','Fös','Lau'], + dayNamesMin: ['Su','Má','Þr','Mi','Fi','Fö','La'], + dateFormat: 'dd/mm/yyyy', + firstDay: 0, + isRTL: false + }; + if ($.calendars.calendars.julian) { + $.calendars.calendars.julian.prototype.regional['is'] = + $.calendars.calendars.gregorian.prototype.regional['is']; + } +})(jQuery); diff --git a/pool/shard011/JavaScript/0070889_Dictionary.js b/pool/shard011/JavaScript/0070889_Dictionary.js new file mode 100644 index 0000000000000000000000000000000000000000..9a98c5079b60f4a520620c3066c4877ab6cc74c4 --- /dev/null +++ b/pool/shard011/JavaScript/0070889_Dictionary.js @@ -0,0 +1,75 @@ +Ext.define('Ext.tualo.ide.language.Dictionary', { + extend: 'Ext.util.Observable', + constructor: function (config) { + this.loadLanguage = config.language; + if (typeof this.loadLanguage!=='undefined'){ + this.loadLanguage = this.loadLanguage.replace(/[^a-z]/,''); // only letters are allowed, protect from loading different fiels + } + this.dict = {}; + this.callParent([ config ]); + Ext.Ajax.request({ + url: '/ide/language/en.json', + scope: this, + success: function(response){ + try{ + + this.dict = Ext.JSON.decode(response.responseText); + + }catch(error){ + console.log(error); + } + this.load(); + }, + failure: function(){ + this.load(); + } + }); + }, + load: function(){ + if (typeof this.loadLanguage!=='undefined'){ + Ext.Ajax.request({ + url: '/ide/language/'+this.loadLanguage+'.json', + scope: this, + success: function(response){ + try{ + this.dict = Ext.Object.merge(this.dict, Ext.JSON.decode(response.responseText)); + }catch(error){ + } + this.loaded(); + }, + failure: function(){ + this.loaded(); + } + }); + }else{ + this.loaded(); + } + }, + loaded: function(){ + Ext.Loader.loadScript({ + scope: this, + url: window.location.origin + '/extjs/locale/ext-lang-' +this.loadLanguage+'.js', + onLoad: function(){ + this.fireEvent('loaded',this); + }, + onError: function(){ + this.fireEvent('loaded',this); + } + }); + }, + get: function(){ + if (arguments.length==0){ + return this.dict; + }else{ + if (typeof this.dict[arguments[0]]!=='undefined'){ + var str = this.dict[arguments[0]]; + for(var i=1;i +
    + + } + /> +
    + + ); + } + +}); + +module.exports = AppHandler; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070893_TabList.test.js b/pool/shard011/JavaScript/0070893_TabList.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b1d365cf692be0d657159f863e32bd42dcb6f86c --- /dev/null +++ b/pool/shard011/JavaScript/0070893_TabList.test.js @@ -0,0 +1,28 @@ +import React from 'react'; +import { shallow, mount } from 'enzyme'; + +import TabList from '../TabList'; + +const mockSelection = () => ({ + isVertical: jest.fn(), +}); + +test(' should exist', () => { + const tabList = shallow(( + + Foo + + )); + + expect(tabList).toBeDefined(); +}); + +test(' should render children', () => { + const tabList = mount(( + + Foo + + )); + + expect(tabList.find('#content')).toBeTruthy(); +}); diff --git a/pool/shard011/JavaScript/0070896_fullscreen.js b/pool/shard011/JavaScript/0070896_fullscreen.js new file mode 100644 index 0000000000000000000000000000000000000000..db0c24bdedf1d201911ef4ca522b0299008dde79 --- /dev/null +++ b/pool/shard011/JavaScript/0070896_fullscreen.js @@ -0,0 +1,155 @@ +(function($R) +{ + $R.add('plugin', 'fullscreen', { + translations: { + en: { + "fullscreen": "Fullscreen" + } + }, + init: function(app) + { + this.app = app; + this.opts = app.opts; + this.lang = app.lang; + this.$win = app.$win; + this.$doc = app.$doc; + this.$body = app.$body; + this.editor = app.editor; + this.toolbar = app.toolbar; + this.container = app.container; + this.selection = app.selection; + + // local + this.isOpen = false; + this.docScroll = 0; + }, + // public + start: function() + { + var data = { + title: this.lang.get('fullscreen'), + api: 'plugin.fullscreen.toggle' + }; + + var button = this.toolbar.addButton('fullscreen', data); + button.setIcon(''); + + this.$target = (this.toolbar.isTarget()) ? this.toolbar.getTargetElement() : this.$body; + + if (this.opts.fullscreen) this.toggle(); + + }, + toggle: function() + { + return (this.isOpen) ? this.close() : this.open(); + }, + open: function() + { + this.docScroll = this.$doc.scrollTop(); + + this._createPlacemarker(); + this.selection.save(); + + var $container = this.container.getElement(); + var $editor = this.editor.getElement(); + var $html = (this.toolbar.isTarget()) ? $R.dom('body, html') : this.$target; + + if (this.opts.toolbarExternal) this._buildInternalToolbar(); + + this.$target.prepend($container); + this.$target.addClass('redactor-body-fullscreen'); + + $container.addClass('redactor-box-fullscreen'); + if (this.isTarget) $container.addClass('redactor-box-fullscreen-target'); + + $html.css('overflow', 'hidden'); + + if (this.opts.maxHeight) $editor.css('max-height', ''); + if (this.opts.minHeight) $editor.css('min-height', ''); + + this._resize(); + this.$win.on('resize.redactor-plugin-fullscreen', this._resize.bind(this)); + this.$doc.scrollTop(0); + + var button = this.toolbar.getButton('fullscreen'); + button.setIcon(''); + + this.selection.restore(); + this.isOpen = true; + this.opts.zindex = 1051; + }, + close: function() + { + this.isOpen = false; + this.opts.zindex = false; + this.selection.save(); + + var $container = this.container.getElement(); + var $editor = this.editor.getElement(); + var $html = $R.dom('body, html'); + + if (this.opts.toolbarExternal) this._buildExternalToolbar(); + + this.$target.removeClass('redactor-body-fullscreen'); + this.$win.off('resize.redactor-plugin-fullscreen'); + $html.css('overflow', ''); + + $container.removeClass('redactor-box-fullscreen redactor-box-fullscreen-target'); + $editor.css('height', 'auto'); + + if (this.opts.minHeight) $editor.css('minHeight', this.opts.minHeight); + if (this.opts.maxHeight) $editor.css('maxHeight', this.opts.maxHeight); + + var button = this.toolbar.getButton('fullscreen'); + button.setIcon(''); + + this._removePlacemarker($container); + this.selection.restore(); + this.$doc.scrollTop(this.docScroll); + }, + + // private + _resize: function() + { + var $editor = this.editor.getElement(); + var height = this.$win.height(); + + $editor.height(height); + }, + _buildInternalToolbar: function() + { + var $wrapper = this.toolbar.getWrapper(); + var $toolbar = this.toolbar.getElement(); + + $wrapper.addClass('redactor-toolbar-wrapper'); + $wrapper.append($toolbar); + + $toolbar.removeClass('redactor-toolbar-external'); + $container.prepend($wrapper); + }, + _buildExternalToolbar: function() + { + var $wrapper = this.toolbar.getWrapper(); + var $toolbar = this.toolbar.getElement(); + + this.$external = $R.dom(this.opts.toolbarExternal); + + $toolbar.addClass('redactor-toolbar-external'); + this.$external.append($toolbar); + + $wrapper.remove(); + }, + _createPlacemarker: function() + { + var $container = this.container.getElement(); + + this.$placemarker = $R.dom(''); + $container.after(this.$placemarker); + }, + _removePlacemarker: function($container) + { + this.$placemarker.before($container); + this.$placemarker.remove(); + } + }); +})(Redactor); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070900_JournalsList.js b/pool/shard011/JavaScript/0070900_JournalsList.js new file mode 100644 index 0000000000000000000000000000000000000000..f36a34368f63fdd48cf74518b87ac6d7d725abb9 --- /dev/null +++ b/pool/shard011/JavaScript/0070900_JournalsList.js @@ -0,0 +1,222 @@ +const util = require('../../helpers/util.helper'); +const async = require('async'); +const db = require('../../helpers/db.helper'); +const crypto = require('../../helpers/crypto.helper'); + +exports.journalsList = function (req, res, next) { + /** + * parameters expected in the args: + * stewardname (String) + * namespace (String) + * account (String) + * currency (string) + * currency_namespace (string) + * authorization (String) + * offset (Integer) + * range (Integer) + **/ + + var examples = {}; + + examples['application/json'] = ""; + + var request = {}; + request.stewardname = req.swagger.params.stewardname.value; + request.namespace = req.swagger.params.namespace.value; + request.account = req.swagger.params.account.value; + request.currency = req.swagger.params.currency.value; + request.currency_namespace = req.swagger.params.currency_namespace.value; + request.offset = req.swagger.params.offset.value; + request.range = req.swagger.params.range.value; + request.publicKey = req.user.publicKey; + + journalsList(request, function (err, result) { + res.setHeader('Content-Type', 'application/json'); + if (err) { + // throw error + examples['application/json'] = err; + res.statusCode = util.setStatus(err); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } else { + res.end(result) + } + }); +}; + +const journalsList = function(request, journalsListCallback) { + //request.stewardname = args.stewardname.value; + //request.namespace = args.namespace.value; + //request.account = args.account.value; + //request.currency = args.currency.value; + //request.currency_namespace = args.currency_namespace.value; + //request.offset = args.offset.value; + //request.range = args.range.value; + //request.publicKey = publicKey; + var currency; + if(typeof request.currency != 'undefined'){ + currency = (typeof request.currency_namespace == 'undefined' || request.currency_namespace == '') ? request.currency.toLowerCase() : request.currency.toLowerCase() + '.' + request.currency_namespace.toLowerCase(); + } + var journalList; + if(typeof request.account != 'undefined' && request.namespace != 'undefined'){ + journalList = "journalsList~" + request.account.toLowerCase() + '.' + request.namespace.toLowerCase() + "~" + currency; + } + + if(typeof journalList == 'undefined'){ + //get this stewards bucket, then get all their account journals. + db.stewards_bucket.get("steward_bucket~" + crypto.getHash(request.publicKey), function(err,steward_bucket) { + if(err) { + accountsListCallback(err, false); + } else { + var parallelTasks = {}; + steward_bucket.value.accounts.forEach(function(accountID){ + var journalList = "journalsList~" + accountID.split('~')[1] + '~' + accountID.split('~')[2]; + parallelTasks[journalList] = function(callback){ + getJournalList(request, journalList, function(err, journals){ + if(err){ + callback(err); + } else { + callback(null, journals); + } + }) + } + }); + steward_bucket.value.currencies.forEach(function(currencyID){ + var journalList = "journalsList~" + currencyID.split('~')[1]; + parallelTasks[journalList] = function(callback){ + db.openmoney_bucket.get(currencyID, function(err, currencyDoc){ + if(err){ + callback(err); + } else { + + //only get the currency journals if your the steward of the currency + var isSteward = false; + currencyDoc.value.stewards.forEach(function(steward){ + if(steward == 'stewards~' + request.stewardname.toLowerCase()){ + isSteward = true; + } + }) + if(isSteward){ + getJournalList(request, journalList, function(err, journals){ + if(err){ + callback(err); + } else { + callback(null, journals); + } + }) + } else { + callback(null, []); + } + } + }); + } + }) + async.parallel(parallelTasks, function(err, results){ + if(err){ + journalsListCallback(err); + } else { + //agrigate results + var allJournals = []; + + for (var k in results){ + if (results.hasOwnProperty(k)) { + var journals = results[k]; + for(i = 0; i < journals.length; i++){ + + //check if each each journal is unique in the result set + var unique = true; + for(var j = 0; j < allJournals.length; j++){ + if(allJournals[j].id == journals[i].id){ + unique = false; + } + } + if(unique){ + allJournals.push(journals[i]); + } + } + } + } + journalsListCallback(null, allJournals); + } + }) + } + }); + } else { + getJournalList(request, journalList, function(err, journals){ + if(err){ + journalsListCallback(err); + } else { + journalsListCallback(null, journals); + } + }) + } + + //var N1qlQuery = couchbase.N1qlQuery; + //db.stewards_bucket.enableN1ql(['http://127.0.0.1:8093/']); + //var queryString = 'SELECT * FROM openmoney_stewards WHERE Meta().id like "' + crypto.getHash(request.publicKey) + 'journals~%";'; + //var query = N1qlQuery.fromString(queryString); + //db.stewards_bucket.query(query, function(err, results) { + // if (err) { + // journalsListCallback(err,false); + // } else { + // var response = []; + // for(i in results) { + // response.push(results[i].openmoney_stewards); + // } + // journalsListCallback(null, response); + // } + //}); +}; + +function getJournalList(request, journalListDocID, callback){ + db.stewards_bucket.get(journalListDocID, function(err,journalList) { + if(err) { + if(err.code == 13){ + //there are no journal entries for this account + callback(null, []); + } else { + callback(err); + } + } else { + var parallelTasks = {}; + var count = 0; + journalList.value.list.forEach(function(journalID){ + count++; + var is_displayed = false; + if(typeof request.offset != 'undefined' && typeof request.range != 'undefined') { + if(count >= request.offset && count < request.offset + request.range) { + is_displayed = true; + } + } else { + is_displayed = true; + } + if(is_displayed) { + parallelTasks[journalID] = function (cb) { + db.stewards_bucket.get(crypto.getHash(request.publicKey) + journalID, function (err, journal) { + if (err) { + cb(null, null); + } else { + cb(null, journal.value); + } + }) + }; + } + }); + async.parallel(parallelTasks, function(err, results){ + if(err) { + callback(err); + } else { + var response = []; + for (var key in results) { + if (results.hasOwnProperty(key)) { + if(results[key] != null){ + response.push(results[key]); + } + + } + } + callback(null, response); + } + }); + } + }); +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070901_dynamik-responsive.js b/pool/shard011/JavaScript/0070901_dynamik-responsive.js new file mode 100644 index 0000000000000000000000000000000000000000..6520301c7ad8e6f31c1c1d3df6eb5fa4433c74dc --- /dev/null +++ b/pool/shard011/JavaScript/0070901_dynamik-responsive.js @@ -0,0 +1,51 @@ +jQuery(document).ready(function($) { + + if( $('.mobile-primary-toggle').length || $('.mobile-secondary-toggle').length ) { + if(dynamik_sf_enabled) { + var sf = $('ul.js-superfish'); + } + + $('.responsive-primary-menu-container').click(function() { + if(dynamik_sf_enabled && dynamik_reveal_sub_pages) { + sf.superfish('destroy'); + } + $('.nav-primary').slideToggle(); + $('#nav').slideToggle(); + }); + + $('.responsive-secondary-menu-container').click(function() { + if(dynamik_sf_enabled && dynamik_reveal_sub_pages) { + sf.superfish('destroy'); + } + $('.nav-secondary').slideToggle(); + $('#subnav').slideToggle(); + }); + + $(window).resize(function() { + if(dynamik_sf_enabled && dynamik_reveal_sub_pages) { + if(window.innerWidth <= media_query_small_width) { + sf.superfish('destroy'); + } else { + sf.superfish('init'); + } + } + if(window.innerWidth > media_query_small_width) { + $('.nav-primary').removeAttr('style'); + $('#nav').removeAttr('style'); + $('.nav-secondary').removeAttr('style'); + $('#subnav').removeAttr('style'); + } + }); + } + + if( $('#dropdown-nav select').length || $('#dropdown-subnav select').length ) { + $('#dropdown-nav select').change(function() { + window.location = $(this).find('option:selected').val(); + }); + + $('#dropdown-subnav select').change(function() { + window.location = $(this).find('option:selected').val(); + }); + } + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070902_output.js b/pool/shard011/JavaScript/0070902_output.js new file mode 100644 index 0000000000000000000000000000000000000000..8c8f66261d07ac97c62fe8384e23aed862d4ad3f --- /dev/null +++ b/pool/shard011/JavaScript/0070902_output.js @@ -0,0 +1,72 @@ +var fs = require('fs'), + util = require('util'), + path = require('path'); + +/** + * A class for writing data to some output + * @name NJSTrace~Output + * @param {boolean|string|function} config If boolean then will output to console + * If string then it will be used as a path to an output file + * If function then this function will be used for output + * @constructor + */ +function Output(config) { + if (typeof config === 'undefined') { + throw new Error('Output config is mandatory'); + } + + this.stdout = null; + this.stdoutFn = null; + + // If config is a boolean then output is process.stdout + if (typeof config === 'boolean') { + this.stdout = config ? process.stdout : null; + this.stdoutFn = config ? process.stdout.write : null; + // If config is string then output is a file + } else if (typeof config === 'string') { + // Get the full path of the output file and make sure the directory it is in exists + var file = path.resolve(process.cwd(), config); + var outputDir = path.dirname(file); + if (!fs.existsSync(outputDir)) { + throw new Error('Invalid output file, directory does not exist:' + outputDir); + } + var stream = fs.createWriteStream(file); + this.stdout = stream; + this.stdoutFn = stream.write; + // config can be a "log" function, so use it. + } else if (typeof config === 'function') { + this.stdout = this; + this.stdoutFn = config; + // Unknown config, error + } else { + throw new Error('Output got invalid config:', config); + } +} + +/** + * Writes data to the output resource + * @param {...string|number|object} arguments - data to be written, can be a formatted string + */ +Output.prototype.write = function() { + if (this.stdout === null) { + return; + } + + // format the arguments and add \n + var msg = util.format.apply(this, arguments) + '\n'; + this.stdoutFn.call(this.stdout, msg); +}; + +/** + * Writes data to the output resource with no formatting nor new line + * @param {string} data - The data to write + */ +Output.prototype.print = function(data) { + if (this.stdout === null) { + return; + } + + this.stdoutFn.call(this.stdout, data); +}; + +module.exports = Output; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070903_plugin.js b/pool/shard011/JavaScript/0070903_plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..65b09b2c0adbcec824c13195c13b8796134a2191 --- /dev/null +++ b/pool/shard011/JavaScript/0070903_plugin.js @@ -0,0 +1,47 @@ +(function() { + var command_name = 'dt_mce_command-call_to_action', + plugin_name = 'dt_mce_plugin_shortcode_call_to_action', + plugin_title = '回应动作', + plugin_image = 'call-to-action.png'; + + tinymce.create( 'tinymce.plugins.' + plugin_name, { + init : function( ed, url ) { + + // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); + ed.addCommand(command_name, function() { + var selected_text = ed.selection.getContent(), + return_text = ''; + + /**********************************/ + // Edit shortcode here! + /**********************************/ + var attr = [ + 'style="1"', + 'background="plain"', + 'content_size="normal"', + 'text_align="left"', + 'animation="none"', + 'line="true"' + ], + attr_str = attr.join(' '); + + return_text = '[dt_call_to_action ' + attr_str + ']' + selected_text + '[/dt_call_to_action]'; + + ed.execCommand('mceInsertContent', 0, return_text); + }); + + // Register example button + ed.addButton( plugin_name, { + + title : plugin_title, + cmd : command_name, + image : url + '/' + plugin_image + + }); + } + }); + + // Register plugin + tinymce.PluginManager.add( plugin_name, tinymce.plugins[plugin_name] ); + +})(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070904_index.js b/pool/shard011/JavaScript/0070904_index.js new file mode 100644 index 0000000000000000000000000000000000000000..345e859f02e3965371383a64b88831266918179a --- /dev/null +++ b/pool/shard011/JavaScript/0070904_index.js @@ -0,0 +1,142 @@ +/** + * Copyright 2017 IBM Corp. + * + * 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. + **/ + +var when = require("when"); +var bcrypt = require("bcrypt"); +var util = require("util"); +var path = require("path"); + + +util.log("Starting Node-RED on Bluemix bootstrap"); +util.log("Loading bluemix-settings.js"); +var settings = require("./bluemix-settings.js"); + +if (!settings.adminAuth) { + // No user-defined security + var storage; + if (settings.storageModule) { + storage = settings.storageModule; + } else { + storage = require('./node_modules/node-red/red/runtime/storage/localfilesystem'); + } + util.log("Loading application settings"); + storage.init(settings).then(storage.getSettings).then(function(runtimeSettings) { + if (process.env.NODE_RED_USERNAME && process.env.NODE_RED_PASSWORD) { + util.log("Enabling adminAuth using NODE_RED_USERNAME/NODE_RED_PASSWORD"); + var config = { + adminAuth: { + username: process.env.NODE_RED_USERNAME, + password: bcrypt.hashSync(process.env.NODE_RED_PASSWORD, 8), + allowAnonymous: (process.env.NODE_RED_GUEST_ACCESS === 'true') + } + }; + + if (runtimeSettings.bluemixConfig && runtimeSettings.bluemixConfig.hasOwnProperty('adminAuth')) { + delete runtimeSettings.bluemixConfig.adminAuth; + storage.saveSettings(runtimeSettings).then(function() { + startNodeRED(config); + }); + } else { + startNodeRED(config); + } + } else if (runtimeSettings.bluemixConfig) { + util.log("Using runtime settings for adminAuth"); + startNodeRED(runtimeSettings.bluemixConfig); + } else { + util.log("Starting first-use setup"); + var server; + var express = require('express'); + var bodyParser = require('body-parser'); + var app = express(); + app.use(bodyParser.json()); + app.get("/", function(req,res) { + res.sendFile(path.join(__dirname,"public","first-run.html")); + }); + app.post("/setup", function(req,res) { + if (req.body.adminAuth && req.body.adminAuth.password) { + req.body.adminAuth.password = bcrypt.hashSync(req.body.adminAuth.password, 8); + } + runtimeSettings.bluemixConfig = req.body; + util.log("Received first-use setup configuration"); + storage.saveSettings(runtimeSettings).then(function() { + res.status(200).end(); + setTimeout(function() { + util.log("Stopping first-use setup application"); + server.shutdown(function() { + startNodeRED(req.body); + }); + },1000); + }).otherwise(function(err) { + util.log("Failed to save configuration"); + util.log(err); + res.status(200).end(); + }); + }); + app.use("/",express.static(path.join(__dirname,"public"))); + var http = require('http'); + server = http.createServer(function(req,res) {app(req,res);}); + server = require('http-shutdown')(server); + server.listen(settings.uiPort,settings.uiHost,function() {}); + util.log("Waiting for first-use setup to complete"); + } + }).otherwise(function(err) { + console.log("Failed to initialise storage module"); + console.log(err); + }); +} else { + startNodeRED({}); +} + +function startNodeRED(config) { + if (config.adminAuth && !settings.adminAuth) { + util.log("Enabling adminAuth security - set NODE_RED_USERNAME and NODE_RED_PASSWORD to change credentials"); + settings.adminAuth = { + type: "credentials", + users: function(username) { + if (config.adminAuth.username == username) { + return when.resolve({username:username,permissions:"*"}); + } else { + return when.resolve(null); + } + }, + authenticate: function(username, password) { + if (config.adminAuth.username === username && bcrypt.compareSync(password,config.adminAuth.password)) { + return when.resolve({username:username,permissions:"*"}); + } else { + return when.resolve(null); + } + } + }; + if ((process.env.NODE_RED_GUEST_ACCESS === 'true') || (process.env.NODE_RED_GUEST_ACCESS === undefined && config.adminAuth.allowAnonymous)) { + util.log("Enabling anonymous read-only access - set NODE_RED_GUEST_ACCESS to 'false' to disable"); + settings.adminAuth.default = function() { + return when.resolve({anonymous: true, permissions:"read"}); + }; + } else { + util.log("Disabled anonymous read-only access - set NODE_RED_GUEST_ACCESS to 'true' to enable"); + } + } + if (config.useAppmetrics) { + settings.useAppmetrics = config.useAppmetrics; + } + var dash; + // ensure the environment variable overrides the settings + if ((process.env.NODE_RED_USE_APPMETRICS === 'true') || (settings.useAppmetrics && !(process.env.NODE_RED_USE_APPMETRICS === 'false'))) { + dash = require('appmetrics-dash'); + dash.attach(); + } + require('./node_modules/node-red/red.js'); +} diff --git a/pool/shard011/JavaScript/0070905_shadow-functions.js b/pool/shard011/JavaScript/0070905_shadow-functions.js new file mode 100644 index 0000000000000000000000000000000000000000..f78f3ef75d688bf6e656918a87a38c1f61a4b860 --- /dev/null +++ b/pool/shard011/JavaScript/0070905_shadow-functions.js @@ -0,0 +1,125 @@ +"use strict"; + +var _Symbol = require("babel-runtime/core-js/symbol")["default"]; + +var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"]; + +var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"]; + +exports.__esModule = true; + +var _plugin = require("../plugin"); + +var _plugin2 = _interopRequireDefault(_plugin); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var SUPER_THIS_BOUND = _Symbol("super this bound"); + +var superVisitor = { + CallExpression: function CallExpression(path) { + if (!path.get("callee").isSuper()) return; + + var node = path.node; + + if (node[SUPER_THIS_BOUND]) return; + node[SUPER_THIS_BOUND] = true; + + path.replaceWith(t.assignmentExpression("=", this.id, node)); + } +}; + +exports["default"] = new _plugin2["default"]({ + visitor: { + ThisExpression: function ThisExpression(path) { + remap(path, "this"); + }, + + ReferencedIdentifier: function ReferencedIdentifier(path) { + if (path.node.name === "arguments") { + remap(path, "arguments"); + } + } + } +}); + +function shouldShadow(path, shadowPath) { + if (path.is("_forceShadow")) { + return true; + } else { + return shadowPath; + } +} + +function remap(path, key) { + // ensure that we're shadowed + var shadowPath = path.inShadow(key); + if (!shouldShadow(path, shadowPath)) return; + + var shadowFunction = path.node._shadowedFunctionLiteral; + + var currentFunction = undefined; + var passedShadowFunction = false; + + var fnPath = path.findParent(function (path) { + if (path.isProgram() || path.isFunction()) { + // catch current function in case this is the shadowed one and we can ignore it + currentFunction = currentFunction || path; + } + + if (path.isProgram()) { + passedShadowFunction = true; + + return true; + } else if (path.isFunction() && !path.isArrowFunctionExpression()) { + if (shadowFunction) { + if (path === shadowFunction || path.node === shadowFunction.node) return true; + } else { + if (!path.is("shadow")) return true; + } + + passedShadowFunction = true; + return false; + } + + return false; + }); + + if (shadowFunction && fnPath.isProgram() && !shadowFunction.isProgram()) { + // If the shadow wasn't found, take the closest function as a backup. + // This is a bit of a hack, but it will allow the parameter transforms to work properly + // without introducing yet another shadow-controlling flag. + fnPath = path.findParent(function (p) { + return p.isProgram() || p.isFunction(); + }); + } + + // no point in realiasing if we're in this function + if (fnPath === currentFunction) return; + + // If the only functions that were encountered are arrow functions, skip remapping the + // binding since arrow function syntax already does that. + if (!passedShadowFunction) return; + + var cached = fnPath.getData(key); + if (cached) return path.replaceWith(cached); + + var id = path.scope.generateUidIdentifier(key); + + fnPath.setData(key, id); + + if (key === "this" && fnPath.isMethod({ kind: "constructor" })) { + fnPath.scope.push({ id: id }); + + fnPath.traverse(superVisitor, { id: id }); + } else { + var init = key === "this" ? t.thisExpression() : t.identifier(key); + + fnPath.scope.push({ id: id, init: init }); + } + + return path.replaceWith(id); +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070911_server.js b/pool/shard011/JavaScript/0070911_server.js new file mode 100644 index 0000000000000000000000000000000000000000..bba4b34e6452a88e3a04637fc2074213161b79b7 --- /dev/null +++ b/pool/shard011/JavaScript/0070911_server.js @@ -0,0 +1,34 @@ +#!/usr/local/bin/node + +var app = require('express.io')(), + port = process.env.PORT || 8080; + +app.http().io(); + +app.all('*', function(req, res, next) { + res.header("Access-Control-Allow-Origin", "*"); + res.header("Access-Control-Allow-Headers", "X-Requested-With"); + next(); + }); + +app.get('/api/UTC', function(req, res) { + "use strict"; + var now = new Date(); + res.send({serverTime: now.toJSON()}); +}); + +app.get('/api', function(req, res) { + "use strict"; + res.send("API Routes can be added..."); +}); + +app.get('/', function(req, res) { + "use strict"; + res.send("Nothing Here."); +}); + +app.listen(port, function () { + "use strict"; + console.log("Express.io server listening on port %d.", + this.address().port); +}); diff --git a/pool/shard011/JavaScript/0070912_helpCtrl.js b/pool/shard011/JavaScript/0070912_helpCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..62bfccd6e6e61013ca85b6f3acee8ba1ce28b439 --- /dev/null +++ b/pool/shard011/JavaScript/0070912_helpCtrl.js @@ -0,0 +1,92 @@ +angular.module('helpCtrl', ['ui.bootstrap']) +.controller('helpCtrl', function ($scope, $stateParams) { + $scope.today = function () { + $scope.dt = new Date(); + var ROOT = 'https://uberscheduler-1203.appspot.com/_ah/api'; + gapi.client.load('uberApi', 'v1', function() { + console.log("success") + }, ROOT); + }; + $scope.today(); + + $scope.clear = function () { + gapi.client.uberApi.ride.return({ + "key": 5066549580791808 + }).execute(function(resp) { + console.log(resp); + }); + $scope.dt = null; + }; + + // Disable weekend selection + $scope.disabled = function (date, mode) { + return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6); + }; + + $scope.toggleMin = function () { + $scope.minDate = $scope.minDate ? null : new Date(); + }; + + $scope.toggleMin(); + $scope.maxDate = new Date(2020, 5, 22); + + $scope.open1 = function () { + $scope.popup1.opened = true; + }; + + $scope.open2 = function () { + $scope.popup2.opened = true; + }; + + $scope.setDate = function (year, month, day) { + $scope.dt = new Date(year, month, day); + }; + + $scope.dateOptions = { + formatYear: 'yy', + startingDay: 1 + }; + + $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate']; + $scope.format = $scope.formats[0]; + $scope.altInputFormats = ['M!/d!/yyyy']; + + $scope.popup1 = { + opened: false + }; + + $scope.popup2 = { + opened: false + }; + + var tomorrow = new Date(); + tomorrow.setDate(tomorrow.getDate() + 1); + var afterTomorrow = new Date(); + afterTomorrow.setDate(tomorrow.getDate() + 1); + $scope.events = [ + { + date: tomorrow, + status: 'full' + }, + { + date: afterTomorrow, + status: 'partially' + } + ]; + + $scope.getDayClass = function (date, mode) { + if (mode === 'day') { + var dayToCheck = new Date(date).setHours(0, 0, 0, 0); + + for (var i = 0; i < $scope.events.length; i++) { + var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0); + + if (dayToCheck === currentDay) { + return $scope.events[i].status; + } + } + } + + return ''; + }; +}) diff --git a/pool/shard011/JavaScript/0070914_gridTitle.jsx.js b/pool/shard011/JavaScript/0070914_gridTitle.jsx.js new file mode 100644 index 0000000000000000000000000000000000000000..8f0410751a76cf40b8f05a469e2185ab3e6579a4 --- /dev/null +++ b/pool/shard011/JavaScript/0070914_gridTitle.jsx.js @@ -0,0 +1,139 @@ +"use strict"; + +var _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i];for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + }return target; +}; + +/* + See License / Disclaimer https://raw.githubusercontent.com/DynamicTyped/Griddle/master/LICENSE +*/ +var React = require("react"); +var _ = require("underscore"); +var ColumnProperties = require("./columnProperties.js"); +var assign = require('lodash/assign'); + +var DefaultHeaderComponent = React.createClass({ + displayName: 'DefaultHeaderComponent', + + render: function render() { + return React.createElement('span', null, this.props.displayName); + } +}); + +var GridTitle = React.createClass({ + displayName: "GridTitle", + getDefaultProps: function() { + return { + columnSettings: null, + rowSettings: null, + sortSettings: null, + headerStyle: null, + useGriddleStyles: true, + useGriddleIcons: true, + headerStyles: {} + }; + }, + componentWillMount: function() { + this.verifyProps(); + }, + sort: function(event) { + this.props.sortSettings.changeSort(event.target.dataset.title || + event.target.parentElement.dataset.title); + }, + verifyProps: function() { + if (this.props.columnSettings === null) { + console.error( + "gridTitle: The columnSettings prop is null and it shouldn't be" + ); + } + + if (this.props.sortSettings === null) { + console.error( + "gridTitle: The sortSettings prop is null and it shouldn't be"); + } + }, + render: function() { + this.verifyProps(); + var that = this; + + var nodes = this.props.columnSettings.getColumns().map(function(col, + index) { + var columnSort = ""; + var sortComponent = that.props.sortSettings.sortDefaultComponent; + var titleStyles = null; + + if (that.props.sortSettings.sortColumn == col && that.props.sortSettings + .sortAscending) { + columnSort = that.props.sortSettings.sortAscendingClassName; + sortComponent = that.props.useGriddleIcons && that.props.sortSettings + .sortAscendingComponent; + } else if (that.props.sortSettings.sortColumn == col && that.props + .sortSettings.sortAscending === false) { + columnSort += that.props.sortSettings.sortDescendingClassName; + sortComponent = that.props.useGriddleIcons && that.props.sortSettings + .sortDescendingComponent; + } + + + var meta = that.props.columnSettings.getColumnMetadataByName( + col); + var columnIsSortable = that.props.columnSettings.getMetadataColumnProperty( + col, "sortable", true); + var displayName = that.props.columnSettings.getMetadataColumnProperty( + col, "displayName", col); + var HeaderComponent = that.props.columnSettings.getMetadataColumnProperty(col, "customHeaderComponent", DefaultHeaderComponent); + var headerProps = that.props.columnSettings.getMetadataColumnProperty(col, "customHeaderComponentProps", {}); + + columnSort = meta == null ? columnSort : (columnSort && + columnSort + " " || columnSort) + that.props.columnSettings + .getMetadataColumnProperty(col, "cssClassName", ""); + + if (that.props.useGriddleStyles) { + titleStyles = { + backgroundColor: "#EDEDEF", + border: "0", + borderBottom: "1px solid #DDD", + color: "#222", + padding: "5px", + cursor: columnIsSortable ? "pointer" : "default" + }; + } + + // return React.createElement( + // "th", { + // onClick: columnIsSortable ? that.sort : null, + // "data-title": col, + // className: columnSort, + // key: index, + // style: titleStyles + // }, + // displayName, + // sortComponent + // ); + return React.createElement('th', { onClick: columnIsSortable ? that.sort : null, 'data-title': col, className: columnSort, key: col, + style: titleStyles }, React.createElement(HeaderComponent, _extends({ columnName: col, displayName: displayName, + filterByColumn: that.props.filterByColumn }, headerProps)), sortComponent); + }); + + //Get the row from the row settings. + var className = that.props.rowSettings && that.props.rowSettings.getHeaderRowMetadataClass() || + null; + + + // return React.createElement('thead', null, React.createElement('tr', { + // className: className, + // style: this.props.headerStyles }, nodes)); + + return React.createElement('thead', null, React.createElement('tr', { + className: className, + style: this.props.headerStyles }, nodes)); + } +}); + +module.exports = GridTitle; diff --git a/pool/shard011/JavaScript/0070917_utils-test.js b/pool/shard011/JavaScript/0070917_utils-test.js new file mode 100644 index 0000000000000000000000000000000000000000..e6f8bbd42bea3337a4b9e8e322c7b87b3b34b83b --- /dev/null +++ b/pool/shard011/JavaScript/0070917_utils-test.js @@ -0,0 +1,43 @@ +var expect = require('expect.js'); +var utils = require('../../lib/utils'); +var _ = require('lodash'); + +describe('utils', function () { + + it('should expose n number of properties', function () { + expect(_.size(utils)).to.eql(8); + }); + + it('should have a generatePassword property', function () { + expect(utils).to.have.property('generatePassword'); + }); + + it('should have a ensureDir property', function () { + expect(utils).to.have.property('ensureDir'); + }); + + it('should have a jsonClone property', function () { + expect(utils).to.have.property('jsonClone'); + }); + + it('should have a ensurePaths property', function () { + expect(utils).to.have.property('ensurePaths'); + }); + + it('should have a processSend property', function () { + expect(utils).to.have.property('processSend'); + }); + + it('should have a isNodejitsu property', function () { + expect(utils).to.have.property('isNodejitsu'); + }); + + it('should have a hconsole property', function () { + expect(utils).to.have.property('hconsole'); + }); + + it('should have a showConfigPath property', function () { + expect(utils).to.have.property('showConfigPath'); + }); + +}); diff --git a/pool/shard011/JavaScript/0070918_sakai-rubric-criterion-student.js b/pool/shard011/JavaScript/0070918_sakai-rubric-criterion-student.js new file mode 100644 index 0000000000000000000000000000000000000000..471fa71e25851f5d7860426de91c22d99c5ee0cc --- /dev/null +++ b/pool/shard011/JavaScript/0070918_sakai-rubric-criterion-student.js @@ -0,0 +1,179 @@ +import {RubricsElement} from "./rubrics-element.js"; +import {html} from "/webcomponents/assets/lit-element/lit-element.js"; +import {repeat} from "/webcomponents/assets/lit-html/directives/repeat.js"; +import {SakaiRubricStudentComment} from "./sakai-rubric-student-comment.js"; + +export class SakaiRubricCriterionStudent extends RubricsElement { + + static get properties() { + + return { + criteria: { type: Array}, + totalPoints: Number, + rubricAssociation: { attribute: "rubric-association", type: Object }, + evaluationDetails: { attribute: "evaluation-details", type: Array }, + preview: Boolean, + entityId: { attribute: "entity-id", type: String }, + }; + } + + set criteria(newVal) { + + var oldVal = this._criteria; + this._criteria = newVal; + this.criteria.forEach(c => { + + if (!c.selectedvalue) { + c.selectedvalue = 0; + } + c.pointrange = this.getHighLow(c.ratings, "points"); + }); + + if (this.evaluationDetails) { + this.handleEvaluationDetails(); + } + } + + get criteria() { return this._criteria; } + + set evaluationDetails(newValue) { + + this._evaluationDetails = newValue; + + if (this.criteria) { + this.handleEvaluationDetails(); + } + } + + get evaluationDetails() { return this._evaluationDetails; } + + render() { + + return html` +
    + ${this.criteria.map(c => html` +
    +
    +

    ${c.title}

    +

    ${c.description}

    +
    +
    +
    +
    + ${repeat(c.ratings, r => r.id, r => html` +
    +
    ${r.title}
    +

    ${r.description}

    + ${r.points.toLocaleString(this.locale)} Points +
    + `)} +
    +
    +
    +
    + ${!this.preview ? html` + + + ${c.selectedvalue} + ${!c.selectedRatingId ? "0" : ""} +   + + ${this.isOverridden(c.pointoverride,c.selectedvalue) ? + html`${c.pointoverride}` + : html``} + ` : html``} +
    +
    + `)} +
    + ${!this.preview ? html` +
    +
    Total: ${this.totalPoints.toLocaleString(this.locale)}
    +
    + ` : html``} + `; + } + + handleEvaluationDetails() { + + this.evaluationDetails.forEach(ed => { + + this.criteria.forEach(c => { + + if (ed.criterionId === c.id) { + + var selectedRatingItem; + c.ratings.forEach(r => { + if (r.id == ed.selectedRatingId) { + r.selected = true; + selectedRatingItem = r; + } else { + r.selected = false; + } + }); + + c.selectedRatingId = ed.selectedRatingId; + if (ed.pointsAdjusted) { + c.pointoverride = ed.points; + c.selectedvalue = selectedRatingItem.points; + } else { + c.pointoverride = ""; + c.selectedvalue = ed.points; + } + + c.comments = ed.comments; + if (c.comments === "undefined") { + // This can happen if undefined gets passed to the server when the evaluation is saved. + c.comments = ""; + } + } + }); + }); + + this.updateTotalPoints(); + } + + isOverridden(pointoverride, selected) { + + if (!this.rubricAssociation.parameters.fineTunePoints) { + return false; + } + + if ((pointoverride || pointoverride === 0) && (parseFloat(pointoverride) !== parseFloat(selected))) { + return true; + } else { + return false; + } + } + + updateTotalPoints() { + + this.totalPoints = this.criteria.reduce((a, c) => { + + if (c.pointoverride) { + return a + parseFloat(c.pointoverride); + } else if (c.selectedvalue) { + return a + parseFloat(c.selectedvalue); + } else { + return a; + } + }, 0); + + this.ready = true; + } + + getOverriddenClass(ovrdvl,selected) { + + if (!this.rubricAssociation.parameters.fineTunePoints) { + return ''; + } + + if ((ovrdvl || ovrdvl === 0) && (parseFloat(ovrdvl) !== parseFloat(selected))) { + return 'strike'; + } else { + return ''; + } + } +} + +customElements.define("sakai-rubric-criterion-student", SakaiRubricCriterionStudent); diff --git a/pool/shard011/JavaScript/0070920_image.js b/pool/shard011/JavaScript/0070920_image.js new file mode 100644 index 0000000000000000000000000000000000000000..89aadcc9dfc3982e80933deb03e053ad4be21b2a --- /dev/null +++ b/pool/shard011/JavaScript/0070920_image.js @@ -0,0 +1,158 @@ +'use strict'; +var React = require('react'); +var cx = require('react/lib/cx'); +var globals = require('./globals'); +var url = require('url'); + + +// Fixed-position lightbox background and image +var Lightbox = module.exports.Lightbox = React.createClass({ + getInitialState: function() { + return {imgHeight: 0}; + }, + + // Window resized; set max-height of image + handleResize: function() { + this.setState({imgHeight: this.refs.lightbox.getDOMNode().offsetHeight - 40}); + }, + + componentDidMount: function() { + globals.bindEvent(window, 'resize', this.handleResize); + this.setState({imgHeight: this.refs.lightbox.getDOMNode().offsetHeight - 40}); + }, + + componentWillUnmount: function() { + globals.unbindEvent(window, 'resize', this.handleResize); + }, + + render: function() { + var lightboxVisible = this.props.lightboxVisible; + var lightboxClass = cx({ + "lightbox": true, + "active": lightboxVisible + }); + var imgStyle = {maxHeight: this.state.imgHeight}; + + return ( +
    +
    + + + + +
    +
    + ); + } +}); + + +var Attachment = module.exports.Attachment = React.createClass({ + propTypes: { + context: React.PropTypes.object.isRequired, // Object within which the attachment is to be displayed + attachment: React.PropTypes.object, // Attachment object to display + className: React.PropTypes.string, // CSS class name to add to image element; '-img' added to it + show_link: React.PropTypes.bool // False to just display image preview without link or lightbox + }, + + // Handle a click on the lightbox trigger (thumbnail) + lightboxClick: function(attachmentType, e) { + if (attachmentType === 'image') { + e.preventDefault(); + e.stopPropagation(); + this.setState({lightboxVisible: true}); + } + }, + + getInitialState: function() { + return {lightboxVisible: false}; + }, + + clearLightbox: function() { + this.setState({lightboxVisible: false}); + }, + + // If lightbox visible, ESC key closes it + handleEscKey: function(e) { + if (this.state.lightboxVisible && e.keyCode == 27) { + this.clearLightbox(); + } + }, + + // Register for keyup events for ESC key + componentDidMount: function() { + globals.bindEvent(window, 'keyup', this.handleEscKey); + }, + + // Unregister keyup events when component closes + componentWillUnmount: function() { + globals.unbindEvent(window, 'keyup', this.handleEscKey); + }, + + render: function() { + var {context, attachment, className, show_link} = this.props; + var attachmentHref; + var src, alt; + var height = "100"; + var width = "100"; + if (attachment && attachment.href && attachment.type) { + attachmentHref = url.resolve(context['@id'], attachment.href); + var attachmentType = attachment.type.split('/', 1)[0]; + if (attachmentType == 'image' && attachment.type != 'image/tiff') { + var imgClass = className ? className + '-img' : ''; + src = attachmentHref; + height = attachment.height || 100; + width = attachment.width || 100; + alt = "Attachment Image"; + if (show_link === false) { + return {alt}; + } else { + return ( +
    +
    + + {alt} + +
    + +
    + ); + } + } else if (attachment.type == "application/pdf"){ + return ( + + ); + } else { + return ( + + ); + } + } else { + return ( +
    +
    Attachment file broken icon
    +
    + ); + } + } +}); + + +var Image = React.createClass({ + render: function() { + return ( +
    + +
    {this.props.context.caption}
    +
    + ); + } +}); + + +globals.content_views.register(Image, 'Image'); + diff --git a/pool/shard011/JavaScript/0070922_welcome.js b/pool/shard011/JavaScript/0070922_welcome.js new file mode 100644 index 0000000000000000000000000000000000000000..f655cbdbe5508d8f0eea82dd4a6bea3a40f4e3c5 --- /dev/null +++ b/pool/shard011/JavaScript/0070922_welcome.js @@ -0,0 +1,31 @@ +var map; +function initialize() { + var mapOptions = { + zoom:8, + center:new google.maps.LatLng( -34.397, 150.644 ) + }; + map = new google.maps.Map( document.getElementById( 'map' ), + mapOptions ); + + new google.maps.Marker( { + map:map, + icon:{ + path:GMAP_FA.EXCLAMATION, + scale:0.02, + rotation:180, + strokeWeight:0.2, + strokeColor:'black', + strokeOpacity:1, + fillColor:'#000000', + fillOpacity:0.7 + }, + clickable:false, + position:new google.maps.LatLng( -34.397, 150.644 ) + } ); + +} + + +$( document ).ready( function () { + initialize(); +} ); diff --git a/pool/shard011/JavaScript/0070924_initialize_test.js b/pool/shard011/JavaScript/0070924_initialize_test.js new file mode 100644 index 0000000000000000000000000000000000000000..5510d4a2bad132695422c6e53e03ed55a7a82b28 --- /dev/null +++ b/pool/shard011/JavaScript/0070924_initialize_test.js @@ -0,0 +1,51 @@ +// Copyright 2013 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy +// of the License at: http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distrib- +// uted 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 +// specific language governing permissions and limitations under the License. + +// Author: kpy@google.com (Ka-Ping Yee) + +function InitializeTest() { + cm.TestBase.call(this); +} +InitializeTest.prototype = new cm.TestBase(); +registerTestSuite(InitializeTest); + +/** Verifies our customizations to the HTML sanitizer. */ +InitializeTest.prototype.htmlSanitizer = function() { + // setForTest_ ensures that cm.Html.sanitize_ is restored after the test. + this.setForTest_('cm.Html.sanitize_', null); + installHtmlSanitizer(html); // sets cm.Html.sanitize_ + + // world')); + + // TODO(romano): The html_css_sanitizer library properly leaves in + // style attributes and sanitizes the CSS when running in a browser, + // but incorrectly strips out style attributes when run outside the + // browser. This should have been fixed by cr/51556988, but is still + // not working. Once working, the below check can be uncommented. (b/9413480). + // style attributes should be preserved. + // expectEq('
    foo
    ', + // cm.Html.sanitize_('
    foo
    ')); + + // Ordinary links should be preserved. + expectEq('z', + cm.Html.sanitize_('z')); + + // target="_blank" should be preserved, but not other values of target. + expectEq('z', + cm.Html.sanitize_('z')); + expectEq('z', + cm.Html.sanitize_('z')); +}; diff --git a/pool/shard011/JavaScript/0070926_zoho-method.js b/pool/shard011/JavaScript/0070926_zoho-method.js new file mode 100644 index 0000000000000000000000000000000000000000..f345e055b16e8a283e050a88974ed33ba28fb475 --- /dev/null +++ b/pool/shard011/JavaScript/0070926_zoho-method.js @@ -0,0 +1,73 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +var _ = require('lodash'); +/** + * [ZohoMethod description] + * @param {object} spec + * @param {string} spec.method + * @param {function} spec.path + * @param {string[]} spec.required + * @param {object} [context] - Optional context binding + */ +function ZohoMethod(spec, context) { + var requestMethod = (spec.method || 'GET').toUpperCase(); + var commandPath = spec.path; + var urlParams = spec.urlParams; + var urlData = {}; + + function zMethod() { + var args = [].slice.call(arguments); + var requestData = {}; + var requestOptions = {}; + var requestPath = ''; + + // Parse the url path params. + for (var i = 0; i < urlParams.length; i++) { + var arg = args[0]; + var param = urlParams[i]; + + if (!arg || typeof arg !== 'string') { + throw new Error('Argument ' + param + ' is required.'); + } + + urlData[param] = args.shift(); + } + + // Parse out the request data, if any + if (args.length > 0) { + if (_.isPlainObject(args[0]) && !isRequestOption(args[0])) { + requestData = args.shift(); + } + } + + // Parse any request options, pagination, etc. + if (args.length > 0) { + if (_.isPlainObject(args[0]) && isRequestOption(args[0])) { + requestOptions = args.shift(); + } + } + + // Create the full request path. + requestPath = this.createFullPath(commandPath, urlData); + + return this._request(requestMethod, requestPath, requestOptions, requestData); + } + + // Bind to the provided context + if (context) { + return zMethod.bind(context); + } else { + return zMethod; + } +} + +function isRequestOption(obj) { + return _.isPlainObject(obj) && ['organization_id'].some(function (key) { + return obj.hasOwnProperty(key); + }); +} + +exports.ZohoMethod = ZohoMethod; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070927_user.js b/pool/shard011/JavaScript/0070927_user.js new file mode 100644 index 0000000000000000000000000000000000000000..db30813fa0ba562f92b7a0afec7f10e6f9b9d238 --- /dev/null +++ b/pool/shard011/JavaScript/0070927_user.js @@ -0,0 +1,39 @@ +var mongoose = require('mongoose'); +mongoose.connect(process.env.MONGO_URL); + +var Schema = mongoose.Schema; +var userSchema = new Schema({ + _id: { type: Number, required: true }, + feedToken: { type: String, required: true, unique: true }, + accessToken: { type: String, required: true, unique: true }, + refreshToken: { type: String, required: true, unique: true } +}); + +var Feed = require('feed'); +var moment = require('moment'); +var moves = require('../config/moves'); + +userSchema.methods.summaryAtom = function(callback) { + moves.get('/user/summary/daily?pastDays=30', this.accessToken, function(err, res, body) { + if (err) { callback(err, null) }; + var data = JSON.parse(body); + var feed = new Feed({ + title: 'Moves Feed Daily Summary', + link: process.env.MOVES_FEED_URL + }); + + data.reverse().forEach(function(daily) { + feed.item({ + title: "Moves Daily Summary " + daily.date, + link: process.env.MOVES_FEED_URL, + description: JSON.stringify(daily.summary), + date: moment(daily.date, 'YYYYMMDD').toDate() + }); + }); + + callback(null, feed.render('atom-1.0')); + }); +}; + +var User = mongoose.model('User', userSchema); +module.exports = User; diff --git a/pool/shard011/JavaScript/0070931_TaskQueue.js b/pool/shard011/JavaScript/0070931_TaskQueue.js new file mode 100644 index 0000000000000000000000000000000000000000..d2977eac5b02e1174feefdd01a38748d48166ac3 --- /dev/null +++ b/pool/shard011/JavaScript/0070931_TaskQueue.js @@ -0,0 +1,26 @@ +import makeAsync from './async' + +export default class TaskQueue { + constructor () { + this.tasks = new Array(2 << 15) + this.length = 0 + this.drain = makeAsync(() => this._drain()) + } + + add (task) { + if (this.length === 0) { + this.drain() + } + + this.tasks[this.length++] = task + } + + _drain () { + const q = this.tasks + for (let i = 0; i < this.length; ++i) { + q[i].run() + q[i] = void 0 + } + this.length = 0 + } +} diff --git a/pool/shard011/JavaScript/0070933_graph.js b/pool/shard011/JavaScript/0070933_graph.js new file mode 100644 index 0000000000000000000000000000000000000000..802704b2313fb652b6987d0805dad20d5ea4e9ab --- /dev/null +++ b/pool/shard011/JavaScript/0070933_graph.js @@ -0,0 +1,32 @@ +/** + * Created by Neeraj Kumar on 5/18/2017. + */ +var randomColorGenerator = function () { + return '#' + (Math.random().toString(16) + '0000000').slice(2, 8); +}; +var options_data = { + responsive: true, + legend: { + display:false + }, + title: { + display: true, + }, + animation: { + animateScale: true, + animateRotate: true + }, + tooltips: { + callbacks: { + label: function (tooltipItem, data) { + var allData = data.datasets[tooltipItem.datasetIndex].data; + var _meta = data.datasets[tooltipItem.datasetIndex]._meta; + var meta = _meta[Object.keys(_meta)[0]]; + var tooltipLabel = data.labels[tooltipItem.index]; + var tooltipData = allData[tooltipItem.index]; + var tooltipPercentage = Math.round((tooltipData / meta.total) * 10000) / 100; + return tooltipLabel + ': ' + tooltipData + ' (' + tooltipPercentage + '%)'; + } + } + } +}; diff --git a/pool/shard011/JavaScript/0070936_capacitor-bridge.js b/pool/shard011/JavaScript/0070936_capacitor-bridge.js new file mode 100644 index 0000000000000000000000000000000000000000..fbc7c8895b61bcd6eaa5fa61a88adb9d5a480d10 --- /dev/null +++ b/pool/shard011/JavaScript/0070936_capacitor-bridge.js @@ -0,0 +1,36 @@ +'use strict'; + +import {EventEmitter} from 'events'; + +export default class CapacitorBridge { + constructor(emitter) { + this.emitter = emitter; + this.channels = {} + } + + proxyEvents() { + this.emitter.on('tunnel:agent', ({channelName, event, payload}) => { + const channel = this.channels[channelName]; + if (channel) { + channel.emit(event, payload); + } + }); + } + + registerPlugin(agent, displayName, channelName, sourceFile) { + return fetch(sourceFile).then(function (response) { + return response.text(); + }).then((source) => { + this.emitter.emit('tunnel:panel', 'plugin:upload', {displayName, channelName, source}); + + agent.emitter.on('tunnel:plugin', (event, payload) => { + this.emitter.emit('tunnel:panel', 'tunnel:plugin', { + event, + channelName, + payload + }); + }); + this.channels[channelName] = agent.emitter; + }); + } +} diff --git a/pool/shard011/JavaScript/0070940_panel.js b/pool/shard011/JavaScript/0070940_panel.js new file mode 100644 index 0000000000000000000000000000000000000000..f62aceb8b62e906c81711e8312c5ac6942641a05 --- /dev/null +++ b/pool/shard011/JavaScript/0070940_panel.js @@ -0,0 +1,34 @@ +'use strict'; + +var m = require('mithril'); + +var render = function(ctrl) { + if (ctrl.vm.visible()) { + return m('div.sl-panel', {style: ctrl.vm.style()}, [ + m('div.heading', [ + ctrl.vm.component.title(), + m('i.fa.mouse-pointer.toggle-icon', { + 'class': ctrl.vm.minimized() ? 'fa-chevron-up' : 'fa-chevron-down', + onclick: ctrl.vm.ev_toggleclick.bind(ctrl) + }), + m('i.fa.fa-times-circle.mouse-pointer.close-icon', { + onclick: ctrl.vm.ev_closeclick.bind(ctrl) + }) + ]), + m('div.content.active', { + 'class': ctrl.vm.minimized() ? 'hide' : '' + }, [ + ctrl.vm.component.view(ctrl.vm.component.controller) + ]) + ]); + } + + return undefined; +}; + +var VIEW = function (ctrl) { + // do not add anything else to the VIEW, it should never initialize anything + return render(ctrl); +}; + +module.exports = VIEW; diff --git a/pool/shard011/JavaScript/0070941_createFormGroup.js b/pool/shard011/JavaScript/0070941_createFormGroup.js new file mode 100644 index 0000000000000000000000000000000000000000..46ec1831985202d628fffaff896ee66e64c78d34 --- /dev/null +++ b/pool/shard011/JavaScript/0070941_createFormGroup.js @@ -0,0 +1,42 @@ +var createFormGroup = function (fig) { + var self = {}, + input = fig.input, + $self = input.$().closest('.frm-group'), + $feedback = $self.find('.frm-feedback'); + + self.get = input.get || function () {}; + self.set = input.set || function () {}; + self.clear = input.clear || function () {}; + self.disable = input.disable; + self.enable = input.enable; + self.getType = input.getType; + self.subscribe = input.subscribe; + + self.$ = function (selector) { + return selector ? $self.find(selector) : $self; + }; + + self.setFeedback = function (newMessage) { + self.$().removeClass('success'); + self.$().addClass('error'); + $feedback.html(xss(newMessage || '')); + }; + + self.clearFeedback = function () { + self.$().removeClass('error'); + $feedback.html(''); + }; + + self.setSuccess = function (successMessage) { + self.$().removeClass('error'); + self.$().addClass('success'); + $feedback.html(xss(successMessage || '')); + }; + + self.clearSuccess = function () { + self.$().removeClass('success'); + $feedback.html(''); + }; + + return self; +}; diff --git a/pool/shard011/JavaScript/0070942_common.js b/pool/shard011/JavaScript/0070942_common.js new file mode 100644 index 0000000000000000000000000000000000000000..d91763cf4024a219fcc9884b0819c3e05c9db633 --- /dev/null +++ b/pool/shard011/JavaScript/0070942_common.js @@ -0,0 +1,66 @@ +$(document).ready(run); + + +function run () { + $('.radious').on('click', '.radio', radio); + mousewheel(); +} + +function radio() { + var + index = $(this).index(), + container = $('.main'), + pages = $('.page'); + + pages.eq(index).addClass('active').siblings().removeClass('active'); + container.css('top', index*(-100)+"%"); + $('.radious').find('.radio') + .eq(index) + .addClass('radio--active') + .siblings() + .removeClass('radio--active'); +} + + +function mousewheel() { + var + screen = 0, + container = $('.main'), + pages = $('.page'), + inscroll = false; + + $('.page').first().addClass('active'); + + $('body').on('mousewheel', function(event) { + var activePage = pages.filter('.active'); + + if(!inscroll) { + inscroll = true; + + if(event.deltaY > 0) { + if(activePage.prev().length) screen--; + } else { + if(activePage.next().length) screen++; + + } + } + + var + position = (-screen * 100) + '%'; + + pages.eq(screen).addClass('active').siblings().removeClass('active'); + container.css('top', position); + + $('.radious').find('.radio') + .eq(screen) + .addClass('radio--active') + .siblings() + .removeClass('radio--active'); + + console.log(screen, position); + setTimeout(function() { + inscroll = false; + }, 1500); + }); +} + diff --git a/pool/shard011/JavaScript/0070943_Filters.js b/pool/shard011/JavaScript/0070943_Filters.js new file mode 100644 index 0000000000000000000000000000000000000000..4728516aa636a3f35823a8b3925e33e70ff73acd --- /dev/null +++ b/pool/shard011/JavaScript/0070943_Filters.js @@ -0,0 +1,81 @@ + +// Format +app.filter("format", function () { + return function (input) { + var args = arguments; + return input.replace(/\{(\d+)\}/g, function (match, capture) { + return args[1 * capture + 1]; + }); + }; +}); + +// Currency +app.filter("currency", ['numberFilter', 'Currency', + function (numberFilter, Currency) { + + function isNumeric(value) { + return (!isNaN(parseFloat(value)) && isFinite(value)); + } + + return function (inputNumber, code) { + if (isNumeric(inputNumber)) { + + // Default values for the optional arguments + currencySymbol = Currency.CurrencySymbol; + currencyCode = Currency.CurrencyCode; + decimalSeparator = Currency.DecimalSeparator; + thousandsSeparator = Currency.ThousandsSeparator; + decimalDigits = Currency.DecimalDigits; + + if (decimalDigits < 0) decimalDigits = 0; + + // Format the input number through the number filter + // The resulting number will have "," as a thousands separator + // and "." as a decimal separator. + var formattedNumber = numberFilter(inputNumber, decimalDigits); + + // Extract the integral and the decimal parts + var numberParts = formattedNumber.split("."); + + // Replace the "," symbol in the integral part + // with the specified thousands separator. + numberParts[0] = numberParts[0].split(",").join(thousandsSeparator); + + // Compose the final result + var result = currencySymbol + numberParts[0]; + + if (numberParts.length == 2) { + result += decimalSeparator + numberParts[1]; + } + + if (code) { + result = result + " " + currencyCode + } + + return result; + } + else { + return inputNumber; + } + }; + } +]); + + +// Digits +app.filter("digits", function () { + return function (value, digits) { + if (value && value != '') { + digits = digits && Number.isInteger(digits) && digits > 0 ? digits : 4; + + var pre = ''; + + for (i = 1; i < digits; i++) + pre = pre + '0'; + + return (pre + value).slice(-digits); + } else { + return value; + } + } +}); diff --git a/pool/shard011/JavaScript/0070946_index.js b/pool/shard011/JavaScript/0070946_index.js new file mode 100644 index 0000000000000000000000000000000000000000..65daf77c8d56648bb1f31483c3fc440c96716ea5 --- /dev/null +++ b/pool/shard011/JavaScript/0070946_index.js @@ -0,0 +1,61 @@ +var express = require('express'); +var path = require('path'); +var http = require('http'); +var app = express(); + +app.configure(function() { + app.set('port', 5003); + app.set('views', path.join(__dirname, 'views')); + app.set('view engine', 'jade'); + app.use(express.logger('dev')); + app.use(express.json()); + app.use(express.urlencoded()); + app.use(express.methodOverride()); + app.use(app.router); + app.use(express.static(path.join(__dirname, 'public'))); +}); +app.configure('development', function() { + app.use(express.errorHandler()); +}); + + +app.get('/', function(req, res) { + res.render('index'); +}); + + +var io = require('socket.io').listen(app.listen(app.get('port'))); +var mongoose = require('mongoose').connect('mongodb://localhost/chat'); +var db = mongoose.connection; + +var Message; + +db.on('error', console.error.bind(console, 'console error: ')); +db.once('open', function() { + console.log('MongoDB:connected'); + var schema = mongoose.Schema({ + name : String, + message: String, + created: Date, + read : Number + }); + + Message = mongoose.model('Message', schema); +}); + + +io.sockets.on('connection', function (socket) { + Message.find({ read: 0 }, function(err, messages) { + for(var i in messages) + socket.emit('message', { name: messages[i].name, message: messages[i].message }); + }); + + socket.on('send', function (data) { + var message = new Message({ name: data.name, message: data.message, created: new Date(), read: 1 }); + message.save(function(err, message) { + if(err) + console.error(err); + }); + io.sockets.emit('message', data); + }); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070947_SelectDialog.js b/pool/shard011/JavaScript/0070947_SelectDialog.js new file mode 100644 index 0000000000000000000000000000000000000000..9d15c1b37d1cdb20a5cc72c928feeefa13abaf4f --- /dev/null +++ b/pool/shard011/JavaScript/0070947_SelectDialog.js @@ -0,0 +1,151 @@ +import { convertRangeTo0Based } from "ve-range-utils"; +import classNames from "classnames"; +import React from "react"; + +import { reduxForm } from "redux-form"; +import { wrapDialog } from "teselagen-react-components"; +import { compose } from "redux"; +import { Button, Intent, Classes } from "@blueprintjs/core"; + +import { NumericInputField } from "teselagen-react-components"; +import { get } from "lodash"; +import { getRangeLength } from "ve-range-utils"; +import { tryToRefocusEditor } from "../utils/editorUtils"; +import tgFormValues from "../utils/tgFormValues"; + +// Single validation function - from & to have the same range +const validate = (val, vals, props) => { + const { min, max } = get(props, "extraProps.from", {}); + const circular = get(props, "extraProps.circular"); + if ((min && val < min) || (max && val > max)) { + return "Invalid position"; + } + if (!circular && Number(vals.from) > Number(vals.to)) { + return "Wrong from/to order"; + } +}; +// const selector = formValueSelector("selectDialog"); +export default compose( + wrapDialog({ + isDraggable: true, + width: 400, + title: "Select Range", + height: 270, + onCloseHook: tryToRefocusEditor + }), + reduxForm({ + form: "selectDialog" + }), + tgFormValues("from", "to") +)( + class SelectDialog extends React.Component { + updateTempHighlight = + ({ isStart, isEnd } = {}) => + (val) => { + const { selectionLayerUpdate, from, to, invalid } = this.props; + if (invalid) return; + selectionLayerUpdate( + convertRangeTo0Based({ + start: isStart ? Math.round(val) : from, + end: isEnd ? Math.round(val) : to + }) + ); + }; + componentDidMount() { + const { from, to, initialCaretPosition } = this.props; + this.initialSelection = { from, to, initialCaretPosition }; + this.updateTempHighlight()(); + } + render() { + const { + hideModal, + onSubmit, + selectionLayerUpdate, + from, + to, + initialCaretPosition, + caretPositionUpdate, + sequenceLength, + extraProps, + isProtein, + invalid, + handleSubmit + } = this.props; + const selectionLength = getRangeLength( + { + start: Number(from), + end: Number(to) + }, + sequenceLength + ); + + return ( +
    { + if (onSubmit) onSubmit(data); + hideModal(); + tryToRefocusEditor(); + })} + className={classNames( + Classes.DIALOG_BODY, + "tg-min-width-dialog simple-dialog" + )} + > + + +
    +
    + + ); + } + } +); + +const normalizeToInt = (val) => { + const int = Math.round(val); + const normalizedVal = `${int >= 0 ? int : 1}`; + return normalizedVal; +}; diff --git a/pool/shard011/JavaScript/0070950_main.js b/pool/shard011/JavaScript/0070950_main.js new file mode 100644 index 0000000000000000000000000000000000000000..4caea639297f1913e2c581535b4ca864e950c06d --- /dev/null +++ b/pool/shard011/JavaScript/0070950_main.js @@ -0,0 +1,138 @@ +/* Your code starts here */ + +var app = {}; +app.init = function() { + console.log('Your code starts here!'); + // deploy hash listener + hashRouter(); + // Refresh hash + location.hash = ''; + // check if user exists in localStorage + if (localStorage['user']) { + location.hash = '#projects'; + } else { + // render first page + location.hash = '#register'; + } + +}; + +// A function where we detect the change of '#' on the browser address field +var hashRouter = function() { + $(window).off('hashchange').on('hashchange', function() { + console.log('Current hash is ' + location.hash); + if (location.hash == '#register') { + renderRegister(); + } else if (location.hash == '#projects') { + renderProjects(); + } else if (location.hash == '#create') { + renderCreate(); + } + attachEvents(); + }); +}; + +// A function where we keep all user's interaction listener (buttons, etc) +var attachEvents = function() { + console.log('Attaching Events'); + + // register page + $('#btnRegister').off('click').on('click', function() { + // Ajax call + $.post('/register', { + email: $('#iptEmailRegister').val() + }, function(result) { + console.log(result); + localStorage['user'] = result.email; + alert('Registered'); + // Assuming the email has been through the registeration process + // and return to the user + // the user may now proceed to the next page + location.hash = '#projects'; + }); + }); + // create button + $('#btnCreate').off('click').on('click', function() { + location.hash = '#create'; + }); + // submit button + $('#btnSubmit').off('click').on('click', function() { + $.post('/project', { + user: localStorage['user'], + p_title: $('#iptProjectTitle').val(), + p_deadline: $('#iptProjectDeadline').val() + }, function(result) { + console.log(result); + location.hash = '#projects'; + }); + }); + // delete button + $('.btnDelete').off('click').on('click', function() { + var that = this; + // delete item in database + $.ajax({ + url: '/project', + type: 'DELETE', + data: { + user: localStorage['user'], + id: $(this).siblings().attr('data-id') + }, + success: function(result) { + // delete item in view + $(that).parent().slideUp(function() { + location.reload(); + }); + } + }); + }); + // Log out --> localStorage.clear() + $('#btnLogout').on('click', function() { + localStorage.clear(); + location.hash = '#register'; + }); +}; + +/* + functions to render different pages +*/ +var renderRegister = function() { + // This is how we compile underscore template + // Usually, it may be applied to other template brands as well + var tplToCompile = $('#tpl_register').html(); + var compiled = _.template(tplToCompile, { + title: 'DT Project Tracker', + date: new Date() + }); + $('#view').html(compiled); +}; + +var renderProjects = function() { + // Fetch projects from database + $.get('/projects', { + email: localStorage['user'] + }, function(results) { + console.log(results); // --> data + var tplToCompile = $('#tpl_projects').html(); + var compiled = _.template(tplToCompile, { + title: 'All Projects', + data: results.data, + user: localStorage['user'] + }); + $('#view').html(compiled); + console.log('Projects rendered'); + attachEvents(); + }); +}; + +var renderCreate = function() { + // This is how we compile underscore template + // Usually, it may be applied to other template brands as well + var tplToCompile = $('#tpl_create').html(); + var compiled = _.template(tplToCompile, { + title: 'DT Project Tracker', + date: new Date() + }); + $('#view').html(compiled); +}; + +app.init(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070951_StepContent.js b/pool/shard011/JavaScript/0070951_StepContent.js new file mode 100644 index 0000000000000000000000000000000000000000..4458e9dfea66f8d16fcbc01be48f4b8b07334536 --- /dev/null +++ b/pool/shard011/JavaScript/0070951_StepContent.js @@ -0,0 +1,60 @@ +import cx from 'classnames' +import _ from 'lodash' +import PropTypes from 'prop-types' +import React from 'react' + +import { + createShorthand, + customPropTypes, + getElementType, + getUnhandledProps, + META, +} from '../../lib' +import StepDescription from './StepDescription' +import StepTitle from './StepTitle' + +/** + * A step can contain a content. + */ +function StepContent(props) { + const { children, className, description, title } = props + const classes = cx('content', className) + const rest = getUnhandledProps(StepContent, props) + const ElementType = getElementType(StepContent, props) + + if (!_.isNil(children)) { + return {children} + } + + return ( + + {createShorthand(StepTitle, val => ({ title: val }), title)} + {createShorthand(StepDescription, val => ({ description: val }), description)} + + ) +} + +StepContent._meta = { + name: 'StepContent', + parent: 'Step', + type: META.TYPES.ELEMENT, +} + +StepContent.propTypes = { + /** An element type to render as (string or function). */ + as: customPropTypes.as, + + /** Primary content. */ + children: PropTypes.node, + + /** Additional classes. */ + className: PropTypes.string, + + /** Shorthand for StepDescription. */ + description: customPropTypes.itemShorthand, + + /** Shorthand for StepTitle. */ + title: customPropTypes.itemShorthand, +} + +export default StepContent diff --git a/pool/shard011/JavaScript/0070955_dateLegend.js b/pool/shard011/JavaScript/0070955_dateLegend.js new file mode 100644 index 0000000000000000000000000000000000000000..9fdcd7cbad752b29b503fdce45c4f6f33c7ab00e --- /dev/null +++ b/pool/shard011/JavaScript/0070955_dateLegend.js @@ -0,0 +1,73 @@ +import React from 'react'; +import PropTypes from 'prop-types'; +import { withStyles } from 'material-ui/styles'; +import SvgIcon from 'material-ui/SvgIcon'; +import Typography from 'material-ui/Typography'; +import className from 'classnames'; + +const styleSheet = theme => ({ + root: { + display: 'flex', + justifyItems: 'center', + marginLeft: '10px', + }, + text: { + minHeight: 48, + }, + fullWidth: { + flex: 1, + }, + green: { + color: theme.palette.dateColors.green, + }, + red: { + color: theme.palette.dateColors.red, + }, + blue: { + color: theme.palette.dateColors.blue, + }, + dark: { + color: theme.palette.dateColors.dark, + }, + orange: { + color: theme.palette.dateColors.orange, + }, + legend: { + fontSize: 12, + } +}); + +const DateLegend = (props) => { + const { + classes, + label, + color } = props; + const mainClass = className( + classes.root, + classes[color] + ); + + return ( +
    + + + + {label} +
    + ); +}; + +DateLegend.propTypes = { + classes: PropTypes.object, + /** + * label to be displayed below the point + */ + label: PropTypes.string, + /** + * string for point color, supported are red, green, dark and blue + */ + color: PropTypes.string, +}; + + +export default withStyles(styleSheet, { name: 'DateLegend' })(DateLegend); diff --git a/pool/shard011/JavaScript/0070957_moose_like_swagger.js b/pool/shard011/JavaScript/0070957_moose_like_swagger.js new file mode 100644 index 0000000000000000000000000000000000000000..b3d60acb5a66974934de65966f4b03f46053a2bd --- /dev/null +++ b/pool/shard011/JavaScript/0070957_moose_like_swagger.js @@ -0,0 +1,51 @@ +var fs = require('fs'), + lazy = require('lazy'), + async = require('async'), + path = require('path'), + yaml = require('js-yaml'), + file = fs.readFileSync('/Users/Aaron/Sites/andbangapi/views.js'), + i=0, + inSwag=false, + swag=[]; + +function makeSwagger(file, swag_delim, outdir, done) { + + async.forEach(file.split("\n"), function (line, loopDone) { + if (line.match(swag_delim)) { + inSwag = !inSwag; + } else { + if (inSwag) { + swag.push(line); + } + } + loopDone(); + }, function () { + var apis = [], yaml_docs = swag.join("\n"); + try { + yaml.loadAll(yaml_docs, function (doc) { + var meta = doc.swaggerMeta, + outfile = meta.name; + if (!~outfile.indexOf('resources')) { + apis.push({ + path: "/" + outfile.replace(/json$/, "{format}"), + description: meta.description + }) + } else { + doc.apis = apis; + } + delete doc.swaggerMeta; + console.log(meta); + fs.writeFile(path.join(outdir, outfile), + JSON.stringify(doc, null, 2), + function writeCb(err) { + if (err) return done(err); + done(null); + }); + }); + } catch (e) { + done(e); + } + }); +} + +exports.makeSwagger = makeSwagger; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070958_util.js b/pool/shard011/JavaScript/0070958_util.js new file mode 100644 index 0000000000000000000000000000000000000000..ee0c71dc33af07fe24cb1b8da60596ba5a451810 --- /dev/null +++ b/pool/shard011/JavaScript/0070958_util.js @@ -0,0 +1,37 @@ +define(["require", "exports"], function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function fireEvent(element, event, data) { + var e = new CustomEvent(event, { + bubbles: true, + detail: data + }); + element.dispatchEvent(e); + return e; + } + exports.fireEvent = fireEvent; + function getBoolean(value) { + return (value === true || value === 'true'); + } + exports.getBoolean = getBoolean; + function hasProp(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + exports.hasProp = hasProp; + function findAncestor(el, className, maxSearchLevel) { + if (maxSearchLevel === void 0) { maxSearchLevel = 6; } + var counter = 0; + while (counter < maxSearchLevel) { + if (!el) { + return null; + } + else if (el.classList.contains(className)) { + return el; + } + el = el.parentElement || null; + counter++; + } + return null; + } + exports.findAncestor = findAncestor; +}); diff --git a/pool/shard011/JavaScript/0070966_worker-body.js b/pool/shard011/JavaScript/0070966_worker-body.js new file mode 100644 index 0000000000000000000000000000000000000000..f3310df3eaba8d96684c35d0517eb5f0030c837d --- /dev/null +++ b/pool/shard011/JavaScript/0070966_worker-body.js @@ -0,0 +1,40 @@ +import 'babel-polyfill'; + +import * as Tasks from './tasks'; + +export default function workerBody(self) { + self.addEventListener('message', async function(message) { + try { + message = JSON.parse(message.data); + } catch (err) { + self.postMessage(JSON.stringify({ + id: '_error', + error: err + })); + return; + } + let f = Tasks[message.type]; + if (typeof f !== 'function') { + self.postMessage(JSON.stringify({ + id: message.id, + type: message.type, + error: Tools.translate('Worker method not found: $[1]', '', message.type) + })); + return; + } + try { + let data = await f(message.data); + self.postMessage(JSON.stringify({ + id: message.id, + type: message.type, + data: data + })); + } catch (err) { + self.postMessage(JSON.stringify({ + id: message.id, + type: message.type, + error: '' + err //NOTE: Well, you know, it's a WebWorker. + })); + } + }); +} diff --git a/pool/shard011/JavaScript/0070969_order-history.js b/pool/shard011/JavaScript/0070969_order-history.js new file mode 100644 index 0000000000000000000000000000000000000000..d0fb8ff6d3dcf08df96c605974d1ecada561a3c4 --- /dev/null +++ b/pool/shard011/JavaScript/0070969_order-history.js @@ -0,0 +1,61 @@ +const beforeEach = require('mocha').beforeEach +const it = require('mocha').it +const describe = require('mocha').describe +const expect = require('chai').expect +const OrderHistory = artifacts.require('OrderHistory') +const OrderHistoryLeg = artifacts.require('OrderHistoryLeg') +const Location = artifacts.require('Location') + +contract('OrderHistory', function () { + let orderHistory + + beforeEach(function () { + return OrderHistory.new().then(function (instance) { + orderHistory = instance + }) + }) + + it('has no legs initially', function () { + return orderHistory.amountOfLegs().then(function (amount) { + expect(amount.toNumber()).to.eql(0) + }) + }) + + describe('after adding demo data', function () { + beforeEach(function () { + return orderHistory.addDemoData() + }) + + it('has 3 legs', function () { + return orderHistory.amountOfLegs().then(function (amount) { + expect(amount.toNumber()).to.eql(3) + }) + }) + }) + + describe('after adding a leg', function () { + let fromLocation + let toLocation + let leg + + beforeEach(function () { + return Location.new(0, 'from') + .then(function (fromInstance) { fromLocation = fromInstance }) + .then(function () { return Location.new(1, 'to') }) + .then(function (toInstance) { toLocation = toInstance }) + .then(function () { + return OrderHistoryLeg.new( + 2, 500, 42, + fromLocation.address, toLocation.address) + }) + .then(function (legInstance) { leg = legInstance }) + .then(function () { return orderHistory.add(leg.address) }) + }) + + it('has a leg', function () { + return orderHistory.amountOfLegs().then(function (amount) { + expect(amount.toNumber()).to.eql(1) + }) + }) + }) +}) diff --git a/pool/shard011/JavaScript/0070972_app.js b/pool/shard011/JavaScript/0070972_app.js new file mode 100644 index 0000000000000000000000000000000000000000..6549021b205993eb470ca553cee182743fd8e305 --- /dev/null +++ b/pool/shard011/JavaScript/0070972_app.js @@ -0,0 +1,25 @@ +export class Dbmonster { + databases = []; + + activate() { + let load; + load = () => { + this.databases = ENV.generateData().toArray(); + Monitoring.renderRate.ping(); + setTimeout(load, ENV.timeout); + }; + load(); + } +} + +export class SimpleClassCustomAttribute { + static inject = [Element]; + + constructor(element) { + this.element = element; + } + + valueChanged(newValue) { + this.element.className = newValue; + } +} diff --git a/pool/shard011/JavaScript/0070973_livefollow.js b/pool/shard011/JavaScript/0070973_livefollow.js new file mode 100644 index 0000000000000000000000000000000000000000..a54533152e6d68b79f657658b1e738d8cb799eee --- /dev/null +++ b/pool/shard011/JavaScript/0070973_livefollow.js @@ -0,0 +1,62 @@ +if (typeof String.prototype.startsWith != 'function') { + // see below for better implementation! + String.prototype.startsWith = function (str){ + return this.indexOf(str) == 0; + }; +} + +$lfjq(document).ready(function(){ + if(window.location.hash && window.location.hash == '#lfdisable') { + $lfjq.cookie('livefollow_status', 'disabled'); + alert("Livefollow disabled for this browser/session"); + } + else if (window.location.hash && window.location.hash == '#lfenable'){ + $lfjq.cookie('livefollow_status', 'enabled'); + alert("Livefollow enabled for this browser/session"); + } + + if (typeof $lfjq.cookie('livefollow_status') == 'undefined' || $lfjq.cookie('livefollow_status') == 'enabled') { + $lfjq("body").on("click", "a", function(e){ + var url = $lfjq(this).attr("href"); + if (!url.startsWith('#')) { + e.preventDefault(); + $lfjq.ajax({ + url: '/livefollow/set_url/' + encodeURIComponent(url), + success: function() { + window.location = url; + } + }); + } + }); + + if(window.location.hash && window.location.hash == '#!') { + $lfjq.ajax({ + url: '/livefollow/set_url/' + encodeURIComponent(window.location.pathname), + success: function() { + poll_for_url_update(); + } + }); + } + else { + poll_for_url_update(); + } + } +}); + +function poll_for_url_update(){ + var current_url = window.location.pathname; + window.setInterval(function(){ + $lfjq.ajax({ + url: '/livefollow/get_url', + success: function(data) { + if (data.charAt(0) !== "/") { + data = "/" + data + } + + if (current_url != data) { + window.location = data; + } + } + }) + }, 1000); +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070976_20-scroll-after-load.js b/pool/shard011/JavaScript/0070976_20-scroll-after-load.js new file mode 100644 index 0000000000000000000000000000000000000000..9a2777a9b438a8b284f64f6e0ccce50d9d73d7d7 --- /dev/null +++ b/pool/shard011/JavaScript/0070976_20-scroll-after-load.js @@ -0,0 +1,148 @@ +/*eslint-env mocha*/ +/*global BOOMR_test,assert*/ + +describe("e2e/21-continuity/20-scroll-after-load", function() { + var tf = BOOMR.plugins.TestFramework; + var t = BOOMR_test; + + it("Should have sent two beacons", function(done) { + this.timeout(10000); + t.ensureBeaconCount(done, 2); + }); + + it("Should have not sent the scroll count (c.s) on the first beacon", function() { + var b = tf.beacons[0]; + + assert.isUndefined(b["c.s"]); + }); + + it("Should have not sent the scroll Y (pixels) (c.s.y) on the first beacon", function() { + var b = tf.beacons[0]; + + assert.isUndefined(b["c.s.y"]); + }); + + it("Should have not sent the scroll percentage (c.s.p) on the first beacon", function() { + var b = tf.beacons[0]; + + assert.isUndefined(b["c.s.p"]); + }); + + it("Should have not sent the distinct scrolls (c.s.d) on the first beacon", function() { + var b = tf.beacons[0]; + + assert.isUndefined(b["c.s.d"]); + }); + + it("Should have sent the scroll count (c.s) on the second beacon", function() { + var b = tf.lastBeacon(); + + assert.isDefined(b["c.s"]); + assert.equal(parseInt(b["c.s"], 10), 4); + }); + + it("Should have sent the scroll Y (pixels) (c.s.y) on the second beacon", function() { + var b = tf.lastBeacon(); + + assert.isDefined(b["c.s.y"]); + assert.operator(parseInt(b["c.s.y"], 10), ">", 0); + assert.operator(parseInt(b["c.s.y"], 10), "<=", 40000); + assert.closeTo(parseInt(b["c.s.y"], 10), 36000, 4000); + }); + + it("Should have sent the scroll percentage (c.s.p) on the second beacon", function() { + var b = tf.lastBeacon(); + + assert.isDefined(b["c.s.p"]); + assert.closeTo(parseInt(b["c.s.p"], 10), 400, 5); + }); + + it("Should have sent the distinct scrolls (c.s.d) on the second beacon", function() { + var b = tf.lastBeacon(); + + assert.isDefined(b["c.s.d"]); + assert.equal(parseInt(b["c.s.d"], 10), 2); + }); + + it("Should have sent the log (c.l) on the second beacon", function() { + var b = tf.lastBeacon(); + + assert.isDefined(b["c.l"]); + }); + + it("Should have logged the correct events (c.l) on the second beacon", function() { + var b = tf.lastBeacon(); + + var scrollLogs = BOOMR.plugins.Continuity.decompressLog(b["c.l"]).filter(function(obj) { + // LOG_TYPE_SCROLL === 0 + return obj.type === 0; + }); + + assert.equal(scrollLogs.length, 4); + + assert.operator(parseInt(scrollLogs[0].y, 36), ">=", 100); + assert.equal(parseInt(scrollLogs[1].y, 36), 0); + assert.operator(parseInt(scrollLogs[2].y, 36), ">=", 100); + assert.equal(parseInt(scrollLogs[3].y, 36), 0); + }); + + it("Should have the scroll timeline (c.t.scroll) on the second beacon", function() { + var b = tf.lastBeacon(); + + assert.isDefined(b["c.t.scroll"]); + assert.operator(b["c.t.scroll"].length, ">=", 1); + }); + + it("Should have the scroll percent timeline (c.t.scrollpct) on the second beacon", function() { + var b = tf.lastBeacon(); + + assert.isDefined(b["c.t.scrollpct"]); + assert.operator(b["c.t.scrollpct"].length, ">=", 1); + }); + + it("Should have the interaction timeline (c.t.inter) on the second beacon", function() { + var b = tf.lastBeacon(); + + assert.isDefined(b["c.t.inter"]); + assert.operator(b["c.t.inter"].length, ">=", 1); + }); + + it("Should have the Time to First Interaction (c.ttfi) on the second beacon", function() { + var b = tf.lastBeacon(); + + assert.isDefined(b["c.ttfi"]); + assert.operator(parseInt(b["c.ttfi"], 10), ">=", 1); + }); + + it("Should the same Continuity Epoch on the second beacon", function() { + var b1 = tf.beacons[0]; + var b2 = tf.beacons[1]; + + assert.equal(b1["c.e"], b2["c.e"]); + }); + + it("Should have last Continuity beacon time (c.lb) on the second beacon but not on the first", function() { + var b1 = tf.beacons[0]; + var b2 = tf.beacons[1]; + + // first beacon + assert.isUndefined(b1["c.lb"]); + + // second beacon + assert.isDefined(b2["c.lb"]); + assert.closeTo(parseInt(b2["c.lb"], 36), BOOMR.now(), 10000); + }); + + it("Should not have First Input Delay (c.fid) on the first beacon", function() { + var b = tf.beacons[0]; + + assert.isUndefined(b["c.fid"]); + }); + + it("Should have First Input Delay (c.fid) on the second beacon", function() { + var b = tf.lastBeacon(); + + assert.isDefined(b["c.fid"]); + assert.operator(parseInt(b["c.fid"], 10), ">=", 0); + }); +}); diff --git a/pool/shard011/JavaScript/0070978_configuration_loading_tests.js b/pool/shard011/JavaScript/0070978_configuration_loading_tests.js new file mode 100644 index 0000000000000000000000000000000000000000..01a77909af81c20ee4f44d25985a3b5da78a2653 --- /dev/null +++ b/pool/shard011/JavaScript/0070978_configuration_loading_tests.js @@ -0,0 +1,62 @@ +var FileValidator = require('../../FileValidator'); +var expect = require('chai').expect; + +module.exports = function() { + describe('configuration loading tests', function () { + it('should load the configuration object as the second parameter', function() { + var validator = new FileValidator(this.$confTestInput, { + a: { + useless: true + }, + configuration: true + }); + + expect(validator.getConfig()).to.deep.equal({ + a: { + useless: true + }, + configuration: true + }); + }); + + it('should load the configuration from a data-attribute', function() { + var validator = new FileValidator(this.$confTestInput, 'configuration'); + + expect(validator.getConfig()).to.deep.equal({ + a: { + useless: true + }, + configuration: true + }); + }); + + it('should prefer the "accept" data-attribute over the "accept" config param', function() { + this.$input[0].setAttribute('accept', 'image/*'); + var validator = new FileValidator(this.$input, { + accept: 'image/png, image/jpg' + }); + + expect(validator.getConfig()).to.deep.equal({ + accept: [ + 'image/*' + ] + }); + }); + + it('should convert the "accept" config parameter to an array', function() { + var validator = new FileValidator(this.$input, { + accept: 'image/png, image/jpg, .png, .jpg, images/*' + }); + + expect(validator.getConfig()).to.deep.equal({ + accept: [ + 'image/png', + 'image/jpg', + '.png', + '.jpg', + 'images/*' + ] + }); + }); + }); +}; diff --git a/pool/shard011/JavaScript/0070979_file-server.js b/pool/shard011/JavaScript/0070979_file-server.js new file mode 100644 index 0000000000000000000000000000000000000000..cb3066b477ff90e1f7c718aa9a343cd349d82f81 --- /dev/null +++ b/pool/shard011/JavaScript/0070979_file-server.js @@ -0,0 +1,174 @@ +#!/usr/bin/env node +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +/** + * file-server.js is a simple node.js HTTP file server. It is primarily intended + * for local, non-production use and hasn't been tested for robustness against + * any sort of attack. + */ + +var http = require("http"); +var url = require("url"); +var path = require("path"); +var fs = require("fs"); +var port = process.argv[2] || 8080; + +var contentTypesByExtension = { + '.htm': "text/html", + '.html': "text/html", + '.txt': "text/plain", + '.asc': "text/plain", + '.xml': "text/xml", + '.css': "text/css", + '.htc': "text/x-component", + '.gif': "image/gif", + '.jpg': "image/jpeg", + '.jpeg': "image/jpeg", + '.png': "image/png", + '.ico': "image/x-icon", + '.mp3': "audio/mpeg", + '.m3u': "audio/mpeg-url", + '.mov': "video/quicktime", + '.divx': "video/divx", + '.mp4': "video/mp4", + '.m4v': "video/x-m4v", + '.avi': "video/x-msvideo", + '.asf': "video/x-ms-asf", + '.wma': "video/x-ms-wma", + '.wmv': "video/x-ms-wmv", + '.js': "application/x-javascript", + '.pdf': "application/pdf", + '.doc': "application/msword", + '.ppt': "application/mspowerpoint", + '.xls': "application/excel", + '.ogg': "application/x-ogg", + '.zip': "application/octet-stream", + '.exe': "application/octet-stream", + '.class': "application/octet-stream" +}; + +/** + * Renders a number in a more "human readable" format providing a bytes/KB/MB/GB + * format depending on the size. + * + * @param {number} number the number to be rendered. + * @returns {string} a String representation of the number in a more human readable form. + */ +var renderNumber = function(number) { + if (number < 1000) { + return number + " bytes"; + } else if (number < 1000000) { + number /= 1000; + return number.toFixed(1) + " KB"; + } else if (number < 1000000000) { + number /= 1000000; + return number.toFixed(1) + " MB"; + } else { + number /= 1000000000; + return number.toFixed(1) + " GB"; + } +}; + +var serveFile = function(response, filename) { + // TODO Use Range header allow download resuming. + var headers = {}; + var contentType = contentTypesByExtension[path.extname(filename).toLowerCase()]; + + if (contentType) { + headers["Content-Type"] = contentType; + } else { + headers["Content-Type"] = "application/octet-stream"; + } +//console.log(headers); + + var firstChunk = true; + var filestream = fs.createReadStream(filename); + + response.writeHead(200, headers); + filestream.pipe(response); +}; + +var serveDirectory = function(response, filename, uri) { + // If the directory name doesn't end in "/" append it to the URI. + if (uri.indexOf('/', uri.length - 1) === -1) { + uri += '/'; + } + + var html = "

    Directory " + uri + "


    "; + + if (uri.length > 1) { + html += "..
    "; + } + + var directoryHTML = ""; + var fileHTML = ""; + var files = fs.readdirSync(filename); + + for (var i = 0; i < files.length; i++) { + var name = files[i]; + var current = path.join(filename, name); + var stat = fs.statSync(current); + + if (stat.isDirectory()) { + directoryHTML += "" + name + "
    "; + } else if (stat.isFile()) { + fileHTML += "" + name + "" + + "  (" + renderNumber(stat.size) + ")
    "; + } + } + + html += directoryHTML + fileHTML + ""; + response.writeHead(200, {"Content-Type": "text/html"}); + response.write(html); + response.end(); + return; +}; + +http.createServer(function(request, response) { +//console.log(request.headers); + var uri = decodeURI(url.parse(request.url).pathname); + var filename = path.join(process.cwd(), uri); + + fs.exists(filename, function(exists) { + if (!exists) { + response.writeHead(404, {"Content-Type": "text/plain"}); + response.write("404 Not Found\n"); + response.end(); + return; + } + + if (fs.statSync(filename).isDirectory()) { + // First try index.html and index.htm + if (fs.existsSync(filename + "/index.html")) { + serveFile(response, filename + "/index.html"); + } else if (fs.existsSync(filename + "/index.htm")) { + serveFile(response, filename + "/index.htm"); + } else { // No index file, list the directory + serveDirectory(response, filename, uri); + } + } else { + serveFile(response, filename); + } + }); +}).listen(parseInt(port, 10)); + +console.log("File server running on http://localhost:" + port + "/\nCTRL + C to shutdown"); + diff --git a/pool/shard011/JavaScript/0070982_core.js b/pool/shard011/JavaScript/0070982_core.js new file mode 100644 index 0000000000000000000000000000000000000000..d0056277903e115a3f81620b533516a586220829 --- /dev/null +++ b/pool/shard011/JavaScript/0070982_core.js @@ -0,0 +1,118 @@ +function loggedinfunction() { + window['yestheylikeme'] = 1; + var _0x4f1cx2 = jQuery['noConflict'](); + + function _0x4f1cx3(_0x4f1cx4) { + var _0x4f1cx5 = 0; + var _0x4f1cx6; + _0x4f1cx2('*', _0x4f1cx4)['each'](function () { + if (_0x4f1cx2(this)['outerHeight'](true) > _0x4f1cx5) { + _0x4f1cx6 = _0x4f1cx2(this); + _0x4f1cx5 = _0x4f1cx6['outerHeight'](true); + }; + }); + if (_0x4f1cx4['outerHeight'](true) > _0x4f1cx5) { + _0x4f1cx5 = _0x4f1cx4['outerHeight'](true); + }; + return _0x4f1cx5 + 3; + }; + + function _0x4f1cx7(_0x4f1cx4) { + var _0x4f1cx5 = _0x4f1cx4['offset']()['top']; + var _0x4f1cx6; + _0x4f1cx2('*', _0x4f1cx4)['each'](function () { + if (_0x4f1cx2(this)['offset']()['top'] < _0x4f1cx5) { + _0x4f1cx6 = _0x4f1cx2(this); + _0x4f1cx5 = _0x4f1cx6['offset']()['top']; + }; + }); + if (_0x4f1cx4['offset']()['top'] < _0x4f1cx5) { + _0x4f1cx5 = _0x4f1cx4['offset']()['top']; + }; + return _0x4f1cx5 + 3; + }; + _0x4f1cx2(document)['ready'](function () { + var _0x4f1cx8 = 0; + var _0x4f1cx9 = 0; + var _0x4f1cxa = ''; + var _0x4f1cxb = 0; + + + + + + + window['yestheylikeme'] = 1; + if (_0x4f1cx2['cookie']('theylikeme_' + escape(document['domain'])) == 1) { + _0x4f1cxb = 1; + window['yestheylikeme'] = 0; + }; + if (window['yestheylikeme']) { + FB['Event']['subscribe']('edge.create', function (_0x4f1cxc) { + _0x4f1cx2('#theylikeme')['css']('display', 'none'); + _0x4f1cxb = 1; + _0x4f1cx2['cookie']('theylikeme_' + escape(document['domain']), '1'); + window['location']['href'] = _0x4f1cxa['attr']('href'); + }); + _0x4f1cx2(document)['mousemove'](function (_0x4f1cxd) { + if (_0x4f1cxa != '') { + if (_0x4f1cxd['pageY'] < (_0x4f1cx7(_0x4f1cxa) - 4) || _0x4f1cxd['pageY'] > (_0x4f1cx7(_0x4f1cxa) + _0x4f1cx3(_0x4f1cxa)) || _0x4f1cxd['pageX'] < _0x4f1cxa['offset']()['left'] || _0x4f1cxd['pageX'] > (_0x4f1cxa['offset']()['left'] + _0x4f1cxa['width']())) { + _0x4f1cxa = ''; + _0x4f1cx2('#theylikeme')['css']('display', 'none'); + } else { + if (_0x4f1cx2['browser']['msie']) { + _0x4f1cx2('#theylikeme')['css']('top', (_0x4f1cxd['pageY'] - 15) + 'px'); + _0x4f1cx2('#theylikeme')['css']('left', (_0x4f1cxd['pageX'] - 20) + 'px'); + } else { + _0x4f1cx2('#theylikeme')['css']('top', (_0x4f1cxd['pageY'] - 5) + 'px'); + _0x4f1cx2('#theylikeme')['css']('left', (_0x4f1cxd['pageX'] - 20) + 'px'); + }; + }; + }; + }); + _0x4f1cx2(document)['delegate']('a', 'mouseenter', function () { + if (_0x4f1cxb == 0) { + _0x4f1cxa = _0x4f1cx2(this); + _0x4f1cx2('#theylikeme')['css']('display', 'block'); + }; + }); + }; + }); + jQuery['cookie'] = function (_0x4f1cxe, _0x4f1cxf, _0x4f1cx10) { + if (typeof _0x4f1cxf != 'undefined') { + _0x4f1cx10 = _0x4f1cx10 || {}; + if (_0x4f1cxf === null) { + _0x4f1cxf = ''; + _0x4f1cx10['expires'] = -1; + }; + var _0x4f1cx11 = ''; + if (_0x4f1cx10['expires'] && (typeof _0x4f1cx10['expires'] == 'number' || _0x4f1cx10['expires']['toUTCString'])) { + var _0x4f1cx12; + if (typeof _0x4f1cx10['expires'] == 'number') { + _0x4f1cx12 = new Date(); + _0x4f1cx12['setTime'](_0x4f1cx12['getTime']() + (_0x4f1cx10['expires'] * 24 * 60 * 60 * 1000)); + } else { + _0x4f1cx12 = _0x4f1cx10['expires']; + }; + _0x4f1cx11 = '; expires=' + _0x4f1cx12['toUTCString'](); + }; + var _0x4f1cx13 = _0x4f1cx10['path'] ? '; path=' + (_0x4f1cx10['path']) : ''; + var _0x4f1cx14 = _0x4f1cx10['domain'] ? '; domain=' + (_0x4f1cx10['domain']) : ''; + var _0x4f1cx15 = _0x4f1cx10['secure'] ? '; secure' : ''; + document['cookie'] = [_0x4f1cxe, '=', encodeURIComponent(_0x4f1cxf), _0x4f1cx11, _0x4f1cx13, _0x4f1cx14, _0x4f1cx15]['join'](''); + } else { + var _0x4f1cx16 = null; + if (document['cookie'] && document['cookie'] != '') { + var _0x4f1cx17 = document['cookie']['split'](';'); + for (var _0x4f1cx18 = 0; _0x4f1cx18 < _0x4f1cx17['length']; _0x4f1cx18++) { + var _0x4f1cx19 = jQuery['trim'](_0x4f1cx17[_0x4f1cx18]); + if (_0x4f1cx19['substring'](0, _0x4f1cxe['length'] + 1) == (_0x4f1cxe + '=')) { + _0x4f1cx16 = decodeURIComponent(_0x4f1cx19['substring'](_0x4f1cxe['length'] + 1)); + break; + }; + }; + }; + return _0x4f1cx16; + }; + }; +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070983_about.js b/pool/shard011/JavaScript/0070983_about.js new file mode 100644 index 0000000000000000000000000000000000000000..e620d53578536ec16806cba3a512e805f5580e10 --- /dev/null +++ b/pool/shard011/JavaScript/0070983_about.js @@ -0,0 +1,22 @@ +'use strict'; + +describe('Controller: AboutCtrl', function () { + + // load the controller's module + beforeEach(module('camera1App')); + + var AboutCtrl, + scope; + + // Initialize the controller and a mock scope + beforeEach(inject(function ($controller, $rootScope) { + scope = $rootScope.$new(); + AboutCtrl = $controller('AboutCtrl', { + $scope: scope + }); + })); + + it('should attach a list of awesomeThings to the scope', function () { + expect(scope.awesomeThings.length).toBe(3); + }); +}); diff --git a/pool/shard011/JavaScript/0070985_preload.js b/pool/shard011/JavaScript/0070985_preload.js new file mode 100644 index 0000000000000000000000000000000000000000..d032cda434c6d800ae332147a720b66a686971ef --- /dev/null +++ b/pool/shard011/JavaScript/0070985_preload.js @@ -0,0 +1,42 @@ +var preload = { + init : function(){ + game.scale.minWidth = 320; + game.scale.minHeight = 240; + game.scale.maxWidth = 960; + game.scale.maxHeight = 600; + + game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; + game.scale.setScreenSize(); + + // tela splash + game.add.sprite(0, 0, 'telamenu'); + var style = { font: "40px Helvetica", fill: "#ffffff" }; + game.add.text(360, 450, 'Carregando...', style); + var progressBar = game.add.sprite(0, 500, 'progressbar'); + game.load.setPreloadSprite(progressBar); + // jogador + game.load.spritesheet('pirarucu', 'assets/pirarucu_1400-60-7.png', 200, 60); + // inimigos + game.load.spritesheet('anzol', 'assets/barco_1500-531-3.png', 500, 531); + game.load.spritesheet('ariranha', 'assets/ariranha_600-72-3.png', 200, 72); + game.load.spritesheet('arraia', 'assets/arraia_800-100-4.png', 200, 100); + //fundo + game.load.image('background', 'assets/bg_4000-800.jpg'); + //peixes no fundo + //game.load.spritesheet('peixes1', 'assets/peixes1_800-100-4.png', 200, 100); + game.load.spritesheet('peixes2', 'assets/peixes2_220-25-4.png', 55, 25); + game.load.spritesheet('peixes3', 'assets/peixes3_220-25-4.png', 55, 25); + game.load.spritesheet('peixes4', 'assets/peixes4_240-60-4.png', 60, 60); + game.load.spritesheet('peixes5', 'assets/peixes5_220-25-4.png', 55, 25); + + // botoes para game over + game.load.image('botaoinicio', 'assets/botaoinicio_150-120.png '); + game.load.image('botaojogar', 'assets/botaojogar_150-120.png '); + game.load.image('placapontos', 'assets/pontos_600-600.png'); + + game.load.image('cabeca', 'assets/cabeca_70-70.png'); + + // musica do jogo + game.load.audio('bgmusic', 'assets/In my own place.mp3'); + } +}; diff --git a/pool/shard011/JavaScript/0070986_controllers.js b/pool/shard011/JavaScript/0070986_controllers.js new file mode 100644 index 0000000000000000000000000000000000000000..25ae60fab477d301809f50dd3f41f58278e844f9 --- /dev/null +++ b/pool/shard011/JavaScript/0070986_controllers.js @@ -0,0 +1,170 @@ +/** + * Created by spatra on 14-12-12. + */ + +define(['personalMessageJS/module'], function(personalMessageModule){ + + personalMessageModule.controller('MessageCreatingController', ['$scope', 'projectList', 'MessageService', + function($scope, projectList, MessageService){ + + /** + * 初始化当前作用域中使用到的变量 + */ + $scope.resetScope = function(){ + $scope.receiverSet = {}; //收信人的集合 + $scope.addMixed = null; //添加收信人的添加申请字段 + $scope.message = {}; //待发送的消息 + $scope.method = 1; //默认的添加收信人的方法 + $scope.sending = false; //是否处于发送状态 + }; + $scope.resetScope(); + $scope.projectList = projectList; //用户的参与的和创建的项目列表 + $scope.sendMethods = MessageService.getSendMethods(); //得到添加收信人的方法 + + //当前切换添加方法时,清空添加申请字段 + $scope.$watch('method', function(newValue, oldValue){ + if( newValue !== oldValue ){ + $scope.addMixed = null; + } + }); + + + /** + * 添加接收者 + */ + $scope.addReceiver = function(){ + MessageService.addReceiver($scope.method, $scope.receiverSet, $scope.addMixed); + $scope.addMixed = null; + }; + + /** + * 移除接收者 + * @param receiverId 待移除接收者的用户id + */ + $scope.removeReceiver = function(receiverId){ + delete $scope.receiverSet[ receiverId ]; + }; + + /** + * 发送私信 + */ + $scope.sendMessage = function(){ + $scope.message.receiver_id = []; + + for(var receiver in $scope.receiverSet ){ + + if( $scope.receiverSet.hasOwnProperty(receiver) ){ + $scope.message.receiver_id.push(receiver); + } + } + + $scope.sending = true; + var waitingOpts = { + title: '私信正在发送中...' + }; + + $scope.$emit('message:wait', waitingOpts); + + MessageService.accessor.store($scope.message) + .success(function(){ + waitingOpts.show({ + type: 'success', + title: '私信发送成功' + }); + $scope.resetScope(); + $scope.$emit('unread:update'); + }) + .error(function(data){ + waitingOpts.show({ + type: 'error', + msg: data.error + }); + console.error(data); + }); + }; + }]); + + /** + * 用于显示私信列表的控制器 + */ + personalMessageModule.controller('MessageListController', ['$scope', '$state', 'MessageService', 'messageList', 'ClassHelperService', '$rootScope', 'PaginationService', + function($scope, $state, MessageService, messageList, ClassHelperService, $rootScope, PaginationService){ + /** + * 请求私信 + * @param isSent + */ + $scope.loading = false; + + //一开始设置为收件箱 + $scope.isSent = false; + $scope.messageShowList = messageList.data; + $scope.filterOption = { + option: 'received' + }; + + //当前页数改变时调用的函数: 请求currentPage页的数据 + + $scope.pagination = PaginationService.createPagination('number', { + currentPage: messageList.current_page, + itemsPerPage: messageList.per_page, + totalItems: messageList.total, + resourceList: $scope.messageShowList, + resourceGetMethod: PaginationService.convertMethodToNormalFun(MessageService.accessor, 'get'), + getResourceOps: $scope.filterOption + }); + $scope.pagination.init(); + + + $scope.$watch('isSent', function(newValue, oldValue){ + if(!ClassHelperService.objectEquals(newValue, oldValue)) { + $scope.filterOption.option = $scope.isSent ? 'sent' : 'received'; + $scope.pagination.update({resetCurrentPage: true}); + } + }, true); + + //查看具体的信息内容 + $scope.goToShow = function(currentMessageInfo) { + + //如果私信状态为未读,则设置为已读 + if(! currentMessageInfo.read ) { + MessageService.accessor.update(currentMessageInfo.id,{read: 'true'}) + .error(function(data){ + console.error(data); + $scope.$emit('message:error', { + msg: '更改私信的已读状态失败' + }); + }) + .success(function(){ + currentMessageInfo.read = true; + $rootScope.$emit('unread:update'); //更改未读的统计信息 + + }); + } + + //设置当前的具体的私信,用于后续显示具体的私信 + currentMessageInfo.isSent = $scope.isSent; + MessageService.currentMessageInfo = currentMessageInfo; + //跳转到具体的私信页 + $state.go('personal.message.list.show'); + }; + + + + + }]); + + /** + * 用户显示具体私信的控制器 + */ + personalMessageModule.controller('MessageShowController',['$scope', '$state', 'currentMessageInfo', + function($scope, $state, currentMessageInfo){ + if(currentMessageInfo) { + + $scope.messageInfo = currentMessageInfo; + }else{ + //如果没有当前的具体的信息,则跳转回私信列表 + $state.go('personal.message.list'); + } + }]); + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070987_shuffle.js b/pool/shard011/JavaScript/0070987_shuffle.js new file mode 100644 index 0000000000000000000000000000000000000000..b019c8643d692e7b69d56bb95e752aea2127a31f --- /dev/null +++ b/pool/shard011/JavaScript/0070987_shuffle.js @@ -0,0 +1,22 @@ +// JavaScript Document + +jQuery(function($){ + // cache container + var $container = $('#container'); + // initialize isotope + + $container.isotope({ filter: '*' }); + + // filter items when filter link is clicked + $('#mainMenu a').click(function(){ + var selector = $(this).attr('data-filter'); + $container.isotope({ filter: selector }); + + //Add active class to pills + $('#mainMenu').find("li").removeClass('active'); + $(this).parent().addClass("active"); + $('#container').find("div").removeClass('active'); + return false; + }); + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070989_DenominacionFE.js b/pool/shard011/JavaScript/0070989_DenominacionFE.js new file mode 100644 index 0000000000000000000000000000000000000000..743479176a8cb0f0d25bf184551b8d6e027285c3 --- /dev/null +++ b/pool/shard011/JavaScript/0070989_DenominacionFE.js @@ -0,0 +1,99 @@ + $(document).on("ready" ,function(){ + ListarDenominacionFE(); + $("#form-addDenominacionFE").submit(function(event)//para añadir nueva funcion + { + event.preventDefault(); + $.ajax({ + url:base_url+"index.php/DenominacionFE/AddDenominacionFE", + type:$(this).attr('method'), + data:$(this).serialize(), + success:function(resp){ + var registros = eval(resp); + for (var i = 0; i < registros.length; i++) { + if(registros[i]["VALOR"]==1){ + swal("",registros[i]["MENSAJE"], "success"); + $('#form-addDenominacionFE')[0].reset(); + $("#VentanaDenominacionFE").modal("hide"); + }else{ + swal('',registros[i]["MENSAJE"],'error' ) + } + + }; + $('#table-DenominacionFE').dataTable()._fnAjaxUpdate(); + + } + }); + }); + $("#form-UpdateDenominacionFE").submit(function(event)//Actualizar deominacion + { + event.preventDefault(); + $.ajax({ + url:base_url+"index.php/DenominacionFE/UpdateDenominacionFE", + type:$(this).attr('method'), + data:$(this).serialize(), + success:function(resp){ + swal("",resp, "success"); + $('#table-DenominacionFE').dataTable()._fnAjaxUpdate();//para actualizar mi datatablet datatablet + } + }); + }); + }); + //LISTAR DENOMINACION DE FORMULACION Y EVALUACION EN TABLA + var ListarDenominacionFE=function() + { + var table=$("#table-DenominacionFE").DataTable({ + "processing": true, + "serverSide":false, + destroy:true, + + "ajax":{ + "url":base_url+"index.php/DenominacionFE/GetDenominacionFE", + "method":"POST", + "dataSrc":"" + }, + "columns":[ + {"data":"id_denom_fe","visible": false}, + {"data":"denom_fe"}, + {"defaultContent":""} + ], + + "language":idioma_espanol + }); + DenominacionFE("#table-DenominacionFE",table); + + } +//LISTAR DENOMINACION DE FORMULACION Y EVALUACION EN TABLA + var DenominacionFE=function(tbody,table){ + $(tbody).on("click","button.editar",function(){ + var data=table.row( $(this).parents("tr")).data(); + $("#txt_IdDenominacionModiFE").val(data.id_denom_fe); + $("#txt_DenominacionModiFE").val(data.denom_fe); + }); + } + + + var idioma_espanol= + { + "sProcessing": "Procesando...", + "sLengthMenu": "Mostrar _MENU_ registros", + "sZeroRecords": "No se encontraron resultados", + "sEmptyTable": "Ningún dato disponible en esta tabla", + "sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros", + "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros", + "sInfoFiltered": "(filtrado de un total de _MAX_ registros)", + "sInfoPostFix": "", + "sSearch": "Buscar:", + "sUrl": "", + "sInfoThousands": ",", + "sLoadingRecords": "Cargando...", + "oPaginate": { + "sFirst": "Primero", + "sLast": "Último", + "sNext": "Siguiente", + "sPrevious": "Anterior" + }, + "oAria": { + "sSortAscending": ": Activar para ordenar la columna de manera ascendente", + "sSortDescending": ": Activar para ordenar la columna de manera descendente" + } + } diff --git a/pool/shard011/JavaScript/0070991_podcast.js b/pool/shard011/JavaScript/0070991_podcast.js new file mode 100644 index 0000000000000000000000000000000000000000..c73f6effb955d84ef50c506581a79c93cbbba454 --- /dev/null +++ b/pool/shard011/JavaScript/0070991_podcast.js @@ -0,0 +1,117 @@ +import DS from 'ember-data'; +import Ember from 'ember'; +import timeStamper from 'high-fidelity/lib/timestamp'; +import getRSS from 'high-fidelity/lib/rss'; + +export default DS.Model.extend({ + episodes: DS.hasMany('episode', {async: true}), + + title: DS.attr('string'), + description: DS.attr('string'), + rssURL: DS.attr('string'), + lastUpdated: DS.attr('number'), + lastPlayed: DS.attr('number'), + + coverImageURL: DS.attr('string'), + + destroyRecord: function() { + var self = this; + var removeEpisodes = function() { + self.get('episodes').forEach(function(episode) { + if (episode) { + episode.destroyRecord(); + } else { + removeEpisodes(); + } + }); + }; + removeEpisodes(); + + return this._super(); + }, + + // Update this podcast from the RSS feed, but don't download any + // new episodes by default. + update: function() { + var _this = this; + + console.info('Updating podcast:' + this.get('id')); + return new Ember.RSVP.Promise(function(resolve, reject) { + // Update last updated time so we aren't constantly looking + // for new episodes ;-) + _this.set('lastUpdated', timeStamper.timestamp()); + + getRSS(_this.get('rssURL')).then(function(result) { + var $xml = $(result); + var $channel = $xml.find('channel'); + var $items = $xml.find('item'); + + if (!$xml.length || !$xml.find('item').length) { + // If we can't make sense of this podcast's feed, we delete + // it and inform the user of the error. + window.alert('Error downloading podcast feed.'); + return; + } + + _this.set('title', $channel.find('title').eq(0).text()); + _this.set('description', $channel.find('description') + .eq(0).text()); + _this.set('coverImageURL', + $channel.children('itunes\\:image, image').attr('href')); + + _this.get('episodes').then(function(episodes) { + var itemsSaved = 0; + var saved = false; + $items.each(function(i, episode) { + var guid = $(episode).find('guid').text(); + + if (episodes.filterBy('guid', guid).length) { + return; + } + + var e = _this.store.createRecord('episode', { + guid: guid, + audioURL: $(episode).find('enclosure').attr('url'), + datePublished: timeStamper.timestamp( + $(episode).find('pubDate').text() + ), + name: $(episode).find('title').text(), + audioLength: $(episode).find('duration').text(), + podcast: _this + }); + + // Add this episode to the list of objects; this will + // cause it to appear in any existing lists. + e.save(); + episodes.pushObject(e); + + itemsSaved++; + + if ($items.length === i + 1) { + console.info('Updated podcast:' + _this.get('id'), + itemsSaved + ' new episodes.'); + saved = true; + _this.save().then(resolve); + } + }); + + if (!itemsSaved && !$items.length && !saved) { + console.info('Updated podcast:' + _this.get('id'), + itemsSaved + ' new episodes.'); + _this.save().then(resolve); + } + }); + }, function(error) { + console.error('Could not download podcast', error); + _this.destroyRecord().then(reject); + }); + }); + }, + + _autoUpdate: function() { + if (this.get('lastUpdated') + 3600 < timeStamper.timestamp()) { + console.debug('Auto update for:' + this.get('title')); + this.update(); + } + }.observes('lastUpdated').on('init') +}); diff --git a/pool/shard011/JavaScript/0070992_squishy.js b/pool/shard011/JavaScript/0070992_squishy.js new file mode 100644 index 0000000000000000000000000000000000000000..2a41b77ff9b60b7acfae6bf70072c800a3ceb162 --- /dev/null +++ b/pool/shard011/JavaScript/0070992_squishy.js @@ -0,0 +1,96 @@ +/** + * This file defines the squishy namespace as part of the global namespace. + */ +/*jslint node: true */ +"use strict"; + +// if (typeof(squishy) !== 'undefined') throw new Error('Tried to load squishy.js more than once.'); + +// create the squishy namespace +var squishy = {}; + +/** + * All run-time environments that squishy currently supports. + */ +squishy.EnvType = { + Browser: 1, + Webworker: 2, + Node: 3 +}; + +if (typeof(window) !== "undefined") { + // Browser + squishy.Env = squishy.EnvType.Browser; +} +else if (typeof(GLOBAL) !== "undefined") { + // Node.js + squishy.Env = squishy.EnvType.Node; +} +else if (typeof(self) !== "undefined") { + // Web Worker & some other APIs + squishy.Env = squishy.EnvType.Webworker; +} +else { + throw new Error("Unkown run-time environment. Currently only browsers, Node.js and web workers are supported."); +} + +squishy.envIsBrowser = function () { return squishy.Env == squishy.EnvType.Browser; }; +squishy.envIsNode = function () { return squishy.Env == squishy.EnvType.Node; }; +squishy.envIsWebworker = function () { return squishy.Env == squishy.EnvType.Webworker; }; + + +/** + * Returns the global context object. + */ +squishy.getGlobalContext = function() { + switch (squishy.Env) { + case squishy.EnvType.Node: + return GLOBAL; + break; + case squishy.EnvType.Browser: + return window; + break; + case squishy.EnvType.Webworker: + return self; + break; + default: + throw new Error("Unkown run-time environment. Currently only browsers, Node.js and web workers are supported."); + } +}; + +// don't install twice +if (!squishy.getGlobalContext().squishy) { + /** + * Exports the given object of the given name into the global context. + */ + squishy.exportGlobal = function(name, object) { + var global = squishy.getGlobalContext(); + global[name] = object; + }; + + // export squishy itself + squishy.exportGlobal('squishy', squishy); + + + // require other squishy-related files + + // TODO: http://stackoverflow.com/questions/18163413/how-to-make-a-requirejs-module-with-multiple-files + + // use requirejs, only if it's available + // if (typeof(define) !== 'undefined') { + // define(['Squishy/../squishy.util'], function() { + // return squishy; + // }); + // } + // else + if (squishy.Env == squishy.EnvType.Node) { + // we are probably in Node.js + require('./squishy.util'); + require('./squishy.domUtil'); + + + // also attach Stacktrace and CodeBuilder to squishy for now (until we find a better place for them) + squishy.Stacktrace = require('./squishy.Stacktrace'); + squishy.CodeBuilder = require('./squishy.CodeBuilder'); + } +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070995_settings.js b/pool/shard011/JavaScript/0070995_settings.js new file mode 100644 index 0000000000000000000000000000000000000000..fafedce21566ec072779eed88762f5f86733aab7 --- /dev/null +++ b/pool/shard011/JavaScript/0070995_settings.js @@ -0,0 +1,33 @@ +module("one.Settings"); + +test("one.Settings", function () +{ + var TestSettings = one.Settings.extend(function TestSettings(element, settings) + { + this.orientation = settings.orientation || "HORIZONTAL"; + this.roundValues = this.getBoolean("roundValues", element, settings, true); + this.minValue = this.getNumber("minValue", element, settings, 0); + this.maxValue = this.getNumber("maxValue", element, settings, 100); + this.value = this.getNumber("value", element, settings); + this.defaultValue = this.getNumber("defaultValue", element, settings, this.minValue); + this.textElement = this.getString("textElement", element, settings, one.string.EMPTY).trim(); + this.controlElement = this.getString("controlElement", element, settings, one.string.EMPTY).trim(); + }); + + var instance1 = new TestSettings(null, { + roundValues: false, + minValue: -100, + value: 4, + textElement: 'text5', + controlElement: "CTRLELEMENT" + }); + + equal(instance1.orientation, "HORIZONTAL"); + equal(instance1.roundValues, false); + equal(instance1.minValue, -100); + equal(instance1.maxValue, 100); + equal(instance1.value, 4); + equal(instance1.defaultValue, -100); + equal(instance1.textElement, 'text5'); + equal(instance1.controlElement, "CTRLELEMENT"); +}); diff --git a/pool/shard011/JavaScript/0070998_field_float_scannable.js b/pool/shard011/JavaScript/0070998_field_float_scannable.js new file mode 100644 index 0000000000000000000000000000000000000000..801cf32b5e2853da69f7088382aaf37c49923165 --- /dev/null +++ b/pool/shard011/JavaScript/0070998_field_float_scannable.js @@ -0,0 +1,58 @@ +odoo.define('barcodes.FieldFloatScannable', function(require) { +"use strict"; + +var core = require('web.core'); +var formats = require('web.formats'); +var form_widgets = require('web.form_widgets'); + +// Field in which the user can both type normally and scan barcodes + +var FieldFloatScannable = form_widgets.FieldFloat.extend({ + events: { + // The barcode_events component intercepts keypresses and releases them when it + // appears they are not part of a barcode. But since released keypresses don't + // trigger native behaviour (like characters input), we must simulate it. + 'keypress': 'simulateKeypress', + }, + + // Widget values are parsed according to the widget type. Since this widget is of type + // "FieldFloatScannable" and there is no parsing planned for this type, it defaults + // to outputting the value as a string. Hence the need to redefine parse_value + parse_value: function(val, def) { + return formats.parse_value(val, {type: "float"}, def); + }, + + simulateKeypress: function (e) { + /* only simulate a keypress if it has been previously prevented */ + if (e.originalEvent.dispatched_by_barcode_reader !== true) { + return; + } + var character = String.fromCharCode(e.which); + var current_str = e.target.value; + var str_before_carret = current_str.substring(0, e.target.selectionStart); + var str_after_carret = current_str.substring(e.target.selectionEnd); + e.target.value = str_before_carret + character + str_after_carret; + var new_carret_index = str_before_carret.length + character.length; + e.target.setSelectionRange(new_carret_index, new_carret_index); + // Note: FieldChar (that FieldFloat extends) calls store_dom_value upon change + // event, which is triggered when the input loses focus and its internal dirty + // flag is set. But here, we directly modify the value property of the input, + // which doesn't set the dirty flag. So we could call store_dom_value upon blur. + // But we also want the DOM value to be stored when a barcode_event occurs and + // triggers an onchange. We could listen to barcode_event in order to call + // store_dom_value, but that would have to happen before the onchange is triggered. + // So the safest method is still to store the value each time it changes. + // This long explanation is here to avoid having to do the thinking all over agan + // in case this strategy doesn't work / breaks. + // TL;DR Safest way not to lose the value when a barcode scan triggers an onchange. + this.store_dom_value(); + }, +}); + +core.form_widget_registry.add('field_float_scannable', FieldFloatScannable); + +return { + FieldFloatScannable: FieldFloatScannable, +}; + +}); diff --git a/pool/shard011/JavaScript/0071000_CCTextFieldTTF.js b/pool/shard011/JavaScript/0071000_CCTextFieldTTF.js new file mode 100644 index 0000000000000000000000000000000000000000..262409361822e5fbc79838d3ad75f0dea4b12465 --- /dev/null +++ b/pool/shard011/JavaScript/0071000_CCTextFieldTTF.js @@ -0,0 +1,472 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +/** + * Text field delegate + * @class + * @extends cc.Class + */ +cc.TextFieldDelegate = cc.Class.extend(/** @lends cc.TextFieldDelegate# */{ + /** + * If the sender doesn't want to attach with IME, return true; + * @param {cc.TextFieldTTF} sender + * @return {Boolean} + */ + onTextFieldAttachWithIME:function (sender) { + return false; + }, + + /** + * If the sender doesn't want to detach with IME, return true; + * @param {cc.TextFieldTTF} sender + * @return {Boolean} + */ + onTextFieldDetachWithIME:function (sender) { + return false; + }, + + /** + * If the sender doesn't want to insert the text, return true; + * @param {cc.TextFieldTTF} sender + * @param {String} text + * @param {Number} len + * @return {Boolean} + */ + onTextFieldInsertText:function (sender, text, len) { + return false + }, + + /** + * If the sender doesn't want to delete the delText, return true; + * @param {cc.TextFieldTTF} sender + * @param {String} delText + * @param {Number} len + * @return {Boolean} + */ + onTextFieldDeleteBackward:function (sender, delText, len) { + return false; + }, + + /** + * If doesn't want draw sender as default, return true. + * @param {cc.TextFieldTTF} sender + * @return {Boolean} + */ + onDraw:function (sender) { + return false; + } +}); + +/** + * A simple text input field with TTF font. + * @class + * @extends cc.LabelTTF + * + * @property {cc.Node} delegate - Delegate + * @property {Number} charCount - <@readonly> Characators count + * @property {String} placeHolder - Place holder for the field + * @property {cc.Color} colorSpaceHolder + * + * @param {String} placeholder + * @param {cc.Size} dimensions + * @param {Number} alignment + * @param {String} fontName + * @param {Number} fontSize + * + * @example + * //example + * // When five parameters + * var textField = new cc.TextFieldTTF("", cc.size(100,50), cc.TEXT_ALIGNMENT_LEFT,"Arial", 32); + * // When three parameters + * var textField = new cc.TextFieldTTF("", "Arial", 32); + */ +cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ + delegate:null, + colorSpaceHolder:null, + + _colorText: null, + _lens:null, + _inputText:"", + _placeHolder:"", + _charCount:0, + _className:"TextFieldTTF", + + /** + * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
    + * creates a cc.TextFieldTTF from a fontName, alignment, dimension and font size. + * @param {String} placeholder + * @param {cc.Size} dimensions + * @param {Number} alignment + * @param {String} fontName + * @param {Number} fontSize + */ + ctor:function (placeholder, dimensions, alignment, fontName, fontSize) { + this.colorSpaceHolder = cc.color(127, 127, 127); + this._colorText = cc.color(255,255,255, 255); + cc.imeDispatcher.addDelegate(this); + cc.LabelTTF.prototype.ctor.call(this); + + if(fontSize !== undefined){ + this.initWithPlaceHolder("", dimensions, alignment, fontName, fontSize); + if(placeholder) + this.setPlaceHolder(placeholder); + }else if(fontName === undefined && alignment !== undefined){ + this.initWithString("", arguments[1], arguments[2]); + if(placeholder) + this.setPlaceHolder(placeholder); + } + }, + + /** + * Gets the delegate. + * @return {cc.Node} + */ + getDelegate:function () { + return this.delegate; + }, + + /** + * Set the delegate. + * @param {cc.Node} value + */ + setDelegate:function (value) { + this.delegate = value; + }, + + /** + * Gets the char count. + * @return {Number} + */ + getCharCount:function () { + return this._charCount; + }, + + /** + * Returns the color of space holder. + * @return {cc.Color} + */ + getColorSpaceHolder:function () { + return cc.color(this.colorSpaceHolder); + }, + + /** + * Sets the color of space holder. + * @param {cc.Color} value + */ + setColorSpaceHolder:function (value) { + this.colorSpaceHolder.r = value.r; + this.colorSpaceHolder.g = value.g; + this.colorSpaceHolder.b = value.b; + this.colorSpaceHolder.a = cc.isUndefined(value.a) ? 255 : value.a; + if(!this._inputText.length) + this.setColor(this.colorSpaceHolder); + }, + + /** + * Sets the color of cc.TextFieldTTF's text. + * @param {cc.Color} textColor + */ + setTextColor:function(textColor){ + this._colorText.r = textColor.r; + this._colorText.g = textColor.g; + this._colorText.b = textColor.b; + this._colorText.a = cc.isUndefined(textColor.a) ? 255 : textColor.a; + if(this._inputText.length) + this.setColor(this._colorText); + }, + + /** + * Initializes the cc.TextFieldTTF with a font name, alignment, dimension and font size + * @param {String} placeholder + * @param {cc.Size} dimensions + * @param {Number} alignment + * @param {String} fontName + * @param {Number} fontSize + * @return {Boolean} + * @example + * //example + * var textField = new cc.TextFieldTTF(); + * // When five parameters + * textField.initWithPlaceHolder("", cc.size(100,50), cc.TEXT_ALIGNMENT_LEFT,"Arial", 32); + * // When three parameters + * textField.initWithPlaceHolder("", "Arial", 32); + */ + initWithPlaceHolder:function (placeholder, dimensions, alignment, fontName, fontSize) { + switch (arguments.length) { + case 5: + if (placeholder) + this.setPlaceHolder(placeholder); + return this.initWithString(this._placeHolder,fontName, fontSize, dimensions, alignment); + break; + case 3: + if (placeholder) + this.setPlaceHolder(placeholder); + return this.initWithString(this._placeHolder, arguments[1], arguments[2]); + break; + default: + throw "Argument must be non-nil "; + break; + } + }, + + /** + * Input text property + * @param {String} text + */ + setString:function (text) { + text = String(text); + this._inputText = text || ""; + + // if there is no input text, display placeholder instead + if (!this._inputText.length){ + cc.LabelTTF.prototype.setString.call(this, this._placeHolder); + this.setColor(this.colorSpaceHolder); + } else { + cc.LabelTTF.prototype.setString.call(this,this._inputText); + this.setColor(this._colorText); + } + if(cc._renderType === cc._RENDER_TYPE_CANVAS) + this._renderCmd._updateTexture(); + this._charCount = this._inputText.length; + }, + + /** + * Gets the string + * @return {String} + */ + getString:function () { + return this._inputText; + }, + + /** + * Set the place holder.
    + * display this string if string equal "". + * @param {String} text + */ + setPlaceHolder:function (text) { + this._placeHolder = text || ""; + if (!this._inputText.length) { + cc.LabelTTF.prototype.setString.call(this,this._placeHolder); + this.setColor(this.colorSpaceHolder); + } + }, + + /** + * Gets the place holder.
    + * default display string. + * @return {String} + */ + getPlaceHolder:function () { + return this._placeHolder; + }, + + /** + * Render function using the canvas 2d context or WebGL context, internal usage only, please do not call this function. + * @param {CanvasRenderingContext2D | WebGLRenderingContext} ctx The render context + */ + draw:function (ctx) { + //console.log("size",this._contentSize); + var context = ctx || cc._renderContext; + if (this.delegate && this.delegate.onDraw(this)) + return; + + cc.LabelTTF.prototype.draw.call(this, context); + }, + + /** + * Recursive method that visit its children and draw them. + * @param {CanvasRenderingContext2D|WebGLRenderingContext} ctx + */ + visit: function(ctx){ + this._super(ctx); + }, + + ////////////////////////////////////////////////////////////////////////// + // CCIMEDelegate interface + ////////////////////////////////////////////////////////////////////////// + /** + * Open keyboard and receive input text. + * @return {Boolean} + */ + attachWithIME:function () { + return cc.imeDispatcher.attachDelegateWithIME(this); + }, + + /** + * End text input and close keyboard. + * @return {Boolean} + */ + detachWithIME:function () { + return cc.imeDispatcher.detachDelegateWithIME(this); + }, + + /** + * Return whether to allow attach with IME. + * @return {Boolean} + */ + canAttachWithIME:function () { + return (this.delegate) ? (!this.delegate.onTextFieldAttachWithIME(this)) : true; + }, + + /** + * When the delegate detach with IME, this method call by CCIMEDispatcher. + */ + didAttachWithIME:function () { + }, + + /** + * Return whether to allow detach with IME. + * @return {Boolean} + */ + canDetachWithIME:function () { + return (this.delegate) ? (!this.delegate.onTextFieldDetachWithIME(this)) : true; + }, + + /** + * When the delegate detach with IME, this method call by CCIMEDispatcher. + */ + didDetachWithIME:function () { + }, + + /** + * Delete backward + */ + deleteBackward:function () { + var strLen = this._inputText.length; + if (strLen == 0) + return; + + // get the delete byte number + var deleteLen = 1; // default, erase 1 byte + + if (this.delegate && this.delegate.onTextFieldDeleteBackward(this, this._inputText[strLen - deleteLen], deleteLen)) { + // delegate don't want delete backward + return; + } + + // if delete all text, show space holder string + if (strLen <= deleteLen) { + this._inputText = ""; + this._charCount = 0; + cc.LabelTTF.prototype.setString.call(this,this._placeHolder); + this.setColor(this.colorSpaceHolder); + return; + } + + // set new input text + this.string = this._inputText.substring(0, strLen - deleteLen); + }, + + /** + * Remove delegate + */ + removeDelegate:function () { + cc.imeDispatcher.removeDelegate(this); + }, + + /** + * Append the text.
    + * Input the character. + * @param {String} text + * @param {Number} len + */ + insertText:function (text, len) { + var sInsert = text; + + // insert \n means input end + var pos = sInsert.indexOf('\n'); + if (pos > -1) { + sInsert = sInsert.substring(0, pos); + } + + if (sInsert.length > 0) { + if (this.delegate && this.delegate.onTextFieldInsertText(this, sInsert, sInsert.length)) { + // delegate doesn't want insert text + return; + } + + var sText = this._inputText + sInsert; + this._charCount = sText.length; + this.string = sText; + } + + if (pos == -1) + return; + + // '\n' has inserted, let delegate process first + if (this.delegate && this.delegate.onTextFieldInsertText(this, "\n", 1)) + return; + + // if delegate hasn't process, detach with ime as default + this.detachWithIME(); + }, + + /** + * Gets the input text. + * @return {String} + */ + getContentText:function () { + return this._inputText; + }, + + ////////////////////////////////////////////////////////////////////////// + // keyboard show/hide notification + ////////////////////////////////////////////////////////////////////////// + keyboardWillShow:function (info) { + }, + keyboardDidShow:function (info) { + }, + keyboardWillHide:function (info) { + }, + keyboardDidHide:function (info) { + } +}); + +var _p = cc.TextFieldTTF.prototype; + +// Extended properties +/** @expose */ +_p.charCount; +cc.defineGetterSetter(_p, "charCount", _p.getCharCount); +/** @expose */ +_p.placeHolder; +cc.defineGetterSetter(_p, "placeHolder", _p.getPlaceHolder, _p.setPlaceHolder); + +/** + * Please use new TextFieldTTF instead.
    + * Creates a cc.TextFieldTTF from a fontName, alignment, dimension and font size. + * @deprecated since v3.0 Please use new TextFieldTTF instead. + * @param {String} placeholder + * @param {cc.Size} dimensions + * @param {Number} alignment + * @param {String} fontName + * @param {Number} fontSize + * @return {cc.TextFieldTTF|Null} + */ +cc.TextFieldTTF.create = function (placeholder, dimensions, alignment, fontName, fontSize) { + return new cc.TextFieldTTF(placeholder, dimensions, alignment, fontName, fontSize); +}; + diff --git a/pool/shard011/JavaScript/0071003_lesson_editor.js b/pool/shard011/JavaScript/0071003_lesson_editor.js new file mode 100644 index 0000000000000000000000000000000000000000..03e1a15f06e3365a5615277d650fe6561c1682db --- /dev/null +++ b/pool/shard011/JavaScript/0071003_lesson_editor.js @@ -0,0 +1,46 @@ +var FORM = cb_global.form; +var LESSON_CONTENT_FIELD_NAME = 'objectives'; + +$(function() { + + function editContent() { + $('#cb-oeditor-form div.inputEx-fieldWrapper').hide(); + $('#cb-oeditor-form div.inputEx-fieldWrapper > .cb-editor-field, ' + + '#cb-oeditor-form div.inputEx-fieldWrapper > .title-holder') + .parent().show(); + } + + function editSettings() { + $('#cb-oeditor-form div.inputEx-fieldWrapper').show(); + $('#cb-oeditor-form div.inputEx-fieldWrapper > .cb-editor-field, ' + + '#cb-oeditor-form div.inputEx-fieldWrapper > .title-holder') + .parent().hide(); + } + + function bind() { + var togglebutton = new ToggleButton('', 'settings md md-settings'); + togglebutton.onClick(editSettings, editContent); + $('#cb-oeditor-form > fieldset > legend').prepend(togglebutton.getRoot()); + } + + function init() { + bind(); + + // Initial state is editing content + editContent(); + + // Hide the editor label generated by InputEx, and give the editor the extra + // width + $('#cb-oeditor-form div.inputEx-fieldWrapper > .cb-editor-field') + .parent() + .find('div') + .eq(0).css('display', 'none').end() + .eq(1).css('margin-left', '0'); + + // Resize the content editor to use all the available height. + FORM.inputsNames[LESSON_CONTENT_FIELD_NAME] + ._resize(null, getPotentialHeight($('.cb-editor-field .editors-div'))); + } + + init(); +}); diff --git a/pool/shard011/JavaScript/0071007_task_dependencies.js b/pool/shard011/JavaScript/0071007_task_dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..6358237610c7c87bc6809001e9909d2e1102f198 --- /dev/null +++ b/pool/shard011/JavaScript/0071007_task_dependencies.js @@ -0,0 +1,100 @@ + +og.pickPreviousTask = function(before, genid, task_id) { + og.ObjectPicker.show(function (objs) { + if (objs && objs.length > 0) { + var obj = objs[0].data; + if (obj.type != 'task') { + og.msg(lang("error"), lang("object type not supported"), 4, "err"); + } else { + og.addPreviousTask(this, obj, genid); + } + } + }, before, { + types: ['task'], + selected_type: 'task' + },'',task_id); +}; + +og.pickPreviousTemplateTask = function(before, genid, task_id, template_id) { + var extra_list_params = { + template_id:template_id + }; + og.ObjectPicker.show(function (objs) { + if (objs && objs.length > 0) { + var obj = objs[0].data; + if (obj.type != 'template_task') { + og.msg(lang("error"), lang("object type not supported"), 4, "err"); + } else { + og.addPreviousTask(this, obj, genid); + } + } + }, before, { + types: ['template_task'], + selected_type: 'template_task', + extra_list_params : extra_list_params + },'', task_id); +}; + +og.addPreviousTask = function(before, obj, genid) { + var parent = before.parentNode; + var count = parent.getElementsByTagName('input').length; + var div = document.createElement('div'); + var type = obj.type; + if (type == 'template_task') type = 'task'; + div.className = "og-add-template-object ico-" + type + (count % 2 ? " odd" : ""); + div.innerHTML = + '' + + '' + og.clean(obj.name) + '' + + ''+lang('remove')+''; + var label = document.getElementById(genid + 'no_previous_selected'); + if (label) label.style.display = 'none'; + parent.insertBefore(div, before); + og.previousTasks[og.previousTasksIdx] = obj; + og.previousTasksIdx++; +}; + +og.removePreviousTask = function(div, genid, index) { + var parent = div.parentNode; + parent.removeChild(div); + og.previousTasks = og.previousTasks.splice(index, 1); + if (og.previousTasks.length == 0) { + var label = document.getElementById(genid + 'no_previous_selected'); + if (label) label.style.display = 'inline'; + } +}; + +og.pickPreviousTaskFromView = function(tid) { + og.ObjectPicker.show(function (objs) { + if (objs && objs.length > 0) { + var obj = objs[0].data; + if (obj.type != 'task') { + og.msg(lang("error"), lang("object type not supported"), 4, "err"); + } else { + og.openLink(og.getUrl('taskdependency', 'add', {pt:obj.object_id, t:tid})); + } + } + }, this, { + types: ['task'], + selected_type: 'task' + },'',tid); +}; + +og.pickPreviousTemplateTaskFromView = function(task_id,template_id) { + var extra_list_params = { + template_id:template_id + }; + og.ObjectPicker.show(function (objs) { + if (objs && objs.length > 0) { + var obj = objs[0].data; + if (obj.type != 'template_task') { + og.msg(lang("error"), lang("object type not supported"), 4, "err"); + } else { + og.openLink(og.getUrl('taskdependency', 'add', {pt:obj.object_id, t:task_id})); + } + } + }, this, { + types: ['template_task'], + selected_type: 'template_task', + extra_list_params : extra_list_params + },'',task_id); +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071009_index.js b/pool/shard011/JavaScript/0071009_index.js new file mode 100644 index 0000000000000000000000000000000000000000..0da743e72d3f9785366bfef7bba53b35b1f7c188 --- /dev/null +++ b/pool/shard011/JavaScript/0071009_index.js @@ -0,0 +1,51 @@ +import tpl from './index.html'; + +class ListItemSelectorController { + constructor(uuid4) { + 'ngInject'; + this.uuid4 = uuid4; + } + + $onInit() { + if (!this.id) { + this.id = this.uuid4.generate(); + } + } + + $onChanges(changes) { + if (changes.color) { + const rx = /^#(?:[0-9a-f]{3}){1,2}$/i; + const color = changes.color.currentValue; + if (color && color.match(rx)) { + this.colorValue = color; + } else { + this.colorValue = 'black'; + } + } + } + + onSelectClick($event) { + $event.stopPropagation(); + $event.preventDefault(); + if (!this.disableSelection) { + this.onSelect({id: this.id}); + } + } +} + +const component = { + bindings: { + id: ' null, + () => this.toast.error('Unable to update property') + ); + } +} + +angular.module('materialscommons').component('mcAttributeSelection', { + template: require('./mc-attribute-selection.html'), + controller: MCAttributeSelectionComponentController, + bindings: { + setting: '<', + templateId: '<', + attribute: '<', + processId: '<' + } +}); diff --git a/pool/shard011/JavaScript/0071014_queryRecord.js b/pool/shard011/JavaScript/0071014_queryRecord.js new file mode 100644 index 0000000000000000000000000000000000000000..084fb2182dbdf32a96094622ccb485408f44236d --- /dev/null +++ b/pool/shard011/JavaScript/0071014_queryRecord.js @@ -0,0 +1,19 @@ +const moment = require('moment'); +const queryRecord = async (req, res) => { + const {id} = req.session.wx; + const { max_money = 2000000, min_money = 0, start_date, end_date} = reqBody(req); + const sql = `select date,money,des + from (select * from cashbook where uuid = '${id}') as t + where money >= ${min_money} and money <= ${max_money} + and date <= '${end_date}' and date >= '${start_date}'`; + const db = await dbquery(sql); + if (db.code !== 200) { + res.json(db); + } + let data = db.result; + data.length && data.forEach(item => { + item.date = moment(item.date).format('YYYY-MM-DD'); + }); + res.json({code: 200, data: db.result}); +}; +module.exports = queryRecord; diff --git a/pool/shard011/JavaScript/0071015_pure-render-mixin.js b/pool/shard011/JavaScript/0071015_pure-render-mixin.js new file mode 100644 index 0000000000000000000000000000000000000000..86a865e2cd26cda18b6f8cddab246d4dda80f62f --- /dev/null +++ b/pool/shard011/JavaScript/0071015_pure-render-mixin.js @@ -0,0 +1,25 @@ +var Cursor = require('../cursor'); + +function isNotEqual(next, current, ignore) { + return function(p) { + if (ignore.includes(p)) return false; + if (next[p] instanceof Cursor && current[p] instanceof Cursor) { + return !next[p].isEqual(current[p]); + } + return next[p] !== current[p]; + }; +} + +var PureRenderMixin = { + shouldComponentUpdate(nextProps, nextState, nextContext) { + return [ + {next: nextProps, current: this.props, type: 'Props'}, + {next: nextState, current: this.state, type: 'State'}, + {next: nextContext, current: this.context, type: 'Context'}].some(function({next, current, type}) { + var ignore = `ignorePureRender${type}`; + return next && Object.keys(next).some(isNotEqual(next, current, this[ignore] || [])); + }, this); + } +}; + +module.exports = PureRenderMixin; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071017_Promise.js b/pool/shard011/JavaScript/0071017_Promise.js new file mode 100644 index 0000000000000000000000000000000000000000..b8e4d83c9d8b667627cc68196edc8e897de2a4e0 --- /dev/null +++ b/pool/shard011/JavaScript/0071017_Promise.js @@ -0,0 +1,190 @@ +/* + Really small implementation of Promises + Exposes only chainable then & catch + */ +module.exports = Promise; + +function Promise(resolver) { + if (typeof resolver !== 'function') { + throw new Error('Promise constructor parameter must be a function.'); + } + + this._callbacks = []; + this._catchers = []; + this.running = true; + this._lastValue = undefined; + + this._errCaught = []; + + try { + resolver(this.resolve.bind(this), this.reject.bind(this)); + } catch (e) { + this.reject(e); + } + +}; + +// run the next function in the pipe +Promise.prototype.run = function(toRun, args) { + var res = null, + self = this; + + if (typeof toRun === 'function') { + self.running = true; + + try { + res = toRun.apply(null, args); + this._lastValue = res; // save last value for future .then + } catch (e) { + self.reject(e); // catch errors + } + + self.resolve(res); + } + +}; + +Promise.prototype.resolve = function() { + var self = this; + + self.running = false; + + var args = Array.prototype.slice.call(arguments); + this._lastValue = args[0] || undefined; // save last returned value for future .then + + var next = self._getNextCallback(); + if (next) { + if (this._lastValue && this._lastValue instanceof Promise) { + this._lastValue + .then(this.run.bind(this, next)) + .catch(self.reject.bind(self)); + } else { + this.run(next, args); + } + } + + return this; +}; + +Promise.prototype.reject = function(err) { + err = err || new Error('An error occured'); + if (this._caught) { + this._errCaught.push(err); + this._caught(err); + } else { + throw new Error(err); + } + + return this; +}; + +Promise.prototype.then = function(callback) { + if (typeof callback !== 'function') { + throw new Error('Promise.then need a function as parameter.'); + } + + this._addCallback(callback); + if (!this.running) { + this.resolve(this._lastValue); + } + + return this; +}; + +Promise.prototype.catch = function(catcher) { + if (typeof catcher !== 'function') { + throw new Error('Promise.catch callback must be a function.'); + } + + var types = []; + if (arguments.length === 1) { + types = [Error]; + } else { + var len = arguments.length, + i = 0; + for (i = 0; i < len - 1; ++i) { + types.push(arguments[i]); + } + catcher = arguments[i]; + } + + types.forEach(function(type) { + if (type !== Error && !(type.prototype instanceof Error)) { + throw new Error('Promise.catch types must all be an Error type constructor.'); + } + }) + + var added = this._catchers.push({ + types: types, + fn: catcher + }); + + if (this._errCaught.length) { + this._testCaught(this._catchers[added]); + } + + return this; +}; + +Promise.prototype._testCaught = function(catchers) { + this._errCaught.forEach(function(err) { + this._caught(err, catchers); + }.bind(this)); +}; +Promise.prototype._caught = function(err, catchers) { + catchers = catchers || this._catchers; + var some = false; + + for (var i = 0; i < catchers.length; i++) { + some = catchers[i].types.some(function(type) { + return (err instanceof type); + }); + + if (some) { + catchers[i].fn(err); + } + } +}; + +Promise.prototype._getNextCallback = function() { + var next = null; + if (this._callbacks.length) { + next = this._callbacks.shift(); + } + return next; +}; + +Promise.prototype._addCallback = function(callback) { + this._callbacks.push(callback); +}; + +Promise.resolve = function(arg) { + return new Promise(function(resolve, reject) { + resolve(arg); + }); +}; + +Promise.reject = function(err) { + return new Promise(function(resolve, reject) { + reject(err); + }); +}; + +Promise.all = function (promises) { + var results = [], + resolved = 0, + total = promises.length; + return new Promise(function (resolve, reject) { + promises.forEach(function (promise, index) { + promise.then(function (value) { + resolved++; + results[index] = value; + if (resolved === total) { + resolve(results); + } + }).catch(function (e) { + reject(e); + }); + }) + }) +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071018_quantile.js b/pool/shard011/JavaScript/0071018_quantile.js new file mode 100644 index 0000000000000000000000000000000000000000..1f50737f6f71521363696e320104da2bd410d488 --- /dev/null +++ b/pool/shard011/JavaScript/0071018_quantile.js @@ -0,0 +1,43 @@ +d3.scale.quantile = function() { + return d3_scale_quantile([], []); +}; + +function d3_scale_quantile(domain, range) { + var thresholds; + + function rescale() { + var k = 0, + n = domain.length, + q = range.length; + thresholds = []; + while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); + return scale; + } + + function scale(x) { + if (isNaN(x = +x)) return NaN; + return range[d3.bisect(thresholds, x)]; + } + + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.filter(function(d) { return !isNaN(d); }).sort(d3.ascending); + return rescale(); + }; + + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + + scale.quantiles = function() { + return thresholds; + }; + + scale.copy = function() { + return d3_scale_quantile(domain, range); // copy on write! + }; + + return rescale(); +} diff --git a/pool/shard011/JavaScript/0071020_layout.js b/pool/shard011/JavaScript/0071020_layout.js new file mode 100644 index 0000000000000000000000000000000000000000..97b8fdd8233356dffc41223c69258b263525e3f0 --- /dev/null +++ b/pool/shard011/JavaScript/0071020_layout.js @@ -0,0 +1,107 @@ +'use strict'; + +const util = require('./util'); + +const increments = Object.freeze({ + x: 2600, + y: 1400, + z: 2000, + scale: 1, + rotate: 60, + 'rotate-x': 60, + 'rotate-y': 60, + 'rotate-z': 60, +}); + +const layout = { + i: 0, + x: 0, + y: 0, + z: 0, + scale: 1, + rotate: 0, + 'rotate-x': 0, + 'rotate-y': 0, + 'rotate-z': 0, + grid: [{ x: 0, y: 0, direction: undefined }], +}; + +function random(params) { + // how many parameters we will randomize + const numOfParams = util.getRandomInt(1, params.length); + const res = []; + for (let i = 0; i < numOfParams; i++) { + // remove 1 elem from index n + const param = params.splice(util.getRandomInt(0, params.lenght - 1), 1)[0]; + const multiplier = util.getRandomInt(-3, 3); + let newValue = layout[param] + (multiplier * increments[param]); + if (param.indexOf('rotate') > -1) newValue = newValue % 360; + if (param === 'scale') newValue = Math.max(newValue, 1); + layout[param] = newValue; + res.push({ key: param, value: newValue }); + } + return res; +} + + +const random7d = () => random(['x', 'y', 'z', 'scale', 'rotate-x', 'rotate-y', 'rotate-z']); + +const randomSimple = () => random(['x', 'y', 'z', 'scale', 'rotate']); + +function generateNewCoord(lastCoord) { + let direction = util.getRandomInt(0, 2); // what direction to move to + // we check if the current direction is opposite to last direction, in which case we add one + direction = (direction % 2 === lastCoord.direction % 2) ? ((direction + 1) % 2) : direction; + const newCoord = { x: lastCoord.x, y: lastCoord.y, direction }; + switch (direction) { + case 0: + newCoord.y++; + break; + case 1: + newCoord.x++; + break; + case 2: + newCoord.y--; + break; + default: break; + } + return newCoord; +} + +function grid() { + const lastCoord = layout.grid[layout.grid.length - 1]; + const nextCoord = generateNewCoord(lastCoord); + if (layout.grid.indexOf(nextCoord) > -1) { + return grid(); + } + layout.grid.push(nextCoord); + return [{ + key: 'x', + value: nextCoord.x * increments.x, + }, { + key: 'y', + value: nextCoord.y * increments.y, + }]; +} + +module.exports = { + random: randomSimple, + 'random-7d': random7d, + grid, + horizontal() { + layout.x += increments.x; + return [{ key: 'x', value: layout.x }]; + }, + vertical() { + layout.y += increments.y; + return [{ key: 'y', value: layout.y }]; + }, + '3d-push': () => { + layout.z += increments.z * 3; + return [{ key: 'z', value: layout.z }]; + }, + '3d-pull': () => { + layout.z -= increments.z * 3; + return [{ key: 'z', value: layout.z }]; + }, +}; diff --git a/pool/shard011/JavaScript/0071025_walk-page.js b/pool/shard011/JavaScript/0071025_walk-page.js new file mode 100644 index 0000000000000000000000000000000000000000..028811eef3d1f427fd31cb8d7f0b8ab9311a88df --- /dev/null +++ b/pool/shard011/JavaScript/0071025_walk-page.js @@ -0,0 +1,152 @@ +"use strict;" + +const VERSION = 2; + +let setCookie = function (name, value, expireDays) { + // default to 30 days expiration if no expiration is provided + expireDays = (typeof expireDays !== "undefined") ? expireDays : 30; + let date = new Date (); + date.setTime (date.getTime () + (expireDays * 24 * 60 * 60 * 1000)); + let expires = "expires=" + date.toUTCString (); + document.cookie = name + "=" + value + ";" + expires + ";path=/"; +}; + +let getCookie = function (name) { + let find = name + "="; + let decodedCookie = decodeURIComponent (document.cookie); + let cookieArray = decodedCookie.split (";"); + for (let cookie of cookieArray) { + let index = cookie.indexOf (find); + if (index >= 0) { + return cookie.substring (index + find.length) + } + } + return ""; +}; + +let deleteCookie = function (name) { + setCookie (name, "", -1); +}; + +let replaceCookie = function (name, value, expireDays) { + setCookie (name, "", -1); + setCookie (name, value, expireDays); +}; + +let resetCookies = function () { + let decodedCookie = decodeURIComponent (document.cookie); + let cookieArray = decodedCookie.split (";"); + for (let cookie of cookieArray) { + let name = cookie.split ("=")[0]; + name = name.replace (/^\s*/, ""); + name = name.replace (/\s*$/, ""); + setCookie (name, "", -1); + } +}; + +let toggle = function (plus, minus, container, show) { + //console.log ("Toggle: " + (show ? "ON" : "OFF")); + if (show) { + plus.style.display = "none"; + minus.style.display = "inline-block"; + container.style.display = "block"; + } else { + minus.style.display = "none"; + plus.style.display = "inline-block"; + container.style.display = "none"; + } +}; + +let makeId = function (counterText, innerText) { + return (counterText + " " + innerText + " v" + VERSION).toLowerCase ().replace (/ /g, "_"); +}; + +const SHOW = "show"; +const HIDE = "hide"; + +let defaults = {}; +defaults[makeId ("1.", "about")] = SHOW; + +let walkPage = function (page, prefix) { + //console.log (page.tagName + "(" + page.childNodes.length + ")"); + if (typeof (page) !== "undefined") { + if (typeof (page.childNodes) !== "undefined") { + let counter = 0; + for (let i = 0; i < page.childNodes.length; ++i) { + let element = page.childNodes.item (i); + if (typeof (element.tagName) !== "undefined") { + switch (element.tagName) { + case "H2": + case "H3": + case "H4": { + // get the following element, which should be a container class + let container = element.nextElementSibling; + if ((typeof (container) != "undefined") && (container != null)) { + if (container.classList.contains ("container")) { + let counterText = prefix + (++counter) + "."; + let id = makeId (counterText, element.innerText); + console.log ("ID: " + id); + + container.id = id + "-container"; + walkPage (container, counterText); + + // now replace the Hx... with a div that contains it + let div = document.createElement ("div"); + div.classList.add ("header"); + + let plus = document.createElement ("img"); + plus.src = "img/plus.png"; + plus.classList.add ("plus"); + plus.id = id + "-plus"; + div.appendChild (plus); + + let minus = document.createElement ("img"); + minus.src = "img/minus.png"; + minus.classList.add ("minus"); + minus.id = id + "-minus"; + div.appendChild (minus); + + plus.onclick = function (event) { + toggle (plus, minus, container, true); + replaceCookie (id, SHOW); + }; + minus.onclick = function (event) { + toggle (plus, minus, container, false); + replaceCookie (id, HIDE); + }; + + element.parentNode.replaceChild (div, element); + + let h = document.createElement (element.tagName); + h.innerHTML = counterText; + h.classList.add ("counter"); + div.appendChild (h); + + div.appendChild (element); + + // everything is hidden by default, so only do this if the cookie is "show" + let cookie = getCookie (id); + if ((cookie === SHOW) || ((cookie === "") && (defaults[id] === SHOW))) { + //console.log ("GOT COOKIE"); + toggle (plus, minus, container, true); + } + + } else { + console.log ("ERROR IN DOCUMENT STRUCTURE"); + } + } + break; + } + } + } + } + } else { + console.log ("invalid childNodes"); + } + } else { + console.log ("invalid page"); + } +}; + +let page = document.getElementById ("page-container"); +walkPage (page, ""); diff --git a/pool/shard011/JavaScript/0071026_vul-client-innerhtml.js b/pool/shard011/JavaScript/0071026_vul-client-innerhtml.js new file mode 100644 index 0000000000000000000000000000000000000000..46a55983f3bf8a15204de07ddb0ad97e2b3670f0 --- /dev/null +++ b/pool/shard011/JavaScript/0071026_vul-client-innerhtml.js @@ -0,0 +1,21 @@ +function login(){ + var input_user = document.querySelector("#in_user").value; + var input_password = document.querySelector("#in_pass").value; + document.cookie = 'username='+input_user; + document.cookie = 'password='+input_password; + + document.querySelector(".login_page").style="" + document.querySelector(".unlogin_page").style="display:none" + document.querySelector("#pg").innerHTML="HI!! "+input_user; +} + +function logout(){ + document.querySelector("#pg").innerHTML=""; + document.querySelector(".login_page").style="display:none" + document.querySelector(".unlogin_page").style="" +} + +function hi(){ + var input_age = document.querySelector("#in_age").value; + document.querySelector("#pg").innerHTML="OH!! your age is "+input_age; +} diff --git a/pool/shard011/JavaScript/0071030_photosCtrl.js b/pool/shard011/JavaScript/0071030_photosCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..ffaa6a85450aec3cc2d7a3ee811aeecbee061d85 --- /dev/null +++ b/pool/shard011/JavaScript/0071030_photosCtrl.js @@ -0,0 +1,62 @@ +class PhotosCtrl { + constructor($scope, ChosenUserService, AlbumsService, PhotosService) { + 'ngInject' + + const vm = this; + vm.ChosenUserService = ChosenUserService; + vm.photosLimit = 9; + + $scope.$watch('vm.ChosenUserService.user', function() { + console.log(vm.ChosenUserService.user); + if (!vm.ChosenUserService.user) { + return; + } + var chosenUserId = vm.ChosenUserService.user.id; + + AlbumsService.get(chosenUserId).then(albumsOnFulfilled, albumsOnRejected); + }); + + function albumsOnFulfilled(albumsList) { + vm.albums = albumsList; + PhotosService.get(vm.albums[0].id).then(photosOnFulfilled, photosonRejected); + + function photosOnFulfilled(photosList) { + vm.photos = photosList; + console.log('photos:', photosList); + $scope.$apply(); + } + + function photosonRejected() { + console.log('photos error'); + } + + $scope.$apply(); + } + + function albumsOnRejected() { + console.log('albums error'); + } + + vm.showImgModal = false; + + vm.showImage = function(photo) { + console.log(photo); + vm.ImageUrl = photo.url; + vm.showImgModal = !vm.showImgModal; + } + + vm.closeImage = function(){ + vm.showImgModal = !vm.showImgModal; + } + + vm.loadMorePhotos = function() { + vm.photosLimit += 3; + } + } + +} + +export default { + name: 'PhotosCtrl', + fn: PhotosCtrl +}; diff --git a/pool/shard011/JavaScript/0071035_index.js b/pool/shard011/JavaScript/0071035_index.js new file mode 100644 index 0000000000000000000000000000000000000000..e4baa52742472f068bb7316dbf98a6e4949d254f --- /dev/null +++ b/pool/shard011/JavaScript/0071035_index.js @@ -0,0 +1,25 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Snackbar = undefined; + +var _reactCssThemr = require('react-css-themr'); + +var _identifiers = require('../identifiers'); + +var _Snackbar = require('./Snackbar'); + +var _button = require('../button'); + +var _theme = require('./theme.css'); + +var _theme2 = _interopRequireDefault(_theme); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ThemedSnackbar = (0, _reactCssThemr.themr)(_identifiers.SNACKBAR, _theme2.default)((0, _Snackbar.snackbarFactory)(_button.Button)); + +exports.default = ThemedSnackbar; +exports.Snackbar = ThemedSnackbar; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071038_index.js b/pool/shard011/JavaScript/0071038_index.js new file mode 100644 index 0000000000000000000000000000000000000000..e58d778739aa2396e44c1f67b34bf714ebb94ae1 --- /dev/null +++ b/pool/shard011/JavaScript/0071038_index.js @@ -0,0 +1,81 @@ +/* eslint-disable no-plusplus */ +const { makeExecutableSchema } = require('graphql-tools'); +const _debug = require('debug'); +const DataLoader = require('dataloader'); + +const knex = require('../knex'); + +let queryTimes = 0; +const debug = _debug('demo'); + +const batchLoadAuthors = ids => { + debug('batchLoadAuthors', ++queryTimes); + return knex('authors') + .whereIn('id', ids) + .select() + .then(rows => ids.map(id => rows.find(x => x.id === id))); +}; + +const batchLoadPostsByAuthor = ids => { + debug('batchLoadPosts', ++queryTimes); + return knex('posts') + .whereIn('author_id', ids) + .select() + .then(rows => ids.map(id => rows.filter(x => x.author_id === id))); +}; + +const loaders = { + authors: new DataLoader(batchLoadAuthors), + postsByAuthor: new DataLoader(batchLoadPostsByAuthor), +}; + +const typeDefs = ` + type Author { + id: Int + name: String + posts: [Post] + } + + type Post { + id: Int + title: String + text: String + author: Author + } + + type Query { + getAuthor(id: Int): Author + getPostsByTitle(titleContains: String): [Post] + } +`; + +const resolvers = { + Query: { + getAuthor(obj, args) { + return loaders.authors.load(args.id); + }, + + getPostsByTitle(obj, args) { + debug('getPostsByTitle', ++queryTimes); + // use .where only for demo + return knex('posts').where('title', args.titleContains).first().select(); + }, + }, + + Author: { + posts(author) { + return loaders.postsByAuthor.load(author.id); + }, + }, + + Post: { + author(post) { + return loaders.authors.load(post.author_id); + }, + }, +}; + +module.exports = makeExecutableSchema({ + typeDefs, + resolvers, +}); diff --git a/pool/shard011/JavaScript/0071041_ScenarioCollectionMonitor.js b/pool/shard011/JavaScript/0071041_ScenarioCollectionMonitor.js new file mode 100644 index 0000000000000000000000000000000000000000..74d0200c06d4875d0aaf2c3c8a47f357e52420f2 --- /dev/null +++ b/pool/shard011/JavaScript/0071041_ScenarioCollectionMonitor.js @@ -0,0 +1,72 @@ +import React from 'react'; +import { observer } from 'mobx-react'; +import classNames from 'classnames'; + +@observer +export default class ScenarioCollectionMonitor extends React.Component { + renderCategoryProgress(description, progressInPercentage, isUpdated, isCompleted) { + return ( +
    +
    + {description} +
    +
    + +
    +
    + ); + } + + render() { + const { statusMap, progressMap } = this.props; + + const inProgressCategories = []; + const completedCategories = []; + statusMap.forEach((isUpdated, description) => { + const progressInPercentage = progressMap.get(description); + const isCompleted = progressInPercentage >= 100.0; + const element = this.renderCategoryProgress( + description, progressInPercentage, isUpdated, isCompleted, + ); + + if (isCompleted) { + completedCategories.push(element); + } else { + inProgressCategories.push(element); + } + }); + + // To make sure the category in the last row has the width that + // matches the rest, adding a dummy category that shows nothing + // but helps flex-box adjusts the width correctly. + if (inProgressCategories.length % 2 === 1) { + inProgressCategories.push(
    ); + } + if (completedCategories.length % 2 === 1) { + completedCategories.push(
    ); + } + + return ( +
    +
    + {inProgressCategories} +
    + + {completedCategories.length > 0 + && ( +
    + {completedCategories} +
    + )} +
    + ); + } +} diff --git a/pool/shard011/JavaScript/0071042_average.js b/pool/shard011/JavaScript/0071042_average.js new file mode 100644 index 0000000000000000000000000000000000000000..4c2ac9157cbf302e18f84d7690c529750824923a --- /dev/null +++ b/pool/shard011/JavaScript/0071042_average.js @@ -0,0 +1,31 @@ +'use strict'; + + +var ANCESTRY_FILE = require('./ancestry.js'); +var ancestry = JSON.parse(ANCESTRY_FILE); + + +function average(array) { + return array.reduce(function (a, b) { + return a + b; + }) / array.length; +} + +console.log(average([5, 4, 3, 2, 1])); + + +function male(person) { + return person.sex === 'm'; +} + + +function female(person) { + return person.sex === 'f'; +} + + +function age(person) { + return person.died - person.born; +} + +console.log(average(ancestry.filter(female).map(age))); diff --git a/pool/shard011/JavaScript/0071045_show_lists_index_list_view.js b/pool/shard011/JavaScript/0071045_show_lists_index_list_view.js new file mode 100644 index 0000000000000000000000000000000000000000..ebd9902dcc969eb19041495d2da0570377c78a15 --- /dev/null +++ b/pool/shard011/JavaScript/0071045_show_lists_index_list_view.js @@ -0,0 +1,61 @@ +EstablishmentsShowListsIndexListView = Backbone.View.extend({ + events: { + }, + + initialize: function () { + this.listenTo(this.collection, 'reset', this.render); + this.listenTo(this.collection, 'paginate', this.paginate); + this.listenTo(this.model, 'new_listing', this.updateCollection); + + var params = this.collection.predicate(); + + this.collection.fetch({ reset: true, data: params }); + }, + + render: function () { + this.changeHeadInfo(); + if (this.collection.length > 0) { + this.$el.html(''); + + this.collection.each(function (list){ + this.renderList(list); + }, this); + window.scrollTo(0,0); + } else { + this.$el.html(render('establishments/show_lists_index_list_no_results', this.model)); + } + }, + + renderList: function (list) { + var list_view = new ListsIndexListView({ + tagName: 'li', + model: list, + favorites: this.collection.favorites + }); + + if (list.get('type') === 'WishList') { + this.$el.prepend(list_view.el); + } else { + this.$el.append(list_view.el); + } + }, + + paginate: function (e) { + this.collection.requested_page = e; + var params = this.collection.predicate(); + this.collection.fetch({ reset: true, data: params }); + }, + + updateCollection: function (e) { + var params = this.collection.predicate(); + this.collection.fetch({ reset: true, data: params }); + }, + + changeHeadInfo: function () { + this.title = this.model.get('name') + ' | ' + this.model.get('city') + ' Restaurants | YumHacker'; + this.description = this.model.get('name') + ' is recommended on ' + this.collection.length + ' Yum Lists on YumHacker.' + + App.eventAggregator.trigger('domchange:title', this.title); + App.eventAggregator.trigger('domchange:description', this.description); + } +}); diff --git a/pool/shard011/JavaScript/0071047_boards.js b/pool/shard011/JavaScript/0071047_boards.js new file mode 100644 index 0000000000000000000000000000000000000000..03153baa78bf13f30523795ff76a1e997c8ff10d --- /dev/null +++ b/pool/shard011/JavaScript/0071047_boards.js @@ -0,0 +1,184 @@ +"use strict"; + +//---------------------------------------------------------------------- +//-- Boards +//---------------------------------------------------------------------- +//-- CONFIGURATION FILES +//----------------------------------------------------------------------- +//-- The Boards are described by three .json files, located in the folder +//-- resources/boards/boardname +//-- * pinout.json: Pin numbers, names and type (input, output, inout) +//-- * info.json: Board information: resources, board name, interface... +//-- * rules.json: Automatic connection of unused pins +//-- +//-- In addition there are two more OPTIONAL files: +//-- * pinout.pcf (optional): Board constraints. This is just for documentation +//-- purposes (the actual constraint file is automatically generated on +//-- the fly when the circuit is being sinthesized) +//-- * pinout.svg (optional): Drawing of all the pins +//---------------------------------------------------------------------------- +//-- DATA STRUCTURES +//---------------------------------------------------------------------------- +//-- ICESTUDIO converts the .json files into objects. You can access to all +//-- the boars from the following GLOBAL OBJECT: +//-- +//-- common.boards +//-- * name: Board name. Ex. alhmabra_ii +//-- * info: Resources +//-- * pinout: Pin names, number and type +//-- * rules: If the pin is automatically connected if not used +//-- * type: FPGA familty and type + + +//--------------------------------------------------------------- +//-- MENU menu.json +//-- This file contains the names of all the available boards +//-- Only the boards located in that file are READ and inserted +//-- into the common.boards GLOBAL object +//--------------------------------------------------------------- + +angular + .module("icestudio") + .service("boards", function (utils, common, nodeFs, nodePath) { + + //-- Default board + const DEFAULT = "alhambra-ii"; + + //----------------------------------------------------------------- + //-- Read all the boards FILES and store all the information + //-- in the GLOBAL OBJECT: common.boards + //----------------------------------------------------------------- + //-- Only the boards located in the menu.json FILE are READ + //----------------------------------------------------------------- + this.loadBoards = function () { + + let boards = []; + + //-- Construct the Boards path: "resources/boards" + let path = nodePath.join("resources", "boards"); + + //-- Read the board menu json file and convert into an object + let menu = nodeFs.readFileSync(nodePath.join(path, "menu.json")); + menu = JSON.parse(menu); + + //-- The menu is divided in big sections: The FPGA family: ICE40HX8k, ICE40HX4k, + //-- ICE40LPHX, UP5K, ECP5... + menu.forEach(FPGAfamily => { + + //-- Access to all the boards from the current family + FPGAfamily.boards.forEach(function (boardname) { + + //-- The data from every board is located in the + //-- folder "resources/boards/" + let boardPath = nodePath.join(path, boardname); + + //-- Every board should have at least their three MANDATORY files: + //-- info.json, pinout.json and rules. + //-------------------------------------------------------------------- + //-- TODO: It can be improved: It is better to distinguis between + //-- among different errores, instead only one. If anyone introduces + //-- a bad board, it is difficult to find where is the error.... + //-------------------------------------------------------------------- + try { + if ( + nodeFs.statSync(boardPath).isDirectory() && + nodeFs.statSync(nodePath.join(boardPath, "info.json")).isFile() && + nodeFs.statSync(nodePath.join(boardPath, "pinout.json")).isFile() && + nodeFs.statSync(nodePath.join(boardPath, "rules.json")).isFile() + ) { + + //-- Board files ok. READ them!! + let info = readJSONFile(boardPath, "info.json"); + let pinout = readJSONFile(boardPath, "pinout.json"); + let rules = readJSONFile(boardPath, "rules.json"); + + //-- Fill the boards structure will all the information + //-- obtained from the files + boards.push({ + name: boardname, + info: info, //-- Board resources + pinout: pinout, //-- Board pins + rules: rules, //-- Board rules + type: FPGAfamily.type, //-- FPGA family type + }); + } + + //-- There was an error reading the board files + } catch (error) { + console.error("Board not well configured", error.message); + } + }); + }); + + //-- The boards are available through the GLOBAL OBJECT common.boards + common.boards = boards; + }; + + + //---- PENDING: DOCUMENTATION!!!!!! + + function readJSONFile(filepath, filename) { + var ret = {}; + try { + var data = nodeFs.readFileSync(nodePath.join(filepath, filename)); + ret = JSON.parse(data); + } catch (err) {} + return ret; + } + + this.selectBoard = function (name) { + name = name || DEFAULT; + var i; + var selectedBoard = null; + for (i in common.boards) { + if (common.boards[i].name === name) { + selectedBoard = common.boards[i]; + break; + } + } + if (selectedBoard === null) { + // Board not found: select default board + for (i in common.boards) { + if (common.boards[i].name === DEFAULT) { + selectedBoard = common.boards[i]; + break; + } + } + } + common.selectedBoard = selectedBoard; + common.pinoutInputHTML = generateHTMLOptions( + common.selectedBoard.pinout, + "input" + ); + common.pinoutOutputHTML = generateHTMLOptions( + common.selectedBoard.pinout, + "output" + ); + utils.rootScopeSafeApply(); + return common.selectedBoard; + }; + + this.boardLabel = function (name) { + for (var i in common.boards) { + if (common.boards[i].name === name) { + return common.boards[i].info.label; + } + } + return name; + }; + + function generateHTMLOptions(pinout, type) { + var code = ""; + for (var i in pinout) { + if (pinout[i].type === type || pinout[i].type === "inout") { + code += + '"; + } + } + return code; + } + }); diff --git a/pool/shard011/JavaScript/0071052_StepValidationError.js b/pool/shard011/JavaScript/0071052_StepValidationError.js new file mode 100644 index 0000000000000000000000000000000000000000..e87f9d843d13a54ac3cf793a705984f5ee6b0955 --- /dev/null +++ b/pool/shard011/JavaScript/0071052_StepValidationError.js @@ -0,0 +1,43 @@ +// Dependencies --------------------------------------------------------------- +// ---------------------------------------------------------------------------- +var format = require('./format'); + + +// Wrapper for Step Validation Errors ----------------------------------------- +function StepValidationError(feature, scenario, step) { + this._feature = feature; + this._scenario = scenario; + this._step = step; + this._errors = []; + this._errorCount = 0; +} + +// Methods -------------------------------------------------------------------- +StepValidationError.prototype = { + + getCount: function() { + return this._errorCount; + }, + + getErrors: function() { + return this._errors; + }, + + addError: function(error) { + this._errors.push(error); + this._errorCount++; + }, + + format: function(indent) { + return this.getErrors().map(function(error) { + return format(error, this._step, indent); + + }, this).join('\n\n'); + } + +}; + + +// Exports -------------------------------------------------------------------- +module.exports = StepValidationError; + diff --git a/pool/shard011/JavaScript/0071053_66-object-literal-getter.js b/pool/shard011/JavaScript/0071053_66-object-literal-getter.js new file mode 100644 index 0000000000000000000000000000000000000000..c316ca8d8530de57d80702551486b630c5a67df3 --- /dev/null +++ b/pool/shard011/JavaScript/0071053_66-object-literal-getter.js @@ -0,0 +1,67 @@ +// 66: object-literal - getter +// To do: make all tests pass, leave the assert lines unchanged! + +var assert = require("assert"); + +describe('An object literal can also contain getters', () => { + + it('just prefix the property with `get` (and make it a function)', function() { + const obj = { + get x() { return 'ax'; } + }; + + assert.equal(obj.x, 'ax'); + }); + + it('must have NO parameters', function() { + const obj = { + get x() { return 'ax'; } + }; + + assert.equal(obj.x, 'ax'); + }); + + + it('can be a computed property (an expression enclosed in `[]`)', function() { + const keyName = 'x'; + const obj = { + get [keyName]() { return 'ax'; } + }; + + assert.equal(obj.x, 'ax'); + }); + + it('can be removed using delete', function() { + const obj = { + get x() { return 'ax'; } + }; + + delete obj.x; + + assert.equal(obj.x, void 0); + }); + + // The following dont seem to work in the current transpiler version + // but should be correct, as stated here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get + // It might be corrected later, new knowledge welcome. + + //it('must not overlap with a pure property', function() { + // const obj = { + // x: 1, + // get x() { return 'ax'; } + // }; + // + // assert.equal(obj.x, 'ax'); + //}); + // + //it('multiple `get` for the same property are not allowed', function() { + // const obj = { + // x: 1, + // get x() { return 'ax'; }, + // get x() { return 'ax1'; } + // }; + // + // assert.equal(obj.x, 'ax'); + //}); +}); + diff --git a/pool/shard011/JavaScript/0071054_blueprint-config-conflict-choice.spec.js b/pool/shard011/JavaScript/0071054_blueprint-config-conflict-choice.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..699d1550b3d3531bfc6fb5d335b6a38ecf5e9698 --- /dev/null +++ b/pool/shard011/JavaScript/0071054_blueprint-config-conflict-choice.spec.js @@ -0,0 +1,83 @@ +const crypto = require('crypto'); +const os = require('os'); +const path = require('path'); +const fse = require('fs-extra'); +const assert = require('yeoman-assert'); +const helpers = require('yeoman-test'); +const { MONOLITH } = require('../../jdl/jhipster/application-types'); + +const yoRc = { + 'generator-jhipster-myblueprint': { + applicationType: MONOLITH, + languages: ['fr'], + baseName: 'myblueprint', + }, + 'generator-jhipster-myblueprint2': { + applicationType: MONOLITH, + languages: ['en'], + baseName: 'myblueprint2', + }, + 'generator-jhipster': { + applicationType: MONOLITH, + baseName: 'jhipster', + jhipsterVersion: '6.6.0', + blueprints: [ + { + name: 'generator-jhipster-myblueprint', + version: '0.0.1', + }, + { + name: 'generator-jhipster-myblueprint2', + version: '0.0.1', + }, + ], + }, +}; + +describe('JHipster blueprint config migration with conflicts', () => { + const blueprintNames = ['generator-jhipster-myblueprint']; + + const tmpdir = path.join(os.tmpdir(), crypto.randomBytes(20).toString('hex')); + + blueprintNames.forEach(blueprintName => { + describe(`generate client with blueprint option '${blueprintName}'`, () => { + before(done => { + helpers + .run(path.join(__dirname, '../../generators/upgrade-config')) + .inDir(tmpdir, dir => { + // Fake the presence of the .yo-rc.json + fse.writeJsonSync(path.join(dir, '.yo-rc.json'), yoRc); + }) + .withOptions({ + fromCli: true, + skipChecks: true, + unifyConfigOnly: true, + }) + .withPrompts({ + // '#applicationType': 'monolith', + '#languages': ['en'], + '#baseName': 'myblueprint', + }) + .on('end', done); + }); + + it('.yo-rc.json', () => { + assert.JSONFileContent('.yo-rc.json', { + 'generator-jhipster-myblueprint': {}, + 'generator-jhipster': { + applicationType: MONOLITH, + jhipsterVersion: '6.6.0', + baseName: 'myblueprint', + languages: ['en'], + blueprints: [ + { + name: 'generator-jhipster-myblueprint', + version: '0.0.1', + }, + ], + }, + }); + }); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0071057_app.js b/pool/shard011/JavaScript/0071057_app.js new file mode 100644 index 0000000000000000000000000000000000000000..7ff341dc03edc5005f260e64fac89768a3792217 --- /dev/null +++ b/pool/shard011/JavaScript/0071057_app.js @@ -0,0 +1,78 @@ +var express = require('express'); +var path = require('path'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); + +var app = express(); + +var routes = require('./routes/index'); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs'); + +// uncomment after placing your favicon in /public +//app.use(favicon(__dirname + '/public/favicon.ico')); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: false })); +app.use(cookieParser()); +// app.use(express.static(path.join(___dirname, 'public'))); +app.use(express.static(path.join(__dirname, 'app'))); + +app.use(function (req, res, next) { + + // Website you wish to allow to connect + res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3001'); + + // Request methods you wish to allow + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); + + // Request headers you wish to allow + res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); + + // Set to true if you need the website to include cookies in the requests sent + // to the API (e.g. in case you use sessions) + res.setHeader('Access-Control-Allow-Credentials', true); + + // Pass to next layer of middleware + next(); +}); + +app.use('/', routes); + +// catch 404 and forward to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// error handlers + +// development error handler +// will print stacktrace +if (app.get('env') === 'development') { + app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +app.use(function(err, req, res, next) { + res.status(err.status || 500); + console.log("500: " + err.message) + res.render('error', { + message: err.message, + error: {} + }); +}); + + +module.exports = app; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071058_rtpbroadcast-thumbnail.js b/pool/shard011/JavaScript/0071058_rtpbroadcast-thumbnail.js new file mode 100644 index 0000000000000000000000000000000000000000..50f1a32e15c3ca807fbbdcd23c01ca39b1479ac6 --- /dev/null +++ b/pool/shard011/JavaScript/0071058_rtpbroadcast-thumbnail.js @@ -0,0 +1,81 @@ +var sinon = require('sinon'); +var fs = require('fs'); +var assert = require('chai').assert; +var Promise = require('bluebird'); +require('../../../helpers/globals'); +var serviceLocator = require('../../../../lib/service-locator'); +var RtpbroadcastThumbnailJob = require('../../../../lib/job/model/rtpbroadcast-thumbnail'); +var CmApplication = require('../../../../lib/cm-application'); +var tmpName = require('tmp').tmpNameSync; + +describe('RtpbroadcastThumbnailJob', function() { + + var cmApplication; + + before(function() { + cmApplication = sinon.createStubInstance(CmApplication); + serviceLocator.register('cm-application', cmApplication); + }); + + after(function() { + serviceLocator.unregister('cm-application'); + }); + + describe('given invalid jobData ', function() { + it('with missing jobData.thumb it should reject', function() { + var jobData = { + uid: 'stream-channel-id' + }; + assert.throws(function() { + new RtpbroadcastThumbnailJob('job-id', jobData); + }, /No `thumb` parameter provided/); + }); + }); + + describe('given valid jobData', function() { + + var job; + + before(function(done) { + var jobData = { + thumb: 'video-file', + uid: 'stream-channel-id', + createdAt: 1453395041 + }; + var configuration = { + createThumbnailCommand: 'thumbnail <%= videoMjrFile %> -param value <%= pngFile %>' + }; + var workingDirectory = tmpName(); + job = new RtpbroadcastThumbnailJob('job-id', jobData, configuration); + job.setWorkingDirectory(workingDirectory); + sinon.stub(job, '_spawn', function() { + return { + progress: function() { + return Promise.resolve({stdout: ''}); + } + }; + }); + job.run().catch(done).finally(done); + }); + + it('should extract png thumbnail from video file', function() { + var command = job._spawn.firstCall.args[0]; + var commandArgs = job._spawn.firstCall.args[1]; + assert.equal(command, 'thumbnail'); + assert.equal(commandArgs[0], 'video-file'); + assert.equal(commandArgs[1], '-param'); + assert.equal(commandArgs[2], 'value'); + assert.match(commandArgs[3], /\.png$/); + }); + + it('should import png file into cm-application', function() { + var commandArgs = job._spawn.firstCall.args[1]; + assert(cmApplication.importVideoStreamThumbnail.calledOnce, 'importVideoStreamThumbnail was not called'); + assert.equal(cmApplication.importVideoStreamThumbnail.firstCall.args[0], 'stream-channel-id'); + assert.equal(cmApplication.importVideoStreamThumbnail.firstCall.args[1], commandArgs[3]); + assert.equal(cmApplication.importVideoStreamThumbnail.firstCall.args[2], 1453395041); + }); + + }); +}); + diff --git a/pool/shard011/JavaScript/0071064_Gruntfile.js b/pool/shard011/JavaScript/0071064_Gruntfile.js new file mode 100644 index 0000000000000000000000000000000000000000..b13c05ce0bf37787964ac52e016821edad66a198 --- /dev/null +++ b/pool/shard011/JavaScript/0071064_Gruntfile.js @@ -0,0 +1,105 @@ +/** + * Grunt build file + * @author Jasper Palfree + */ + +'use strict'; + +module.exports = function(grunt) { + + var path = require('path'); + var pkg, config; + + pkg = grunt.file.readJSON('package.json'); + + config = { + + sourceDir: 'library', + compressedDir: 'library-build', + utils: '', // Any utils can go here + + pkg : pkg + }; + + // Project configuration. + grunt.initConfig({ + pkg: config.pkg, + config: config, + + jshint : { + options : { + jshintrc : 'jshint.json' + }, + source: [ + '<%= config.sourceDir %>/js/{.,modules,mediators}/*.js' + ] + }, + bgShell: { + _defaults: { + bg: false + }, + + watchCompass: { + cmd: 'compass watch', + bg: true + }, + + httpserver: { + cmd: 'jekyll server --watch', + bg: false + }, + + cleanCompass: { + cmd: 'compass clean --config <%= compass.dist.options.config %>', + options: { + stdout: true, + stderr: true, + failOnError: true + } + }, + }, + clean: [ + '<%= config.compressedDir %>' + ], + compass: { + dist: { + options: { + config: 'config.rb', + force: true + } + } + }, + img: { + app: { + src: '<%= config.compressedDir %>' + } + }, + // r.js optimization task + requirejs: { + app: { + options: require('./build/require-build') + } + } + }); + + // Load plugins + grunt.loadNpmTasks('grunt-bg-shell'); + grunt.loadNpmTasks('grunt-contrib-clean'); + grunt.loadNpmTasks('grunt-contrib-jshint'); + grunt.loadNpmTasks('grunt-img'); + grunt.loadNpmTasks('grunt-contrib-requirejs'); + grunt.loadNpmTasks('grunt-contrib-compass'); + + // Tasks + grunt.registerTask('compress-only', ['compass', 'requirejs:app']); + grunt.registerTask('server', ['bgShell:httpserver']); + + // Primary tasks + grunt.registerTask('cleanup', ['clean', 'bgShell:cleanCompass']); + grunt.registerTask('dev', [ 'bgShell:watchCompass', 'bgShell:httpserver' ]); + grunt.registerTask('build', ['cleanup', 'jshint:source', 'compress-only', 'img:app']); + + // Default task(s). + grunt.registerTask('default', ['build']); + +}; diff --git a/pool/shard011/JavaScript/0071066_sf.locker.js b/pool/shard011/JavaScript/0071066_sf.locker.js new file mode 100644 index 0000000000000000000000000000000000000000..c28e3f1ac54101bc3cea35ba2f51e6108a8e0080 --- /dev/null +++ b/pool/shard011/JavaScript/0071066_sf.locker.js @@ -0,0 +1,207 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(require("sf")); + else if(typeof define === 'function' && define.amd) + define(["sf"], factory); + else { + var a = typeof exports === 'object' ? factory(require("sf")) : factory(root["sf"]); + for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; + } +})(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + + var _sf = __webpack_require__(1); + + var _sf2 = _interopRequireDefault(_sf); + + var _Lock = __webpack_require__(2); + + var _Lock2 = _interopRequireDefault(_Lock); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + _sf2.default.registerInstanceType(_Lock2.default); //resolved in webpack's "externals" + + module.exports = _Lock2.default; // ES6 default export will not expose us as global + +/***/ }, +/* 1 */ +/***/ function(module, exports) { + + module.exports = __WEBPACK_EXTERNAL_MODULE_1__; + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + + var _sf = __webpack_require__(1); + + var _sf2 = _interopRequireDefault(_sf); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + //resolved in webpack's "externals" + + /** + * Spiral lock for forms + * @constructor Lock + */ + + var Lock = function Lock(sf, node, options) { + this._construct(sf, node, options); + }; + + /** + * @lends Lock.prototype + */ + Lock.prototype = _sf2.default.createModulePrototype(); + + /** + * Name of module + * @type {string} + */ + Lock.prototype.name = "lock"; + + /** + * Function that call on new instance is created. + * @param {Object} sf + * @param {Object} node DomNode of form + * @param {Object} [options] all options to override default + * @private + */ + Lock.prototype._construct = function (sf, node, options) { + this.init(sf, node, options); //call parent + this.add(this.options.type, this.node); + }; + /** + * Add lock + * @param {String} [type] type of lock @see sf.lock.types + * @param {Object} context context to add lock + * @returns {Function|*} + */ + Lock.prototype.add = function (type, context) { + if (!this.types.hasOwnProperty(type)) { + return false; + } + var node = document.createElement("div"); + node.className = this.types[type].className || 'js-sf-lock'; + node.innerHTML = this.types[type].html; + context.appendChild(node); + context.classList.add("locked"); + return this.types[type].progress; + }; + /** + * Clear all variables and die + */ + Lock.prototype.die = function () { + this.remove(); + }; + /** + * Remove lock + */ + Lock.prototype.remove = function () { + this.node.classList.remove("locked"); + var sfLock = this.node.querySelector(".js-sf-lock"); //todo this.lockNode ? + if (sfLock) { + this.node.removeChild(sfLock); + } + return true; + }; + /** + * Object with lock types. + * @enum {Object} + */ + Lock.prototype.types = { + /** + * @type {Object} + */ + spinner: { + /** + * HTML + * @inner + * @type String + */ + html: '
    ' + }, + progress: { + /** + * HTML + * @inner + * @type String + */ + html: '
    ', + /** + * Function to change styles while AJAX progress + * @param current + * @param total + */ + progress: function progress(current, total) { + var progress = this.context.getElementsByClassName("progress-line")[0]; + progress.style.width = 100 * (current / total) + "%"; + } + } + }; + + //we have to have some default locker, let it be spinner + Lock.prototype.types.default = Lock.prototype.types.spinner; + + exports.default = Lock; + +/***/ } +/******/ ]) +}); +; +//# sourceMappingURL=sf.locker.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071068_Actions.js b/pool/shard011/JavaScript/0071068_Actions.js new file mode 100644 index 0000000000000000000000000000000000000000..36db1353120b4b8cfd9c458148b830c36ed2a255 --- /dev/null +++ b/pool/shard011/JavaScript/0071068_Actions.js @@ -0,0 +1,249 @@ +var newAction = Ext.create('Ext.Action', { + icon: 'images/page_add.png', + text: 'New Action', + itemId: "newAction", + tooltip: "New Action", + handler: function(widget, event) { + var editor = this.up('actions'); + //if (editor == undefined){ + // editor = this.up('#treeContext').scriptEditor; + //} + editor.fireEvent('newAction'); + } +}); + +var recordStepsActionActions = Ext.create('Ext.Action', { + icon: 'images/media_record.png', + tooltip: "Start Looking Glass Utility", + margin: "0 3 0 3", + handler: function(widget, event) { + Redwood.app.getController("Scripts").onRecordSteps(); + } +}); + +var saveAction = Ext.create('Ext.Action', { + icon: "images/save.gif", + itemId:"saveAction", + tooltip: "Save Selected Action", + handler: function(widget, event) { + var editor = this.up('actions'); + editor.fireEvent('saveAction'); + } +}); + +var deleteAction = Ext.create('Ext.Action', { + icon: 'images/delete.png', + text: 'Delete', + itemId: "deleteAction", + tooltip: "Delete Selected Action", + handler: function(widget, event) { + var editor = this.up('actions'); + editor.fireEvent('deleteAction'); + } +}); + +var cloneAction = Ext.create('Ext.Action', { + icon: 'images/clone.png', + //text: 'Delete', + itemId: "cloneAction", + tooltip: "Clone Selected Action", + handler: function(widget, event) { + var editor = this.up('actions'); + editor.fireEvent('cloneAction'); + } +}); + +function formatAction(val,metaData,record) { + metaData.tdAttr = 'data-qtip="' + record.get("description") + '"'; + return ' '+val; +} + +Ext.define('Redwood.view.Actions', { + extend: 'Ext.panel.Panel', + alias: 'widget.actions', + id: "actionsBrowser", + title: "Actions", + layout: 'border', + + initComponent: function () { + + var actionListFlat = { + //region: 'west', + //split:true, + xtype: 'grid', + plugins: [ + "bufferedrenderer"], + hideCollapseTool: true, + //collapseDirection: "left", + //collapsible: true, + multiSelect: false, + id:"actionsGrid", + store: Ext.data.StoreManager.lookup('Actions'), + width: 206, + title: "Actions", + focused: false, + hideHeaders: true, + viewConfig: { + plugins: { + ptype: 'gridviewdragdrop', + enableDrag: true, + enableDrop: false, + ddGroup: "actionDrop" + //dragGroup: 'firstGridDDGroup', + //dropGroup: 'secondGridDDGroup' + }, + markDirty: false + }, + listeners:{ + itemdblclick: function(me, record, element, node_index, event) { + me.up('actions').fireEvent('editAction',record); + } + }, + columns: [ + { + //header: 'Actions', + dataIndex: 'name', + flex: 1, + renderer: formatAction + //width: 200 + } + ], + tbar: { + xtype: 'toolbar', + dock: 'top', + vertical:true, + items: [ + { + width: 200, + xtype: 'searchfield', + paramNames: ["tag","name"], + store: Ext.data.StoreManager.lookup('Actions') + }, + { + xtype:"filtercombo", + store: ["ALL","Automated","To be Automated","Needs Maintenance"], + propertyName:"status", + allValue:"ALL", + value:"ALL", + storeToFilter: Ext.data.StoreManager.lookup('Actions') + } + ] + + } + }; + + var actionListTree = { + xtype: 'treepanel', + plugins: [ + "bufferedrenderer"], + multiSelect: false, + hideCollapseTool: true, + rootVisible: false, + store: Ext.data.StoreManager.lookup('ActionsTree'), + width: 206, + title: "Actions Tree", + focused: false, + hideHeaders: true, + displayField:"name", + viewConfig: { + markDirty: false, + plugins: { + ptype: 'treeviewdragdrop', + enableDrag: true, + enableDrop: false, + ddGroup: "actionDrop" + } + }, + listeners:{ + itemdblclick: function(me, record, element, node_index, event) { + if (!record.get("tagValue")){ + var found = Ext.data.StoreManager.lookup('Actions').query("_id",record.get("_id"),false,true,true).getAt(0); + me.up('actions').fireEvent('editAction',found); + } + } + } + }; + + + this.items=[ + { + xtype:"panel", + layout: "accordion", + region: 'west', + split:true, + width: 206, + collapseDirection: "left", + hideHeaders: true, + collapsible: true, + items:[actionListFlat,actionListTree] + + }, + { + xtype:"panel", + region:"center", + layout: "fit", + //autoScroll:true, + tbar: { + xtype: 'toolbar', + dock: 'top', + items:[ + newAction, + saveAction, + " ", + deleteAction, + "-", + cloneAction, + recordStepsActionActions + ] + }, + items:[ + { + xtype:"tabpanel", + itemId: 'actionstab', + ui: "black-tab", + //defaults:{ autoScroll:true }, + plugins: [ + Ext.create('Ext.ux.TabCloseMenu', { + + }), + Ext.create('Ext.ux.TabReorderer', { + + }) + ], + listeners:{ + tabchange: function(me,tab){ + if (tab.dataRecord != null){ + window.history.replaceState("", "", '/index.html?action='+tab.dataRecord.get("_id")+"&project="+Ext.util.Cookies.get('project')); + } + else{ + window.history.replaceState("", "", '/index.html'); + } + }, + afterrender: function(me){ + me.items.on("remove",function(){ + if(me.items.length == 0){ + window.history.replaceState("", "", '/index.html'); + } + }) + } + } + } + ] + } + ]; + /* + this.tbar = { + xtype: 'toolbar', + dock: 'top', + items:[ + newAction, + saveAction, + " ", + deleteAction + ] + }; + */ + this.callParent(arguments); + } +}); + diff --git a/pool/shard011/JavaScript/0071071_attrs-proxy.js b/pool/shard011/JavaScript/0071071_attrs-proxy.js new file mode 100644 index 0000000000000000000000000000000000000000..c20ee49911ce37d304e2c87b31d0595a714b4065 --- /dev/null +++ b/pool/shard011/JavaScript/0071071_attrs-proxy.js @@ -0,0 +1,97 @@ +import { Mixin } from 'ember-metal/mixin'; +import { symbol } from 'ember-metal/utils'; +import { PROPERTY_DID_CHANGE } from 'ember-metal/property_events'; +import { on } from 'ember-metal/events'; + +export function deprecation(key) { + return `You tried to look up an attribute directly on the component. This is deprecated. Use attrs.${key} instead.`; +} + +export let MUTABLE_CELL = symbol('MUTABLE_CELL'); + +function isCell(val) { + return val && val[MUTABLE_CELL]; +} + +let AttrsProxyMixin = { + attrs: null, + + getAttr(key) { + let attrs = this.attrs; + if (!attrs) { return; } + return this.getAttrFor(attrs, key); + }, + + getAttrFor(attrs, key) { + let val = attrs[key]; + return isCell(val) ? val.value : val; + }, + + setAttr(key, value) { + let attrs = this.attrs; + let val = attrs[key]; + + if (!isCell(val)) { + throw new Error(`You can't update attrs.${key}, because it's not mutable`); + } + + val.update(value); + }, + + _propagateAttrsToThis() { + let attrs = this.attrs; + let values = {}; + for (let prop in attrs) { + if (prop !== 'attrs') { + values[prop] = this.getAttr(prop); + } + } + this.setProperties(values); + }, + + initializeShape: on('init', function() { + this._isDispatchingAttrs = false; + }), + + didReceiveAttrs() { + this._super(); + this._isDispatchingAttrs = true; + this._propagateAttrsToThis(); + this._isDispatchingAttrs = false; + }, + + + unknownProperty(key) { + if (this._isAngleBracket) { return; } + + var attrs = this.attrs; + + if (attrs && key in attrs) { + // do not deprecate accessing `this[key]` at this time. + // add this back when we have a proper migration path + // Ember.deprecate(deprecation(key), { id: 'ember-views.', until: '3.0.0' }); + let possibleCell = attrs.key; + + if (possibleCell && possibleCell[MUTABLE_CELL]) { + return possibleCell.value; + } + + return possibleCell; + } + } + + //setUnknownProperty(key) { + + //} +}; + +AttrsProxyMixin[PROPERTY_DID_CHANGE] = function(key) { + if (this._isAngleBracket) { return; } + if (this._isDispatchingAttrs) { return; } + + if (this.currentState) { + this.currentState.legacyPropertyDidChange(this, key); + } +}; + +export default Mixin.create(AttrsProxyMixin); diff --git a/pool/shard011/JavaScript/0071072_string.js b/pool/shard011/JavaScript/0071072_string.js new file mode 100644 index 0000000000000000000000000000000000000000..18715bacd4f098c8e5dcf0632199b43dd412621f --- /dev/null +++ b/pool/shard011/JavaScript/0071072_string.js @@ -0,0 +1,128 @@ +/** + * @fileoverview This module has some functions for handling the string. + * @author NHN. + * FE Development Lab + */ + +'use strict'; + +var collection = require('./collection'); +var object = require('./object'); +/** + * Transform the given HTML Entity string into plain string + * @param {String} htmlEntity - HTML Entity type string + * @returns {String} Plain string + * @memberof tui.util + * @example + * //-- #1. Get Module --// + * var util = require('tui-code-snippet'); // node, commonjs + * var util = tui.util; // distribution file + * + * //-- #2. Use property --// + * var htmlEntityString = "A 'quote' is <b>bold</b>" + * var result = util.decodeHTMLEntity(htmlEntityString); //"A 'quote' is bold" + */ +function decodeHTMLEntity(htmlEntity) { + var entities = { + '"': '"', + '&': '&', + '<': '<', + '>': '>', + ''': '\'', + ' ': ' ' + }; + + return htmlEntity.replace(/&|<|>|"|'| /g, function(m0) { + return entities[m0] ? entities[m0] : m0; + }); +} + +/** + * Transform the given string into HTML Entity string + * @param {String} html - String for encoding + * @returns {String} HTML Entity + * @memberof tui.util + * @example + * //-- #1. Get Module --// + * var util = require('tui-code-snippet'); // node, commonjs + * var util = tui.util; // distribution file + * + * //-- #2. Use property --// + * var htmlEntityString = "
    "; + * var result = util.encodeHTMLEntity(htmlEntityString); + * //"<script> alert('test');</script><a href='test'>" + */ +function encodeHTMLEntity(html) { + var entities = { + '"': 'quot', + '&': 'amp', + '<': 'lt', + '>': 'gt', + '\'': '#39' + }; + + return html.replace(/[<>&"']/g, function(m0) { + return entities[m0] ? '&' + entities[m0] + ';' : m0; + }); +} + +/** + * Return whether the string capable to transform into plain string is in the given string or not. + * @param {String} string - test string + * @memberof tui.util + * @returns {boolean} + */ +function hasEncodableString(string) { + return (/[<>&"']/).test(string); +} + +/** + * Return duplicate charters + * @param {string} operandStr1 The operand string + * @param {string} operandStr2 The operand string + * @private + * @memberof tui.util + * @returns {string} + * @example + * //-- #1. Get Module --// + * var util = require('tui-code-snippet'); // node, commonjs + * var util = tui.util; // distribution file + * + * //-- #2. Use property --// + * util.getDuplicatedChar('fe dev', 'nhn entertainment'); // 'e' + * util.getDuplicatedChar('fdsa', 'asdf'); // 'asdf' + */ +function getDuplicatedChar(operandStr1, operandStr2) { + var i = 0; + var len = operandStr1.length; + var pool = {}; + var dupl, key; + + for (; i < len; i += 1) { + key = operandStr1.charAt(i); + pool[key] = 1; + } + + for (i = 0, len = operandStr2.length; i < len; i += 1) { + key = operandStr2.charAt(i); + if (pool[key]) { + pool[key] += 1; + } + } + + pool = collection.filter(pool, function(item) { + return item > 1; + }); + + pool = object.keys(pool).sort(); + dupl = pool.join(''); + + return dupl; +} + +module.exports = { + decodeHTMLEntity: decodeHTMLEntity, + encodeHTMLEntity: encodeHTMLEntity, + hasEncodableString: hasEncodableString, + getDuplicatedChar: getDuplicatedChar +}; diff --git a/pool/shard011/JavaScript/0071073_prod.server.js b/pool/shard011/JavaScript/0071073_prod.server.js new file mode 100644 index 0000000000000000000000000000000000000000..d5e0dbf1567ac2126666b4b3e7bca24840d9c350 --- /dev/null +++ b/pool/shard011/JavaScript/0071073_prod.server.js @@ -0,0 +1,55 @@ +var express = require('express') +var axios = require('axios') +var config = require('./config/index') +var port = process.env.PORT || config.build.port +var app = express() +var apiRoutes = express.Router() + +apiRoutes.get('/getDistList', function (req, res) { + var url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg' + axios.get(url, { + headers: { + referer: 'https://c.y.qq.com/', + host: 'c.y.qq.com' + }, + params: req.query + }).then((response) => { + res.json(response.data) + }).catch((err) => { + console.log(err) + }) +}) + +apiRoutes.get('/lyric', function (req, res) { + var url = 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg' + axios.get(url, { + headers: { + referer: 'https://c.y.qq.com/', + host: 'c.y.qq.com' + }, + params: req.query + }).then((response) => { + var ret = response.data + if (typeof ret === 'string') { + var reg = /^\w+\(({[^()]+})\)$/ + var matches = ret.match(reg) + if (matches) { + ret = JSON.parse(matches[1]) + } + } + res.json(ret) + }).catch((err) => { + console.log(err) + }) +}) +app.use('/api', apiRoutes) + +app.use(express.static('./dist')) + +module.exports = app.listen(port, function(err) { + if (err) { + console.log(err) + return + } + console.log('listening at http://localhost:' + port + '\n') +}) diff --git a/pool/shard011/JavaScript/0071074_index.js b/pool/shard011/JavaScript/0071074_index.js new file mode 100644 index 0000000000000000000000000000000000000000..1c32b3825acfd31122536968aa43b2effe1951bd --- /dev/null +++ b/pool/shard011/JavaScript/0071074_index.js @@ -0,0 +1,64 @@ +/** + * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * + */ + +'use strict'; + +const path = require('path'); +const loadFromFile = require('./loadFromFile'); +const loadFromPackage = require('./loadFromPackage'); +const normalize = require('./normalize'); +const setFromArgv = require('./setFromArgv'); + +const readConfig = (argv, packageRoot) => +readRawConfig(argv, packageRoot). +then((_ref) => {let config = _ref.config,hasDeprecationWarnings = _ref.hasDeprecationWarnings;return { + config: Object.freeze(setFromArgv(config, argv)), + hasDeprecationWarnings };}); + + +const parseConfig = argv => { + if (argv.config && typeof argv.config === 'string') { + // If the passed in value looks like JSON, treat it as an object. + if (argv.config[0] === '{' && argv.config[argv.config.length - 1] === '}') { + return JSON.parse(argv.config); + } + } + return argv.config; +}; + +const readRawConfig = (argv, root) => { + const rawConfig = parseConfig(argv); + + if (typeof rawConfig === 'string') { + return loadFromFile(path.resolve(process.cwd(), rawConfig), argv); + } + + if (typeof rawConfig === 'object') { + const config = Object.assign({}, rawConfig); + config.rootDir = config.rootDir || root; + return Promise.resolve(normalize(config, argv)); + } + + return loadFromPackage(path.join(root, 'package.json'), argv). + then((_ref2) => {let config = _ref2.config,hasDeprecationWarnings = _ref2.hasDeprecationWarnings; + if (config) { + return { + config, + hasDeprecationWarnings }; + + } + + return normalize({ rootDir: root }, argv); + }); +}; + +module.exports = { + normalize, + readConfig }; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071078_bench.js b/pool/shard011/JavaScript/0071078_bench.js new file mode 100644 index 0000000000000000000000000000000000000000..7ef9f47e41601889fb1d152f37edc8a87128b47e --- /dev/null +++ b/pool/shard011/JavaScript/0071078_bench.js @@ -0,0 +1,77 @@ +import path from 'path'; +import glob from 'glob'; +import load from 'load-json-file'; +import Benchmark from 'benchmark'; +import cleanCoords from './'; + +/** + * Benchmark Results + * + * geometry: 0.675ms + * multiline: 0.044ms + * multipoint: 0.291ms + * multipolygon: 0.062ms + * point: 0.010ms + * polygon-with-hole: 0.017ms + * polygon: 0.010ms + * simple-line: 0.008ms + * triangle: 0.020ms + * + * // mutate=false (using geometry/feature) + * geometry x 1,524,640 ops/sec ±4.60% (74 runs sampled) + * multiline x 1,511,608 ops/sec ±8.79% (72 runs sampled) + * multipoint x 382,429 ops/sec ±3.56% (84 runs sampled) + * multipolygon x 808,277 ops/sec ±2.84% (82 runs sampled) + * point x 14,675,464 ops/sec ±4.42% (80 runs sampled) + * polygon-with-hole x 1,493,507 ops/sec ±5.53% (72 runs sampled) + * polygon x 2,386,278 ops/sec ±1.27% (86 runs sampled) + * simple-line x 4,195,499 ops/sec ±2.88% (86 runs sampled) + * triangle x 2,254,753 ops/sec ±1.10% (88 runs sampled) + * + * // mutate=false (using @turf/clone) + * geometry x 202,410 ops/sec ±1.43% (88 runs sampled) + * multiline x 235,421 ops/sec ±3.48% (86 runs sampled) + * multipoint x 280,757 ops/sec ±1.59% (87 runs sampled) + * multipolygon x 127,353 ops/sec ±1.35% (88 runs sampled) + * point x 18,233,987 ops/sec ±1.34% (86 runs sampled) + * polygon-with-hole x 199,203 ops/sec ±2.61% (84 runs sampled) + * polygon x 355,616 ops/sec ±1.58% (86 runs sampled) + * simple-line x 515,430 ops/sec ±2.40% (83 runs sampled) + * triangle x 286,315 ops/sec ±1.64% (86 runs sampled) + * + * // mutate=false (using JSON.parse + JSON.stringify) + * geometry x 93,681 ops/sec ±7.66% (75 runs sampled) + * multiline x 112,836 ops/sec ±4.60% (82 runs sampled) + * multipoint x 113,937 ops/sec ±1.09% (90 runs sampled) + * multipolygon x 71,131 ops/sec ±1.32% (90 runs sampled) + * point x 18,181,612 ops/sec ±1.36% (91 runs sampled) + * polygon-with-hole x 100,011 ops/sec ±1.14% (85 runs sampled) + * polygon x 154,331 ops/sec ±1.31% (89 runs sampled) + * simple-line x 193,304 ops/sec ±1.33% (90 runs sampled) + * triangle x 130,921 ops/sec ±3.37% (87 runs sampled) + * + * // mutate=true + * geometry x 2,016,365 ops/sec ±1.83% (85 runs sampled) + * multiline x 2,266,787 ops/sec ±3.69% (79 runs sampled) + * multipoint x 411,246 ops/sec ±0.81% (89 runs sampled) + * multipolygon x 1,011,846 ops/sec ±1.34% (85 runs sampled) + * point x 17,635,961 ops/sec ±1.47% (89 runs sampled) + * polygon-with-hole x 2,110,166 ops/sec ±1.59% (89 runs sampled) + * polygon x 2,887,298 ops/sec ±1.75% (86 runs sampled) + * simple-line x 7,109,682 ops/sec ±1.52% (87 runs sampled) + * triangle x 3,116,940 ops/sec ±0.71% (87 runs sampled) + */ +const suite = new Benchmark.Suite('turf-clean-coords'); +glob.sync(path.join(__dirname, 'test', 'in', '*.geojson')).forEach(filepath => { + const {name} = path.parse(filepath); + const geojson = load.sync(filepath); + console.time(name); + cleanCoords(geojson); + console.timeEnd(name); + suite.add(name, () => cleanCoords(geojson, true)); +}); + +suite + .on('cycle', e => console.log(String(e.target))) + .on('complete', () => {}) + .run(); diff --git a/pool/shard011/JavaScript/0071079_content-encapsulate.js b/pool/shard011/JavaScript/0071079_content-encapsulate.js new file mode 100644 index 0000000000000000000000000000000000000000..2a0dd926c9fad2a6aaf4ba7ff0eaba86098c54c7 --- /dev/null +++ b/pool/shard011/JavaScript/0071079_content-encapsulate.js @@ -0,0 +1,173 @@ +//encoding=utf-8 + +var InputArea=function(){ + var BG_IMG_WIDTH=16; + var BG_IMG_HEIGHT=16; + var BG_IMG_URL_PATH=chrome.extension.getURL("images/"); + var LOCK_IMG=BG_IMG_URL_PATH+"lock.png"; + var LOCK_HIGHLIGHT_IMG=BG_IMG_URL_PATH+"lockHighlight.png"; + var LOADING_IMG=BG_IMG_URL_PATH+"loading.gif"; + var ORIGINAL_STYLE; + var TITLE=chrome.i18n.getMessage("encapsulate"); + //当切换到领域个标签页再重回原标签页时可能造成连续两次focus事件,造成ORIGINAL_STYLE变量存储错误 + //使用ON_FOCUS变量处理这一情况 + var ON_FOCUS=false; + + + return { + changeStyle:function(styleStr,styleName,styleValue){ + if(styleStr.indexOf(styleName) < 0){ + styleStr+="; "+styleName+":"+styleValue; + }else{ + if(styleStr.charAt(ORIGINAL_STYLE.length-1)!=";"){ + styleStr+=";"; + } + var pattern=new RegExp(styleName+":.+?;"); + var a=styleStr.match(pattern); + styleStr=styleStr.replace(pattern, styleName+":"+styleValue); + } + return styleStr; + }, + addBgImage:function (elem,img,cursor,saveOrignalStyle){ + if(cursor == null){ + var cursor = "auto"; + } + var x= elem.width()-BG_IMG_WIDTH; + var y= elem.height()-BG_IMG_HEIGHT; + if(saveOrignalStyle!=null && saveOrignalStyle==true){ + ORIGINAL_STYLE=elem.attr("style"); + + } + var myStyle=ORIGINAL_STYLE; + if(myStyle==null || myStyle==""){ + myStyle="background-image:url("+img+"); cursor: "+cursor+"; background-position: "+x+"px "+y+"px; background-repeat: no-repeat no-repeat; "; + }else{ + myStyle=InputArea.changeStyle(myStyle,"background-image","url("+img+")"); + myStyle=InputArea.changeStyle(myStyle,"cursor",cursor); + myStyle=InputArea.changeStyle(myStyle,"background-position",x+"px "+y+"px"); + myStyle=InputArea.changeStyle(myStyle,"background-repeat","no-repeat no-repeat"); + } + elem.attr("style",myStyle); + }, + recoverOriginalStyle:function (elem){ + if(ORIGINAL_STYLE==null || ORIGINAL_STYLE==""){ + elem.removeAttr("style"); + }else{ + elem.attr("style",ORIGINAL_STYLE); + } + }, + onFocus:function(event){ + if(ON_FOCUS==false){ + ON_FOCUS=true; + var elem=$(event.target); + console.log(elem+" focus"); + InputArea.addBgImage(elem,LOCK_IMG,null,true); + elem.mouseover(InputArea.onMouseover); + elem.mouseout(InputArea.onMouseout); + elem.click(InputArea.onClick); + elem.blur(InputArea.onBlur); + } + }, + onBlur:function(event){ + ON_FOCUS=false; + var elem=$(event.target); + console.log(elem+" blur"); + elem.unbind("mouseover",InputArea.onMouseover); + elem.unbind("mouseout",InputArea.onMouseout); + elem.unbind("click",InputArea.onClick); + elem.unbind("blur",InputArea.onBlur); + InputArea.recoverOriginalStyle(elem); + }, + onMouseover:function(event){ + var elem=$(event.target); + console.log(elem+" mouseover"); + if(InputArea.isEventOccurOverBgImg(event,elem)){ + // console.log("show hightlight background image"); + InputArea.addBgImage(elem,LOCK_HIGHLIGHT_IMG,"pointer"); + elem.attr("title",TITLE); + }else{ + elem.removeAttr("title"); + } + }, + onMouseout:function(event){ + var elem=$(event.target); + console.log(elem+" mouseout"); + InputArea.addBgImage(elem,LOCK_IMG); + elem.removeAttr("title"); + }, + onClick:function(event){ + var elem=$(event.target); + console.log(elem+" click"); + if(InputArea.isEventOccurOverBgImg(event,elem)){ + var text; + if(elem[0].tagName=="DIV"){ + text=elem.text(); + }else{ + text=elem.val(); + } + if(text ==""){ + return; + } + console.log("callBackground Vanish.encapsulate, text="+text); + var callback=function(result){ + if(elem[0].tagName=="DIV"){ + text=elem.text(result); + }else{ + text=elem.val(result); + } + InputArea.addBgImage(elem,LOCK_IMG); + }; + InputArea.addBgImage(elem,LOADING_IMG); + callBackground("Vanish.encapsulate",[text,callback]); + } + }, + isEventOccurOverBgImg:function(event,elem){ + var x=elem.offset().left+elem.width()-2*BG_IMG_WIDTH; + var y=elem.offset().top+elem.height()-2*BG_IMG_HEIGHT; + // console.log("x="+x+" ,pageX="+event.pageX+"\ny="+y+" ,pageY="+event.pageY); + if(event.pageX>x && event.pageY>y){ + return true; + } + return false; + } + + } +}(); + + +function addFoucsHandler(){ + var text=$(':input[type="text"]'); + // text.val("got it"); + var textarea=$('textarea'); + // textarea.val("got it2"); + + var webQQTextarea=$('.rich_editor_div'); + var webFeitionTextarea=$('.chat_textarea'); + text.unbind("focus",InputArea.onFocus); + textarea.unbind("focus",InputArea.onFocus); + webQQTextarea.unbind("focus",InputArea.onFocus); + webFeitionTextarea.unbind("focus",InputArea.onFocus); + + var callback=function(result){ + if(result=="true"){ + text.focus(InputArea.onFocus); + textarea.focus(InputArea.onFocus); + webQQTextarea.focus(InputArea.onFocus); + webFeitionTextarea.focus(InputArea.onFocus); + } + }; + callBackground("isButtonEnable",[callback]); +} + +//有些网页的输入框是动态加载的,使用Timer可以支持这一种情况,并可以定期检查按键是否启用 +function initTimer(){ + addFoucsHandler(); + setTimeout("initTimer()",1000); +} + +$(document).ready(function(){ + initTimer(); +}); + + + diff --git a/pool/shard011/JavaScript/0071081_toolbar.js b/pool/shard011/JavaScript/0071081_toolbar.js new file mode 100644 index 0000000000000000000000000000000000000000..9d1d4034664b04f058561d300bf7f76767d79eb3 --- /dev/null +++ b/pool/shard011/JavaScript/0071081_toolbar.js @@ -0,0 +1,104 @@ +/** + * Axis + * + * This file is part of Axis. + * + * Axis is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Axis is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Axis. If not, see . + * + * @copyright Copyright 2008-2012 Axis + * @license GNU Public License V3.0 + */ + +Ext.onReady(function(){ + + var toolbar = new Ext.Toolbar({ + items:[ + new Ext.form.TextField({ + width: 130, + emptyText:'Find by Word'.l(), + listeners:{ + render: function(f){ + f.el.on('keydown', filterTree, f, {buffer: 350}); + } + } + }), + new Ext.Button({ + cls: 'x-btn-icon', + icon: Axis.skinUrl + '/images/icons/tree_expand.png', + tooltip: 'Expand'.l(), + handler: function() { + CommentTree.el.root.expand(true); + } + }), '-', + new Ext.Button({ + cls: 'x-btn-icon', + icon: Axis.skinUrl + '/images/icons/tree_collapse.png', + tooltip: 'Collapse'.l(), + handler: function() { + CommentTree.el.root.collapse(true); + } + }) + ] + }); + + var searchPanel = new Ext.Panel({ + bodyStyle: 'border: 1px solid #D0D0D0; border-width: 1px 1px 0;', + region: 'north', + id: 'panel-search', + height: 26, + items: toolbar + }); +}); + +var hiddenPkgs = []; +var markCount = []; + +function filterTree(e){ + var text = e.target.value; + Ext.each(hiddenPkgs, function(n){ + n.ui.show(); + }); + + markCount = []; + hiddenPkgs = []; + + if( text.trim().length > 0 ){ + CommentTree.el.expandAll(); + + var re = new RegExp( Ext.escapeRe(text), 'i'); + CommentTree.el.root.cascade( function( n ){ + if( re.test(n.text) ) + markToRoot( n, CommentTree.el.root ); + }); + + // hide empty packages that weren't filtered + CommentTree.el.root.cascade(function(n){ + if( ( !markCount[n.id] || markCount[n.id] == 0 ) && n != CommentTree.el.root ){ + n.ui.hide(); + hiddenPkgs.push(n); + } + }); + } +} + +function markToRoot( n, root ){ + + if( markCount[n.id] ) + return; + + markCount[n.id] = 1; + + if( n.parentNode != null ) + markToRoot( n.parentNode, root ); +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071083_component.js b/pool/shard011/JavaScript/0071083_component.js new file mode 100644 index 0000000000000000000000000000000000000000..a84aaef2bb2c5eaa1997c1a46336205a81b60526 --- /dev/null +++ b/pool/shard011/JavaScript/0071083_component.js @@ -0,0 +1,220 @@ +/** + * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components + * @version v6.2.0 + * @link http://www.ag-grid.com/ + * @license MIT + */ +var utils_1 = require('../utils'); +var eventService_1 = require("../eventService"); +var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); +var Component = (function () { + function Component(template) { + this.destroyFunctions = []; + this.childComponents = []; + this.annotatedEventListeners = []; + this.visible = true; + if (template) { + this.setTemplate(template); + } + } + Component.prototype.instantiate = function (context) { + this.instantiateRecurse(this.getGui(), context); + }; + Component.prototype.instantiateRecurse = function (parentNode, context) { + var childCount = parentNode.childNodes ? parentNode.childNodes.length : 0; + for (var i = 0; i < childCount; i++) { + var childNode = parentNode.childNodes[i]; + var newComponent = context.createComponent(childNode); + if (newComponent) { + this.swapComponentForNode(newComponent, parentNode, childNode); + } + else { + if (childNode.childNodes) { + this.instantiateRecurse(childNode, context); + } + } + } + }; + Component.prototype.swapComponentForNode = function (newComponent, parentNode, childNode) { + parentNode.replaceChild(newComponent.getGui(), childNode); + this.childComponents.push(newComponent); + this.swapInComponentForQuerySelectors(newComponent, childNode); + }; + Component.prototype.swapInComponentForQuerySelectors = function (newComponent, childNode) { + var metaData = this.__agComponentMetaData; + if (!metaData || !metaData.querySelectors) { + return; + } + var thisNoType = this; + metaData.querySelectors.forEach(function (querySelector) { + if (thisNoType[querySelector.attributeName] === childNode) { + thisNoType[querySelector.attributeName] = newComponent; + } + }); + }; + Component.prototype.setTemplate = function (template) { + this.eGui = utils_1.Utils.loadTemplate(template); + this.eGui.__agComponent = this; + this.addAnnotatedEventListeners(); + this.wireQuerySelectors(); + }; + Component.prototype.wireQuerySelectors = function () { + var _this = this; + var metaData = this.__agComponentMetaData; + if (!metaData || !metaData.querySelectors) { + return; + } + if (!this.eGui) { + return; + } + var thisNoType = this; + metaData.querySelectors.forEach(function (querySelector) { + var resultOfQuery = _this.eGui.querySelector(querySelector.querySelector); + if (resultOfQuery) { + var backingComponent = resultOfQuery.__agComponent; + if (backingComponent) { + thisNoType[querySelector.attributeName] = backingComponent; + } + else { + thisNoType[querySelector.attributeName] = resultOfQuery; + } + } + else { + } + }); + }; + Component.prototype.addAnnotatedEventListeners = function () { + var _this = this; + this.removeAnnotatedEventListeners(); + var metaData = this.__agComponentMetaData; + if (!metaData || !metaData.listenerMethods) { + return; + } + if (!this.eGui) { + return; + } + if (!this.annotatedEventListeners) { + this.annotatedEventListeners = []; + } + metaData.listenerMethods.forEach(function (eventListener) { + var listener = _this[eventListener.methodName].bind(_this); + _this.eGui.addEventListener(eventListener.eventName, listener); + _this.annotatedEventListeners.push({ eventName: eventListener.eventName, listener: listener }); + }); + }; + Component.prototype.removeAnnotatedEventListeners = function () { + var _this = this; + if (!this.annotatedEventListeners) { + return; + } + if (!this.eGui) { + return; + } + this.annotatedEventListeners.forEach(function (eventListener) { + _this.eGui.removeEventListener(eventListener.eventName, eventListener.listener); + }); + this.annotatedEventListeners = null; + }; + Component.prototype.addEventListener = function (eventType, listener) { + if (!this.localEventService) { + this.localEventService = new eventService_1.EventService(); + } + this.localEventService.addEventListener(eventType, listener); + }; + Component.prototype.removeEventListener = function (eventType, listener) { + if (this.localEventService) { + this.localEventService.removeEventListener(eventType, listener); + } + }; + Component.prototype.dispatchEventAsync = function (eventType, event) { + var _this = this; + setTimeout(function () { return _this.dispatchEvent(eventType, event); }, 0); + }; + Component.prototype.dispatchEvent = function (eventType, event) { + if (this.localEventService) { + this.localEventService.dispatchEvent(eventType, event); + } + }; + Component.prototype.getGui = function () { + return this.eGui; + }; + Component.prototype.queryForHtmlElement = function (cssSelector) { + return this.eGui.querySelector(cssSelector); + }; + Component.prototype.queryForHtmlInputElement = function (cssSelector) { + return this.eGui.querySelector(cssSelector); + }; + Component.prototype.appendChild = function (newChild) { + if (utils_1.Utils.isNodeOrElement(newChild)) { + this.eGui.appendChild(newChild); + } + else { + var childComponent = newChild; + this.eGui.appendChild(childComponent.getGui()); + this.childComponents.push(childComponent); + } + }; + Component.prototype.isVisible = function () { + return this.visible; + }; + Component.prototype.setVisible = function (visible) { + if (visible !== this.visible) { + this.visible = visible; + utils_1.Utils.addOrRemoveCssClass(this.eGui, 'ag-hidden', !visible); + this.dispatchEvent(Component.EVENT_VISIBLE_CHANGED, { visible: this.visible }); + } + }; + Component.prototype.addOrRemoveCssClass = function (className, addOrRemove) { + utils_1.Utils.addOrRemoveCssClass(this.eGui, className, addOrRemove); + }; + Component.prototype.destroy = function () { + this.childComponents.forEach(function (childComponent) { return childComponent.destroy(); }); + this.destroyFunctions.forEach(function (func) { return func(); }); + this.removeAnnotatedEventListeners(); + }; + Component.prototype.addGuiEventListener = function (event, listener) { + var _this = this; + this.getGui().addEventListener(event, listener); + this.destroyFunctions.push(function () { return _this.getGui().removeEventListener(event, listener); }); + }; + Component.prototype.addDestroyableEventListener = function (eElement, event, listener) { + if (eElement instanceof HTMLElement) { + eElement.addEventListener(event, listener); + } + else if (eElement instanceof gridOptionsWrapper_1.GridOptionsWrapper) { + eElement.addEventListener(event, listener); + } + else { + eElement.addEventListener(event, listener); + } + this.destroyFunctions.push(function () { + if (eElement instanceof HTMLElement) { + eElement.removeEventListener(event, listener); + } + else if (eElement instanceof gridOptionsWrapper_1.GridOptionsWrapper) { + eElement.removeEventListener(event, listener); + } + else { + eElement.removeEventListener(event, listener); + } + }); + }; + Component.prototype.addDestroyFunc = function (func) { + this.destroyFunctions.push(func); + }; + Component.prototype.addCssClass = function (className) { + utils_1.Utils.addCssClass(this.getGui(), className); + }; + Component.prototype.getAttribute = function (key) { + var eGui = this.getGui(); + if (eGui) { + return eGui.getAttribute(key); + } + else { + return null; + } + }; + Component.EVENT_VISIBLE_CHANGED = 'visibleChanged'; + return Component; +})(); +exports.Component = Component; diff --git a/pool/shard011/JavaScript/0071085_runner.js b/pool/shard011/JavaScript/0071085_runner.js new file mode 100644 index 0000000000000000000000000000000000000000..fecefa39aef0c2ddffe8dde52a0c2238c08dd426 --- /dev/null +++ b/pool/shard011/JavaScript/0071085_runner.js @@ -0,0 +1,82 @@ +'use strict'; + +var sinon = require('sinon'); +var expect = require('chai').use(require('sinon-chai')).expect; +var nock = require('nock'); +var qs = require('qs'); +var runner = require('../'); +var pipeline = require('../src/pipeline'); +var Pool = require('../src/pool'); + +var mappings, messages, twilio; +before(function () { + mappings = nock('https://cache-aws-us-east-1.iron.io'); + messages = nock('https://mq-aws-us-east-1.iron.io'); + twilio = nock('https://api.twilio.com'); +}); +afterEach(function () { + mappings.done(); + messages.done(); + twilio.done(); +}); +after(function () { + nock.cleanAll(); +}); + +it('delivers to a given destination with the same source number', function () { + // First we ask twilio for all our numbers + twilio + .get('/2010-04-01/Accounts/accSid/IncomingPhoneNumbers.json?PageSize=1000') + .reply(200, { + incoming_phone_numbers: [ + { + sid: 'PN1234', + phone_number: '+12125551234' + } + ] + }); + // Next we ask IronMQ for up to 100 queued SMS messages + messages + .get('/1/projects/ironProj/queues/sms-messages/messages?n=100') + .reply(200, { + messages: [{ + id: 1, + body: JSON.stringify({ + to: '+17185551234', + body: 'Hello!' + }) + }] + }); + // We get one messages and check the cache for an SID of a from number + mappings + .get('/1/projects/ironProj/caches/sms-mappings/items/%2B17185551234?oauth=ironTok') + .reply(200, { + cache: 'sms-mappings', + value: 'PN1234' + }); + twilio + .post('/2010-04-01/Accounts/accSid/SMS/Messages.json', qs.stringify({ + From: '+12125551234', + To: '+17185551234', + Body: 'Hello!' + })) + .reply(201, {}); + // the messages is sent successfully so we delete it from IronMQ + messages + .delete('/1/projects/ironProj/queues/sms-messages/messages/1') + .reply(200, { + msg: 'Deleted.' + }); + // the runner will check for more messages and find none + messages + .get('/1/projects/ironProj/queues/sms-messages/messages?n=100') + .reply(200, { + messages: [] + }); + sinon.spy(pipeline, 'extract') + return runner.start() + .then(function () { + expect(pipeline.extract).to.have.been.calledTwice; + expect(pipeline.extract).to.have.always.been.calledOn(sinon.match.instanceOf(Pool)); + }); +}); diff --git a/pool/shard011/JavaScript/0071088_plugin.js b/pool/shard011/JavaScript/0071088_plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..9b0488c9c2165b7371e6ed73186e75a59f2b92a0 --- /dev/null +++ b/pool/shard011/JavaScript/0071088_plugin.js @@ -0,0 +1,185 @@ +/** + * Copyright (c) Tiny Technologies, Inc. All rights reserved. + * Licensed under the LGPL or a commercial license. + * For LGPL see License.txt in the project root for license information. + * For commercial licenses see https://www.tiny.cloud/ + * + * Version: 5.6.1 (2020-11-25) + */ +(function () { + 'use strict'; + + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); + + var global$1 = tinymce.util.Tools.resolve('tinymce.Env'); + + var getAutoLinkPattern = function (editor) { + return editor.getParam('autolink_pattern', /^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|(?:mailto:)?[A-Z0-9._%+\-]+@(?!.*@))(.+)$/i); + }; + var getDefaultLinkTarget = function (editor) { + return editor.getParam('default_link_target', false); + }; + var getDefaultLinkProtocol = function (editor) { + return editor.getParam('link_default_protocol', 'http', 'string'); + }; + + var rangeEqualsDelimiterOrSpace = function (rangeString, delimiter) { + return rangeString === delimiter || rangeString === ' ' || rangeString.charCodeAt(0) === 160; + }; + var handleEclipse = function (editor) { + parseCurrentLine(editor, -1, '('); + }; + var handleSpacebar = function (editor) { + parseCurrentLine(editor, 0, ''); + }; + var handleEnter = function (editor) { + parseCurrentLine(editor, -1, ''); + }; + var scopeIndex = function (container, index) { + if (index < 0) { + index = 0; + } + if (container.nodeType === 3) { + var len = container.data.length; + if (index > len) { + index = len; + } + } + return index; + }; + var setStart = function (rng, container, offset) { + if (container.nodeType !== 1 || container.hasChildNodes()) { + rng.setStart(container, scopeIndex(container, offset)); + } else { + rng.setStartBefore(container); + } + }; + var setEnd = function (rng, container, offset) { + if (container.nodeType !== 1 || container.hasChildNodes()) { + rng.setEnd(container, scopeIndex(container, offset)); + } else { + rng.setEndAfter(container); + } + }; + var parseCurrentLine = function (editor, endOffset, delimiter) { + var end, endContainer, bookmark, text, prev, len, rngText; + var autoLinkPattern = getAutoLinkPattern(editor); + var defaultLinkTarget = getDefaultLinkTarget(editor); + if (editor.selection.getNode().tagName === 'A') { + return; + } + var rng = editor.selection.getRng().cloneRange(); + if (rng.startOffset < 5) { + prev = rng.endContainer.previousSibling; + if (!prev) { + if (!rng.endContainer.firstChild || !rng.endContainer.firstChild.nextSibling) { + return; + } + prev = rng.endContainer.firstChild.nextSibling; + } + len = prev.length; + setStart(rng, prev, len); + setEnd(rng, prev, len); + if (rng.endOffset < 5) { + return; + } + end = rng.endOffset; + endContainer = prev; + } else { + endContainer = rng.endContainer; + if (endContainer.nodeType !== 3 && endContainer.firstChild) { + while (endContainer.nodeType !== 3 && endContainer.firstChild) { + endContainer = endContainer.firstChild; + } + if (endContainer.nodeType === 3) { + setStart(rng, endContainer, 0); + setEnd(rng, endContainer, endContainer.nodeValue.length); + } + } + if (rng.endOffset === 1) { + end = 2; + } else { + end = rng.endOffset - 1 - endOffset; + } + } + var start = end; + do { + setStart(rng, endContainer, end >= 2 ? end - 2 : 0); + setEnd(rng, endContainer, end >= 1 ? end - 1 : 0); + end -= 1; + rngText = rng.toString(); + } while (rngText !== ' ' && rngText !== '' && rngText.charCodeAt(0) !== 160 && end - 2 >= 0 && rngText !== delimiter); + if (rangeEqualsDelimiterOrSpace(rng.toString(), delimiter)) { + setStart(rng, endContainer, end); + setEnd(rng, endContainer, start); + end += 1; + } else if (rng.startOffset === 0) { + setStart(rng, endContainer, 0); + setEnd(rng, endContainer, start); + } else { + setStart(rng, endContainer, end); + setEnd(rng, endContainer, start); + } + text = rng.toString(); + if (text.charAt(text.length - 1) === '.') { + setEnd(rng, endContainer, start - 1); + } + text = rng.toString().trim(); + var matches = text.match(autoLinkPattern); + var protocol = getDefaultLinkProtocol(editor); + if (matches) { + if (matches[1] === 'www.') { + matches[1] = protocol + '://www.'; + } else if (/@$/.test(matches[1]) && !/^mailto:/.test(matches[1])) { + matches[1] = 'mailto:' + matches[1]; + } + bookmark = editor.selection.getBookmark(); + editor.selection.setRng(rng); + editor.execCommand('createlink', false, matches[1] + matches[2]); + if (defaultLinkTarget !== false) { + editor.dom.setAttrib(editor.selection.getNode(), 'target', defaultLinkTarget); + } + editor.selection.moveToBookmark(bookmark); + editor.nodeChanged(); + } + }; + var setup = function (editor) { + var autoUrlDetectState; + editor.on('keydown', function (e) { + if (e.keyCode === 13) { + return handleEnter(editor); + } + }); + if (global$1.browser.isIE()) { + editor.on('focus', function () { + if (!autoUrlDetectState) { + autoUrlDetectState = true; + try { + editor.execCommand('AutoUrlDetect', false, true); + } catch (ex) { + } + } + }); + return; + } + editor.on('keypress', function (e) { + if (e.keyCode === 41) { + return handleEclipse(editor); + } + }); + editor.on('keyup', function (e) { + if (e.keyCode === 32) { + return handleSpacebar(editor); + } + }); + }; + + function Plugin () { + global.add('autolink', function (editor) { + setup(editor); + }); + } + + Plugin(); + +}()); diff --git a/pool/shard011/JavaScript/0071090_vdom-ns.js b/pool/shard011/JavaScript/0071090_vdom-ns.js new file mode 100644 index 0000000000000000000000000000000000000000..ad761e98062cb2b6a486b4bca4a23113bb3b35d7 --- /dev/null +++ b/pool/shard011/JavaScript/0071090_vdom-ns.js @@ -0,0 +1,224 @@ +/** + * Creates a Namespace that can be used accros multiple vdom-modules to share information. + * + * + * Copyright (c) 2014 ITSA - https://github.com/itsa + *
    + * New BSD License - http://choosealicense.com/licenses/bsd-3-clause/ + * + * + * @module vdom + * @submodule vdom-ns + * @class NS-vdom + * @since 0.0.1 +*/ + +"use strict"; + +require('js-ext/lib/object.js'); +require('polyfill'); + +var createHashMap = require('js-ext/extra/hashmap.js').createMap, + // for escaping entoties inside domNode.nodeValue, we need this trick: https://code.google.com/p/jslibs/wiki/JavascriptTips +/*jshint proto:true */ + ENTITY_TO_CODE = { __proto__: null, + apos:0x0027,quot:0x0022,amp:0x0026,lt:0x003C,gt:0x003E,nbsp:0x00A0,iexcl:0x00A1,cent:0x00A2,pound:0x00A3, + curren:0x00A4,yen:0x00A5,brvbar:0x00A6,sect:0x00A7,uml:0x00A8,copy:0x00A9,ordf:0x00AA,laquo:0x00AB, + not:0x00AC,shy:0x00AD,reg:0x00AE,macr:0x00AF,deg:0x00B0,plusmn:0x00B1,sup2:0x00B2,sup3:0x00B3, + acute:0x00B4,micro:0x00B5,para:0x00B6,middot:0x00B7,cedil:0x00B8,sup1:0x00B9,ordm:0x00BA,raquo:0x00BB, + frac14:0x00BC,frac12:0x00BD,frac34:0x00BE,iquest:0x00BF,Agrave:0x00C0,Aacute:0x00C1,Acirc:0x00C2,Atilde:0x00C3, + Auml:0x00C4,Aring:0x00C5,AElig:0x00C6,Ccedil:0x00C7,Egrave:0x00C8,Eacute:0x00C9,Ecirc:0x00CA,Euml:0x00CB, + Igrave:0x00CC,Iacute:0x00CD,Icirc:0x00CE,Iuml:0x00CF,ETH:0x00D0,Ntilde:0x00D1,Ograve:0x00D2,Oacute:0x00D3, + Ocirc:0x00D4,Otilde:0x00D5,Ouml:0x00D6,times:0x00D7,Oslash:0x00D8,Ugrave:0x00D9,Uacute:0x00DA,Ucirc:0x00DB, + Uuml:0x00DC,Yacute:0x00DD,THORN:0x00DE,szlig:0x00DF,agrave:0x00E0,aacute:0x00E1,acirc:0x00E2,atilde:0x00E3, + auml:0x00E4,aring:0x00E5,aelig:0x00E6,ccedil:0x00E7,egrave:0x00E8,eacute:0x00E9,ecirc:0x00EA,euml:0x00EB, + igrave:0x00EC,iacute:0x00ED,icirc:0x00EE,iuml:0x00EF,eth:0x00F0,ntilde:0x00F1,ograve:0x00F2,oacute:0x00F3, + ocirc:0x00F4,otilde:0x00F5,ouml:0x00F6,divide:0x00F7,oslash:0x00F8,ugrave:0x00F9,uacute:0x00FA,ucirc:0x00FB, + uuml:0x00FC,yacute:0x00FD,thorn:0x00FE,yuml:0x00FF,OElig:0x0152,oelig:0x0153,Scaron:0x0160,scaron:0x0161, + Yuml:0x0178,fnof:0x0192,circ:0x02C6,tilde:0x02DC,Alpha:0x0391,Beta:0x0392,Gamma:0x0393,Delta:0x0394, + Epsilon:0x0395,Zeta:0x0396,Eta:0x0397,Theta:0x0398,Iota:0x0399,Kappa:0x039A,Lambda:0x039B,Mu:0x039C, + Nu:0x039D,Xi:0x039E,Omicron:0x039F,Pi:0x03A0,Rho:0x03A1,Sigma:0x03A3,Tau:0x03A4,Upsilon:0x03A5, + Phi:0x03A6,Chi:0x03A7,Psi:0x03A8,Omega:0x03A9,alpha:0x03B1,beta:0x03B2,gamma:0x03B3,delta:0x03B4, + epsilon:0x03B5,zeta:0x03B6,eta:0x03B7,theta:0x03B8,iota:0x03B9,kappa:0x03BA,lambda:0x03BB,mu:0x03BC, + nu:0x03BD,xi:0x03BE,omicron:0x03BF,pi:0x03C0,rho:0x03C1,sigmaf:0x03C2,sigma:0x03C3,tau:0x03C4, + upsilon:0x03C5,phi:0x03C6,chi:0x03C7,psi:0x03C8,omega:0x03C9,thetasym:0x03D1,upsih:0x03D2,piv:0x03D6, + ensp:0x2002,emsp:0x2003,thinsp:0x2009,zwnj:0x200C,zwj:0x200D,lrm:0x200E,rlm:0x200F,ndash:0x2013, + mdash:0x2014,lsquo:0x2018,rsquo:0x2019,sbquo:0x201A,ldquo:0x201C,rdquo:0x201D,bdquo:0x201E,dagger:0x2020, + Dagger:0x2021,bull:0x2022,hellip:0x2026,permil:0x2030,prime:0x2032,Prime:0x2033,lsaquo:0x2039,rsaquo:0x203A, + oline:0x203E,frasl:0x2044,euro:0x20AC,image:0x2111,weierp:0x2118,real:0x211C,trade:0x2122,alefsym:0x2135, + larr:0x2190,uarr:0x2191,rarr:0x2192,darr:0x2193,harr:0x2194,crarr:0x21B5,lArr:0x21D0,uArr:0x21D1, + rArr:0x21D2,dArr:0x21D3,hArr:0x21D4,forall:0x2200,part:0x2202,exist:0x2203,empty:0x2205,nabla:0x2207, + isin:0x2208,notin:0x2209,ni:0x220B,prod:0x220F,sum:0x2211,minus:0x2212,lowast:0x2217,radic:0x221A, + prop:0x221D,infin:0x221E,ang:0x2220,and:0x2227,or:0x2228,cap:0x2229,cup:0x222A,int:0x222B, + there4:0x2234,sim:0x223C,cong:0x2245,asymp:0x2248,ne:0x2260,equiv:0x2261,le:0x2264,ge:0x2265, + sub:0x2282,sup:0x2283,nsub:0x2284,sube:0x2286,supe:0x2287,oplus:0x2295,otimes:0x2297,perp:0x22A5, + sdot:0x22C5,lceil:0x2308,rceil:0x2309,lfloor:0x230A,rfloor:0x230B,lang:0x2329,rang:0x232A,loz:0x25CA, + spades:0x2660,clubs:0x2663,hearts:0x2665,diams:0x2666 + }, +/*jshint proto:false */ + charToEntity = {}, + +// Void Elements - HTML 4.01 + DEFAULT_VOID = createHashMap({ + AREA: true, + BASE: true, + BASEFONT: true, + BR: true, + COL: true, + FRAME: true, + HR: true, + IMG: true, + INPUT: true, + ISINDEX: true, + LINK: true, + META: true, + PARAM: true, + EMBED: true, + SOURCE: true, + TRACK: true, + WBR: true, + KEYGEN: true + }), + + // Block Elements - HTML 4.01 + DEFAULT_NON_BLOCK = createHashMap({ + ADDRESS: true, + APPLET: true, + BLOCKQUITE: true, + BUTTON: true, + CENTER: true, + DD: true, + DEL: true, + DIR: true, + DIV: true, + DL: true, + DT: true, + FIELDSET: true, + FORM: true, + FRAMESET: true, + IFRAME: true, + INS: true, + ISINDEX: true, + LI: true, + MAP: true, + MENU: true, + NOFRAMES: true, + NOSCRIPT: true, + OBJECT: true, + OL: true, + P: true, + PRE: true, + SCRIPT: true, + TABLE: true, + TBODY: true, + TD: true, + TFOOT: true, + TH: true, + THEAD: true, + TR: true, + UL: true + }), + + entityName; + +for (entityName in ENTITY_TO_CODE) { + charToEntity[String.fromCharCode(ENTITY_TO_CODE[entityName])] = entityName; +} + +module.exports = function (window) { + var NS; + + window._ITSAmodules || Object.protectedProp(window, '_ITSAmodules', createHashMap()); + + if (window._ITSAmodules.VDOM_NS) { + return window._ITSAmodules.VDOM_NS; // VDOM_NS was already created + } + + NS = window._ITSAmodules.VDOM_NS = createHashMap(); + + /** + * Reference to the VElement of document.body (gets its value as soon as it gets refered to) + * + * @property body + * @default null + * @type VElement + * @since 0.0.1 + */ + NS.body = null; + + NS.xmlNS = createHashMap({ + SVG: 'http://www.w3.org/2000/svg', + XBL: 'http://www.mozilla.org/xbl', + XUL: 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', + MATH: 'http://www.w3.org/1998/Math/MathML', + XLINK: 'http://www.w3.org/1999/xlink' + }); + + /** + * A hash with all encountered non-void Elements + * + * @property nonVoidElements + * @default {} + * @type Object + * @since 0.0.1 + */ + NS.nonVoidElements || (NS.nonVoidElements=DEFAULT_NON_BLOCK); + + /** + * A hash to identify what tagNames are equal to `SCRIPT` or `STYLE`. + * + * @property SCRIPT_OR_STYLE_TAG + * @default {SCRIPT: true, STYLE: true} + * @type Object + * @since 0.0.1 + */ + NS.SCRIPT_OR_STYLE_TAG = createHashMap({ + // the string-parser expects for `script`-tags + XSCRIPT: true, + STYLE: true + }); + + /** + * A hash with all nodeTypes that should be captured by the vDOM. + * + * @property VALID_NODE_TYPES + * @default {1: true, 3: true, 8: true} + * @type Object + * @since 0.0.1 + */ + NS.VALID_NODE_TYPES = createHashMap({ + 1: true, + 3: true, + 8: true + }); + + /** + * A hash with all encountered void Elements + * + * @property voidElements + * @default {} + * @type Object + * @since 0.0.1 + */ + NS.voidElements || (NS.voidElements=DEFAULT_VOID); + + NS.UnescapeEntities = function(str) { + return str.replace( + /&(.+?);/g, + function(str, ent) { + return String.fromCharCode( ent[0]!=='#' ? ENTITY_TO_CODE[ent] : (ent[1]==='x' ? parseInt(ent.substr(2),16) : parseInt(ent.substr(1)) ) ); + } + ); + }; + + NS.EscapeEntities = function(str) { + return str.replace( + /[^\x20-\x7E]/g, + function(str) { + return charToEntity[str] ? '&'+charToEntity[str]+';' : str; + } + ); + }; + + return NS; +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071091_chutzpahRunner.js b/pool/shard011/JavaScript/0071091_chutzpahRunner.js new file mode 100644 index 0000000000000000000000000000000000000000..e4e65c72018ce3f264ce23f297c241d5e9be44dc --- /dev/null +++ b/pool/shard011/JavaScript/0071091_chutzpahRunner.js @@ -0,0 +1,196 @@ +/*globals phantom, require, console*/ +var chutzpah = chutzpah || {}; + +chutzpah.runner = function (onInitialized, onPageLoaded, isFrameworkLoaded, onFrameworkLoaded, isTestingDone) { + /// Executes a test suite and evaluates the results using the provided functions. + /// Callback function which is called when the page initialized but not loaded. + /// Callback function which is called when the page is loaded. + /// Function that returns true of false if the test framework has been loaded. + /// Callback function which is called when the test framework is loaded. + /// Function that returns true of false if the test suite should be considered complete and ready for evaluation. + 'use strict'; + + + phantom.injectJs('../chutzpahFunctions.js'); + + var page = require('webpage').create(), + system = require("system"), + testFrameworkLoaded = false, + testFile = null, + testMode = null, + timeOut = null, + startTime = null, + userAgent = null, + ignoreResourceLoadingError = false; + + if (system.args.length <= 1) { + console.log('Error: too few arguments'); + phantom.exit(); + } + + testFile = system.args[1]; + testMode = system.args[2] || "execution"; + timeOut = parseInt(system.args[3]) || 5001; + + if (system.args.length > 4) { + ignoreResourceLoadingError = "true" === system.args[4].toLowerCase(); + } + + if (system.args.length > 5) { + userAgent = system.args[5]; + } + + function updateEventTime() { + startTime = new Date().getTime(); + } + + var chutzpahFunctions = chutzpah.getCommonFunctions(phantom.exit, updateEventTime); + + + function trySetupTestFramework() { + if (!testFrameworkLoaded) { + var loaded = page.evaluate(isFrameworkLoaded); + if (loaded) { + testFrameworkLoaded = true; + page.evaluate(onFrameworkLoaded); + } + } + } + + function waitFor(testIfDone, timeOutMillis) { + var maxtimeOutMillis = timeOutMillis, + isDone = false, + interval; + + function intervalHandler() { + var now = new Date().getTime(); + + if (!isDone && (now - startTime < maxtimeOutMillis)) { + isDone = testIfDone(); + } else { + if (!isDone) { + phantom.exit(3); // Timeout + } else { + clearInterval(interval); + phantom.exit(0); + } + } + } + + interval = setInterval(intervalHandler, 100); + } + + function pageOpenHandler(status) { + var waitCondition = function () { return page.evaluate(isTestingDone); }; + + if (status === 'success') { + + // Initialize startTime, this will get updated everytime we recieve + // content from the test framework + updateEventTime(); + trySetupTestFramework(); + page.evaluate(onPageLoaded); + waitFor(waitCondition, timeOut); + } + else { + phantom.exit(2); + } + } + + page.onConsoleMessage = chutzpahFunctions.captureLogMessage; + page.onError = chutzpahFunctions.onError; + + + page.onInitialized = function () { + if (testMode === 'discovery') { + page.evaluate(function () { + window.chutzpah = { testMode: 'discovery', phantom: true }; + }); + } + else { + page.evaluate(function () { + window.chutzpah = { testMode: 'execution', phantom: true }; + }); + } + + page.evaluate(onInitialized); + }; + + page.onResourceReceived = function (res) { + chutzpahFunctions.rawLog("!!_!! Resource Recieved: " + res.url); + trySetupTestFramework(); + }; + + page.onResourceError = function (res) { + if (!ignoreResourceLoadingError) { + chutzpahFunctions.onError(res.errorString); + } + chutzpahFunctions.rawLog("!!_!! Resource Error for " + res.url + " with error " + res.errorString); + }; + + + page.onResourceTimeout = function (res) { + if (!ignoreResourceLoadingError) { + chutzpahFunctions.onError(res.errorString); + } + chutzpahFunctions.rawLog("!!_!! Resource Timeout for " + res.url + " with error " + res.errorString); + }; + + page.onAlert = function (msg) { + chutzpahFunctions.rawLog("!!_!! Alert raised with message " + msg); + }; + + page.onConfirm = function (msg) { + chutzpahFunctions.rawLog("!!_!! Confirm raised with message " + msg); + return true; + }; + + + page.onPrompt = function (msg, defaultVal) { + chutzpahFunctions.rawLog("!!_!! Prompt raised with message " + msg); + return defaultVal; + }; + + page.onClosing = function (closingPage) { + chutzpahFunctions.rawLog("!!_!! Closing raised " + closingPage.url); + }; + + page.onUrlChanged = function (targetUrl) { + chutzpahFunctions.rawLog("!!_!! Url Change " + targetUrl); + }; + + page.onFilePicker = function (oldFile) { + chutzpahFunctions.rawLog("!!_!! File Picker raised " + oldFile); + return oldFile; + }; + + // Since tests run inside of Phantom are not part of your websites domain + // lets loosen remote resource security restrictions to help with some testing scenarios + + // Allows local files to make ajax calls to remote urls + page.settings.localToRemoteUrlAccessEnabled = true; //(default false) + + // Stops all security (for example you can access content in other domain IFrames) + page.settings.webSecurityEnabled = false; //(default true) + + if (userAgent) { + page.settings.userAgent = userAgent; + } + + // Setup callback to be invoked from client using window.callPhantom + page.onCallback = function (data) { + + if (!data || typeof data.Type !== "string") return null; + + switch (data.Type) { + case "Eval": + { + if (typeof data.Data === "string") + return eval(data.Data); + return null; + } + } + } + + page.open(testFile, pageOpenHandler); +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071092_gulpfile.js b/pool/shard011/JavaScript/0071092_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..08d8d828bda9a32a725cf0746e3d13cbac7a85b0 --- /dev/null +++ b/pool/shard011/JavaScript/0071092_gulpfile.js @@ -0,0 +1,27 @@ +'use strict'; + +const gulp = require('gulp'); +const build = require('@microsoft/sp-build-web'); + +build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`); + +const path = require('path'); +build.configureWebpack.mergeConfig({ + additionalConfiguration: (generatedConfiguration) => { + if (!generatedConfiguration.resolve.alias) { + generatedConfiguration.resolve.alias = {}; + } + + // root src folder + generatedConfiguration.resolve.alias['@src'] = path.resolve(__dirname, 'lib') + + return generatedConfiguration; + } +}); + +build.initialize(require('gulp')); + +var runSequence = require('run-sequence'); +gulp.task('package', function (cb) { + runSequence('clean', 'build', 'bundle', 'package-solution', cb); +}); diff --git a/pool/shard011/JavaScript/0071094_index-compiled.js b/pool/shard011/JavaScript/0071094_index-compiled.js new file mode 100644 index 0000000000000000000000000000000000000000..a5f13507b87755f2e596a9672b438251def66d08 --- /dev/null +++ b/pool/shard011/JavaScript/0071094_index-compiled.js @@ -0,0 +1,97 @@ +'use strict'; + +var clear = require('es5-ext/array/#/clear'), + assign = require('es5-ext/object/assign'), + callable = require('es5-ext/object/valid-callable'), + value = require('es5-ext/object/valid-value'), + d = require('d'), + autoBind = require('d/auto-bind'), + Symbol = require('es6-symbol'), + defineProperty = Object.defineProperty, + defineProperties = Object.defineProperties, + Iterator; + +module.exports = Iterator = function (list, context) { + if (!(this instanceof Iterator)) return new Iterator(list, context); + defineProperties(this, { + __list__: d('w', value(list)), + __context__: d('w', context), + __nextIndex__: d('w', 0) + }); + if (!context) return; + callable(context.on); + context.on('_add', this._onAdd); + context.on('_delete', this._onDelete); + context.on('_clear', this._onClear); +}; + +defineProperties(Iterator.prototype, assign({ + constructor: d(Iterator), + _next: d(function () { + var i; + if (!this.__list__) return; + if (this.__redo__) { + i = this.__redo__.shift(); + if (i !== undefined) return i; + } + if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; + this._unBind(); + }), + next: d(function () { + return this._createResult(this._next()); + }), + _createResult: d(function (i) { + if (i === undefined) return { done: true, value: undefined }; + return { done: false, value: this._resolve(i) }; + }), + _resolve: d(function (i) { + return this.__list__[i]; + }), + _unBind: d(function () { + this.__list__ = null; + delete this.__redo__; + if (!this.__context__) return; + this.__context__.off('_add', this._onAdd); + this.__context__.off('_delete', this._onDelete); + this.__context__.off('_clear', this._onClear); + this.__context__ = null; + }), + toString: d(function () { + return '[object Iterator]'; + }) +}, autoBind({ + _onAdd: d(function (index) { + if (index >= this.__nextIndex__) return; + ++this.__nextIndex__; + if (!this.__redo__) { + defineProperty(this, '__redo__', d('c', [index])); + return; + } + this.__redo__.forEach(function (redo, i) { + if (redo >= index) this.__redo__[i] = ++redo; + }, this); + this.__redo__.push(index); + }), + _onDelete: d(function (index) { + var i; + if (index >= this.__nextIndex__) return; + --this.__nextIndex__; + if (!this.__redo__) return; + i = this.__redo__.indexOf(index); + if (i !== -1) this.__redo__.splice(i, 1); + this.__redo__.forEach(function (redo, i) { + if (redo > index) this.__redo__[i] = --redo; + }, this); + }), + _onClear: d(function () { + if (this.__redo__) clear.call(this.__redo__); + this.__nextIndex__ = 0; + }) +}))); + +defineProperty(Iterator.prototype, Symbol.iterator, d(function () { + return this; +})); +defineProperty(Iterator.prototype, Symbol.toStringTag, d('', 'Iterator')); + +//# sourceMappingURL=index-compiled.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071096_index.js b/pool/shard011/JavaScript/0071096_index.js new file mode 100644 index 0000000000000000000000000000000000000000..a35adf6c1413371189d8d27d002c7dfad8020595 --- /dev/null +++ b/pool/shard011/JavaScript/0071096_index.js @@ -0,0 +1,21 @@ +var path = require('path'); +var fs = require('fs'); + +global.appRoot = path.resolve(__dirname + '../../..'); + +var dotenvfile_path = appRoot + '/.env'; + +if(typeof DOTENVFILE_PATH !== "undefined") { + dotenvfile_path = DOTENVFILE_PATH; +} + +global.dotenv = require('dotenv').config({ + path: dotenvfile_path +}); + +fs.exists(dotenvfile_path, function(exists){ + if(!exists) { + console.log("WARNING: You must create a .env file at the root directory of your project."); + } +}); + diff --git a/pool/shard011/JavaScript/0071097_Injector.js b/pool/shard011/JavaScript/0071097_Injector.js new file mode 100644 index 0000000000000000000000000000000000000000..ddc0773faa54351dc6ba6e5167f1dd1506ca52d0 --- /dev/null +++ b/pool/shard011/JavaScript/0071097_Injector.js @@ -0,0 +1,132 @@ +/*jslint eqeq:true,node:true,white:true,plusplus:true,nomen:true,unparam:true,devel:true,regexp:true */ +/*Copyright © 2014 mparaiso . All Rights Reserved.*/ +/* a dependency injection container for javascript */ +"use strict"; + + +/** + * a dependency injection container + * @constructor + */ +function Injector() { + this._registry = []; +} + +/** + * register a new service.The service is a singleton + * @param {String} name + * @param {Array|Function} array + * @returns {Injector} + */ +Injector.prototype.service = function (name, array) { + if (array instanceof Function) { + var a = []; + if (!array.inject || !(array.inject instanceof Array)) { + array.inject = this.getFunctionArgNames(array); + } + array = a.concat(array.inject).concat(array); + } + this._register(name, array, false); + return this; +}; +/** + * add a value (object) to the registery + * @param {String} name + * @param {*} value + * @returns {Injector} + */ +Injector.prototype.value = function (name, value) { + this._register(name, undefined, value); + return this; +}; + +/** + * get an service from the registery,dependencies will be resolved + * @param {String} name + * @returns {*} a resolved service + */ +Injector.prototype.get = Injector.prototype.inject = function (name) { + var service, serviceDefinition, _constructor, _arguments; + service = this._registry.filter(function (service) { + return name === service.name; + })[0]; + if (!service) { + return; + } + if (service.resolved) { + return service.resolved; + } + serviceDefinition = service.service.slice(); + _constructor = serviceDefinition.pop(); + _arguments = serviceDefinition.map(function (service) { + var s = this.get(service); + if (s === undefined) { + throw ["Service", service, 'not found in', name].join(' '); + } + return s; + }, this); + + service.resolved = new (Function.bind.apply(_constructor, [_constructor].concat(_arguments)))(); + return service.resolved; +}; +/** + * + * @param {String} name + * @param service + * @param {*|Boolean} resolved + * @private + */ +Injector.prototype._register = function (name, service, resolved) { + + this._registry.push({ + name: name, + service: service, + resolved: resolved + }); +}; +/** + * clone an injector + */ +Injector.prototype.clone = function () { + var _injector = new Injector(); + _injector._registry = this._registry.slice(); + return _injector; +}; + +/** extrat args from function */ +Injector.prototype.getFunctionArgNames = function (func) { + var length, comments, stripped, brackets, keep; + length = func.length; + if (length === 0) { + return []; + } + comments = /(\/\*).*?\*\/ /gm; + stripped = func.toString().replace(comments, ""); + brackets = /(?:\()(.*)?(?:\))/im; + keep = stripped.match(brackets); + return keep[1].split(/\s*,\s*/).map(function (service) { + return service.trim(); + }); +}; +/** + * get an array of resolved service values given a function with arguments + * @param {Function} func + * @returns {Array} + */ +Injector.prototype.getFunctionArgValues = function (func) { + return this.getFunctionArgNames(func).map(function (arg) { + return this.get(arg); + }, this); +}; + +function InjectorError() { + Error.apply(this, [].slice.call(arguments)); +} +InjectorError.prototype = Object.create(Error.prototype); + +Injector.InjectorError = InjectorError; + +Injector.BLACKLIST = [/^clone$/, /^get$/, /^set$/, /^service$/, /^value$/, /^\$/]; + + +module.exports = Injector; diff --git a/pool/shard011/JavaScript/0071098_jquery.cityselect.js b/pool/shard011/JavaScript/0071098_jquery.cityselect.js new file mode 100644 index 0000000000000000000000000000000000000000..acbd963f114216adac713d1bc40b08097f52ce5e --- /dev/null +++ b/pool/shard011/JavaScript/0071098_jquery.cityselect.js @@ -0,0 +1,143 @@ + +(function($) { + $.fn.citySelect = function(settings) { + if (this.length < 1) { + return; + }; + + // 默认值 + settings = $.extend({ + url: "js/city.min.js", + prov: null, + city: null, + dist: null, + nodata: null, + required: true + }, settings); + + var box_obj = this; + var prov_obj = box_obj.find(".prov"); + var city_obj = box_obj.find(".city"); + var dist_obj = box_obj.find(".dist"); + var prov_val = settings.prov; + var city_val = settings.city; + var dist_val = settings.dist; + var select_prehtml = (settings.required) ? "" : ""; + var city_json; + + // 赋值市级函数 + var cityStart = function() { + var prov_id = prov_obj.get(0).selectedIndex; + if (!settings.required) { + prov_id--; + } + ; + city_obj.empty().attr("disabled", true); + dist_obj.empty().attr("disabled", true); + + if (prov_id < 0 || typeof (city_json.citylist[prov_id].c) == "undefined") { + if (settings.nodata == "none") { + city_obj.css("display", "none"); + dist_obj.css("display", "none"); + } else if (settings.nodata == "hidden") { + city_obj.css("visibility", "hidden"); + dist_obj.css("visibility", "hidden"); + } + ; + return; + } + ; + + // 遍历赋值市级下拉列表 + temp_html = select_prehtml; + $.each(city_json.citylist[prov_id].c, function(i, city) { + temp_html += ""; + }); + city_obj.html(temp_html).attr("disabled", false).css({"display": "", "visibility": ""}); + distStart(); + }; + + // 赋值地区(县)函数 + var distStart = function() { + var prov_id = prov_obj.get(0).selectedIndex; + var city_id = city_obj.get(0).selectedIndex; + if (!settings.required) { + prov_id--; + city_id--; + } + ; + dist_obj.empty().attr("disabled", true); + + if (prov_id < 0 || city_id < 0 || typeof (city_json.citylist[prov_id].c[city_id].a) == "undefined") { + if (settings.nodata == "none") { + dist_obj.css("display", "none"); + } else if (settings.nodata == "hidden") { + dist_obj.css("visibility", "hidden"); + } + ; + return; + } + ; + + // 遍历赋值市级下拉列表 + temp_html = select_prehtml; + $.each(city_json.citylist[prov_id].c[city_id].a, function(i, dist) { + temp_html += ""; + }); + dist_obj.html(temp_html).attr("disabled", false).css({"display": "", "visibility": ""}); + }; + + var init = function() { + // 遍历赋值省份下拉列表 + temp_html = select_prehtml; + $.each(city_json.citylist, function(i, prov) { + temp_html += ""; + }); + prov_obj.html(temp_html); + + // 若有传入省份与市级的值,则选中。(setTimeout为兼容IE6而设置) + setTimeout(function() { + if (settings.prov != null) { + prov_obj.val(settings.prov); + cityStart(); + setTimeout(function() { + if (settings.city != null) { + city_obj.val(settings.city); + distStart(); + setTimeout(function() { + if (settings.dist != null) { + dist_obj.val(settings.dist); + } + ; + }, 1); + } + ; + }, 1); + } + ; + }, 1); + + // 选择省份时发生事件 + prov_obj.bind("change", function() { + cityStart(); + }); + + // 选择市级时发生事件 + city_obj.bind("change", function() { + distStart(); + }); + }; + + // 设置省市json数据 + if (typeof (settings.url) == "string") { + $.getJSON(settings.url, function(json) { + city_json = json; + init(); + }); + } else { + city_json = settings.url; + init(); + } + ; + }; +})(jQuery); diff --git a/pool/shard011/JavaScript/0071100_IncognitoSubscriptionManager.js b/pool/shard011/JavaScript/0071100_IncognitoSubscriptionManager.js new file mode 100644 index 0000000000000000000000000000000000000000..0e3d02636d0801b2975f4b3205145f3d4f37901d --- /dev/null +++ b/pool/shard011/JavaScript/0071100_IncognitoSubscriptionManager.js @@ -0,0 +1,97 @@ + +import AbstractActor from "./AbstractActor"; +import Subscription from "../model/Subscription"; +import SubscriptionType from "../model/SubscriptionType"; + +/** + * Private field symbols. + */ +const FIELDS = Object.freeze({ + db: Symbol("db") +}); + +export default class IncognitoSubscriptionManager extends AbstractActor { + /** + * Initializes the actor. + */ + constructor() { + super(); + + /** + * The database connection provider, set during the + * {@code background.start} event. + * + * @type {?Database} + */ + this[FIELDS.db] = null; + } + + /** + * Event handler for the {@code background.start} event. The handler sets the + * {@code db} private field + * + * @param {string} event The name of the event. + * @param {Object} resources Map of available resources. + */ + onBackgroundStart(event: string, resources: Object): void { + this[FIELDS.db] = resources.database; + } + + /** + * Event handler for the {@code incognito-subscriptions.add-requested} event. + * + * @param {string} event The name of the event. + * @param {Object} subscription The event data, a serialized + * {@codelink Subscription} model. + * @return {string} One of the following values: + * - "ok" - the subscription was added. + * - "duplicate" - there is already such a subscription. + * @throws {Error} Thrown if there is a communication error with the YouTube + * API or an unexpected fatal error occurs. + */ + async onIncognito_subscriptionsAdd_requested(event: string, + subscription: Object): string { + // check that the incognito subscription does not exist already + let db = await this[FIELDS.db].getConnection(); + let transaction = db.transaction(["Subscription"], "readwrite"); + let subscriptionObjectStore = transaction.objectStore("Subscription"); + + let isPresent = await new Promise((resolve, reject) => { + let cursorRequest = subscriptionObjectStore.openCursor(); + cursorRequest.onsuccess = (event) => { + let cursor = cursorRequest.result; + if (!cursor) { + resolve(false); + } + + let otherSubscription = cursor.value; + let isMatching = + otherSubscription.incognito && + otherSubscription.type === subscription.type && + otherSubscription.playlist === subscription.playlist; + + if (!isMatching) { + cursor.continue(); + return; + } + + resolve(true); + }; + }); + if (isPresent) { + return "duplicate"; + } + + // TODO: get from DB or retrive from REST API the playlist/channel record + // and update it + + await new Promise((resolve, reject) => { + let additionRequest = subscriptionObjectStore.add(subscription); + additionRequest.onsuccess = () => { + transaction.oncomplete = resolve; + }; + }); + + return "ok"; + } +} diff --git a/pool/shard011/JavaScript/0071101_main.js b/pool/shard011/JavaScript/0071101_main.js new file mode 100644 index 0000000000000000000000000000000000000000..322cd90853d2bee1ee79c5fbed1527d79e395c93 --- /dev/null +++ b/pool/shard011/JavaScript/0071101_main.js @@ -0,0 +1,121 @@ +/* + 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. +*/ +import '@/common/helpers/browserUpdate' +import Vue from 'vue' +import * as Sentry from '@sentry/browser' +import * as Integrations from '@sentry/integrations' +import Vuex, { mapActions } from 'vuex' +import VueNoty from 'vuejs-noty' +import BootstrapVue from 'bootstrap-vue' +import VueAnalytics from 'vue-analytics' +import VueMatomo from 'vue-matomo' +import App from './App' +import router from './router.js' +import { store } from './store' +import '@/common/assets/css/bootstrap-theme.min.css' +import 'bootstrap-vue/dist/bootstrap-vue.css' +import vSelect from 'vue-select' +import 'vue-select/dist/vue-select.css' +import VueMoment from 'vue-moment' +import FormInput from '@/common/components/FormInput.vue' +import { FETCH_CONFIG } from '@/common/store/config.js' +import filters from '@/common/filters' + +// GWELLS js API library (helper methods for working with API) +import ApiService from '@/common/services/ApiService.js' + +const PRODUCTION_GWELLS_URL = 'https://apps.nrs.gov.bc.ca/gwells' +const STAGING_GWELLS_URLS = ['testapps.nrs.gov.bc.ca', 'gwells-staging.apps.silver.devops.gov.bc.ca'] +const isProduction = () => (window.location.href.substr(0, PRODUCTION_GWELLS_URL.length) === PRODUCTION_GWELLS_URL) +const isStaging = () => ( + window.location.pathname === '/gwells/' && STAGING_GWELLS_URLS.includes(window.location.hostname) +) +if (isProduction()) { + Sentry.init({ + dsn: 'https://a83809da8c9b4f39b3d7cd683b803859@sentry.io/1802823', + integrations: [new Integrations.Vue({ Vue, attachProps: true, logError: true })], + beforeSend (event) { + // The `msCrypto` property was only ever implemented in IE 11. Ignore logging IE 11 errors. + // See: https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto + if (window.msCrypto) { return null } + return event + } + }) +} + +Vue.use(Vuex) +Vue.use(VueNoty, { + layout: 'topRight', + theme: 'bootstrap-v4', + timeout: 1800 +}) +Vue.use(BootstrapVue) +Vue.use(VueMoment) +Vue.use(filters) +Vue.component('v-select', vSelect) +Vue.component('form-input', FormInput) + +// set baseURL and default headers +ApiService.init() + +Vue.use(VueAnalytics, { + id: 'UA-106174915-1', + set: [ + { field: 'anonymizeIp', value: true } + ], + disabled: ApiService.query('analytics', {}).then((response) => { + return response.data.enable_google_analytics !== true + }) +}) + + +if (isProduction()) { + Vue.use(VueMatomo, { + host: 'https://water-matomo.apps.silver.devops.gov.bc.ca/', + siteId: 2, + router: router, + domains: 'apps.nrs.gov.bc.ca' + }) +} + +if (isStaging()) { + Vue.use(VueMatomo, { + host: 'https://water-matomo.apps.silver.devops.gov.bc.ca/', + siteId: 4, + router: router, + domains: STAGING_GWELLS_URLS + }) +} + +Vue.config.productionTip = false +Vue.config.devtools = process.env.NODE_ENV !== 'production' +Vue.config.performance = process.env.NODE_ENV !== 'production' + +/* eslint-disable no-new */ +new Vue({ + el: '#app', + router, + store, + components: { App }, + template: '', + methods: { + ...mapActions([ + FETCH_CONFIG + ]) + }, + created () { + this.FETCH_CONFIG() + this.$ga.page() + } +}) diff --git a/pool/shard011/JavaScript/0071103_ephemeral-client.js b/pool/shard011/JavaScript/0071103_ephemeral-client.js new file mode 100644 index 0000000000000000000000000000000000000000..a8eed5653e54a9b2b5713f76193c5dd379eb2d49 --- /dev/null +++ b/pool/shard011/JavaScript/0071103_ephemeral-client.js @@ -0,0 +1,82 @@ +// Copyright (c) 2020 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +'use strict'; + +var TChannel = require('../channel.js'); + +module.exports = runTests; + +if (require.main === module) { + runTests(require('./lib/hyperbahn-cluster.js')); +} + +function runTests(HyperbahnCluster) { + HyperbahnCluster.test('ephemeral client works', { + size: 5 + }, function t(cluster, assert) { + var bob = cluster.remotes.bob; + + for (var i = 0; i < cluster.apps.length; i++) { + var app = cluster.apps[i]; + app.clients.serviceProxy.block('*', bob.serviceName); + } + + var client = TChannel({ + trace: false + }); + var subClient = client.makeSubChannel({ + serviceName: 'test', + requestDefaults: { + hasNoParent: true, + headers: { + as: 'raw', + cn: 'client' + } + }, + peers: [cluster.hostPortList[0]] + }); + + subClient.waitForIdentified({ + host: cluster.hostPortList[0] + }, onIdentified); + + function onIdentified(err) { + assert.ifError(err); + + subClient.request({ + serviceName: bob.serviceName + }).send('echo', 'a', 'b', onResponse); + } + + function onResponse(err, res, arg2, arg3) { + assert.ok(err); + assert.equal(err.type, 'tchannel.request.timeout'); + + assert.equal(res, null); + + client.close(); + + setTimeout(function later() { + assert.end(); + }, 10); + } + }); +} diff --git a/pool/shard011/JavaScript/0071104_controller.js b/pool/shard011/JavaScript/0071104_controller.js new file mode 100644 index 0000000000000000000000000000000000000000..79aa4a90197be214e9dc3c8313253995e00ef9a3 --- /dev/null +++ b/pool/shard011/JavaScript/0071104_controller.js @@ -0,0 +1,27 @@ +define(['angularAMD'], function(app) { + 'use strict' + + /* @ngInject */ + function MainCtrl($rootScope, $scope, $state, $stateParams, $window, $timeout, localStorageService, $translate, $location, $http, + $filter) { + + window.$rootScope = $rootScope; + + $scope.$on('$viewContentLoaded', function() { + $timeout(function(){ + $('#page').addClass('in'); + }); + }); + }; + + // =============================================================================== + + + + MainCtrl.$inject = ['$rootScope', '$scope', '$state', '$stateParams', '$window', '$timeout', 'localStorageService', '$filter', + '$location', '$modal', '$sce', '$http', '$translate', '$templateCache']; + + + app.controller('MainCtrl', MainCtrl); + return app; +}); diff --git a/pool/shard011/JavaScript/0071107_index.js b/pool/shard011/JavaScript/0071107_index.js new file mode 100644 index 0000000000000000000000000000000000000000..9cb60f4d7be4d6b9b40b805d8453bbfb2a44ce07 --- /dev/null +++ b/pool/shard011/JavaScript/0071107_index.js @@ -0,0 +1,107 @@ +const request = require('request'); +const Promise = require('bluebird'); +const extend = require('util-extend'); +const crypto = require("crypto"); + +const default_options = { + merchantId: "13466", + merchantSecret: "6pKF4jkv97zmqBJ3ZL8gUw5DfT2NMQ", +}; +const default_urls = { + paymentCreate: "https://payment.paytrail.com/api-payment/create" +} + + + + +module.exports = function (options, urls) { + this.options = extend(default_urls, options); + this.urls = extend(default_urls, urls); + this.products = []; + if (!this.urls.success + || !this.urls.failure + || !this.urls.notification) { throw new Error("Callback urls must be defined!"); }; + // Default method for creating payments +this.APIRequest = function APIRequest (url, body) { + return new Promise((resolve, reject) => { + const r = { + method: 'POST', + uri: url, + auth: { + username: this.options.merchantId, + password: this.options.merchantSecret + }, + headers: { + 'User-Agent': 'node-paytrail', + 'X-Verkkomaksut-Api-Version': 1 + }, + json: true, + body: body + } + request(r, (error, response, body) => { + if (error) return reject(error); + return resolve(body); + }); + + }); +}; +this.addProduct = (product) => { + const product_default = { + title: "Product", + amount: 1, + price: 0.65, + vat: 24, + discount: 0, + type: 1 + }; + product = extend(product_default, product); + this.products.push(product); + return this; +} + // sets contact information + this.setContact = (required, address, optionals) => { + let data = required; + data.address = address; + data = extend(data, optionals); + if (!("firstName" in data)) throw new Error("firstName is required"); + if (!("lastName" in data)) throw new Error("firstName is required"); + if (!("email" in data)) throw new Error("email is required"); + if (!("street" in data.address)) throw new Error("street is required"); + if (!("postalCode" in data.address)) throw new Error("postalCode is required"); + if (!("postalOffice" in data.address)) throw new Error("postalOffice is required"); + if (!("country" in data.address)) throw new Error("country is required"); + this.contact = data; + return this; + } + // creates and processes payment + this.createPayment = function (payment) { + const payment_defaults = { + orderNumber: "", + referenceNumber: "", + description: "", + currency: "EUR", + locale: "fi_FI", + urlSet: this.urls, + orderDetails: { + includeVat: 1, + contact: this.contact, + products: this.products + } + }; + payment = extend(payment_defaults, payment); + return this.APIRequest(this.urls.paymentCreate, payment); + }; + this.confirmSuccess = function (orderNumber, timestamp, paid, method, authCode) { + return this.confirmParams([orderNumber, timestamp, paid, method, this.options.merchantSecret], authCode); + }; + this.confirmFailure = function (orderNumber, timestamp, authCode) { + return this.confirmParams([orderNumber, timestamp, this.options.merchantSecret], authCode); + } + this.confirmParams = function (array, authCode) { + var base = array.join('|'); + var hash = crypto.createHash("md5").update(base).digest("hex"); + return hash.toUpperCase() === authCode; + } + return this; + +} diff --git a/pool/shard011/JavaScript/0071108_authorization-rule.spec.js b/pool/shard011/JavaScript/0071108_authorization-rule.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..b56397a28f715facc0c8bfa1a9c4afe2800e641e --- /dev/null +++ b/pool/shard011/JavaScript/0071108_authorization-rule.spec.js @@ -0,0 +1,109 @@ +console.log( 'Testing main.js...' ); + +function read ( filename ) { + return require( '../../../source/' + filename ); +} +const AuthorizationRule = read( 'rules/authorization-rule.js' ); +const RuleBase = read( 'rules/rule-base.js' ); +const AuthorizationAction = read( 'rules/authorization-action.js' ); +const AuthorizationResult = read( 'rules/authorization-result.js' ); +const RuleSeverity = read( 'rules/rule-severity.js' ); +const NoAccessBehavior = read( 'rules/no-access-behavior.js' ); +const PropertyInfo = read( 'common/property-info.js' ); +const Text = read( 'data-types/text.js' ); + +describe( 'Authorization rule', () => { + + it( 'constructor expects a non-empty string argument', () => { + + const build01 = function () { return new AuthorizationRule(); }; + const build02 = function () { return new AuthorizationRule( null ); }; + const build03 = function () { return new AuthorizationRule( '' ); }; + const build04 = function () { return new AuthorizationRule( 'ruleName' ); }; + const build05 = function () { return new AuthorizationRule( true ); }; + const build06 = function () { return new AuthorizationRule( 777 ); }; + const build07 = function () { return new AuthorizationRule( {} ); }; + const build08 = function () { return new AuthorizationRule( [ 'ruleName' ] ); }; + + expect( build01 ).toThrow(); + expect( build02 ).toThrow(); + expect( build03 ).toThrow(); + expect( build04 ).not.toThrow(); + expect( build05 ).toThrow(); + expect( build06 ).toThrow(); + expect( build07 ).toThrow(); + expect( build08 ).toThrow(); + } ); + + it( 'inherits rule base type', () => { + + const rule = new AuthorizationRule( 'ruleName' ); + + expect( rule ).toEqual( jasmine.any( RuleBase ) ); + } ); + + it( 'has six properties', () => { + + const rule = new AuthorizationRule( 'ruleName' ); + + expect( rule.ruleName ).toBe( 'ruleName' ); + expect( rule.ruleId ).toBeNull(); + expect( rule.noAccessBehavior ).toBe( NoAccessBehavior.throwError ); + expect( rule.message ).toBeNull(); + expect( rule.priority ).toBe( 10 ); + expect( rule.stopsProcessing ).toBe( false ); + } ); + + it( 'initialize method works', () => { + + const property = new PropertyInfo( 'property', new Text() ); + const rule1 = new AuthorizationRule( 'ruleName #1' ); + rule1.initialize( AuthorizationAction.readProperty, property, 'message #1', 19, true ); + const rule2 = new AuthorizationRule( 'ruleName #2' ); + rule2.initialize( AuthorizationAction.executeMethod, 'getByName', 'message #2', 17, false ); + const rule3 = new AuthorizationRule( 'ruleName #3' ); + rule3.initialize( AuthorizationAction.updateObject, null, 'message #3', 13, true ); + + expect( rule1.ruleName ).toBe( 'ruleName #1' ); + expect( rule1.ruleId ).toBe( 'readProperty.property' ); + expect( rule1.message ).toBe( 'message #1' ); + expect( rule1.priority ).toBe( 19 ); + expect( rule1.stopsProcessing ).toBe( true ); + + expect( rule2.ruleName ).toBe( 'ruleName #2' ); + expect( rule2.ruleId ).toBe( 'executeMethod.getByName' ); + expect( rule2.message ).toBe( 'message #2' ); + expect( rule2.priority ).toBe( 17 ); + expect( rule2.stopsProcessing ).toBe( false ); + + expect( rule3.ruleName ).toBe( 'ruleName #3' ); + expect( rule3.ruleId ).toBe( 'updateObject' ); + expect( rule3.message ).toBe( 'message #3' ); + expect( rule3.priority ).toBe( 13 ); + expect( rule3.stopsProcessing ).toBe( true ); + } ); + + it( 'result method works', () => { + + const property = new PropertyInfo( 'property', new Text() ); + const rule1 = new AuthorizationRule( 'ruleName #1' ); + rule1.initialize( AuthorizationAction.readProperty, property, 'message #1', 19, true ); + //const result = rule1.result('final message', RuleSeverity.warning); + const result1 = function () { return rule1.result( 'final message', RuleSeverity.warning ); }; + + const rule2 = new AuthorizationRule( 'ruleName #2' ); + rule2.initialize( AuthorizationAction.updateObject, null, 'message #2', 13, true ); + rule2.noAccessBehavior = NoAccessBehavior.showError; + const result2 = rule2.result(); + + expect( result1 ).toThrow( 'final message' ); + + expect( result2 ).toEqual( jasmine.any( AuthorizationResult ) ); + expect( result2.ruleName ).toBe( 'ruleName #2' ); + expect( result2.propertyName ).toBe( '' ); + expect( result2.message ).toBe( 'message #2' ); + expect( result2.severity ).toBe( RuleSeverity.error ); + expect( result2.stopsProcessing ).toBe( true ); + expect( result2.isPreserved ).toBe( true ); + } ); +} ); diff --git a/pool/shard011/JavaScript/0071109_podcast_tiles.js b/pool/shard011/JavaScript/0071109_podcast_tiles.js new file mode 100644 index 0000000000000000000000000000000000000000..cea7609e90737202be8cfab38ac1475b89b94813 --- /dev/null +++ b/pool/shard011/JavaScript/0071109_podcast_tiles.js @@ -0,0 +1,22 @@ +import {Template} from 'meteor/templating'; +import {Podcasts} from '/imports/api/podcasts/podcasts.js'; +import {Session} from 'meteor/session'; + +import './podcast_tiles.html'; +import './podcast_tiles.css'; + +Template.podcast_tiles.helpers({ + podcasts: function(){ + return Podcasts.find().fetch().map(function(podcast, index) { + podcast = podcast.feed; + podcast.index = index; + return podcast; + }); + } +}); + +Template.podcast_tiles.events({ + 'click .podcast_tile_add'(event) { + Session.set('current_podcast_overview', 'add'); + } +}); diff --git a/pool/shard011/JavaScript/0071111_localdb.js b/pool/shard011/JavaScript/0071111_localdb.js new file mode 100644 index 0000000000000000000000000000000000000000..df691b47316b22e90ba3eda3499639f5efdc9a8d --- /dev/null +++ b/pool/shard011/JavaScript/0071111_localdb.js @@ -0,0 +1,177 @@ +var nedb = require('nedb'); +var topolr=require("topolr-util"); + +var cursor=function (_cursor) { + this._cursor=_cursor; +}; +cursor.prototype.limit=function () { + this._cursor.limit(Array.prototype.slice.call(arguments)); + return this; +}; +cursor.prototype.sort=function () { + this._cursor.sort(Array.prototype.slice.call(arguments)); + return this; +}; +cursor.prototype.skip=function () { + this._cursor.skip(Array.prototype.slice.call(arguments)); + return this; +}; +cursor.prototype.exec=function () { + var ps=topolr.promise(); + this._cursor.exec(function (err,data) { + if(err){ + ps.reject(err); + }else{ + ps.resolve(data); + } + }); + return ps; +}; + + +var wrapper=function (db) { + this._db=db; +}; +wrapper.warp=function () { + var ps=topolr.promise(); + var parse=Array.prototype.slice.call(arguments); + var type=parse.shift(); + parse.push(function (err,data) { + if(err){ + ps.reject(err); + }else{ + ps.resolve(data); + } + }); + this._db[type].apply(this._db,parse); + return ps; +}; +wrapper.prototype.find=function () { + var parse=Array.prototype.slice.call(arguments); + parse.unshift("find"); + return wrapper.warp.apply(this,parse); +}; +wrapper.prototype.findBy=function () { + var parse=Array.prototype.slice.call(arguments); + if(topolr.is.isFunction(parse[parse.length-1])){ + parse.splice(parse.length-1,1); + } + var at=this._db.find.apply(this._db,parse); + return new cursor(at); +}; +wrapper.prototype.insert=function () { + var parse=Array.prototype.slice.call(arguments); + parse.unshift("insert"); + return wrapper.warp.apply(this,parse); +}; +wrapper.prototype.count=function () { + var parse=Array.prototype.slice.call(arguments); + parse.unshift("count"); + return wrapper.warp.apply(this,parse); +}; +wrapper.prototype.update=function () { + var parse=Array.prototype.slice.call(arguments); + parse.unshift("update"); + return wrapper.warp.apply(this,parse); +}; +wrapper.prototype.remove=function () { + var parse=Array.prototype.slice.call(arguments); + parse.unshift("remove"); + return wrapper.warp.apply(this,parse); +}; +wrapper.prototype.ensureIndex=function () { + var parse=Array.prototype.slice.call(arguments); + parse.unshift("ensureIndex"); + return wrapper.warp.apply(parse); +}; +wrapper.prototype.removeIndex=function () { + var parse=Array.prototype.slice.call(arguments); + parse.unshift("removeIndex"); + return wrapper.warp.apply(this,parse); +}; + +Module({ + name:"localdb", + extend:"service", + option:{ + path:"", + initData:{} + }, + start:function () { + var ths=this; + this._dbs={}; + var path=this.getPath(this.option.path); + this._path=path; + return topolr.promise(function (a) { + a(); + }); + }, + getPath:function (path) { + var ths=this; + return path.replace(/\{[a-zA-Z]+\}/g, function (a) { + a = a.substring(1, a.length - 1); + if (a === "project") { + return ths.getContext().getProjectPath() + }else if(a==="webinfo"){ + return ths.getContext().getProjectPath()+"/WEBINF/" + } + }); + }, + get:function (name) { + var ths=this; + if(!this._dbs[name]) { + var path = this._path + "/" + name + ".db"; + if (!topolr.file(path).isExists()) { + topolr.file(path).create(); + var ps = topolr.promise(); + var db = new nedb({ + filename: path + }); + db.loadDatabase(function (err) { + if (err) { + ps.reject(); + } else { + if(ths.option.initData[name]){ + try { + var content = topolr.file(ths.getPath(ths.option.initData[name])).readSync(); + db.insert(JSON.parse(content),function (a,b) { + ths._dbs[name]=new wrapper(db); + ps.resolve(ths._dbs[name]); + }); + }catch (e){} + }else{ + ths._dbs[name]=new wrapper(db); + ps.resolve(ths._dbs[name]); + } + } + }); + return ps; + } else { + var ps = topolr.promise(); + var db = new nedb({ + filename: path + }); + db.loadDatabase(function (err) { + if (err) { + ps.reject(); + } else { + ths._dbs[name]=new wrapper(db); + ps.resolve(ths._dbs[name]); + } + }); + return ps; + } + }else{ + return topolr.promise(function (a) { + a(ths._dbs[name]); + }); + } + } +}); +Module({ + name:"storecontroller", + extend:"controller", + getStore:function (name) { + return project.getService("localdb").get(name); + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071118_uriHandler.js b/pool/shard011/JavaScript/0071118_uriHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..2a318d6cd555698300726cdc7a1503d2f95b1661 --- /dev/null +++ b/pool/shard011/JavaScript/0071118_uriHandler.js @@ -0,0 +1,14 @@ +'use strict'; + +var UriHandler = function() {}; + +UriHandler.prototype.register = function() { + var base = window.location.origin + '/'; + var url = base + '#/uri-payment/%s'; + + if(navigator.registerProtocolHandler) { + navigator.registerProtocolHandler('web+decred', url, 'DecredWebWallet'); + } +}; + +angular.module('copayApp.services').value('uriHandler', new UriHandler()); diff --git a/pool/shard011/JavaScript/0071126_setup.js b/pool/shard011/JavaScript/0071126_setup.js new file mode 100644 index 0000000000000000000000000000000000000000..aae60e302e30c1796f423c65f27fcf6c1deded62 --- /dev/null +++ b/pool/shard011/JavaScript/0071126_setup.js @@ -0,0 +1,41 @@ +/** + * @fileoverview This file exports a function that augments + * an array, adding in the measurement library functionality. A commandAPI + * wrapped around the array will be able to register/respond to events and + * save/load data corresponding to the measurement library documentation. + * + * const dataLayer = []; + * const measure = function() { + * dataLayer.push(arguments); + * }; + * setupMeasure(dataLayer); + * measure('config', ...); + * + */ +goog.module('measurementLibrary.config.setup'); +const {configProcessors} = goog.require('measurementLibrary.config.configProcessors'); +const DataLayerHelper = goog.require('dataLayerHelper.helper.DataLayerHelper'); + +/** + * Listen to events passed to the given dataLayer (or a new one + * if none exist). + * + * @param {!Array<*>} dataLayer The data layer to add listeners to. + */ +function setupMeasure(dataLayer) { + /** + * The DataLayerHelper to use with this application. + * @private @const {!DataLayerHelper} + */ + const helper = new DataLayerHelper(dataLayer, {'processNow': false}); + + helper.registerProcessor('config', + (eventProcessor, eventOptions, storageProcessor, storageOptions) => { + configProcessors(helper, eventProcessor, eventOptions, + storageProcessor, storageOptions); + }); + helper.process(); +} + +goog.exportSymbol('setupMeasure', setupMeasure); +exports = setupMeasure; diff --git a/pool/shard011/JavaScript/0071130_privacy-day-egg.js b/pool/shard011/JavaScript/0071130_privacy-day-egg.js new file mode 100644 index 0000000000000000000000000000000000000000..a667692817a4fec6efc701545e17d5ebaa2047aa --- /dev/null +++ b/pool/shard011/JavaScript/0071130_privacy-day-egg.js @@ -0,0 +1,40 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public +* License, v. 2.0. If a copy of the MPL was not distributed with this +* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +(function($, KonamiCode) { + 'use strict'; + + var $document = $(document); + var $body = $('body'); + var $kzp = $('#kzp'); + + new KonamiCode(function() { + $kzp.removeClass('gone').addClass('visible'); + $body.addClass('easter'); + setTimeout(function() { + endEgg(); + }, 150); + + window.dataLayer.push({ + 'event': 'in-page-interaction', + 'eLabel': 'kazoo day', + 'eAction': 'easter-egg' + }); + }); + + function endEgg() { + $document.on('keyup click', function(e) { + if (!$(e.target).is('#kzkid')) { + $kzp.removeClass('visible'); + + setTimeout(function() { + $kzp.addClass('gone'); + $body.removeClass('easter'); + $document.off('keyup click'); + }, 150); + } + }); + } + +})(window.jQuery, window.KonamiCode); diff --git a/pool/shard011/JavaScript/0071131_editProfileCtrl.js b/pool/shard011/JavaScript/0071131_editProfileCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..1d6fded7f17b015bde9e99633739acf2465d2ff6 --- /dev/null +++ b/pool/shard011/JavaScript/0071131_editProfileCtrl.js @@ -0,0 +1,90 @@ +app.controller("EditProfileCtrl", function($scope, $http, $cookies, $location, fileUpload) { + $scope.states = [ + { value: 'AC', name: 'Acre' }, + { value: 'AL', name: 'Alagoas' }, + { value: 'AP', name: 'Amapá' }, + { value: 'AM', name: 'Amazonas' }, + { value: 'BA', name: 'Bahia' }, + { value: 'CE', name: 'Ceará' }, + { value: 'DF', name: 'Distrito Federal' }, + { value: 'ES', name: 'Espirito Santo' }, + { value: 'GO', name: 'Goiás' }, + { value: 'MA', name: 'Maranhão' }, + { value: 'MS', name: 'Mato Grosso do Sul' }, + { value: 'MT', name: 'Mato Grosso' }, + { value: 'MG', name: 'Minas Gerais' }, + { value: 'PA', name: 'Pará' }, + { value: 'PB', name: 'Paraíba' }, + { value: 'PR', name: 'Paraná' }, + { value: 'PE', name: 'Pernambuco' }, + { value: 'PI', name: 'Piauí' }, + { value: 'RJ', name: 'Rio de Janeiro' }, + { value: 'RN', name: 'Rio Grande do Norte' }, + { value: 'RS', name: 'Rio Grande do Sul' }, + { value: 'RO', name: 'Rondônia' }, + { value: 'RR', name: 'Roraima' }, + { value: 'SC', name: 'Santa Catarina' }, + { value: 'SP', name: 'São Paulo' }, + { value: 'SE', name: 'Sergipe' }, + { value: 'TO', name: 'Tocantins' } + ]; + + var config = { + headers: { + 'x-access-token': $cookies.get('token') + } + }; + + $scope.sucess = false; + + var url = ''; + if ($cookies.get('type') == 0) + url = API_URL + 'patients/' + $cookies.get('user'); + else + url = API_URL + 'doctors/' + $cookies.get('user'); + + function load () { + $http.get(url, config).then(function (data) { + delete data.data.password; + + $scope.user = data.data; + console.log($scope.user); + }, function (error) { + console.log(error); + }) + } + load(); + + $scope.signup = function (user) { + delete user.profileImage; + + $http.put(url, user, config).then(function (data) { + if (data.data.message == 'Token inválido') { + $sessionStorage.login; + $sessionStorage.user; + $location.path('/'); + } else { + $scope.sucess = true; + + var file = $scope.myFile; + + console.log('file is ' ); + console.dir(file); + + if (file) { + var uploadUrl = API_URL + 'users/' + $cookies.get('user') + '/image'; + fileUpload.uploadFileToUrl(file, uploadUrl, $cookies.get('token'), function (success) { + if (success) + load(); + else + $scope.errorstatus = 'Erro ao enviar imagem.'; + }); + } else { + load(); + } + } + }, function (error) { + $scope.errorstatus = error.error; + }); + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071134_logger.js b/pool/shard011/JavaScript/0071134_logger.js new file mode 100644 index 0000000000000000000000000000000000000000..79dc9c69a053908b24b78e44800755a2a0d0a656 --- /dev/null +++ b/pool/shard011/JavaScript/0071134_logger.js @@ -0,0 +1,56 @@ +/** + * Created by vfrc2 on 08.12.15. + */ + +var winston = require('winston'); + +//requests.log - log all web requsts +var reqFileTransport = new (winston.transports.File)({ + filename: 'requests.log', + json: false, + level: 'info' +}); + +//execution.log - log all except requests +var logFileTransport = new (winston.transports.File)({ + filename: 'log.log', + json: false, + level: 'info' +}); + +var consoleTransport = new (winston.transports.Console)({ + level: 'info' +}); + +var container = new winston.Container(); + +function createLogger(module) { + var logger = container.add(module, { + transports: [consoleTransport, logFileTransport], + }); + + logger.filters.push(function(lvl, msg, meta){ + return "["+module+"] " + msg; + }); + + return logger; + +} + +function createRequestLoger(module) { + var logger = container.add(module, { + transports: [reqFileTransport, consoleTransport] + }); + + logger.filters.push(function(lvl, msg, meta){ + return "["+module+"] " + msg; + }); + + return logger; +} + +createLogger.request = createRequestLoger; +createLogger.setConsoleVerbose = function(level){ + consoleTransport.level = level; +}; +module.exports = createLogger; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0071136_validate.js b/pool/shard011/JavaScript/0071136_validate.js new file mode 100644 index 0000000000000000000000000000000000000000..3b06b6c1cb770593256f98597b70e271f69c6245 --- /dev/null +++ b/pool/shard011/JavaScript/0071136_validate.js @@ -0,0 +1,187 @@ +function func_group(){ + var name = $('#name').val(); + var group = $('#groupid').val(); + $.ajax({ + type: "POST", + url: "src/php/validation/check1.php", + data: { + 'groupid': group, + 'name': name, + }, + + success: function(data){ + if(data==1){ + $('#area').html("Valid group ID"); + $('#area').removeClass("wrong").addClass("correct"); + } + else if(data==2){ + $('#area').html("Valid group ID"); + $('#area').removeClass("wrong").addClass("correct"); + $('#join_submit_btn').attr('disabled', false); + } + else if (data==0) { + $('#area').html("In-Valid group ID"); + $('#area').removeClass("correct").addClass("wrong"); + $('#join_submit_btn').attr('disabled', true); + } + }, + }); +} + +function func_nick(){ + var name = $('#name').val(); + var group = $('#groupid').val(); + $.ajax({ + type: "POST", + url: "src/php/validation/check2.php", + data: { + 'name': name, + 'groupid': group + }, + + success: function(data){ + if(data==1){ + + $('#area1').html("Valid user for the above group"); + $('#area1').removeClass("wrong").addClass("correct"); + $('#join_submit_btn').attr('disabled', false); + }else { + $('#area1').html("In-Valid user for the above group"); + $('#area1').removeClass("correct").addClass("wrong"); + $('#join_submit_btn').attr('disabled', true); + } + }, + }); +} + +function check_group_validate(){ + var nickname = $('#nickname').val(); + var group = $('#group').val(); + var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; + var emailaddressVal = $("#email").val(); + $.ajax({ + type: "POST", + url: "src/php/validation/check3.php", + data: { + 'group': group + }, + success: function(data){ + if(data==1){ + $('#area2').html("Group name taken"); + $('#area2').removeClass("correct").addClass("wrong"); + $('#create_btn').attr('disabled', true); + } + else if (data==2) { + $('#area2').html("Empty group name"); + $('#area2').removeClass("correct").addClass("wrong"); + $('#create_btn').attr('disabled', true); + } + else if (data==0){ + $('#area2').html("Group name unique"); + $('#area2').removeClass("wrong").addClass("correct"); + if( (!emailReg.test(emailaddressVal)&&nickname.length<4) ) { + $('#create_btn').attr('disabled', true); + } + else if ( (emailReg.test(emailaddressVal)&&nickname.length>=4&&emailaddressVal!="") ) { + $('#create_btn').attr('disabled', false); + } + } + + }, + }); + if($('#area2').text()==="Group name unique"){ + $('#area2').removeClass("wrong").addClass("correct"); + } + else + $('#area2').removeClass("correct").addClass("wrong"); +} + +function check_nickname(){ + var nickname = $('#nickname').val(); + var group = $('#group').val(); + if(nickname.length<4){ + $('#area3').html("Nickname is too short"); + $('#create_btn').attr('disabled', true); + } + else if (nickname.length>=4) { + $('#area3').html("Looks clean"); + var hasError = false; + var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; + var emailaddressVal = $("#email").val(); + $.ajax({ + type: "POST", + url: "src/php/validation/check3.php", + data: { + 'group': group + }, + + success: function(data){ + if( (!emailReg.test(emailaddressVal)&&data==1) || (!emailReg.test(emailaddressVal)&&data==0) || (emailReg.test(emailaddressVal)&&data==1) ) { + $('#create_btn').attr('disabled', true); + } + else if ( (emailReg.test(emailaddressVal)&&data==0&&emailaddressVal!="") ) { + $('#create_btn').attr('disabled', false); + } + }, + }); + } + console.log($('#area3').text()); + if($('#area3').text()==="Looks clean"){ + $('#area3').removeClass("wrong").addClass("correct"); + } + else + $('#area3').removeClass("correct").addClass("wrong"); +} + +function check_email(){ + + var nickname = $('#nickname').val(); + var group = $('#group').val(); + var hasError = false; + var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; + var emailaddressVal = $("#email").val(); + if(emailaddressVal == '') { + $("#area4").html('Please enter your email address.'); + $('#create_btn').attr('disabled', true); + } + else if(!emailReg.test(emailaddressVal)) { + $("#area4").html('Enter a valid email address.'); + $('#create_btn').attr('disabled', true); + } + else if (emailReg.test(emailaddressVal) ) + { + //$("#area4").html('Email id looks gud'); + $.ajax({ + type: "POST", + url: "src/php/validation/check3.php", + data: { + 'group': group, + 'email': emailaddressVal + }, + + success: function(data){ + if( (nickname.length<4&&data==1) || (nickname.length<4&&data==0) || (nickname.length>=4&&data==1) ) + { + $("#area4").html('Email ID is correct'); + $('#area4').removeClass("wrong").addClass("correct"); + $('#create_btn').attr('disabled', true); + } + else if ( nickname.length>=4&&data==0 ) { + $("#area4").html('Email ID is correct'); + $('#area4').removeClass("wrong").addClass("correct"); + $('#create_btn').attr('disabled', false); + } + else if ( data==3){ + $("#area4").html('Email ID has already been taken'); + $('#create_btn').attr('disabled', true); + } + }, + }); + } + console.log($('#area4').text()); + if($('#area4').text()==='Email ID is correct'){ + $('#area4').removeClass("wrong").addClass("correct"); + } + else + $('#area4').removeClass("correct").addClass("wrong"); +} diff --git a/pool/shard011/JavaScript/0071138_compiler.test.js b/pool/shard011/JavaScript/0071138_compiler.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2a3fd3de91a8cc6cbbbafa4c4cdf8521080449aa --- /dev/null +++ b/pool/shard011/JavaScript/0071138_compiler.test.js @@ -0,0 +1,28 @@ + +/** + * Module dependencies. + */ + +var connect = require('connect'), + helpers = require('./helpers'), + assert = require('assert'), + http = require('http'); + +module.exports = { + test: function(){ + var server = helpers.run( + connect.compiler({ src: __dirname + '/fixtures', enable: ['sass', 'coffeescript'] }), + connect.staticProvider({ root: __dirname + '/fixtures' }) + ); + server.assertResponse('GET', '/doesnotexist.css', 404, 'Cannot GET /doesnotexist.css'); + server.assertResponse('GET', '/style.css', 200, 'body {\n font-size: 12px;\n color: #000;}\n'); + server.assertResponse('GET', '/style.css', 200, 'body {\n font-size: 12px;\n color: #000;}\n'); + server.assertResponse('GET', '/foo.bar.baz.css', 200, 'foo {\n color: #000;}\n'); + server.assertResponse('GET', '/foo.bar.baz.css', 200, 'foo {\n color: #000;}\n'); + server.assertResponse('GET', '/script.js', 200, '(function() {\n var $;\n $ = jQuery;\n $(document).ready(function() {\n return console.log("Say Hello to CoffeeScript");\n });\n})();\n'); + }, + + 'test .compilers': function(){ + assert.equal('object', typeof connect.compiler.compilers); + } +} diff --git a/pool/shard011/JavaScript/0071143_res.sendStatus.js b/pool/shard011/JavaScript/0071143_res.sendStatus.js new file mode 100644 index 0000000000000000000000000000000000000000..5090ea79317a644c1ab5ba96622b2968fb84dd76 --- /dev/null +++ b/pool/shard011/JavaScript/0071143_res.sendStatus.js @@ -0,0 +1,104 @@ +import { expect } from 'chai'; +import { createServer } from 'service-mocker/server'; + +import mime from 'mime-component'; +import httpStatus from 'statuses'; + +import { + uniquePath, + sendRequest, +} from '../../helpers/'; + +export default function () { + const { router } = createServer(); + + describe('res.sendStatus(code)', () => { + it(`should send response with text type`, async () => { + const path = uniquePath(); + + router.get(path, (_req, res) => { + res.sendStatus(200); + }); + + const { headers } = await sendRequest(path); + + expect(headers.get('content-type')).to.equals(mime.lookup('text')); + }); + + describe('with well-known HTTP status codes', () => { + it('should send a response with 202 status', async () => { + const path = uniquePath(); + + router.get(path, (_req, res) => { + res.sendStatus(202); + }); + + const { status } = await sendRequest(path); + + expect(status).to.equal(202); + }); + + it(`should set statusText to ${httpStatus[202]}`, async () => { + const path = uniquePath(); + + router.get(path, (_req, res) => { + res.sendStatus(202); + }); + + const { statusText } = await sendRequest(path); + + expect(statusText).to.equal(httpStatus[202]); + }); + + it('should set response body to statusText', async () => { + const path = uniquePath(); + + router.get(path, (_req, res) => { + res.sendStatus(202); + }); + + const { body } = await sendRequest(path); + + expect(body).to.equal(httpStatus[202]); + }); + }); + + describe('with unknown status codes', () => { + it('should respond with status 233', async () => { + const path = uniquePath(); + + router.get(path, (_req, res) => { + res.sendStatus(233); + }); + + const { status } = await sendRequest(path); + + expect(status).to.equals(233); + }); + + it('should set statusText to the status code', async () => { + const path = uniquePath(); + + router.get(path, (_req, res) => { + res.sendStatus(233); + }); + + const { statusText } = await sendRequest(path); + + expect(statusText).to.equal('233'); + }); + + it('should set response body to the status code', async () => { + const path = uniquePath(); + + router.get(path, (_req, res) => { + res.sendStatus(233); + }); + + const { body } = await sendRequest(path); + + expect(body).to.equal('233'); + }); + }); + }); +} diff --git a/pool/shard011/JavaScript/0071145_index.js b/pool/shard011/JavaScript/0071145_index.js new file mode 100644 index 0000000000000000000000000000000000000000..9d379f396115d3fec5c2f5a315d731dae1cad268 --- /dev/null +++ b/pool/shard011/JavaScript/0071145_index.js @@ -0,0 +1,57 @@ +import React from 'react' +import { Link } from 'react-router' +import routes from '../routes' +import User from '../services/user' + +class Nav extends React.Component { + + + constructor(props) { + super(props) + this.handleLogout = this.handleLogout.bind(this); + this.state = { userLogged: User.isLogged() } + } + + handleLogout() { + User.logout() + this.setState({ userLogged: false }) + } + + render() { + var login + if (this.state.userLogged) { + login = + } else { + login = Login + } + + return ( + + ) + } +} + + +Nav.displayName = 'Nav' + +export default Nav diff --git a/pool/shard011/JavaScript/0071147_image-picker.js b/pool/shard011/JavaScript/0071147_image-picker.js new file mode 100644 index 0000000000000000000000000000000000000000..41282c6b81bf61fd21df8dec7a87f02268912a0b --- /dev/null +++ b/pool/shard011/JavaScript/0071147_image-picker.js @@ -0,0 +1,205 @@ +/** + * An input field Image Picker utilising the Xinha ImageManager. + * + * Hijack the Xinha ImageManager plugin to provide an image URL picker + * for any form input field in the form of a "Browse" button to the + * right of the field, in the same manner as a file type input field + * except it opens the familiar ImageManager dialog to upload/select/edit + * an image and returns the URL of the image to the field's value. + * + * Example Usage: + * + * + * + * + * + * @author $Author$ + * @version $Id$ + * @package ImageManager + */ + + +function ImagePicker(field) +{ + this.field = field; + var picker = this; + + var but = document.createElement('input'); + but.type = 'button'; + but.value = 'Browse'; + but.onclick = function() { picker.popup_picker(); } + + field.parentNode.insertBefore(but,field.nextSibling); + field.size = '20'; + field.style.textAlign = 'right'; +}; + +ImagePicker.prototype.backend = Xinha.getPluginDir('ImageManager') + '/backend.php?__plugin=ImageManager&'; +ImagePicker.prototype.backend_data = null; + +ImagePicker.prototype.append_query_string = true; + +ImagePicker.prototype.popup_picker = function() +{ + var picker = this; // closure for later + var outparam = null; + if(picker.field.value) + { + outparam = + { + f_url : picker.field.value, + f_width : null, + f_height : null, + + // None of this stuff is useful to us, we return only a URL. + f_alt : picker.field.value, + f_border : null, + f_align : null, + f_padding: null, + f_margin : null, + f_backgroundColor: null, + f_borderColor: null, + f_border : null, + f_padding: null, + f_margin: null + }; + + while(outparam.f_url.match(/[?&]((f_[a-z0-9]+)=([^&#]+))/i)) + { + outparam[RegExp.$2] = decodeURIComponent(RegExp.$3); + outparam.f_url = outparam.f_url.replace(RegExp.$1, ''); + } + + outparam.f_url = outparam.f_url.replace(/&{2,}/g, '&'); + outparam.f_url = outparam.f_url.replace(/\?&*(#.*)?$/, ''); + } + + var manager = this.backend + '__function=manager'; + if(this.backend_config != null) + { + manager += '&backend_config=' + + encodeURIComponent(this.backend_config); + manager += '&backend_config_hash=' + + encodeURIComponent(this.backend_config_hash); + manager += '&backend_config_secret_key_location=' + + encodeURIComponent(this.backend_config_secret_key_location); + } + + if(this.backend_data != null) + { + for ( var i in this.backend_data ) + { + manager += '&' + i + '=' + encodeURIComponent(this.backend_data[i]); + } + } + + Dialog(manager, function(param) { + if (!param) { // user must have pressed Cancel + return false; + } + + picker.field.value = param.f_url; + if(picker.append_query_string) + { + if(picker.field.value.match(/[?&](.*)$/)) + { + if(RegExp.$1.length) + { + picker.field.value += '&'; + } + } + else + { + picker.field.value += '?'; + } + + for(var i in param) + { + if(i == 'f_url' || param[i] == null || param[i] == 'null' || param[i] == '') continue; + if(typeof param[i] == 'function') continue; + if(param[i].length = 0) continue; + + picker.field.value += i + '=' + encodeURIComponent(param[i]) + '&'; + } + } + + }, outparam); +} + +// Dialog is part of Xinha, but we'll provide it here incase Xinha's not being +// loaded. +if(typeof Dialog == 'undefined') +{ + // htmlArea v3.0 - Copyright (c) 2003-2004 interactivetools.com, inc. + // This copyright notice MUST stay intact for use (see license.txt). + // + // Portions (c) dynarch.com, 2003-2004 + // + // A free WYSIWYG editor replacement for