commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
c5f451746dcd93a7b71158df28fb449e628fcabf
|
Allow disabling babel cache
|
buildjs/webpack.config.js
|
buildjs/webpack.config.js
|
'use strict';
const path = require('path');
const fs = require('fs');
const findPackage = require('./src/find_package.js');
const webpack = require('webpack');
const resolve = require('resolve');
const mkdirp = require('mkdirp');
// We must place our files in a special folder for integration /w the android
// build system.
const destination = process.env.SILK_BUILDJS_DEST;
const babelCache = path.join(destination, '../.babelcache');
const modulePath = findPackage(process.env.SILK_BUILDJS_SOURCE);
const pkg = require(path.join(modulePath, 'package.json'));
const localWebpack = path.join(modulePath, 'webpack.config.js');
mkdirp.sync(babelCache);
const name = pkg.name;
let main = pkg.main || './index.js';
if (!path.extname(main)) {
main += '.js';
}
if (main.indexOf('./') !== 0) {
main = `./${main}`;
}
const absMain = path.resolve(modulePath, main);
let mainDir;
try {
mainDir = fs.realpathSync(path.dirname(absMain));
} catch (err) {
mainDir = path.dirname(absMain);
}
// XXX: Would be nicer to abort this in the bash script rather than after we
// have booted up node here...
if (
main.indexOf('build/Release') === 0 ||
main.indexOf('./build/Release') === 0 ||
/\.node$/.test(main)
) {
console.log(`Module contains no JS main skipping webpack ...`);
process.exit(0);
}
if (!main) {
throw new Error(`package.json must have main in ${process.cwd()}`);
}
const externals = [
// TODO: auto generate these ...
'base_version',
'bleno',
'mic',
'noble',
'node-hid',
'node-webrtc',
'opencv',
'segfault-handler',
'silk-alog',
'silk-battery',
'silk-camera',
'silk-core-version',
'silk-cv',
'silk-dialog-engine',
'silk-gc1',
'silk-input',
'silk-kws',
'silk-lights',
'silk-modwatcher',
'silk-movie',
'silk-netstatus',
'silk-ntp',
'silk-properties',
'silk-sensors',
'silk-sysutils',
'silk-vad',
'silk-vibrator',
'silk-volume',
'silk-wifi',
'v8-profiler',
'kissfft',
'silk-caffe',
(context, request, callback) => {
if (resolve.isCore(request)) {
callback(null, true);
return;
}
// For extra fun node will allow resolving .main without a ./ this behavior
// makes .main look nicer but is completely different than how requiring
// without a specific path is handled elsewhere... To ensure we don't
// accidentally resolve a node module to a local file we handle this case
// very specifically.
if (context === modulePath && pkg.main === request) {
const resolvedPath = path.resolve(context, request);
if (!fs.existsSync(resolvedPath)) {
callback(new Error(`${modulePath} has a .main which is missing ...`));
return;
}
}
// Handle path rewriting for native modules
if (
/\.node$/.test(request) ||
request.indexOf('build/Release') !== -1
) {
if (path.isAbsolute(request)) {
callback(null, true);
return;
}
const absExternalPath = path.resolve(context, request);
let relativeExternalPath = path.relative(mainDir, absExternalPath);
if (relativeExternalPath.indexOf('.') !== 0) {
relativeExternalPath = `./${relativeExternalPath}`;
}
callback(null, relativeExternalPath);
return;
}
resolve(request, {
basedir: context,
package: pkg,
extensions: ['.js', '.json'],
}, (err, resolvedPath) => {
if (err) {
console.log(`Missing module imported from ${context} (${request})`);
callback(null, true);
return;
}
callback(null, false);
});
}
];
const entry = {};
entry[main] = main;
const config = {
context: modulePath,
externals,
target: 'node',
node: {
__dirname: false,
__filename: false,
},
devtool: 'source-map',
entry,
output: {
path: path.join(destination),
libraryTarget: 'commonjs2',
filename: `[name]`,
},
resolve: {
extensions: ['', '.js', '.json'],
// Common "gothcha" modules ...
alias: {
'any-promise': require.resolve('./shims/any-promise.js'),
'json3': require.resolve('./shims/json3.js'),
},
},
babel: {
cacheDirectory: babelCache,
presets: [
require('babel-preset-silk-node4'),
],
},
module : {
loaders: [
{ test: /\.json$/, loader: require.resolve('json-loader') },
{
test: /\.js$/,
loader: require.resolve('babel-loader'),
query: {
babelrc: false,
}
}
]
}
}
if (fs.existsSync(localWebpack)) {
console.log(`${localWebpack} found agumenting buildjs ...`);
const rules = Object.assign({}, require(localWebpack));
if (rules.externals && Array.isArray(rules.externals)) {
// Order is important here the rules should be ordered such that the
// webpack.config comes from the module first and our global rules second.
config.externals = rules.externals.concat(config.externals);
delete rules.externals;
}
Object.assign(config, rules);
}
module.exports = config;
|
JavaScript
| 0 |
@@ -377,69 +377,8 @@
ST;%0A
-const babelCache = path.join(destination, '../.babelcache');%0A
cons
@@ -438,16 +438,16 @@
OURCE);%0A
+
const pk
@@ -568,32 +568,260 @@
);%0A%0A
-mkdirp.sync(babelCache);
+%0Alet babelCache;%0Aif (!process.env.BABEL_CACHE %7C%7C process.env.BABEL_CACHE === '1') %7B%0A babelCache = path.join(destination, '../.babelcache');%0A mkdirp.sync(babelCache);%0A%7D else %7B%0A console.log('~ babel cache has been disabled ~');%0A babelCache = false;%0A%7D
%0A%0Aco
|
ca9ee2eb092abd14d2bda84618300f966d2d4f96
|
Support IE9 a bit
|
busstops/static/js/map.js
|
busstops/static/js/map.js
|
(function () {
'use strict';
/*jslint
browser: true
*/
/*global
L, loadjs
*/
var mapContainer = document.getElementById('map');
if (!mapContainer || !mapContainer.clientWidth) {
return;
}
function getIcon(indicator, bearing, active) {
var className = 'leaflet-div-icon';
if (active) {
className += ' active';
}
if (indicator) {
var indicatorParts = indicator.split(' ');
if (indicatorParts.length === 2 && (indicatorParts[0] == 'Stop' || indicatorParts[0] === 'Stand' || indicatorParts[0] === 'Stance')) {
indicator = indicatorParts[1];
} else {
indicator = indicator.slice(0, 3);
}
} else {
indicator = '';
}
if (!isNaN(bearing)) {
indicator = '<div class="arrow" style="transform: rotate(' + bearing + 'deg)"></div>' + indicator;
}
return L.divIcon({
iconSize: [20, 20],
html: indicator,
popupAnchor: [0, -5],
className: className
});
}
function setUpMap() {
var h1 = document.getElementsByTagName('h1')[0],
items = document.getElementsByTagName('li'),
i, // transient
metaElements, // transient
latLng, // transient
mainLocations = [], // locations with labels
labels = []; // label elements
for (i = items.length - 1; i >= 0; i -= 1) {
if (items[i].getAttribute('itemtype') === 'https://schema.org/BusStop' && items[i].className != 'OTH') {
metaElements = items[i].getElementsByTagName('meta');
if (metaElements.length) {
latLng = [
parseFloat(metaElements[0].getAttribute('content')),
parseFloat(metaElements[1].getAttribute('content'))
];
mainLocations.push(latLng);
labels.push(items[i]);
}
}
}
// Add the main stop (for the stop point detail page)
if (h1.getAttribute('itemprop') === 'name') {
metaElements = document.getElementsByTagName('meta');
for (i = 0; i < metaElements.length; i++) {
if (metaElements[i].getAttribute('itemprop') === 'latitude') {
mainLocations.push([
parseFloat(metaElements[i].getAttribute('content')),
parseFloat(metaElements[i + 1].getAttribute('content'))
]);
break;
}
}
}
if (mainLocations.length) {
var map = L.map('map', {
tap: false
}),
tileURL = 'https://bustimes.org/styles/klokantech-basic/{z}/{x}/{y}' + (L.Browser.retina ? '@2x' : '') + '.png',
setUpPopup = function (location, label) {
var marker = L.marker(location, {
icon: getIcon(label.dataset.indicator, label.dataset.heading),
riseOnHover: true
}).addTo(map).bindPopup(label.innerHTML),
a = label.getElementsByTagName('a');
if (a.length) {
a[0].onmouseover = a[0].ontouchstart = function() {
if (!marker.getPopup().isOpen()) {
marker.openPopup();
}
};
marker.on('mouseover', function() {
marker.openPopup();
});
}
};
L.tileLayer(tileURL, {
attribution: '© <a href="https://openmaptiles.org">OpenMapTiles</a> | © <a href="https://www.openstreetmap.org">OpenStreetMap contributors</a>'
}).addTo(map);
if (mainLocations.length > labels.length) { // on a stop point detail page
i = mainLocations.length - 1;
L.marker(mainLocations[i], {icon: getIcon(mapContainer.dataset.indicator, mapContainer.dataset.heading, true)}).addTo(map);
map.setView(mainLocations[i], 17);
} else {
var polyline;
if (window.geometry) {
polyline = L.geoJson(window.geometry, {
style: {
weight: 2
}
});
polyline.addTo(map);
}
map.fitBounds((polyline || L.polyline(mainLocations)).getBounds(), {
padding: [10, 20]
});
}
for (i = labels.length - 1; i >= 0; i -= 1) {
setUpPopup(mainLocations[i], labels[i], items[i]);
}
}
}
loadjs(['/static/js/bower_components/leaflet/dist/leaflet.js', '/static/js/bower_components/leaflet/dist/leaflet.css'], {
success: setUpMap
});
})();
|
JavaScript
| 0 |
@@ -835,23 +835,24 @@
if (
-!isNaN(bearing)
+bearing !== null
) %7B%0A
@@ -902,16 +902,188 @@
style=%22
+-ms-transform: rotate(' + bearing + 'deg);-webkit-transform: rotate(' + bearing + 'deg);-moz-transform: rotate(' + bearing + 'deg);-o-transform: rotate(' + bearing + 'deg);
transfor
@@ -3305,24 +3305,35 @@
n(label.
-dataset.
+getAttribute('data-
indicato
@@ -3337,16 +3337,18 @@
ator
+')
, label.
data
@@ -3343,31 +3343,44 @@
, label.
-dataset.
+getAttribute('data-
heading
+')
),%0A
@@ -4436,24 +4436,35 @@
ntainer.
-dataset.
+getAttribute('data-
indicato
@@ -4464,16 +4464,18 @@
ndicator
+')
, mapCon
@@ -4485,23 +4485,36 @@
ner.
-dataset.
+getAttribute('data-
heading
+')
, tr
|
17413fcb8520e621c684876956924528882e9e62
|
add prod env for nodemon, without debug
|
gruntfile.js
|
gruntfile.js
|
'use strict';
module.exports = function(grunt) {
// Unified Watch Object
var watchFiles = {
serverViews: ['app/views/**/*.*'],
serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'],
clientViews: ['public/modules/**/views/**/*.html'],
clientJS: ['public/js/*.js', 'public/modules/**/*.js'],
clientCSS: ['public/modules/**/*.css'],
mochaTests: ['app/tests/**/*.js']
};
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-daemon');
// Project Configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
serverViews: {
files: watchFiles.serverViews,
options: {
livereload: true
}
},
serverJS: {
files: watchFiles.serverJS,
tasks: ['jshint'],
options: {
livereload: true
}
},
clientViews: {
files: watchFiles.clientViews,
options: {
livereload: true
}
},
clientJS: {
files: watchFiles.clientJS,
tasks: ['jshint'],
options: {
livereload: true
}
},
clientCSS: {
files: watchFiles.clientCSS,
tasks: ['csslint'],
options: {
livereload: true
}
}
},
jshint: {
all: {
src: watchFiles.clientJS.concat(watchFiles.serverJS),
options: {
jshintrc: true
}
}
},
csslint: {
options: {
csslintrc: '.csslintrc'
},
all: {
src: watchFiles.clientCSS
}
},
uglify: {
production: {
options: {
mangle: false
},
files: {
'public/dist/application.min.js': 'public/dist/application.js'
}
}
},
cssmin: {
combine: {
files: {
'public/dist/application.min.css': '<%= applicationCSSFiles %>'
}
}
},
nodemon: {
dev: {
script: 'server.js',
options: {
nodeArgs: ['--debug=7000'],
ext: 'js,html',
watch: watchFiles.serverViews.concat(watchFiles.serverJS)
}
}
},
nodeprod: {
all: {
script: 'server.js',
options: {
ext: 'js,html',
watch: watchFiles.serverViews.concat(watchFiles.serverJS)
}
}
},
'node-inspector': {
custom: {
options: {
'web-port': 1337,
'web-host': 'localhost',
'save-live-edit': true,
'no-preload': true,
'stack-trace-limit': 50,
'hidden': []
}
}
},
ngAnnotate: {
production: {
files: {
'public/dist/application.js': '<%= applicationJavaScriptFiles %>'
}
}
},
concurrent: {
default: ['nodeprod', 'watch'],
debug: ['nodemon', 'watch', 'node-inspector'],
options: {
logConcurrentOutput: true,
limit: 10
}
},
env: {
test: {
NODE_ENV: 'test'
},
secure: {
NODE_ENV: 'secure'
},
production: {
NODE_ENV: 'production',
src: '../../RacketSport_SecureGruntEnv.json'
}
},
mochaTest: {
src: watchFiles.mochaTests,
options: {
reporter: 'spec',
require: 'server.js'
}
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
}
});
// Load NPM tasks
require('load-grunt-tasks')(grunt);
// Making grunt default to force in order not to break the project.
grunt.option('force', true);
// A Task for loading the configuration object
grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() {
var init = require('./config/init')();
var config = require('./config/config');
grunt.config.set('applicationJavaScriptFiles', config.assets.js);
grunt.config.set('applicationCSSFiles', config.assets.css);
});
// Default task(s).
grunt.registerTask('default', ['lint', 'concurrent:default']);
// Debug task.
grunt.registerTask('debug', ['lint', 'concurrent:debug']);
// Secure task(s).
grunt.registerTask('secure', ['env:secure', 'lint', 'concurrent:default']);
// Lint task(s).
grunt.registerTask('lint', ['jshint', 'csslint']);
// Build task(s).
grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'cssmin']);
// Test task.
grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);
grunt.registerTask('prod', ['env:production', 'lint', 'concurrent:default']);
};
|
JavaScript
| 0 |
@@ -399,91 +399,8 @@
%09%7D;%0A
-%09grunt.loadNpmTasks('grunt-contrib-connect');%0A%09grunt.loadNpmTasks('grunt-daemon');%0A
%09//
@@ -1797,172 +1797,8 @@
%09%7D,%0A
-%09%09nodeprod: %7B%0A%09%09%09all: %7B%0A%09%09%09%09script: 'server.js',%0A%09%09%09%09options: %7B%0A%09%09%09%09%09ext: 'js,html',%0A%09%09%09%09%09watch: watchFiles.serverViews.concat(watchFiles.serverJS)%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D,%0A
%09%09'n
@@ -2466,13 +2466,24 @@
c: '
-../..
+/var/lib/jenkins
/Rac
|
7fe53d68c085808e1eaa2e1f9b3531b56f15958a
|
Fix missing Jekyll compilation task
|
gruntfile.js
|
gruntfile.js
|
// Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
sass: {
files: 'scss/**/*.scss',
tasks: ['build']
},
eslint: {
files: 'js/**/*.js',
tasks: ['eslint']
},
docs: {
files: ['docs/**/*.*', 'scss/**/**/*.scss'],
tasks: ['docs']
}
},
clean: {
grunticon: ['dist/assets/icons/ui', 'dist/assets/icons/thematic'],
svg: ['icons/ui/dist']
},
pure_grids: {
responsive: {
dest: 'scss/modules/_grid-units.scss',
options: {
units: [5,12,24],
includeOldIEWidths: false,
mediaQueries: {
sm: 'screen and (min-width: 36.5em)', //584px
md: 'screen and (min-width: 48em)', //768px
lg: 'screen and (min-width: 64em)', //1024px
xl: 'screen and (min-width: 75em)' //1200px
},
selectorPrefix: '.wfp-u-'
}
}
},
sass: {
options: {
outputStyle: 'expanded',
sourceMap: true,
indentedSyntax: true,
sassDir: 'scss',
cssDir: 'dist/css'
},
dev: {
files: [{
expand: true,
cwd: 'scss/',
src: ['*.scss'],
dest: 'dist/css/',
ext: '.css'
}]
},
dist: {
options: {
sourceMap: false
},
files: [{
expand: true,
cwd: 'scss/',
src: ['*.scss'],
dest: 'dist/css/',
ext: '.css'
}]
},
docs: {
files: {
'docs/css/main.css': 'docs/_sass/main.scss'
}
},
docsDist: {
options: {
sourceMap: false
},
files: {
'docs/css/main.css': 'docs/_sass/main.scss'
}
}
},
postcss: {
options: {
processors: [
require('autoprefixer')({ browsers: ['last 2 version'] })
],
map: {
inline: false,
}
},
dist: {
options: {
processors: [ require('cssnano')() ],
map: false
},
src: 'dist/css/*.css'
},
dev: {
src: 'dist/css/*.css'
},
docs: {
src: 'docs/css/*.css'
},
docsDist: {
options: {
processors: [ require('cssnano')() ],
map: false
},
src: 'docs/css/*.css'
}
},
grunticon: {
ui: {
files: [{
expand: true,
cwd: 'icons/ui/src',
src: ['*.svg'],
dest: 'dist/assets/icons/ui'
}],
options: {
dynamicColorOnly: true,
colors: {
light: '#ffffff',
dark: '#000000'
},
datasvgcss: 'ui-icons.svg.css',
datapngcss: 'ui-icons.png.css',
urlpngcss: 'ui-icons.fallback.css'
}
},
thematic: {
files: [{
expand: true,
cwd: 'icons/thematic',
src: ['*.svg'],
dest: 'dist/assets/icons/thematic'
}],
options: {
datasvgcss: 'thematic-icons.svg.css',
datapngcss: 'thematic-icons.png.css',
urlpngcss: 'thematic-icons.fallback.css',
cssprefix: '.thematic-'
}
}
},
svgtoolkit: {
light: {
options: {
generatePNGs: false,
colorize: '#ffffff'
},
files: [{
expand: true,
cwd: 'icons/ui/src',
src: '*.svg',
dest: 'icons/ui/dist/light'
}]
},
dark: {
options: {
generatePNGs: false,
colorize: '#232323'
},
files: [{
expand: true,
cwd: 'icons/ui/src',
src: '*.svg',
dest: 'icons/ui/dist/dark'
}]
},
primary: {
options: {
generatePNGs: false,
colorize: '#2A93FC'
},
files: [{
expand: true,
cwd: 'icons/ui/src',
src: '*.svg',
dest: 'icons/ui/dist/primary'
}]
}
},
datauri: {
light: {
options: {
classPrefix: 'icon-light-',
usePlaceholder: true
},
files: [{
src: 'icons/ui/dist/light/**/*.svg',
dest: 'scss/modules/icons/_icons-light.scss'
}]
},
dark: {
options: {
classPrefix: 'icon-dark-',
usePlaceholder: true
},
files: [{
src: 'icons/ui/dist/dark/**/*.svg',
dest: 'scss/modules/icons/_icons-dark.scss'
}]
},
primary: {
options: {
classPrefix: 'icon-primary-',
usePlaceholder: true
},
files: [{
src: 'icons/ui/dist/primary/**/*.svg',
dest: 'scss/modules/icons/_icons-primary.scss'
}]
}
},
jekyll: {
dist: {
options: {
src: './docs',
config: './docs/_config.yml',
dest: './dist/docs'
}
}
},
eslint: {
options: {
config: '.eslintrc.json',
force: true
},
all: ['js/**/*.js']
},
sasslint: {
options: {
config: '.sass-lint.yml',
},
target: ['scss/**/*.scss']
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-grunticon');
grunt.loadNpmTasks('grunt-datauri');
grunt.loadNpmTasks('grunt-jekyll');
grunt.loadNpmTasks('grunt-postcss');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-sass-lint');
grunt.loadNpmTasks('grunt-svg-toolkit');
grunt.loadNpmTasks('grunt-pure-grids');
grunt.loadNpmTasks('eslint-grunt');
// Build SVGs and SCSS
grunt.registerTask('gen-svg', ['clean:svg', 'svgtoolkit', 'datauri', 'clean:svg']);
// Build Grunticon Icons
grunt.registerTask('gen-icons', ['clean:grunticon', 'grunticon']);
// Build WFP UI Docs locally
grunt.registerTask('docs', ['sasslint', 'sass:docs', 'postcss:docs']);
// Build WFP UI Docs
grunt.registerTask('docs-build', ['sasslint', 'sass:docs', 'postcss:docs', 'gen-icons']);
// Build dist-ready WFP UI Docs
grunt.registerTask('docs-dist', ['sasslint', 'sass:docsDist', 'postcss:docsDist', 'gen-icons', 'jekyll:dist']);
// Build WFP UI
grunt.registerTask('build', ['eslint', 'gen-svg', 'sasslint', 'sass:dev', 'postcss:dev']);
// Build a dist-ready WFP UI
grunt.registerTask('dist', ['gen-svg', 'gen-icons', 'sass:dist', 'postcss:dist']);
// Set default grunt task to `dist`
grunt.registerTask('default', ['dist']);
};
|
JavaScript
| 0.999817 |
@@ -6127,16 +6127,26 @@
ss:docs'
+, 'jekyll'
%5D);%0A //
@@ -6252,16 +6252,26 @@
n-icons'
+, 'jekyll'
%5D);%0A //
@@ -6404,21 +6404,16 @@
'jekyll
-:dist
'%5D);%0A /
|
42a0959e5e34607758f43b520e5c0a52b7108ca3
|
Fix order of javascript concatenation.
|
gruntfile.js
|
gruntfile.js
|
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
files: ['app/scripts/*.js'],
options: {
reporter: require('jshint-stylish'),
jshintrc: true
}
},
jasmine: {
app : {
src: 'app/scripts/*.js',
options: {
specs: 'test/js/spec.*.js'
}
}
},
uglify: {
main: {
options: {
beautify: false
},
files: {
'app/build/js/main.min.js': 'app/build/js/main.js'
}
}
},
concat: {
dist: {
src: ['app/scripts/app.js', 'app/vendor/jQuery/dist/jquery.min.js'],
dest: 'app/build/js/main.js'
}
},
watch: {
options: {
interrupt: true,
spawn: false
},
css: {
files: ['app/styles/**/*.scss'],
tasks: ['sass']
},
js: {
files: ['app/scripts/**/*.js'],
tasks: ['jshint', 'concat', 'uglify']
},
grunt: {
options: {
reload: true
},
files: ['gruntfile.js']
}
},
sass: {
options: {
style: 'nested',
sourceMap: true
},
dist: {
files: {
'app/build/css/style.css' : 'app/styles/style.scss'
}
}
},
connect: {
server: {
options: {
hostname: '127.0.0.1',
port: 8888,
base: 'app',
keepalive: false
}
}
}
});
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['connect:server', 'watch']);
grunt.registerTask('test', ['jasmine']);
};
|
JavaScript
| 0.00008 |
@@ -641,30 +641,8 @@
c: %5B
-'app/scripts/app.js',
'app
@@ -671,24 +671,46 @@
uery.min.js'
+, 'app/scripts/app.js'
%5D,%0A d
|
dbd7bd95c1dd0ef00aa8ba9351bb1e2a25369f0d
|
copy bower.json, not package.json
|
gruntfile.js
|
gruntfile.js
|
/*
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
module.exports = function(grunt) {
var readManifest = require('../tools/loader/readManifest.js');
var Polymer = readManifest('build.json');
grunt.initConfig({
'wct-test': {
local: {
options: {remote: false},
},
remote: {
options: {remote: true},
},
},
'wct-sauce-tunnel': {
default: {},
},
copy: {
Polymer: {
src: 'layout.html',
dest: 'dist/layout.html'
}
},
concat: {
Polymer: {
options: {
nonull: true
},
files: {
'dist/polymer.js': readManifest('build.json')
}
}
},
uglify: {
options: {
nonull: true
},
Polymer: {
options: {
beautify: {
ascii_only: true,
},
banner: grunt.file.read('banner.txt') + '// @version: <%= buildversion %>'
},
files: {
'dist/polymer.min.js': 'dist/polymer.js'
}
}
},
audit: {
polymer: {
options: {
repos: [
'../polymer-expressions',
'../polymer-gestures',
'../polymer'
]
},
files: {
'dist/build.log': ['dist/polymer.js', 'dist/polymer.min.js', 'dist/layout.html']
}
}
},
'string-replace': {
polymer: {
files: {
'dist/polymer-versioned.js': 'src/polymer.js'
},
options: {
replacements: [
{
pattern: 'master',
replacement: '<%= buildversion %>'
}
]
}
}
},
pkg: grunt.file.readJSON('package.json')
});
grunt.loadTasks('../tools/tasks');
// plugins
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-audit');
grunt.loadNpmTasks('grunt-string-replace');
grunt.loadNpmTasks('web-component-tester');
grunt.registerTask('default', ['minify']);
grunt.registerTask('minify', ['version', 'string-replace', 'concat', 'uglify', 'copy', 'audit']);
grunt.registerTask('test', ['wct-test:local']);
grunt.registerTask('test-remote', ['wct-test:remote']);
grunt.registerTask('test-buildbot', ['test']);
grunt.registerTask('release', function() {
grunt.option('release', true);
grunt.task.run('minify');
grunt.task.run('audit');
});
};
|
JavaScript
| 0.000018 |
@@ -914,16 +914,17 @@
src:
+%5B
'layout.
@@ -929,16 +929,31 @@
t.html',
+ 'bower.json'%5D,
%0A
@@ -965,27 +965,16 @@
: 'dist/
-layout.html
'%0A
|
c72aea65494ba2514c3afad48528428958bdcf52
|
Update local Grunt task for building `docs`
|
gruntfile.js
|
gruntfile.js
|
// Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
sass: {
files: 'scss/**/*.scss',
tasks: ['build']
},
eslint: {
files: 'js/**/*.js',
tasks: ['eslint']
},
jekyll: {
files: ['docs/**/*.*', 'scss/**/**/*.scss'],
tasks: ['docs-build']
}
},
clean: {
grunticon: ['dist/assets/icons/ui', 'dist/assets/icons/thematic'],
svg: ['icons/ui/dist']
},
pure_grids: {
responsive: {
dest: 'scss/modules/_grid-units.scss',
options: {
units: [5,12,24],
includeOldIEWidths: false,
mediaQueries: {
sm: 'screen and (min-width: 36.5em)', //584px
md: 'screen and (min-width: 48em)', //768px
lg: 'screen and (min-width: 64em)', //1024px
xl: 'screen and (min-width: 75em)' //1200px
},
selectorPrefix: '.unit-'
}
}
},
sass: {
options: {
outputStyle: 'expanded',
sourceMap: true,
indentedSyntax: true,
sassDir: 'scss',
cssDir: 'dist/css'
},
dev: {
files: [{
expand: true,
cwd: 'scss/',
src: ['*.scss'],
dest: 'dist/css/',
ext: '.css'
}]
},
dist: {
options: {
sourceMap: false
},
files: [{
expand: true,
cwd: 'scss/',
src: ['*.scss'],
dest: 'dist/css/',
ext: '.css'
}]
},
docs: {
files: {
'docs/css/main.css': 'docs/_sass/main.scss'
}
},
docsDist: {
options: {
sourceMap: false
},
files: {
'docs/css/main.css': 'docs/_sass/main.scss'
}
}
},
postcss: {
options: {
processors: [
require('autoprefixer')({ browsers: ['last 2 version'] })
],
map: {
inline: false,
}
},
dist: {
options: {
processors: [ require('cssnano')() ],
map: false
},
src: 'dist/css/*.css'
},
dev: {
src: 'dist/css/*.css'
},
docs: {
src: 'docs/css/*.css'
},
docsDist: {
options: {
processors: [ require('cssnano')() ],
map: false
},
src: 'docs/css/*.css'
}
},
grunticon: {
ui: {
files: [{
expand: true,
cwd: 'icons/ui/src',
src: ['*.svg'],
dest: 'dist/assets/icons/ui'
}],
options: {
dynamicColorOnly: true,
colors: {
light: '#ffffff',
dark: '#000000'
},
datasvgcss: 'ui-icons.svg.css',
datapngcss: 'ui-icons.png.css',
urlpngcss: 'ui-icons.fallback.css'
}
},
thematic: {
files: [{
expand: true,
cwd: 'icons/thematic',
src: ['*.svg'],
dest: 'dist/assets/icons/thematic'
}],
options: {
datasvgcss: 'thematic-icons.svg.css',
datapngcss: 'thematic-icons.png.css',
urlpngcss: 'thematic-icons.fallback.css',
cssprefix: '.thematic-'
}
}
},
svgtoolkit: {
light: {
options: {
generatePNGs: false,
colorize: '#ffffff'
},
files: [{
expand: true,
cwd: 'icons/ui/src',
src: '*.svg',
dest: 'icons/ui/dist/light'
}]
},
dark: {
options: {
generatePNGs: false,
colorize: '#232323'
},
files: [{
expand: true,
cwd: 'icons/ui/src',
src: '*.svg',
dest: 'icons/ui/dist/dark'
}]
},
primary: {
options: {
generatePNGs: false,
colorize: '#2A93FC'
},
files: [{
expand: true,
cwd: 'icons/ui/src',
src: '*.svg',
dest: 'icons/ui/dist/primary'
}]
}
},
datauri: {
light: {
options: {
classPrefix: 'icon-light-',
usePlaceholder: true
},
files: [{
src: 'icons/ui/dist/light/**/*.svg',
dest: 'scss/modules/icons/_icons-light.scss'
}]
},
dark: {
options: {
classPrefix: 'icon-dark-',
usePlaceholder: true
},
files: [{
src: 'icons/ui/dist/dark/**/*.svg',
dest: 'scss/modules/icons/_icons-dark.scss'
}]
},
primary: {
options: {
classPrefix: 'icon-primary-',
usePlaceholder: true
},
files: [{
src: 'icons/ui/dist/primary/**/*.svg',
dest: 'scss/modules/icons/_icons-primary.scss'
}]
}
},
jekyll: {
dev: {
options: {
src: './docs',
config: './docs/_config-dev.yml',
dest: './dist/docs'
}
},
dist: {
options: {
src: './docs',
config: './docs/_config.yml',
dest: './dist/docs'
}
}
},
eslint: {
options: {
config: '.eslintrc.json',
force: true
},
all: ['js/**/*.js']
},
sasslint: {
options: {
config: '.sass-lint.yml',
},
target: ['scss/**/*.scss']
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-grunticon');
grunt.loadNpmTasks('grunt-datauri');
grunt.loadNpmTasks('grunt-jekyll');
grunt.loadNpmTasks('grunt-postcss');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-sass-lint');
grunt.loadNpmTasks('grunt-svg-toolkit');
grunt.loadNpmTasks('grunt-pure-grids');
grunt.loadNpmTasks('eslint-grunt');
// Build SVGs and SCSS
grunt.registerTask('gen-svg', ['clean:svg', 'svgtoolkit', 'datauri', 'clean:svg']);
// Build Grunticon Icons
grunt.registerTask('gen-icons', ['clean:grunticon', 'grunticon']);
// Build WFP UI Docs
grunt.registerTask('docs-build', ['sasslint', 'sass:docs', 'postcss:docs', 'gen-icons', 'jekyll:dev']);
// Build dist-ready WFP UI Docs
grunt.registerTask('docs-dist', ['sasslint', 'sass:docsDist', 'postcss:docsDist', 'gen-icons', 'jekyll:dist']);
// Build WFP UI
grunt.registerTask('build', ['eslint', 'gen-svg', 'sasslint', 'sass:dev', 'postcss:dev']);
// Build a dist-ready WFP UI
grunt.registerTask('dist', ['gen-svg', 'gen-icons', 'sass:dist', 'postcss:dist']);
// Set default grunt task to `dist`
grunt.registerTask('default', ['dist']);
};
|
JavaScript
| 0 |
@@ -287,30 +287,28 @@
%7D,%0A
-jekyll
+docs
: %7B%0A
@@ -373,22 +373,16 @@
: %5B'docs
--build
'%5D%0A
@@ -6171,24 +6171,142 @@
unticon'%5D);%0A
+ // Build WFP UI Docs locally%0A grunt.registerTask('docs', %5B'sasslint', 'sass:docs', 'postcss:docs', 'jekyll:dev'%5D);%0A
// Build W
|
7c12c7b1246b991c68f4b51573538e02b3968beb
|
Add aria-label to floatingActionButton (#8574)
|
app/javascript/mastodon/features/ui/components/columns_area.js
|
app/javascript/mastodon/features/ui/components/columns_area.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ReactSwipeableViews from 'react-swipeable-views';
import { links, getIndex, getLink } from './tabs_bar';
import { Link } from 'react-router-dom';
import BundleContainer from '../containers/bundle_container';
import ColumnLoading from './column_loading';
import DrawerLoading from './drawer_loading';
import BundleColumnError from './bundle_column_error';
import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, DirectTimeline, FavouritedStatuses, ListTimeline } from '../../ui/util/async-components';
import detectPassiveEvents from 'detect-passive-events';
import { scrollRight } from '../../../scroll';
const componentMap = {
'COMPOSE': Compose,
'HOME': HomeTimeline,
'NOTIFICATIONS': Notifications,
'PUBLIC': PublicTimeline,
'COMMUNITY': CommunityTimeline,
'HASHTAG': HashtagTimeline,
'DIRECT': DirectTimeline,
'FAVOURITES': FavouritedStatuses,
'LIST': ListTimeline,
};
const shouldHideFAB = path => path.match(/^\/statuses\//);
@component => injectIntl(component, { withRef: true })
export default class ColumnsArea extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
intl: PropTypes.object.isRequired,
columns: ImmutablePropTypes.list.isRequired,
isModalOpen: PropTypes.bool.isRequired,
singleColumn: PropTypes.bool,
children: PropTypes.node,
};
state = {
shouldAnimate: false,
}
componentWillReceiveProps() {
this.setState({ shouldAnimate: false });
}
componentDidMount() {
if (!this.props.singleColumn) {
this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false);
}
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.isRtlLayout = document.getElementsByTagName('body')[0].classList.contains('rtl');
this.setState({ shouldAnimate: true });
}
componentWillUpdate(nextProps) {
if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
componentDidUpdate(prevProps) {
if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) {
this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false);
}
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.setState({ shouldAnimate: true });
}
componentWillUnmount () {
if (!this.props.singleColumn) {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
handleChildrenContentChange() {
if (!this.props.singleColumn) {
const modifier = this.isRtlLayout ? -1 : 1;
this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier);
}
}
handleSwipe = (index) => {
this.pendingIndex = index;
const nextLinkTranslationId = links[index].props['data-preview-title-id'];
const currentLinkSelector = '.tabs-bar__link.active';
const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`;
// HACK: Remove the active class from the current link and set it to the next one
// React-router does this for us, but too late, feeling laggy.
document.querySelector(currentLinkSelector).classList.remove('active');
document.querySelector(nextLinkSelector).classList.add('active');
}
handleAnimationEnd = () => {
if (typeof this.pendingIndex === 'number') {
this.context.router.history.push(getLink(this.pendingIndex));
this.pendingIndex = null;
}
}
handleWheel = () => {
if (typeof this._interruptScrollAnimation !== 'function') {
return;
}
this._interruptScrollAnimation();
}
setRef = (node) => {
this.node = node;
}
renderView = (link, index) => {
const columnIndex = getIndex(this.context.router.history.location.pathname);
const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] });
const icon = link.props['data-preview-icon'];
const view = (index === columnIndex) ?
React.cloneElement(this.props.children) :
<ColumnLoading title={title} icon={icon} />;
return (
<div className='columns-area' key={index}>
{view}
</div>
);
}
renderLoading = columnId => () => {
return columnId === 'COMPOSE' ? <DrawerLoading /> : <ColumnLoading />;
}
renderError = (props) => {
return <BundleColumnError {...props} />;
}
render () {
const { columns, children, singleColumn, isModalOpen } = this.props;
const { shouldAnimate } = this.state;
const columnIndex = getIndex(this.context.router.history.location.pathname);
this.pendingIndex = null;
if (singleColumn) {
const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/statuses/new' className='floating-action-button'><i className='fa fa-pencil' /></Link>;
return columnIndex !== -1 ? [
<ReactSwipeableViews key='content' index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}>
{links.map(this.renderView)}
</ReactSwipeableViews>,
floatingActionButton,
] : [
<div className='columns-area'>{children}</div>,
floatingActionButton,
];
}
return (
<div className={`columns-area ${ isModalOpen ? 'unscrollable' : '' }`} ref={this.setRef}>
{columns.map(column => {
const params = column.get('params', null) === null ? null : column.get('params').toJS();
const other = params && params.other ? params.other : {};
return (
<BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading(column.get('id'))} error={this.renderError}>
{SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn {...other} />}
</BundleContainer>
);
})}
{React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))}
</div>
);
}
}
|
JavaScript
| 0 |
@@ -64,16 +64,32 @@
import %7B
+ defineMessages,
injectI
@@ -1188,16 +1188,122 @@
ne,%0A%7D;%0A%0A
+const messages = defineMessages(%7B%0A publish: %7B id: 'compose_form.publish', defaultMessage: 'Toot' %7D,%0A%7D);%0A%0A
const sh
@@ -5041,16 +5041,22 @@
odalOpen
+, intl
%7D = thi
@@ -5436,16 +5436,66 @@
-button'
+ aria-label=%7Bintl.formatMessage(messages.publish)%7D
%3E%3Ci clas
|
e453164dc87ddbf3c6558173980231eb019471cc
|
Fix test after update
|
app/scripts/flashcards/services/flashcardlistDetailsService.js
|
app/scripts/flashcards/services/flashcardlistDetailsService.js
|
'use strict'
angular.module('flashcardModule.services')
.service('flashcardListDetailsService', function(Flashcards, FlashcardLists) {
this.getListDetails = function(listId) {
return FlashcardLists.get( { flashcardListId: listId } );
};
this.getFlashcards = function(listId) {
return Flashcards.query( { flashcard_list_id: listId } );
};
this.removeFlashcardFromList = function(flashcard, flashcards) {
var params = {
flashcard_list_id: flashcard.flashcard_list_id,
id: flashcard.id
};
var createNewListWithoutElement = function(response) {
var result = flashcards.slice(0);
for (var f in flashcards) {
if (flashcards[f].id === flashcard.id) {
result.splice(f, 1);
return result;
}
}
};
return Flashcards
.remove(params)
.$promise
.then(createNewListWithoutElement);
};
this.updateFlashcard = function(flashcard) {
return Flashcards
.update(flashcard)
.$promise;
}
this.createNewFlashcard = function(listId) {
var newFlashcard = new Flashcards({
flashcard_list_id: listId
});
return Flashcards
.save(newFlashcard);
}
});
|
JavaScript
| 0 |
@@ -1502,16 +1502,42 @@
ashcard)
+%0A .$promise
;%0A
|
587b8f35718b789111a2da350ca389eff6c13773
|
stop navigation in main webview
|
electron.js
|
electron.js
|
"use strict";
const path = require("path");
const { Menu, app, shell, BrowserWindow } = require('electron');
const defaultMenu = require('electron-default-menu');
const URL = process.env.FAAO_URL || "https://azu.github.io/faao/";
// context-menu for window
require('electron-context-menu')();
// Standard stuff
app.on("gpu-process-crashed", (event) => {
console.log("gpu-process-crashed", event);
});
app.on('ready', () => {
const menu = defaultMenu(app, shell);
Menu.setApplicationMenu(Menu.buildFromTemplate(menu));
// browser-window
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
javascript: true,
plugins: true,
nodeIntegration: true, // We will disable this?
nativeWindowOpen: true,
webviewTag: true
}
});
mainWindow.maximize();
mainWindow.loadURL(URL);
});
// https://github.com/electron/electron/blob/master/docs/tutorial/security.md#checklist
app.on('web-contents-created', (event, contents) => {
contents.on('will-attach-webview', (event, webPreferences, params) => {
// Strip away preload scripts if unused or verify their location is legitimate
delete webPreferences.preload;
delete webPreferences.preloadURL;
// Disable node integration
webPreferences.nodeIntegration = false;
});
});
|
JavaScript
| 0 |
@@ -13,20 +13,19 @@
;%0Aconst
-path
+url
= requi
@@ -32,12 +32,11 @@
re(%22
-path
+url
%22);%0A
@@ -909,16 +909,469 @@
RL(URL);
+%0A%0A // prevent navigation in main webview%0A mainWindow.webContents.on('dom-ready', function(e) %7B%0A mainWindow.webContents.on('will-navigate', (event, URL) =%3E %7B%0A const %7B protocol %7D = url.parse(URL);%0A if (protocol === %22http:%22 %7C%7C protocol === %22https:%22) %7B%0A event.preventDefault();%0A shell.openExternal(URL);%0A console.log(%22Stop navigation:%22 + URL);%0A %7D%0A %7D);%0A %7D);
%0A%7D);%0A//
|
66e0c9be5cb078f562f58bb6ca17df9f8071949e
|
change getUrlParameter variable naming style
|
corehq/apps/hqwebapp/static/hqwebapp/js/urllib.js
|
corehq/apps/hqwebapp/static/hqwebapp/js/urllib.js
|
var COMMCAREHQ_URLS = {};
hqDefine('hqwebapp/js/urllib.js', function () {
// http://stackoverflow.com/a/21903119/240553
var getUrlParameter = function (sParam) {
return getUrlParameterFromString(sParam, window.location.search);
};
var getUrlParameterFromString = function (sParam, sSearch) {
var sPageURL = decodeURIComponent(sSearch.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var registerUrl = function(name, url) {
COMMCAREHQ_URLS[name] = url;
};
var reverse = function (name) {
var args = arguments;
var index = 1;
return COMMCAREHQ_URLS[name].replace(/---/g, function () {
return args[index++];
});
};
return {
getUrlParameter: getUrlParameter,
getUrlParameterFromString: getUrlParameterFromString,
registerUrl: registerUrl,
reverse: reverse,
};
});
|
JavaScript
| 0 |
@@ -149,26 +149,25 @@
= function (
-sP
+p
aram) %7B%0A
@@ -203,18 +203,17 @@
mString(
-sP
+p
aram, wi
@@ -292,18 +292,16 @@
on (
-sP
+p
aram, s
-S
earc
@@ -317,24 +317,23 @@
var
-sP
+p
ageU
-RL
+rl
= decod
@@ -347,17 +347,16 @@
ponent(s
-S
earch.su
@@ -380,20 +380,19 @@
-sURL
+url
Variable
@@ -399,16 +399,15 @@
s =
-sP
+p
ageU
-RL
+rl
.spl
@@ -419,34 +419,33 @@
'),%0A
-sP
+p
arameterName,%0A
@@ -482,20 +482,19 @@
0; i %3C
-sURL
+url
Variable
@@ -522,18 +522,17 @@
-sP
+p
arameter
@@ -542,12 +542,11 @@
e =
-sURL
+url
Vari
@@ -583,18 +583,17 @@
if (
-sP
+p
arameter
@@ -604,18 +604,17 @@
%5B0%5D ===
-sP
+p
aram) %7B%0A
@@ -636,18 +636,17 @@
return
-sP
+p
arameter
@@ -680,10 +680,9 @@
e :
-sP
+p
aram
|
6a73033c47f7dc7280a7465e9e13078ad0332070
|
simplify destination path
|
gulp/info.js
|
gulp/info.js
|
'use strict';
var chalk = require('chalk');
var gulp = require('gulp');
var path = require('path');
var rump = require('rump');
var pkg = require('../package');
gulp.task(rump.taskName('info:server'), function() {
var destination = path.join(rump.configs.main.paths.destination.root,
rump.configs.main.paths.destination.static);
console.log();
console.log(chalk.magenta('--- Server', 'v' + pkg.version));
console.log('Static files from', chalk.green(destination), 'are served',
'on port', chalk.yellow(rump.configs.browserSync.port));
console.log();
});
gulp.tasks[rump.taskName('info')].dep.push(rump.taskName('info:server'));
|
JavaScript
| 0.999987 |
@@ -70,36 +70,8 @@
');%0A
-var path = require('path');%0A
var
@@ -90,24 +90,24 @@
re('rump');%0A
+
var pkg = re
@@ -205,18 +205,8 @@
n =
-path.join(
rump
@@ -245,83 +245,8 @@
root
-,%0A rump.configs.main.paths.destination.static)
;%0A%0A
|
985aada5e498f5c9eb1fcb90eeb4301cf65a55f1
|
Fix preview delay on Web by sending a dummy file.
|
web/setup/publish.js
|
web/setup/publish.js
|
// @flow
/*
https://api.lbry.tv/api/v1/proxy currently expects publish to consist
of a multipart/form-data POST request with:
- 'file' binary
- 'json_payload' collection of publish params to be passed to the server's sdk.
*/
import { X_LBRY_AUTH_TOKEN } from '../../ui/constants/token';
import { doUpdateUploadProgress } from 'lbryinc';
// A modified version of Lbry.apiCall that allows
// to perform calling methods at arbitrary urls
// and pass form file fields
export default function apiPublishCallViaWeb(
apiCall: (any, any, any, any) => any,
connectionString: string,
token: string,
method: string,
params: { file_path: string },
resolve: Function,
reject: Function
) {
const { file_path: filePath } = params;
if (!filePath) {
return apiCall(method, params, resolve, reject);
}
const counter = new Date().getTime();
const fileField = filePath;
// Putting a dummy value here, the server is going to process the POSTed file
// and set the file_path itself
params.file_path = '__POST_FILE__';
const jsonPayload = JSON.stringify({
jsonrpc: '2.0',
method,
params,
id: counter,
});
const body = new FormData();
body.append('file', fileField);
body.append('json_payload', jsonPayload);
function makeRequest(connectionString, method, token, body, params) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(method, connectionString);
xhr.setRequestHeader(X_LBRY_AUTH_TOKEN, token);
xhr.responseType = 'json';
xhr.upload.onprogress = e => {
let percentComplete = Math.ceil((e.loaded / e.total) * 100);
window.store.dispatch(doUpdateUploadProgress(percentComplete, params, xhr));
};
xhr.onload = () => {
window.store.dispatch(doUpdateUploadProgress(undefined, params));
resolve(xhr);
};
xhr.onerror = () => {
window.store.dispatch(doUpdateUploadProgress(undefined, params));
reject(new Error(__('There was a problem with your upload')));
};
xhr.onabort = () => {
window.store.dispatch(doUpdateUploadProgress(undefined, params));
};
xhr.send(body);
});
}
return makeRequest(connectionString, 'POST', token, body, params)
.then(xhr => {
let error;
if (xhr && xhr.response) {
if (xhr.status >= 200 && xhr.status < 300 && !xhr.response.error) {
return resolve(xhr.response.result);
} else if (xhr.response.error) {
error = new Error(xhr.response.error.message);
} else {
error = new Error(__('Upload likely timed out. Try a smaller file while we work on this.'));
}
}
if (error) {
return Promise.reject(error);
}
})
.catch(reject);
}
|
JavaScript
| 0 |
@@ -654,12 +654,30 @@
ring
+, preview: boolean
%7D,%0A
-
re
@@ -745,16 +745,25 @@
filePath
+, preview
%7D = par
@@ -891,35 +891,252 @@
;%0A
-const fileField = filePath;
+let fileField = filePath;%0A%0A if (preview) %7B%0A // Send dummy file for the preview. The tx-fee calculation does not depend on it.%0A const dummyContent = 'x';%0A fileField = new File(%5BdummyContent%5D, 'dummy.md', %7B type: 'text/markdown' %7D);%0A %7D
%0A%0A
|
6e0413c649c16287bf4cac132e66f0d86b76481c
|
test webhook
|
client/app/admin/admin.controller.spec.js
|
client/app/admin/admin.controller.spec.js
|
'use strict';
describe('Controller: AdminAccountCtrl', function () {
// load the controller's module
beforeEach(module('fahrtenbuchApp'));
var AdminAccountCtrl, $scope, $location, $httpBackend, fakeResponse;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, _$location_, _$httpBackend_) {
$scope = $rootScope.$new();
$location = _$location_;
$httpBackend = _$httpBackend_;
fakeResponse = '';
AdminAccountCtrl = $controller('AdminAccountCtrl', {
$scope: $scope
});
$location.path('/admin/account');
}));
it('Ensure that the method was invoked', function () {
$httpBackend.expectGET('/api/accounts').respond([{test: "test"}]);
$httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
$httpBackend.flush();
expect($location.path()).toBe('/admin/account');
expect($scope.accounts).toBeDefined();
expect($scope.accounts).toEqual([{test: "test"}]);
});
// it('Ensure that the method was invoked', function () {
// // $httpBackend.expectGET('/api/accounts').respond([{test: "test"}]);
// // $httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
// // $httpBackend.flush();
// expect($location.path()).toBe('/admin/account');
// // var valid = scope.addAccount();
// // expect(valid).toBeFalsy();
// $httpBackend.expectGET('/api/accounts').respond([{_id: 1}, {_id: 2}, {_id: 3}]);
// $httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
// $httpBackend.when('DELETE', '/api/accounts/1').respond(fakeResponse);
// $httpBackend.flush();
// console.log($scope.accounts);
// $scope.deleteAccount($scope.accounts[0]);
// $scope.$watch();
// $scope.$apply();
// console.log($scope.accounts);
// var account = scope.accounts[0];
// console.log(account);
// angular.forEach(scope.accounts, function(a, i) {
// console.log(a);
// if (a === account) {
// console.log("hi");
// scope.accounts.splice(i, 1);
// }
// });
// console.log(scope.accounts);
// expect($scope.accounts).toEqual([{_id: 2}, {_id: 3}]);
// });
});
// describe('Controller: AdminUserCtrl', function () {
// // load the controller's module
// beforeEach(module('fahrtenbuchApp'));
// var AdminUserCtrl, scope, $httpBackend, testTrip;
// // Initialize the controller and a mock scope
// beforeEach(inject(function (_$httpBackend_, $controller, $rootScope, $routeParams) {
// $httpBackend = _$httpBackend_;
// scope = $rootScope.$new();
// AdminUserCtrl = $controller('AdminUserCtrl', {
// $scope: scope,
// $routeParams: {id: 12345678}
// });
// testTrip = {_id: 12345678, stays: [{destination: "test"}]};
// }));
// it('should get trips', inject(function() {
// $httpBackend.expectGET('/api/trips/' + testTrip._id).respond(testTrip);
// $httpBackend.flush();
// expect(scope.trip).toEqual({_id: 12345678, stays: [{destination: "test"}]});
// expect(scope.destinations).toEqual("test");
// }));
// });
// @todo AdminCarCtrl
// @todo AdminCarAddCtrl
|
JavaScript
| 0.000001 |
@@ -3150,16 +3150,17 @@
// %7D);%0A%0A
+%0A
// @todo
|
e88fa29fa549dec087e0a0999cfdaa6d681512cb
|
add modal and move to inherit from component
|
client/src/components/routes/RoutePage.js
|
client/src/components/routes/RoutePage.js
|
import React from 'react';
import '../../styles/routes/route.css';
const RoutePage = ({
id, log_number, status, delivery_count,
updated_at, driver, truck, deliveries
}) => {
const last_updated = new Date(updated_at).toDateString();
const delivery_list = deliveries.map(delivery => <p>{delivery.invoice_number}</p>)
return (
<div id={`route-${id}`}>
<h1>Route -> Log number {log_number}</h1>
<ul>
<li>Status: {status}</li>
<li>Driver: {driver.username}</li>
<li>Truck: {truck.name}</li>
<li>Last Updated: {last_updated}</li>
</ul>
<h2>Deliveries:</h2>
<div className="deliveries">
{delivery_list}
</div>
</div>
);
}
export default RoutePage;
|
JavaScript
| 0 |
@@ -5,16 +5,29 @@
rt React
+, %7BComponent%7D
from 'r
@@ -34,16 +34,127 @@
eact';%0A%0A
+import %7B Modal %7D from 'react-bootstrap';%0A%0Aimport DeliveryContainer from '../../containers/DeliveryContainer';%0A%0A
import '
@@ -187,20 +187,20 @@
css';%0A%0Ac
-onst
+lass
RoutePa
@@ -206,104 +206,44 @@
age
-= (%7B%0A id, log_number, status, delivery_count, %0A updated_at, driver, truck, deliveries%0A%7D) =%3E %7B%0A
+extends Component%7B%0A%0A render () %7B%0A
co
@@ -270,16 +270,27 @@
ew Date(
+this.props.
updated_
@@ -311,16 +311,18 @@
ng();%0A
+
+
const de
@@ -335,16 +335,27 @@
_list =
+this.props.
deliveri
@@ -361,24 +361,25 @@
ies.map(
+(
delivery
=%3E %3Cp%3E%7B
@@ -374,46 +374,114 @@
very
- =%3E %3Cp%3E%7Bdelivery.invoice_number%7D%3C/p%3E)%0A
+, index) =%3E %0A %3CDeliveryContainer key=%7Bindex%7D route_id=%7Bthis.props.id%7D delivery=%7Bdelivery%7D/%3E%0A )%0A%0A
re
@@ -487,16 +487,18 @@
eturn (%0A
+
%3Cdiv
@@ -515,15 +515,28 @@
e-$%7B
+this.props.
id%7D%60%7D%3E%0A
+
@@ -562,16 +562,27 @@
number %7B
+this.props.
log_numb
@@ -600,13 +600,17 @@
+
%3Cul%3E%0A
+
@@ -626,16 +626,27 @@
tatus: %7B
+this.props.
status%7D%3C
@@ -646,24 +646,26 @@
tatus%7D%3C/li%3E%0A
+
%3Cli%3E
@@ -673,16 +673,27 @@
river: %7B
+this.props.
driver.u
@@ -710,24 +710,26 @@
li%3E%0A
+
+
%3Cli%3ETruck: %7B
@@ -728,16 +728,27 @@
Truck: %7B
+this.props.
truck.na
@@ -748,32 +748,34 @@
ruck.name%7D%3C/li%3E%0A
+
%3Cli%3ELast
@@ -810,16 +810,18 @@
%3E%0A
+
%3C/ul%3E%0A
@@ -828,29 +828,157 @@
+
+
%3Ch2%3E
-Deliveries:
+%0A Deliveries:%0A %3Cbutton className=%22btn btn-primary%22 onClick=%7Bthis.props.createDelivery%7D%3EAdd Delivery%3C/button%3E%0A
%3C/h2%3E%0A
+
@@ -1016,16 +1016,18 @@
+
%7Bdeliver
@@ -1034,16 +1034,18 @@
y_list%7D%0A
+
%3C/
@@ -1057,20 +1057,28 @@
+
%3C/div%3E%0A
+
);%0A
+ %7D%0A
%7D%0A%0Ae
|
2cc07b445f4e7224e83bcbc6be07875ceb01757f
|
Fix incorrect loading state for some analysis items
|
client/src/js/analyses/components/Item.js
|
client/src/js/analyses/components/Item.js
|
import React from "react";
import CX from "classnames";
import { get } from "lodash-es";
import { connect } from "react-redux";
import { LinkContainer } from "react-router-bootstrap";
import { Row, Col, Label } from "react-bootstrap";
import { getTaskDisplayName } from "../../utils/utils";
import { Icon, Loader, RelativeTime } from "../../base";
import { removeAnalysis } from "../actions";
import { getCanModify } from "../../samples/selectors";
export const AnalysisItem = props => {
const itemClass = CX("list-group-item spaced", { hoverable: props.ready });
const loaderIcon = <Loader size="14px" color="#3c8786" style={{ display: "inline" }} />;
const canRemove = props.ready && props.canModify;
const endIcon = canRemove ? (
<Icon name="trash" bsStyle="danger" onClick={props.onRemove} style={{ fontSize: "17px" }} pullRight />
) : (
<span className="pull-right">{loaderIcon}</span>
);
const reference = props.placeholder ? null : (
<span>
{props.reference.name}
<Label style={{ marginLeft: "5px" }}>{props.index.version}</Label>
</span>
);
const content = (
<div className={itemClass} style={{ color: "#555" }}>
<Row>
<Col xs={4} sm={4} md={4}>
<strong>{getTaskDisplayName(props.algorithm)}</strong>
</Col>
<Col xs={5} sm={4} md={4}>
Started <RelativeTime time={props.created_at} />
{props.placeholder ? null : ` by ${props.user.id}`}
</Col>
<Col xs={2} sm={2} md={2}>
{reference}
</Col>
<Col xs={1} smHidden mdHidden lgHidden>
{endIcon}
</Col>
<Col xsHidden sm={2} md={2}>
{canRemove ? endIcon : <strong className="pull-right">{loaderIcon} In Progress</strong>}
</Col>
</Row>
</div>
);
if (props.placeholder) {
return content;
}
return <LinkContainer to={`/samples/${props.sampleId}/analyses/${props.id}`}>{content}</LinkContainer>;
};
const mapStateToProps = state => ({
sampleId: get(state.samples.detail, "id"),
canModify: getCanModify(state)
});
const mapDispatchToProps = (dispatch, ownProps) => ({
onRemove: () => {
dispatch(removeAnalysis(ownProps.id));
}
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(AnalysisItem);
|
JavaScript
| 0.000006 |
@@ -461,250 +461,87 @@
nst
-AnalysisItem = props =%3E %7B%0A const itemClass = CX(%22list-group-item spaced%22, %7B hoverable: props.ready %7D);%0A const loaderIcon = %3CLoader size=%2214px%22 color=%22#3c8786%22 style=%7B%7B display: %22inline%22 %7D%7D /%3E;%0A const canRemove = props.ready && props.
+RightIcon = (%7B canModify, onRemove, ready %7D) =%3E %7B%0A if (ready) %7B%0A if (
canM
@@ -549,52 +549,30 @@
dify
-;%0A
+) %7B
%0A
-const endIcon = canRemove ? (%0A
+ return
%3CIc
@@ -613,22 +613,16 @@
nClick=%7B
-props.
onRemove
@@ -668,16 +668,59 @@
t /%3E
-%0A
+;%0A
-) :
+ %7D%0A%0A return null;%0A %7D%0A%0A return
(%0A
@@ -727,20 +727,19 @@
%3C
-span
+div
classNa
@@ -758,32 +758,202 @@
ht%22%3E
-%7BloaderIcon%7D%3C/span%3E%0A
+%0A %3CLoader size=%2214px%22 color=%22#3c8786%22 /%3E%0A %3C/div%3E%0A );%0A%7D;%0A%0Aexport const AnalysisItem = props =%3E %7B%0A const itemClass = CX(%22list-group-item spaced%22, %7B hoverable: props.ready %7D
);%0A%0A
@@ -1637,341 +1637,116 @@
=%7B2%7D
- sm=%7B2%7D md=%7B2%7D%3E%0A %7Breference%7D%0A %3C/Col%3E%0A %3CCol xs=%7B1%7D smHidden mdHidden lgHidden%3E%0A %7BendIcon%7D%0A %3C/Col%3E%0A %3CCol xsHidden sm=%7B2%7D md=%7B2%7D%3E%0A %7BcanRemove ? endIcon : %3Cstrong className=%22pull-right%22%3E%7BloaderIcon%7D In Progress%3C/strong%3E%7D
+%3E%7Breference%7D%3C/Col%3E%0A %3CCol xsHidden sm=%7B2%7D md=%7B2%7D%3E%0A %3CRightIcon %7B...props%7D /%3E
%0A
|
59292ad3c81f2b89f27c3ed0c6dea73c6c8f299f
|
Update Boot.js
|
projects/game1/src/js/states/Boot.js
|
projects/game1/src/js/states/Boot.js
|
(function() {
'use strict';
function Boot() {
}
Boot.prototype.preload = function() {
// Load animations before game start
game.load.json('preload-loading-icon',
'assets/img/preload/loading-icon.json');
game.load.json('preload-game-name',
'assets/img/preload/game-name.json');
// configure game
if (game.device.desktop) {
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
game.scale.pageAlignHorizontally = true;
game.scale.pageAlignVertically = true;
} else {
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
// game.scale.minWidth = 480;
// game.scale.minHeight = 260;
// game.scale.maxWidth = 640;
// game.scale.maxHeight = 480;
// game.scale.forceOrientation(true);
// game.scale.pageAlignHorizontally = true;
// game.scale.refresh(true);
}
};
Boot.prototype.create = function() {
game.state.start('ladingScreen');
}
window['CountryLife'] = window['CountryLife'] || {};
window['CountryLife'].Boot = Boot;
}());
|
JavaScript
| 0.000001 |
@@ -654,35 +654,32 @@
ALL;%0A
- //
game.scale.minW
@@ -693,35 +693,32 @@
480;%0A
- //
game.scale.minH
@@ -733,35 +733,32 @@
260;%0A
- //
game.scale.maxW
@@ -772,35 +772,32 @@
640;%0A
- //
game.scale.maxH
@@ -812,35 +812,32 @@
480;%0A
- //
game.scale.forc
@@ -859,35 +859,32 @@
ue);%0A
- //
game.scale.page
@@ -920,19 +920,16 @@
- //
game.sc
|
918715bffe45adab0506213e6d37ce404f094954
|
Fix regression in agg nested association
|
js/aggregation/controllers/aggCtrl.js
|
js/aggregation/controllers/aggCtrl.js
|
/**
* aggCtrl
* @desc this controller is attached to each aggregation displayed
*/
Curiosity.controller('aggCtrl', function($scope, $modal, aggFactory, template){
$scope.aggTypeSelected = false;
$scope.data = aggFactory.info;
$scope.tplData = template.info;
/**
* @desc function call by ng-init, called to load aggregation specifique data, and load template in $templateCache
* @param string name : the name of the aggregation attached to the controller
*/
$scope.init = function (name) {
$scope.curAgg = {};
$scope.curAgg.validate = false;
if (typeof(name) === "undefined") {
$scope.curAgg = aggFactory.newEmptyAggregation(false);
}
else {
$scope.curAgg = aggFactory.getAggregation(name);
initTemplate($scope.curAgg);
}
}
/**
* @desc remove an aggregation from a container, used for nestedAgg
* @param array container target array
* @param int idx row's index to remove
*/
$scope.removeAgg = function (container, idx) {
container.splice(idx, 1);
}
/**
* @desc remove an aggregation from the aggregation list of aggFactory
* @param object agg : the aggregation to remove
* @param int id : the aggregation id
*/
$scope.removeMainAgg = function (agg, id) {
aggFactory.removeMainAgg(agg, id);
}
/**
* @desc change an aggregation type (terms, range ...)
* @param object agg the aggregation to change type
* @idx int idx the index of the new aggregation type in aggList
*/
$scope.changeAggType = function (agg,idx) {
if (typeof (idx) != "undefined" && idx != null && idx >= 0) {
agg.type = $scope.data.aggList[idx].type;
agg.displayTemplate = $scope.data.aggList[idx].template;
agg.resultTemplate = $scope.data.aggList[idx].resultTemplate;
agg.aggTypeSelected = true;
}
}
/**
* @desc modifie the validate attr of an aggregation
* @param object agg the agg to modify
*/
$scope.validateAgg = function (agg) {
agg.validate = !agg.validate;
}
/**
* @desc add a nested aggregation to an aggregation
* @param object agg the agg to modify
*/
$scope.addNestedAgg = function (agg) {
aggFactory.addNestedAgg(agg)
}
/**
* @desc ask template service to add a template to the $templateCache whenever the template id different from default
* @param string the template name
*/
$scope.loadTpl = function (tpl) {
if (typeof(tpl) !== "undefined" && tpl != "default") {
template.addTemplateToCacheFromName("aggregationsTemplates", tpl);
}
}
/**
* @desc add an interval to a range aggregation
* @param object agg target aggregation
*/
$scope.addInterval = function (agg) {
if (typeof (agg.intervals) === "undefined") {
agg.intervals = [];
}
agg.intervals.push({});
}
/**
* @desc remove an interval to a range aggregation
* @param object agg target aggregation
* @param int index index to remove
*/
$scope.removeInterval = function(agg, index) {
if (typeof (agg.intervals) !== "undefined") {
agg.intervals.splice(index, 1);
}
}
/**
* @desc open a modal which contains the fields list. When closed change aggregation field attr value
* @params 'sm' | 'lg' size modal size
*/
$scope.openModalFields = function (size, curAgg) {
var modalInstance = $modal.open({
templateUrl: 'template/modal/fieldsModal.html',
controller: mappingModalCtrl,
resolve: {
item: function () {
return curAgg;
}}
});
modalInstance.result.then(function (value) {
value.item.field = value.value;
}, function () {
})
};
/**
* @desc load aggregation and nested aggregation template in $templateCache
* @param object agg target aggregation
*/
function initTemplate(agg) {
$scope.loadTpl(agg.tpl);
if (typeof(agg.nested) !== "undefined") {
for (sub_agg in agg.nested)
initTemplate(sub_agg);
}
}
});
|
JavaScript
| 0.000006 |
@@ -3815,16 +3815,17 @@
%22) %7B%0D%0A%09%09
+%09
for (sub
@@ -3843,18 +3843,21 @@
.nested)
+ %7B
%0D%0A
+%09
%09%09%09initT
@@ -3868,19 +3868,37 @@
ate(
+agg.nested%5B
sub_agg
+%5D
);%0D%0A
+%09%09%09%7D%0D%0A
%09%09%7D%0D
|
254ff41957131ef5faeb1f671da340e9f3832e05
|
fix for how datasets where loaded into the subscription selectors
|
components/modal/AreaSubscriptionModal.js
|
components/modal/AreaSubscriptionModal.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { toastr } from 'react-redux-toastr';
// Redux
import { connect } from 'react-redux';
// Services
import AreasService from 'services/AreasService';
import UserService from 'services/UserService';
import DatasetService from 'services/DatasetService';
// Components
import Spinner from 'components/ui/Spinner';
import SubscriptionSelector from 'components/subscriptions/SubscriptionSelector';
// Utils
import { logEvent } from 'utils/analytics';
class AreaSubscriptionModal extends React.Component {
constructor(props) {
super(props);
const { subscriptionDataset, subscriptionType, subscriptionThreshold } = props;
const subscription = props.area.subscription;
const initialSubscriptionSelectors = subscription
? subscription.attributes.datasetsQuery.map((elem, index) =>
({ index,
selectedDataset: elem.id,
selectedType: elem.type,
selectedThreshold: elem.threshold }))
: [{ index: 0, selectedDataset: null, selectedType: null, selectedThreshold: 1 }];
if (subscriptionDataset) {
const selectorFound = initialSubscriptionSelectors
.find(selector => selector.selectedDataset === subscriptionDataset);
if (selectorFound) {
selectorFound.selectedType = subscriptionType;
selectorFound.selectedThreshold = subscriptionThreshold;
} else if (subscription) {
initialSubscriptionSelectors.push({
index: initialSubscriptionSelectors.length,
selectedDataset: subscriptionDataset,
selectedType: subscriptionType,
selectedThreshold: subscriptionThreshold
});
} else {
initialSubscriptionSelectors[0].selectedType = subscriptionType;
initialSubscriptionSelectors[0].selectedThreshold = subscriptionThreshold || 1;
initialSubscriptionSelectors[0].selectedDataset = subscriptionDataset;
}
}
this.state = {
loadingDatasets: false,
loading: false,
datasets: [],
subscriptionSelectors: initialSubscriptionSelectors
};
// Services
this.datasetService = new DatasetService(null, {
apiURL: process.env.WRI_API_URL,
language: props.locale
});
this.areasService = new AreasService({ apiURL: process.env.WRI_API_URL });
this.userService = new UserService({ apiURL: process.env.WRI_API_URL });
// ------------------- Bindings -----------------------
this.handleCancel = this.handleCancel.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleRemoveSubscriptionSelector = this.handleRemoveSubscriptionSelector.bind(this);
this.handleUpdateSubscriptionSelector = this.handleUpdateSubscriptionSelector.bind(this);
this.handleNewSubscriptionSelector = this.handleNewSubscriptionSelector.bind(this);
// ----------------------------------------------------
}
componentDidMount() {
this.loadDatasets();
}
handleCancel() {
this.setState({
saved: false
});
this.props.toggleModal(false);
}
handleSubmit() {
const { subscriptionSelectors } = this.state;
const { mode, area, user } = this.props;
let incomplete = false;
subscriptionSelectors.forEach((val) => {
if (!val.selectedType || !val.selectedDataset || !val.selectedThreshold) {
incomplete = true;
}
});
if (incomplete) {
toastr.error('Data missing', 'Please select a dataset, subscription type and threshold for all items');
} else {
logEvent('My RW', 'Edit subscription', area.attributes.name);
const datasets = subscriptionSelectors.map(val => val.selectedDataset);
const datasetsQuery = subscriptionSelectors
.map(val => ({
id: val.selectedDataset,
type: val.selectedType,
threshold: val.selectedThreshold }
));
if (mode === 'new') {
if (datasets.length >= 1) {
this.userService.createSubscriptionToArea(
area.id,
datasets,
datasetsQuery,
user,
this.props.locale
).then(() => {
toastr.success('Success!', 'Subscription created successfully');
this.props.toggleModal(false);
this.props.onSubscriptionCreated();
})
.catch(err => toastr.error('Error creating the subscription', err));
} else {
toastr.error('Error', 'Please select at least one dataset');
}
} else if (mode === 'edit') {
if (datasets.length >= 1) {
this.userService.updateSubscriptionToArea(
area.subscription.id,
datasets,
datasetsQuery,
user,
this.props.locale
).then(() => {
toastr.success('Success!', 'Subscription updated successfully');
this.props.toggleModal(false);
this.props.onSubscriptionUpdated();
}).catch(err => toastr.error('Error updating the subscription', err));
} else {
this.userService.deleteSubscription(area.subscription.id, user.token)
.then(() => {
toastr.success('Success!', 'Subscription updated successfully');
this.props.toggleModal(false);
this.props.onSubscriptionUpdated();
})
.catch(err => toastr.error('Error updating the subscription', err));
}
}
}
}
loadDatasets() {
this.datasetService.getSubscribableDatasets('metadata').then((response) => {
this.setState({
loadingDatasets: false,
datasets: response.filter(val => val.attributes.subscribable)
});
}).catch(err => toastr.error('Error', err)); // TODO: update the UI
}
handleRemoveSubscriptionSelector(index) {
const { subscriptionSelectors } = this.state;
subscriptionSelectors.splice(index, 1);
this.setState({ subscriptionSelectors });
}
handleUpdateSubscriptionSelector(element) {
const { subscriptionSelectors } = this.state;
subscriptionSelectors[element.index] = element;
this.setState({ subscriptionSelectors });
}
handleNewSubscriptionSelector() {
const { subscriptionSelectors } = this.state;
subscriptionSelectors.push({ index: subscriptionSelectors.length, dataset: null, type: null });
this.setState({
subscriptionSelectors
});
}
render() {
const {
datasets,
loading,
loadingDatasets,
subscriptionSelectors
} = this.state;
const { area } = this.props;
return (
<div className="c-area-subscription-modal" ref={(node) => { this.el = node; }}>
<div className="header-div">
<h2>{`${area.attributes.name} subscriptions`}</h2>
</div>
<div className="header-text">
Select the datasets that you want to subscribe to.
</div>
<Spinner isLoading={loading || loadingDatasets} className="-light" />
<div className="datasets-container">
{subscriptionSelectors.map((val, index) =>
(<SubscriptionSelector
datasets={datasets}
data={val}
onRemove={this.handleRemoveSubscriptionSelector}
onUpdate={this.handleUpdateSubscriptionSelector}
index={index}
key={val.index}
/>)
)}
</div>
<div className="new-container">
<button className="c-btn -b -fullwidth" onClick={this.handleNewSubscriptionSelector}>
Add dataset
</button>
</div>
<div className="buttons">
<button className="c-btn -primary" onClick={this.handleSubmit}>
Done
</button>
<button className="c-btn -secondary" onClick={this.handleCancel}>
Cancel
</button>
</div>
</div>
);
}
}
AreaSubscriptionModal.propTypes = {
area: PropTypes.object.isRequired,
toggleModal: PropTypes.func.isRequired,
mode: PropTypes.string.isRequired, // edit | new
locale: PropTypes.string.isRequired,
subscriptionDataset: PropTypes.string,
subscriptionType: PropTypes.string,
subscriptionThreshold: PropTypes.number,
// Store
user: PropTypes.object.isRequired,
// Callbacks
onSubscriptionCreated: PropTypes.func,
onSubscriptionUpdated: PropTypes.func
};
const mapStateToProps = state => ({
user: state.user,
locale: state.common.locale
});
export default connect(mapStateToProps, null)(AreaSubscriptionModal);
|
JavaScript
| 0.000001 |
@@ -5650,24 +5650,36 @@
lter(val =%3E
+Object.keys(
val.attribut
@@ -5694,16 +5694,28 @@
ribable)
+.length %3E 0)
%0A %7D
|
9b8ccc4ee7de1e26e898165e2e41158f628ed966
|
add className test
|
components/result/__tests__/index.test.js
|
components/result/__tests__/index.test.js
|
import React from 'react';
import { mount } from 'enzyme';
import Result from '..';
import Button from '../../button';
describe('Progress', () => {
it('🙂 successPercent should decide the progress status when it exists', () => {
const wrapper = mount(
<Result
status="success"
title="Successfully Purchased Cloud Server ECS!"
subTitle="Order number: 2017182818828182881 Cloud server configuration takes 1-5 minutes, please wait."
extra={[
<Button type="primary" key="console">
Go Console
</Button>,
<Button key="buy">Buy Again</Button>,
]}
/>,
);
expect(wrapper.find('.anticon-check-circle')).toHaveLength(1);
});
it('🙂 different status, different class', () => {
const wrapper = mount(<Result status="warning" />);
expect(wrapper.find('.ant-result-warning')).toHaveLength(1);
wrapper.setProps({
status: 'error',
});
expect(wrapper.find('.ant-result-error')).toHaveLength(1);
wrapper.setProps({
status: '500',
});
expect(wrapper.find('.ant-result-500')).toHaveLength(1);
});
it('🙂 When status = 404, the icon is an image', () => {
const wrapper = mount(<Result status="404" />);
expect(wrapper.find('.ant-result-404 .ant-result-image')).toHaveLength(1);
});
it('🙂 When extra is undefined, the extra dom is undefined', () => {
const wrapper = mount(<Result status="404" />);
expect(wrapper.find('.ant-result-extra')).toHaveLength(0);
});
});
|
JavaScript
| 0.00001 |
@@ -1522,13 +1522,224 @@
);%0A %7D);
+%0A%0A it('%F0%9F%99%82 result should support className', () =%3E %7B%0A const wrapper = mount(%3CResult status=%22404%22 title=%22404%22 className=%22my-result%22 /%3E);%0A expect(wrapper.find('.ant-result.my-result')).toHaveLength(1);%0A %7D);
%0A%7D);%0A
|
f00ab3f3e9a7b0eb9e433dc73deef185dc0b63e3
|
Correct default sensor data path
|
defaults.js
|
defaults.js
|
'use strict';
module.exports = {
SERVE_INSECURE: false,
SENSOR_DATA_PATH: '/var/lib/homecontrol/sensordata/temperatureSensors/TA',
PROGRAMME_DATA_PATH: '/var/lib/homecontrol/programdata',
WEBAPP_DATA_PATH: '/var/lib/homecontrol/webapp'
};
|
JavaScript
| 0 |
@@ -120,30 +120,8 @@
data
-/temperatureSensors/TA
',%0A
|
f4c6ef155145ee832c17a40851d82e9163e42644
|
edit format
|
modules/dashboard-ui/provision/tenants/DbTenant.js
|
modules/dashboard-ui/provision/tenants/DbTenant.js
|
'use strict';
var DbTenant = {
"_id": ObjectId("551286bce603d7e01ab1688e"),
"locked" : true,
"code": "DBTN",
"name": "Dashboard Tenant",
"description": "this is the main dashboard tenant",
"oauth":{},
"applications": [
{
"product": "DSBRD",
"package": "DSBRD_DEFLT",
"appId": ObjectId('5512926a7a1f0e2123f638de'),
"description": "this is the main application for the dashboard tenant",
"_TTL": 7 * 24 * 3600 * 1000, // 7 days hours
"keys": [
{
"key": "38145c67717c73d3febd16df38abf311",
"extKeys": [
{
"expDate": new Date().getTime() + 7 * 24 * 3600 * 1000, // + 7 days
"extKey": "9b96ba56ce934ded56c3f21ac9bdaddc8ba4782b7753cf07576bfabcace8632eba1749ff1187239ef1f56dd74377aa1e5d0a1113de2ed18368af4b808ad245bc7da986e101caddb7b75992b14d6a866db884ea8aee5ab02786886ecf9f25e974",
"device": null,
"geo": null
}
],
"config": {
"dev":{
"dashboardui":{
"permissions":[
"members",
"environments",
"productization",
"product-acl",
"multi-tenancy",
"tenant-app-acl"
"services"
]
},
"mail": {
"from": '[email protected]',
"transport": {
"type": "sendmail",
"options": {
}
}
},
"urac": {
"hashIterations": 1024, //used by hasher
"seedLength": 32, //used by hasher
"link": {
"addUser": "http://dashboard.soajs.org/#/setNewPassword",
"changeEmail": "http://dashboard.soajs.org/#/changeEmail/validate",
"forgotPassword": "http://dashboard.soajs.org/#/resetPassword",
"join": "http://dashboard.soajs.org/#/join/validate"
},
"tokenExpiryTTL": 2 * 24 * 3600 * 1000,// token expiry limit in seconds
"validateJoin": true, //true if registration needs validation
"mail": { //urac mail options
"join": {
"subject": 'Welcome to SOAJS',
"path": "./mail/urac/join.tmpl"
},
"forgotPassword": {
"subject": 'Reset Your Password at SOAJS',
"path": "./mail/urac/forgotPassword.tmpl"
},
"addUser": {
"subject": 'Account Created at SOAJS',
"path": "./mail/urac/addUser.tmpl"
},
"changeUserStatus": {
"subject": "Account Status changed at SOAJS",
//use custom HTML
"content": "<p>Dear <b>{{ username }}</b>, <br />Your account status has changed to <b>{{ status }}</b> by the administrator on {{ ts|date('F jS, Y') }}.<br /><br /> Regards,<br/> SOAJS Team. </p>"
},
"changeEmail": {
"subject": "Change Account Email at SOAJS",
"path": "./mail/urac/changeEmail.tmpl"
}
}
}
}
}
}
]
}
]
};
|
JavaScript
| 0.000003 |
@@ -1119,16 +1119,17 @@
app-acl%22
+,
%0A%09%09%09%09%09%09%09
|
6c14e2c2e22af6765c896fa9858c4b5db800edf5
|
change the js to deferred object
|
lexos/static/js/scripts_dendrogram.js
|
lexos/static/js/scripts_dendrogram.js
|
/**
* the function to convert the from into json
* @returns {{string: string}} - the from converted to json
*/
function jsonifyForm () {
var form = {}
$.each($('form').serializeArray(), function (i, field) {
form[field.name] = field.value || ''
})
return form
}
/**
* the function to run the error modal
* @param htmlMsg {string} - the message to display, you can put html in it
*/
function runModal (htmlMsg) {
$('#error-modal-message').html(htmlMsg)
$('#error-modal').modal()
}
/**
* the function to do ajax in dendrogram
* @param url {string} - the url to do post
*/
function doAjax (url) {
// show loading icon
$('#status-analyze').css({'visibility': 'visible'})
var form = jsonifyForm()
$.ajax({
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(form),
complete: function (response) {
$('#status-analyze').css({'visibility': 'hidden'})
$('#dendrogram-result').html(response['responseJSON']['dendroDiv'])
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('textStatus: ' + textStatus)
console.log('errorThrown: ' + errorThrown)
runModal('error encountered while plotting the dendrogram.')
}
}
)
}
/**
* the error message for the submission
* @returns {string | null} - if it is null, it means no error, else then the string is the error message
*/
function submissionError () {
const err = 'A dendrogram requires at least 2 active documents to be created.'
const activeFiles = $('#num_active_files').val()
if (activeFiles < 2)
return err
else
return null
}
/**
* When the HTML documents finish loading
*/
$(document).ready(function () {
/**
* the events after dendrogram is clicked
*/
$('#getdendro').on('click', function () {
const error = submissionError() // the error happens during submission
if (error === null) { // if there is no error
doAjax('/dendrogramDiv', null)
}
else {
runModal(error)
}
})
})
|
JavaScript
| 0.000001 |
@@ -562,52 +562,8 @@
ram%0A
- * @param url %7Bstring%7D - the url to do post%0A
*/%0A
@@ -579,19 +579,16 @@
doAjax (
-url
) %7B%0A
@@ -665,16 +665,72 @@
ble'%7D)%0A%0A
+ // convert form into an object map string to string%0A
var
@@ -750,20 +750,50 @@
yForm()%0A
+%0A
+// make the ajax request%0A
$.ajax(%7B
@@ -793,20 +793,16 @@
.ajax(%7B%0A
-
@@ -827,20 +827,29 @@
-
url:
-url
+'/dendrogramDiv'
,%0A
@@ -854,20 +854,16 @@
-
-
contentT
@@ -906,28 +906,24 @@
8',%0A
-
dataType: 'j
@@ -932,28 +932,24 @@
n',%0A
-
-
data: JSON.s
@@ -962,17 +962,23 @@
fy(form)
-,
+%0A %7D)
%0A
@@ -982,21 +982,26 @@
- complete:
+.done(%0A
fun
@@ -1023,75 +1023,8 @@
) %7B%0A
- $('#status-analyze').css(%7B'visibility': 'hidden'%7D)%0A
@@ -1078,24 +1078,8 @@
se%5B'
-responseJSON'%5D%5B'
dend
@@ -1100,17 +1100,17 @@
%7D
-,
+)
%0A
@@ -1114,18 +1114,26 @@
- error:
+.fail(%0A
fun
@@ -1371,32 +1371,33 @@
')%0A %7D
+)
%0A %7D%0A )
@@ -1389,22 +1389,131 @@
-%7D%0A
+.always(%0A function () %7B%0A $('#status-analyze').css(%7B'visibility': 'hidden'%7D)%0A %7D
)%0A%7D%0A%0A/**
@@ -1703,16 +1703,40 @@
const
+active_file_num_too_few_
err = 'A
@@ -1893,16 +1893,40 @@
return
+active_file_num_too_few_
err%0A
@@ -2009,24 +2009,8 @@
/%0A$(
-document).ready(
func
@@ -2287,30 +2287,8 @@
jax(
-'/dendrogramDiv', null
)%0A
@@ -2348,17 +2348,16 @@
%7D%0A
-%0A
%7D)%0A%0A
|
81e54660bb62584827516cf36276d74e11744e2e
|
Fix point-grid aggregation bug
|
lib/cartodb/models/aggregation/aggregation-query.js
|
lib/cartodb/models/aggregation/aggregation-query.js
|
/**
* Returns a template function (function that accepts template parameters and returns a string)
* to generate an aggregation query.
* Valid options to define the query template are:
* - placement
* The query template parameters taken by the result template function are:
* - sourceQuery
* - res
* - columns
* - dimensions
*/
const templateForOptions = (options) => {
let templateFn = aggregationQueryTemplates[options.placement];
if (!templateFn) {
throw new Error("Invalid Aggregation placement: '" + options.placement + "'");
}
return templateFn;
};
/**
* Generates an aggregation query given the aggregation options:
* - query
* - resolution - defined as in torque:
* aggregation cell is resolution*resolution pixels, where tiles are always 256x256 pixels
* - columns
* - placement
* - dimensions
*/
const queryForOptions = (options) => templateForOptions(options)({
sourceQuery: options.query,
res: 256/options.resolution,
columns: options.columns,
dimensions: options.dimensions
});
module.exports = queryForOptions;
const SUPPORTED_AGGREGATE_FUNCTIONS = {
'count': {
sql: (column_name, params) => `count(${params.aggregated_column || '*'})`
},
'avg': {
sql: (column_name, params) => `avg(${params.aggregated_column || column_name})`
},
'sum': {
sql: (column_name, params) => `sum(${params.aggregated_column || column_name})`
},
'min': {
sql: (column_name, params) => `min(${params.aggregated_column || column_name})`
},
'max': {
sql: (column_name, params) => `max(${params.aggregated_column || column_name})`
},
'mode': {
sql: (column_name, params) => `_cdb_mode(${params.aggregated_column || column_name})`
}
};
const sep = (list) => {
let expr = list.join(', ');
return expr ? ', ' + expr : expr;
};
const aggregateColumns = ctx => {
return Object.assign({
_cdb_feature_count: {
aggregate_function: 'count'
}
}, ctx.columns || {});
};
const aggregateColumnNames = ctx => {
let columns = aggregateColumns(ctx);
return sep(Object.keys(columns));
};
const aggregateColumnDefs = ctx => {
let columns = aggregateColumns(ctx);
return sep(Object.keys(columns).map(column_name => {
const aggregate_function = columns[column_name].aggregate_function || 'count';
const aggregate_definition = SUPPORTED_AGGREGATE_FUNCTIONS[aggregate_function];
if (!aggregate_definition) {
throw new Error("Invalid Aggregate function: '" + aggregate_function + "'");
}
const aggregate_expression = aggregate_definition.sql(column_name, columns[column_name]);
return `${aggregate_expression} AS ${column_name}`;
}));
};
const aggregateDimensions = ctx => ctx.dimensions || {};
const dimensionNames = ctx => {
return sep(Object.keys(aggregateDimensions(ctx)));
};
const dimensionDefs = ctx => {
let dimensions = aggregateDimensions(ctx);
return sep(Object.keys(dimensions).map(dimension_name => {
const expression = dimensions[dimension_name];
return `${expression} AS ${dimension_name}`;
}));
};
// SQL expression to compute the aggregation resolution (grid cell size).
// This is equivalent to `${256/ctx.res}*CDB_XYZ_Resolution(CDB_ZoomFromScale(!scale_denominator!))`
// This is defined by the ctx.res parameter, which is the number of grid cells per tile linear dimension
// (i.e. each tile is divided into ctx.res*ctx.res cells).
const gridResolution = ctx => `(${256*0.00028/ctx.res}*!scale_denominator!)::double precision`;
// Notes:
// * We need to filter spatially using !bbox! to make the queries efficient because
// the filter added by Mapnik (wrapping the query)
// is only applied after the aggregation.
// * This queries are used for rendering and the_geom is omitted in the results for better performance
const aggregationQueryTemplates = {
'centroid': ctx => `
WITH _cdb_params AS (
SELECT
${gridResolution(ctx)} AS res,
!bbox! AS bbox
)
SELECT
row_number() over() AS cartodb_id,
ST_SetSRID(
ST_MakePoint(
AVG(ST_X(_cdb_query.the_geom_webmercator)),
AVG(ST_Y(_cdb_query.the_geom_webmercator))
), 3857
) AS the_geom_webmercator
${dimensionDefs(ctx)}
${aggregateColumnDefs(ctx)}
FROM (${ctx.sourceQuery}) _cdb_query, _cdb_params
WHERE _cdb_query.the_geom_webmercator && _cdb_params.bbox
GROUP BY
Floor(ST_X(_cdb_query.the_geom_webmercator)/_cdb_params.res),
Floor(ST_Y(_cdb_query.the_geom_webmercator)/_cdb_params.res)
${dimensionNames(ctx)}
`,
'point-grid': ctx => `
WITH _cdb_params AS (
SELECT
${gridResolution(ctx)} AS res,
!bbox! AS bbox
),
_cdb_clusters AS (
SELECT
Floor(ST_X(_cdb_query.the_geom_webmercator)/_cdb_params.res)::int AS _cdb_gx,
Floor(ST_Y(_cdb_query.the_geom_webmercator)/_cdb_params.res)::int AS _cdb_gy
${dimensionDefs(ctx)}
${aggregateColumnDefs(ctx)}
FROM (${ctx.sourceQuery}) _cdb_query, _cdb_params
WHERE the_geom_webmercator && _cdb_params.bbox
GROUP BY _cdb_gx, _cdb_gy ${dimensionNames}
)
SELECT
ST_SetSRID(ST_MakePoint(_cdb_gx*(res+0.5), _cdb_gy*(res+0.5)), 3857) AS the_geom_webmercator
${dimensionNames(ctx)}
${aggregateColumnNames(ctx)}
FROM _cdb_clusters, _cdb_params
`,
'point-sample': ctx => `
WITH _cdb_params AS (
SELECT
${gridResolution(ctx)} AS res,
!bbox! AS bbox
), _cdb_clusters AS (
SELECT
MIN(cartodb_id) AS cartodb_id
${dimensionDefs(ctx)}
${aggregateColumnDefs(ctx)}
FROM (${ctx.sourceQuery}) _cdb_query, _cdb_params
WHERE _cdb_query.the_geom_webmercator && _cdb_params.bbox
GROUP BY
Floor(ST_X(_cdb_query.the_geom_webmercator)/_cdb_params.res),
Floor(ST_Y(_cdb_query.the_geom_webmercator)/_cdb_params.res)
${dimensionNames(ctx)}
) SELECT
_cdb_clusters.cartodb_id,
the_geom, the_geom_webmercator
${dimensionNames(ctx)}
${aggregateColumnNames(ctx)}
FROM
_cdb_clusters INNER JOIN (${ctx.sourceQuery}) _cdb_query
ON (_cdb_clusters.cartodb_id = _cdb_query.cartodb_id)
`
};
|
JavaScript
| 0.000002 |
@@ -5401,16 +5401,21 @@
ionNames
+(ctx)
%7D%0A )%0A
|
0b40a8d3543337847ea0f50911118efb410d3e28
|
Fix for role format
|
server/authentication/signIn.js
|
server/authentication/signIn.js
|
const superagent = require('superagent');
const config = require('../config');
const generateApiGatewayToken = require('./apiGateway');
const logger = require('../../log');
async function signIn(username, password) {
logger.info(`Log in for: ${username}`);
try {
const loginResult = await superagent
.post(`${config.nomis.apiUrl}/users/login`)
.set('Authorization', `Bearer ${generateApiGatewayToken()}`)
.send({username, password})
.timeout({response: 2000, deadline: 2500});
logger.info(`Elite2 login result: [${loginResult.status}]`);
if (loginResult.status !== 200 && loginResult.status !== 201) {
logger.info(`Elite2 login failed for [${username}]`);
logger.warn(loginResult.body);
throw new Error('Login error');
}
logger.info(`Elite2 login success for [${username}]`);
const eliteAuthorisationToken = loginResult.body.token;
const profileResult = await superagent
.get(`${config.nomis.apiUrl}/users/me`)
.set('Authorization', `Bearer ${generateApiGatewayToken()}`)
.set('Elite-Authorization', eliteAuthorisationToken);
logger.info(`Elite2 profile success for [${username}]`);
const role = await getRole(eliteAuthorisationToken);
const roleCode = role.roleCode.substring(role.roleCode.lastIndexOf('_') + 1);
logger.info(`Elite2 profile success for [${username}] with role [${roleCode}]`);
return {...profileResult.body, ...{token: eliteAuthorisationToken}, ...{role}, ...{roleCode}};
} catch (exception) {
logger.error(`Elite 2 login error [${username}]:`);
logger.error(exception);
throw exception;
}
}
async function getRole(eliteAuthorisationToken) {
const rolesResult = await superagent
.get(`${config.nomis.apiUrl}/users/me/roles`)
.set('Authorization', `Bearer ${generateApiGatewayToken()}`)
.set('Elite-Authorization', eliteAuthorisationToken);
logger.info(`Elite2 get roles success with body ${rolesResult.body}`);
logger.info(`Elite2 get roles success with body.roles ${rolesResult.body.roles}`);
const roles = rolesResult.body.roles ? rolesResult.body.role : rolesResult.body;
logger.info(`Elite2 get roles - resulting roless ${roles}`);
if (roles && roles.length > 0) {
const role = roles.find(role => {
return role.roleCode.includes('LICENCES');
});
logger.info(`Selected role: ${role.roleCode}`);
if (role) return role;
}
throw new Error('Login error - no acceptable role');
}
function signInFor(username, password) {
return signIn(username, password);
}
module.exports = function createSignInService() {
return {signIn: (username, password) => signInFor(username, password)};
};
|
JavaScript
| 0.000007 |
@@ -2049,17 +2049,16 @@
oken);%0A%0A
-%0A
logg
@@ -2069,127 +2069,43 @@
nfo(
-%60Elite2 get roles success with body $%7BrolesResult.body%7D%60);%0A logger.info(%60Elite2 get roles success with body.roles $%7B
+'Roles response');%0A logger.info(
role
@@ -2120,16 +2120,8 @@
body
-.roles%7D%60
);%0A%0A
@@ -2158,123 +2158,8 @@
body
-.roles ? rolesResult.body.role : rolesResult.body;%0A%0A logger.info(%60Elite2 get roles - resulting roless $%7Broles%7D%60)
;%0A%0A
|
761828678960105ee1234270fed0679837106879
|
fix user auth logs
|
server/controllers/auth-logs.js
|
server/controllers/auth-logs.js
|
'use strict';
/* global require */
var AuthLog = require('mongoose').model('AuthLog');
exports.getNumber = function (req, res) {
AuthLog.getNumber(req.params.user, function(error, logsNumber) {
res.send({error: error, number: logsNumber});
});
};
exports.list = function (req, res) {
AuthLog.list(req.params.user, req.params.itemsPerPage, req.params.page, function(error, logs) {
res.send({error: error, logs: logs});
});
};
exports.getMostRecent = function (req, res) {
AuthLog.getMostRecent(req.params.user, req.params.action, function(error, logs) {
res.send({error: error, logs: logs});
});
};
|
JavaScript
| 0.000003 |
@@ -304,74 +304,220 @@
-AuthLog.list(req.params.user, req.params.itemsPerPage, req.params.
+var itemsPerPage = isNaN(req.params.itemsPerPage) ? 20 : parseInt(req.params.itemsPerPage);%0A var page = isNaN(req.params.page) ? 0 : parseInt(req.params.page);%0A%0A AuthLog.list(req.params.user, itemsPerPage,
page
|
97b865873bc2fbf41ad3bbd6aaf21e15f018382d
|
increase timeout
|
node-tests/blueprints/ember-datetimepicker-test.js
|
node-tests/blueprints/ember-datetimepicker-test.js
|
'use strict';
const {
setupTestHooks,
emberNew,
emberGenerate
} = require('ember-cli-blueprint-test-helpers/helpers');
const { expect } = require('ember-cli-blueprint-test-helpers/chai');
describe('Acceptance: ember generate and destroy ember-datetimepicker', function() {
setupTestHooks(this, {
disabledTasks: [],
timeout: 60000
});
it('syncs dependencies between dev and blueprint', function() {
return emberNew()
.then(() => emberGenerate(['ember-datetimepicker']))
.then(() => {
let pkg = require('../../package.json');
[
'ember-cli-moment-shim',
'jquery-datetimepicker'
].forEach(dep => {
expect(pkg.devDependencies[dep]).to.be.ok;
});
});
});
});
|
JavaScript
| 0.00001 |
@@ -339,10 +339,18 @@
ut:
-60
+2 * 60 * 1
000%0A
|
a8ee090fead6e4ef9d8c198880941048e11811be
|
Clean up toast logic in AppActions
|
common/app/flux/Actions.js
|
common/app/flux/Actions.js
|
import { Actions } from 'thundercats';
import { Observable } from 'rx';
export default Actions({
shouldBindMethods: true,
refs: { displayName: 'AppActions' },
setTitle(title = 'Learn To Code') {
return { title: title + ' | Free Code Camp' };
},
getUser() {
return this.readService$('user', null, null)
.map(({
username,
picture,
progressTimestamps = [],
isFrontEndCert,
isBackEndCert,
isFullStackCert
}) => {
return {
username,
picture,
points: progressTimestamps.length,
isFrontEndCert,
isBackEndCert,
isFullStackCert
};
})
.catch(err => Observable.just({ err }));
},
// routing
// goTo(path: String) => path
goTo: null,
// goBack(arg?) => arg?
goBack: null,
// toast(args: { type?: String, message: String, title: String }) => args
toast(args) {
return {
transform(state) {
const id = state.toast && state.toast.id ? state.toast.id : 0;
const toast = { ...args, id: id + 1 };
return { ...state, toast };
}
};
},
// updateLocation(location: { pathname: String }) => location
updateLocation(location) {
return {
transform(state) {
return { ...state, location };
}
};
}
});
|
JavaScript
| 0.000003 |
@@ -980,18 +980,92 @@
-const id =
+return %7B%0A ...state,%0A toast: %7B%0A ...args,%0A id:
sta
@@ -1114,10 +1114,9 @@
d :
-0;
+1
%0A
@@ -1124,46 +1124,11 @@
-const toast = %7B ...args, id: id + 1
+
%7D
-;
%0A
@@ -1136,33 +1136,8 @@
-return %7B ...state, toast
%7D;%0A
|
df7da53955b1fb3452af24e1dc1dc3d07c13d30e
|
add export Logo from components
|
common/components/index.js
|
common/components/index.js
|
export Sidebar from './Sidebar'
export Header from './Header'
export Footer from './Footer'
export Root from './Root'
export RouteAuth from './RouteAuth'
|
JavaScript
| 0 |
@@ -147,8 +147,34 @@
teAuth'%0A
+export Logo from './Logo'%0A
|
759f0cd1762e058acd8efc127b212608385de1a9
|
connect AddListing.js to store
|
client/src/components/AddListing/AddListing.js
|
client/src/components/AddListing/AddListing.js
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
export default class AddListing extends Component {
render() {
return (
<h2>Add Listing</h2>
);
}
}
|
JavaScript
| 0 |
@@ -78,168 +78,323 @@
x';%0A
-import %7B bindActionCreators %7D from 'redux';%0A%0Aexport default class AddListing extends Component %7B%0A render() %7B%0A return (%0A %3Ch2%3EAdd Listing%3C/h2%3E%0A );%0A %7D%0A%0A%7D
+%0Aclass AddListing extends Component %7B%0A constructor(props) %7B%0A super(props);%0A %7D%0A render() %7B%0A return (%0A %3Ch2%3EAdd Listing%3C/h2%3E%0A );%0A %7D%0A%0A%7D%0A%0Aconst mapStateToProps = (state) =%3E %7B%0A const %7B listingForm %7D = state.listing;%0A return %7B%0A listingForm,%0A %7D;%0A%7D;%0A%0Aexport default connect(mapStateToProps)(AddListing);
%0A
|
35f5399e1329a1e7b4c1a3b332ff10ce29c5c828
|
Update unmuteMeet.js
|
TamperMonkey/misc/unmuteMeet.js
|
TamperMonkey/misc/unmuteMeet.js
|
// ==UserScript==
// @name Unmute me
// @namespace http://omnimed.com
// @version 0.1
// @description unmute the mic in the meet
// @author ggirard
// @match https://meet.google.com/*
// ==/UserScript==
(function() {
'use strict';
setInterval(function(){
if (document.querySelector("div[jsname='LgbsSe']").parentElement.classList.contains("FTMc0c")) {
document.querySelector("div[jsname='LgbsSe']").click();
}
}, 1000);
})();
|
JavaScript
| 0 |
@@ -93,17 +93,17 @@
0.
-1
+2
%0A// @des
@@ -339,32 +339,18 @@
me='
-LgbsSe'%5D%22).parentElement
+BOHaEe'%5D%22)
.cla
@@ -430,13 +430,13 @@
me='
-LgbsS
+BOHaE
e'%5D%22
|
6204fcf7c0254bae2847d4798bccf1e2fe5e179f
|
clean up callbacks in download
|
download.js
|
download.js
|
var path = require('path')
var fs = require('fs')
var get = require('simple-get')
var pump = require('pump')
var tfs = require('tar-fs')
var zlib = require('zlib')
var util = require('./util')
function downloadPrebuild (opts, cb) {
var downloadUrl = util.getDownloadUrl(opts)
var cachedPrebuild = util.cachedPrebuild(downloadUrl)
var localPrebuild = util.localPrebuild(downloadUrl)
var tempFile = util.tempFile(cachedPrebuild)
var rc = opts.rc
var log = opts.log
if (opts.nolocal) return download()
log.info('looking for local prebuild @', localPrebuild)
fs.exists(localPrebuild, function (exists) {
if (exists) {
log.info('found local prebuild')
cachedPrebuild = localPrebuild
return unpack()
}
download()
})
function download () {
ensureNpmCacheDir(function (err) {
if (err) return onerror(err)
log.info('looking for cached prebuild @', cachedPrebuild)
fs.exists(cachedPrebuild, function (exists) {
if (exists) {
log.info('found cached prebuild')
return unpack()
}
log.http('request', 'GET ' + downloadUrl)
var req = get(downloadUrl, function (err, res) {
if (err) return onerror(err)
log.http(res.statusCode, downloadUrl)
if (res.statusCode !== 200) return onerror()
fs.mkdir(util.prebuildCache(), function () {
log.info('downloading to @', tempFile)
pump(res, fs.createWriteStream(tempFile), function (err) {
if (err) return onerror(err)
fs.rename(tempFile, cachedPrebuild, function (err) {
if (err) return cb(err)
log.info('renaming to @', cachedPrebuild)
unpack()
})
})
})
})
req.setTimeout(30 * 1000, function () {
req.abort()
})
})
function onerror (err) {
fs.unlink(tempFile, function () {
cb(err || new Error('Prebuilt binaries for node version ' + process.version + ' are not available'))
})
}
})
}
function unpack () {
var binaryName
var updateName = opts.updateName || function (entry) {
if (/\.node$/i.test(entry.name)) binaryName = entry.name
}
log.info('unpacking @', cachedPrebuild)
pump(fs.createReadStream(cachedPrebuild), zlib.createGunzip(), tfs.extract(rc.path, {readable: true, writable: true}).on('entry', updateName), function (err) {
if (err) return cb(err)
if (!binaryName) return cb(new Error('Missing .node file in archive'))
var resolved
try {
resolved = path.resolve(rc.path || '.', binaryName)
} catch (err) {
return cb(err)
}
log.info('unpack', 'resolved to ' + resolved)
if (rc.abi === process.versions.modules) {
try {
require(resolved)
} catch (err) {
return cb(err)
}
log.info('unpack', 'required ' + resolved + ' successfully')
cb(null, resolved)
} else {
cb(null, resolved)
}
})
}
function ensureNpmCacheDir (cb) {
var cacheFolder = util.npmCache()
if (fs.access) {
fs.access(cacheFolder, fs.R_OK | fs.W_OK, function (err) {
if (err && err.code === 'ENOENT') {
return makeNpmCacheDir()
}
if (err) return cb(err)
cb()
})
} else {
fs.exists(cacheFolder, function (exists) {
if (!exists) return makeNpmCacheDir()
cb()
})
}
function makeNpmCacheDir () {
log.info('npm cache directory missing, creating it...')
fs.mkdir(cacheFolder, function (err) {
if (err) return cb(err)
cb()
})
}
}
}
module.exports = downloadPrebuild
|
JavaScript
| 0 |
@@ -3002,24 +3002,30 @@
ssfully')%0A
+ %7D%0A
cb(nul
@@ -3041,58 +3041,8 @@
ed)%0A
- %7D else %7B%0A cb(null, resolved)%0A %7D%0A
@@ -3310,43 +3310,14 @@
-if (err) return cb(err)%0A
cb(
+err
)%0A
@@ -3588,77 +3588,10 @@
er,
-function (err) %7B%0A if (err) return cb(err)%0A cb()%0A %7D
+cb
)%0A
|
7d92325c6a2c8cbf7046ed925d77151f0336ab40
|
Update transform-column to work with the latest functions
|
packages/data-mate/bench/transform-column-suite.js
|
packages/data-mate/bench/transform-column-suite.js
|
'use strict';
const { Suite } = require('./helpers');
const { config, data } = require('./fixtures/data.json');
const { DataFrame, ColumnTransform } = require('./src');
const run = async () => {
const suite = Suite('Transform Column');
const dataFrame = DataFrame.fromJSON(config, data);
for (const column of dataFrame.columns) {
const fieldInfo = `${column.name} (${column.config.type}${column.config.array ? '[]' : ''})`;
Object.entries(ColumnTransform)
.filter(([, transform]) => {
if (!transform.accepts || !transform.accepts.length) return false;
if (!transform.accepts.includes(column.vector.type)) return false;
if (transform.required_args && transform.required_args.length) return false;
return true;
})
.forEach(([name, transform]) => {
suite.add(`${fieldInfo} ${name}`, {
fn() {
column.transform(transform);
}
});
});
}
return suite.run({
async: true,
initCount: 2,
minSamples: 2,
maxTime: 20,
});
};
if (require.main === module) {
run().then((suite) => {
suite.on('complete', () => {});
});
} else {
module.exports = run;
}
|
JavaScript
| 0 |
@@ -8,16 +8,116 @@
rict';%0A%0A
+const %7B isEmpty %7D = require('@terascope/utils');%0Aconst %7B FieldType %7D = require('@terascope/types');%0A
const %7B
@@ -213,16 +213,20 @@
%0Aconst %7B
+%0A
DataFra
@@ -233,45 +233,1298 @@
me,
-ColumnTransform %7D = require('./src');
+functionConfigRepository,%0A FunctionDefinitionType, dataFrameAdapter%0A%7D = require('./src');%0A%0A/**%0A * @todo add tuple support%0A * @param fieldType %7Bimport('@terascope/types').FieldType%7D%0A*/%0Afunction getFieldType(fieldType) %7B%0A if (fieldType === FieldType.Long) return FieldType.Number;%0A if (fieldType === FieldType.Byte) return FieldType.Number;%0A if (fieldType === FieldType.Short) return FieldType.Number;%0A if (fieldType === FieldType.Float) return FieldType.Number;%0A if (fieldType === FieldType.Double) return FieldType.Number;%0A if (fieldType === FieldType.Integer) return FieldType.Number;%0A if (fieldType === FieldType.Domain) return FieldType.String;%0A if (fieldType === FieldType.Keyword) return FieldType.String;%0A if (fieldType === FieldType.KeywordCaseInsensitive) return FieldType.String;%0A if (fieldType === FieldType.KeywordPathAnalyzer) return FieldType.String;%0A if (fieldType === FieldType.KeywordCaseInsensitive) return FieldType.String;%0A if (fieldType === FieldType.KeywordTokens) return FieldType.String;%0A if (fieldType === FieldType.KeywordTokensCaseInsensitive) return FieldType.String;%0A if (fieldType === FieldType.Hostname) return FieldType.String;%0A if (fieldType === FieldType.Text) return FieldType.String;%0A return fieldType;%0A%7D
%0A%0Aco
@@ -1581,16 +1581,25 @@
ransform
+/Validate
Column'
@@ -1833,23 +1833,32 @@
ies(
-ColumnTransform
+functionConfigRepository
)%0A
@@ -1879,25 +1879,21 @@
ter((%5B,
-transform
+fnDef
%5D) =%3E %7B%0A
@@ -1916,246 +1916,547 @@
if (
-!transform.accepts %7C%7C !transform.accepts.length) return false;%0A if (!transform.accepts.includes(column.vector.type)) return false;%0A if (transform.required_args && transform.required_args.length) return false;
+fnDef.type !== FunctionDefinitionType.FIELD_TRANSFORM%0A && fnDef.type !== FunctionDefinitionType.FIELD_VALIDATION) %7B%0A return false;%0A %7D%0A if (fnDef.required_arguments && fnDef.required_arguments.length) %7B%0A return false;%0A %7D%0A if (%0A !isEmpty(fnDef.accepts)%0A && !fnDef.accepts.includes(getFieldType(column.config.type))%0A ) %7B%0A return false;%0A %7D
%0A
@@ -2525,25 +2525,21 @@
(%5Bname,
-transform
+fnDef
%5D) =%3E %7B%0A
@@ -2645,34 +2645,45 @@
-column.transform(transform
+dataFrameAdapter(fnDef).column(column
);%0A
|
7c014ecddc9c293ad5e3b635489d8cc36363c376
|
Update form error handling to better support HTML5 `invalid` attribute.
|
rocketbelt/components/forms/rocketbelt.forms.js
|
rocketbelt/components/forms/rocketbelt.forms.js
|
'use strict';
((rb, document) => {
const aria = rb.aria;
const DESCRIBED_BY_ERROR_ID_ATTR = 'data-rb-describedbyerrorid';
function onClassMutation(mutations) {
const mutationsLen = mutations.length;
for (let k = 0; k < mutationsLen; k++) {
const mutation = mutations[k];
const el = mutation.target;
const message = el.parentNode.querySelector('.validation-message');
let describedByErrorId = '';
let describedByIds = [];
let i = -1;
if (mutation.oldValue !== 'invalid' && mutation.target.classList.contains('invalid')) {
// If "invalid" was added, do the decoratin'
el.setAttribute(aria.invalid, 'true');
describedByErrorId = el.getAttribute(DESCRIBED_BY_ERROR_ID_ATTR);
describedByIds = el.getAttribute(aria.describedby).split(' ');
i = describedByIds.indexOf(describedByErrorId);
if (message) {
message.setAttribute(aria.role, 'alert');
message.setAttribute(aria.live, 'polite');
// If a validation message exists && the related element is newly invalid,
// add message id to described-by
if (i === -1) {
describedByIds.push(describedByErrorId);
el.setAttribute(aria.describedby, describedByIds.join(' '));
}
}
} else if (mutation.oldValue === 'invalid' && !el.classList.contains('invalid')) {
// If "invalid" was removed
el.setAttribute(aria.invalid, 'false');
describedByErrorId = el.getAttribute(DESCRIBED_BY_ERROR_ID_ATTR);
describedByIds = el.getAttribute(aria.describedby).split(' ');
i = describedByIds.indexOf(describedByErrorId);
if (message) {
message.removeAttribute('role');
message.removeAttribute(aria.live);
// If a validation message exists && the related element longer invalid,
// remove message id from described-by
if (i > -1) {
describedByIds.splice(i, 1);
el.setAttribute(aria.describedby, describedByIds.join(' '));
}
}
}
}
}
function decorateInputs() {
const formEls = document.querySelectorAll('.form-group input, .form-group select, .form-group textarea, .form-group fieldset');
const formElsLen = formEls.length;
for (let i = 0; i < formElsLen; i++) {
const formEl = formEls[i];
// Set an observer to listen for .invalid.
const observer = new MutationObserver(mutations => { onClassMutation(mutations); });
observer.observe(formEl, { subtree: false, attributes: true, attributeOldValue: true, attributeFilter: ['class'] });
const messages = formEl.parentNode.querySelectorAll('.validation-message, .helper-text');
const msgLen = messages.length;
if (msgLen > 0) {
let describedByIds = '';
if (formEl.hasAttribute(aria.describedby)) {
describedByIds = `${formEl.getAttribute(aria.describedby)} `;
}
for (let j = 0; j < msgLen; j++) {
const thisMsg = messages[j];
const id = thisMsg.id ? thisMsg.id : `rb-a11y_${rb.getShortId()}`;
describedByIds += `${id} `;
if (thisMsg.classList.contains('validation-message')) {
formEl.setAttribute(DESCRIBED_BY_ERROR_ID_ATTR, id);
}
// Don't clobber any existing attributes!
if (!thisMsg.id) {
thisMsg.id = id;
}
}
if (!formEl.hasAttribute(aria.describedby)) {
formEl.setAttribute(aria.describedby, describedByIds.trim());
}
}
}
}
rb.onDocumentReady(decorateInputs);
rb.forms = rb.forms || {};
rb.forms.decorateInputs = decorateInputs;
})(window.rb, document);
|
JavaScript
| 0 |
@@ -2183,16 +2183,23 @@
ctorAll(
+%0A
'.form-g
@@ -2273,16 +2273,21 @@
ieldset'
+%0A
);%0A c
@@ -2379,28 +2379,360 @@
onst
+ el =
formEl
- = formEls%5Bi%5D
+s%5Bi%5D;%0A%0A // %22invalid%22 will be raised by the checkValidity() call below.%0A // .invalid is added and will be handled by the MutationObserver%0A // created by this function.%0A // https://daverupert.com/2017/11/happier-html5-forms/%0A el.addEventListener('invalid', () =%3E %7B%0A el.classList.add('invalid');%0A %7D, false)
;%0A%0A
@@ -2897,17 +2897,21 @@
rve(
-formEl, %7B
+el, %7B%0A
sub
@@ -2922,16 +2922,24 @@
: false,
+%0A
attribu
@@ -2944,24 +2944,32 @@
butes: true,
+%0A
attributeOl
@@ -2981,16 +2981,24 @@
e: true,
+%0A
attribu
@@ -3016,16 +3016,22 @@
'class'%5D
+%0A
%7D);%0A%0A
@@ -3051,21 +3051,17 @@
sages =
-formE
+e
l.parent
@@ -3229,21 +3229,17 @@
if (
-formE
+e
l.hasAtt
@@ -3296,21 +3296,17 @@
ds = %60$%7B
-formE
+e
l.getAtt
@@ -3613,37 +3613,33 @@
) %7B%0A
-formE
+e
l.setAttribute(D
@@ -3829,21 +3829,17 @@
if (!
-formE
+e
l.hasAtt
@@ -3876,21 +3876,17 @@
-formE
+e
l.setAtt
@@ -3949,32 +3949,273 @@
%7D%0A %7D%0A %7D
+%0A%0A const formsAndGroups =%0A document.querySelectorAll('form.validate-on-blur, .form-group.validate-on-blur');%0A for (const el of formsAndGroups) %7B%0A el.addEventListener('blur', () =%3E %7B%0A el.checkValidity();%0A %7D);%0A %7D
%0A %7D%0A%0A rb.onDoc
|
5ba234d4a409314e7de358e677460c5a57e70421
|
Update left.js
|
src/assets/js/app/left.js
|
src/assets/js/app/left.js
|
$(function(){
leftStatusBarUpdate();
})
function leftStatusBarUpdate()
{
var app_name = storage.getItem(config.storageAppNameKey);
if(s3AuthObj)
$('#publisher-name').text(s3AuthObj.rootDirectory);
if(app_name)
$('#app-list > li').first().text(app_name);
if(s3AuthObj && app_name)
$("#app-icon").attr("src", "https://librelio-europe.s3.amazonaws.com/" +
s3AuthObj.rootDirectory + "/" + app_name +
"/APP/SOURCES/iOS/Icon.png");
}
|
JavaScript
| 0 |
@@ -310,32 +310,34 @@
Obj && app_name)
+ %7B
%0A $(%22#app
@@ -402,32 +402,16 @@
com/%22 +%0A
-
@@ -469,32 +469,16 @@
-
%22/APP/SO
@@ -498,11 +498,139 @@
n.png%22);
+%0A%0A $(%22#app-icon%22).error(function() %7B%0A $(%22#app-icon%22).attr(%22src%22, %22assets/img/no-icon.png%22);%0A %7D);%0A %7D%0A
%0A%7D%0A
|
fc67fb6e6291e1fe050cc016c191d2849bda0877
|
Move distribution.
|
aplomb/router.js
|
aplomb/router.js
|
var hash = require('hash.murmur3.32')
var fnv = require('b-tree/benchmark/fnv')
function Router (options) {
this.delegates = options.delegates
this.extract = options.extract
var length = 256, dist = Math.floor(length / options.delegates.length)
this.buckets = []
this.delegates.forEach(function (del) {
for (var i=0; i<dist; i++) {
length--
this.buckets.push({
url: del
})
}
}, this)
while (length-- > 0) {
this.buckets.push({ url: this.delegates[this.delegates.length - 1] })
}
}
Router.prototype.match = function (obj) {
var key = this.extract(obj)
return this.buckets[fnv(new Buffer(key), 0, Buffer.byteLength(key)).readUIntLE(0, 1)].url
}
Router.prototype.newDelegate = function (del) {
// redistribute buckets
}
Router.prototype.removeDelegate = function () {
// keep old config until migration complete
}
exports.Router = Router
|
JavaScript
| 0 |
@@ -116,19 +116,18 @@
is.d
-elegates =
+istribute(
opti
@@ -139,16 +139,17 @@
elegates
+)
%0A thi
@@ -176,16 +176,243 @@
extract%0A
+%7D%0A%0ARouter.prototype.match = function (obj) %7B%0A var key = this.extract(obj)%0A return this.buckets%5Bfnv(new Buffer(key), 0, Buffer.byteLength(key)).readUIntLE(0, 1)%5D.url%0A%7D%0A%0ARouter.prototype.distribute = function (delegates) %7B%0A
var
@@ -452,24 +452,16 @@
ength /
-options.
delegate
@@ -470,16 +470,47 @@
length)%0A
+ this.delegates = delegates%0A
this
@@ -821,24 +821,24 @@
gth - 1%5D %7D)%0A
+
%7D%0A%7D%0A%0ARou
@@ -838,179 +838,8 @@
%0A%7D%0A%0A
-Router.prototype.match = function (obj) %7B%0A var key = this.extract(obj)%0A return this.buckets%5Bfnv(new Buffer(key), 0, Buffer.byteLength(key)).readUIntLE(0, 1)%5D.url%0A%7D%0A%0A
Rout
|
a476ddf7cedf6145baf12ce4efe5be8f6947d838
|
Remove unnecessary logging
|
app/app/Board.js
|
app/app/Board.js
|
/*
Copyright (c) 2017 Jirtdan Team and other collaborators
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";
/*jshint esversion: 6*/
import {ConnectionLine} from './controls/ConnectionLine.js'
//FIXME: Draft
//TODO: Dependency from raphael needs to be removed.
export class Board {
constructor(paper) {
this.paper = paper;
this.connections = [];
this.controls = [];
this.isConnecting = false;
}
addControl(control) {
//TODO:
this.controls.push(control);
}
startConnection(pin) {
//TODO:
this.isConnecting = true;
this.inputPin = pin;
}
startFinishConnection(pin) {
if (!this.isConnecting) {
this.startConnection(pin);
return;
}
this.finishConnection(pin);
}
finishConnection(pin) {
console.log(pin);
if (!this.isConnecting) return;
if (this.inputPin == pin) return;
if (this.inputPin.canConnect(pin)) {
this.createConnection(this.inputPin, pin);
}
this.isConnecting = false;
}
/**
* Create new connection and add it to the list.
*/
createConnection(pin1, pin2) {
this.connections.push(new ConnectionLine(this, pin1, pin2));
}
/**
* Translate all connections depending on pins they connect to.
* This method is fired on drag-drop of the control.
*/
translateConnections(pin, x, y) {
for (var i = 0; i < this.connections.length; i++) {
this.connections[i].onPinTranslate(pin, x, y);
}
}
}
|
JavaScript
| 0 |
@@ -1851,34 +1851,8 @@
) %7B%0A
- console.log(pin);%0A
|
91d463a5d9403ca491764a7a75c16c38abf763c3
|
Update formatter.js
|
app/formatter.js
|
app/formatter.js
|
document.getElementById("formatButton").addEventListener("click", format, false);
document.getElementById("selectAllButton").addEventListener("click", selectAll, false);
function format() {
var input = document.getElementById("json-input").value;
try {
input = JSON.parse(input);
input = JSON.stringify(input, null, 4);
document.getElementById("json-input").value = input;
notifyCompletion("done");
} catch (error) {
notifyCompletion("failed");
document.getElementById("errorOut").innerHTML = error;
}
}
function selectAll() {
document.getElementById("json-input").select();
}
function notifyCompletion(status) {
if (status == "done") {
document.getElementById("notification-area").innerHTML = "JSON formatted! <b>Your JSON is perfectly valid.</b>";
$("#notification-area").fadeTo("fast", 1);
setTimeout(function () {
$("#notification-area").fadeTo("slow", 0);
}, 4500);
} else if (status == "failed") {
document.getElementById("notification-area").innerHTML = "Something went wrong, see below for details. <b>Your JSON is invalid.</b>";
$("#notification-area").fadeTo("fast", 1);
setTimeout(function () {
$("#notification-area").fadeTo("slow", 0);
$("#errorOut").fadeTo("slow", 0);
}, 10000);
}
}
|
JavaScript
| 0 |
@@ -491,72 +491,16 @@
led%22
-);%0A document.getElementById(%22errorOut%22).innerHTML = error
+, error)
;%0A
@@ -614,16 +614,21 @@
n(status
+, err
) %7B%0A
@@ -1036,77 +1036,22 @@
= %22
-Something went wrong, see below for details. %3Cb%3EYour JSON is invalid.
+%3Cb%3E%22 + err + %22
%3C/b%3E
|
dcdc63948bc4982c36a34f73d7fb0e8f94b64783
|
Add numbers to multiple choice questions
|
app/generator.js
|
app/generator.js
|
const Generator = require('yeoman-generator');
const {toId, toAppId, toName, isValidAppId} = require('./utilities.js');
const PROJECT_TYPES = [{
name: 'JavaScript App',
value: 'js'
}, {
name: 'TypeScript App',
value: 'ts'
}];
const IDE_TYPES = [{
name: 'None',
value: 'none'
}, {
name: 'Visual Studio Code',
value: 'vsc'
}];
module.exports = class extends Generator {
prompting() {
return this.prompt([
{
type: 'input',
name: 'name',
message: 'Your project name',
default: this.appname, // defaults to current working dir
filter: toId
}, {
type: 'input',
name: 'version',
message: 'Initial version',
default: '0.1.0'
}, {
type: 'list',
name: 'proj_type',
message: 'Type of project',
choices: PROJECT_TYPES
}, {
type: 'input',
name: 'app_id',
message: 'App ID',
default: answers => 'example.' + toAppId(answers.name),
validate: input => isValidAppId(input) ||
'Invalid App ID, use alphanumeric characters and periods only, EG: com.domain.app'
}, {
type: 'input',
name: 'app_name',
message: 'App name',
default: answers => toName(answers.name)
}, {
type: 'input',
name: 'app_description',
message: 'App description',
default: 'Example Tabris.js App'
}, {
type: 'input',
name: 'author_name',
message: 'Author',
default: this.user.git.name
}, {
type: 'input',
name: 'author_email',
message: 'Email',
default: this.user.git.email
}, {
type: 'list',
name: 'ide_type',
message: 'Configure for IDE',
choices: IDE_TYPES
}
]).then(answers => {
let main = answers.proj_type === 'js' ? 'src/app.js' : 'dist/app.js';
this._props = Object.assign(answers, {main});
});
}
writing() {
this.fs.copyTpl(
this.templatePath('_package.json'),
this.destinationPath('package.json'),
this._props
);
this.fs.copyTpl(
this.templatePath('cordova'),
this.destinationPath('cordova'),
this._props
);
if (this._props.proj_type === 'ts') {
this.fs.copyTpl(
this.templatePath('ts/_gitignore'),
this.destinationPath('.gitignore')
);
this.fs.copyTpl(
this.templatePath('ts/src'),
this.destinationPath('src'),
this._props
);
this.fs.copyTpl(
this.templatePath('ts/tsconfig.json'),
this.destinationPath('tsconfig.json')
);
this.fs.copyTpl(
this.templatePath('ts/tslint.json'),
this.destinationPath('tslint.json')
);
} else if (this._props.proj_type === 'js') {
this.fs.copyTpl(
this.templatePath('js/_gitignore'),
this.destinationPath('.gitignore')
);
this.fs.copyTpl(
this.templatePath('js/.eslintrc'),
this.destinationPath('.eslintrc')
);
this.fs.copyTpl(
this.templatePath('js/src'),
this.destinationPath('src'),
this._props
);
}
if (this._props.ide_type === 'vsc') {
this.fs.copyTpl(
this.templatePath('.vscode'),
this.destinationPath('.vscode')
);
}
}
install() {
this.npmInstall(['[email protected]'], {
save: true
});
if (this._props.proj_type === 'js') {
this.npmInstall(['eslint'], {
saveDev: true
});
} else if (this._props.proj_type === 'ts') {
this.npmInstall(['typescript', 'tslint', 'npm-run-all'], {
saveDev: true
});
}
}
};
|
JavaScript
| 0.999246 |
@@ -148,16 +148,20 @@
name: '
+1 -
JavaScri
@@ -193,24 +193,28 @@
%7B%0A name: '
+2 -
TypeScript A
@@ -267,16 +267,20 @@
name: '
+1 -
None',%0A
@@ -308,16 +308,20 @@
name: '
+2 -
Visual S
|
0455c61ae3a104c997dccc4171bff584dca4bd3a
|
Update assertString.js
|
src/lib/util/assertString.js
|
src/lib/util/assertString.js
|
export default function assertString(input) {
const isString = (typeof input === 'string' || input instanceof String);
if (!isString) {
let invalidType;
if (input === null) {
invalidType = 'null';
} else {
invalidType = typeof input;
if (invalidType === 'object' && input.constructor) {
invalidType = input.constructor.name;
} else {
invalidType = `a ${invalidType}`;
}
}
let message = 'This library (validator.js) validates strings only, ';
message += `Instead it received ${invalidType}.`;
throw new TypeError(message);
}
}
|
JavaScript
| 0.000001 |
@@ -526,9 +526,9 @@
+= %60
-I
+i
nste
|
9bed3a30ba955051b30c5a2cecc01616a264e222
|
Remove temporary artificial results limit.
|
public/app/services/searchService.js
|
public/app/services/searchService.js
|
(function () {
'use strict';
define(
[
'lodash',
'jquery'
],
function (_, $) {
return function (baseUrl, ajaxOptions, noCache, logErrors) {
var queryString;
queryString = function (parameters) {
return _.map(parameters, function (value, key) {
return '(' + key + ':' + value + ')';
})
.join(' AND ');
};
return function (parameters, callback) {
$.ajax(_.merge({}, ajaxOptions, {
url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : '') + '&limit=500',
success: function (result) {
if (!result.ok) {
return callback(new Error('Invalid response received from server'));
}
delete result.ok;
callback(undefined, _.values(result));
},
error: function (jqXHR, textStatus, err) {
if (logErrors && console && typeof console.error === 'function') {
console.error(err);
}
callback(err);
}
}));
};
};
}
);
}());
|
JavaScript
| 0 |
@@ -723,23 +723,8 @@
'')
- + '&limit=500'
,%0A
|
2cf8bd6d20ad8651d54c26938e395cfef88b526e
|
Comment deleting now works, w00t.
|
public/includes/js/commentsThingy.js
|
public/includes/js/commentsThingy.js
|
/**
* At least we all get to write some Javascript, eh?
*
* JD woz 'ere 2k15
*
* Based entirely off http://www.webcodo.net/comments-system-using-php-ajax/
*/
var commentsThingy = function EmptyCommentsThingy() {
console.error("Failed to build the native Comments function.");
};
var deleteComment = function emptyDeleteComment() {
console.error("Failed to build the native Delete Comments function.");
};
(function () {
var commentRoot, containerDiv, containerId, newCommentCount, writeBox;
newCommentCount = 250;
writeBox = [
'<div class="col-xs-12 col-sm-10 col-sm-offset-1" id="commentWriteBox">',
'<div class="new-com-bt">',
'<span>Write a comment ...</span>',
'</div>',
'<div class="new-com-cnt">',
'<p id="commentError"></p>',
'<textarea id="newCommentBody"></textarea>',
'<p>You have <span id="newCommentCount">', newCommentCount, '</span> characters left.</p>',
'<div class="bt-add-com">Post comment</div>',
'<div class="bt-cancel-com">Cancel</div>',
'</div>',
'</div>'
].join('');
function createComment(data) {
containerDiv.innerHTML += [
'<div class="col-xs-12 col-sm-10 col-sm-offset-1 commentItem">',
'<img src="/uploads/', md5(data.author.email), '">',
'<div class="commentText">', '<div class="commentHead">',
'<h5><a href="/profile.php?type=' + data.author.role + '&id=', data.author.id, '">',
data.author.name,
'</a></h5>',
'<span class="com-dt">', data.created, '</span>',
((data.permissions.delete) ? '<span class="com-dt-delete"><a href="#" onclick="deleteComment(' + data.id + ');">Delete </a> </span>' : ''),
'</div>',
'<p>', data.comment, '</p>',
'</div>',
'</div>'
].join('');
}
function initWriteBox() {
containerDiv.innerHTML += writeBox;
setTimeout(function () {
document.querySelector('#commentWriteBox .new-com-bt').onclick = function OnNewCommentButtonClick() {
document.querySelector('#commentWriteBox .new-com-bt').style.display = 'none';
document.querySelector('#commentWriteBox .new-com-cnt').style.display = 'block';
document.getElementById('newCommentBody').focus();
};
document.getElementById('newCommentBody').onkeyup = function OnNewCommentBodyKeyUp() {
var commentLength, opacity;
commentLength = document.getElementById('newCommentBody').value.length;
if (commentLength > 0) {
if (commentLength > newCommentCount) {
opacity = 0.6;
document.getElementById('commentError').innerText = 'Please enter a shorter comment.';
document.getElementById('newCommentCount').innerText = "-" + (commentLength - newCommentCount);
}
else {
opacity = 1;
document.getElementById('commentError').innerText = '';
document.getElementById('newCommentCount').innerText = '' + (newCommentCount - commentLength);
}
}
else {
opacity = 0.6;
document.getElementById('newCommentCount').innerText = '' + newCommentCount;
}
document.querySelector('#commentWriteBox .bt-add-com').style.opacity = opacity;
};
document.querySelector('#commentWriteBox .bt-cancel-com').onclick = function OnNewCommentCancelClick() {
document.getElementById('newCommentBody').value = '';
document.getElementById('newCommentCount').innerText = '' + newCommentCount;
document.getElementById('commentError').innerText = '';
document.querySelector('#' + containerId + ' .new-com-cnt').style.display = 'none';
document.querySelector('#' + containerId + ' .new-com-bt').style.display = 'block';
};
document.querySelector('#commentWriteBox .bt-add-com').onclick = function OnNewCommentSubmit() {
var commentBody, writeBoxElem;
commentBody = document.getElementById('newCommentBody').value;
if ((commentBody.length == 0) || (commentBody.length > newCommentCount)) {
return;
}
writeBoxElem = document.getElementById('commentWriteBox');
writeBoxElem.innerHTML = '<div class="loader">Sending...</div>';
API.POST(
"/comment", {root: commentRoot, comment: commentBody},
function onCommentCreate(data) {
writeBoxElem.parentNode.removeChild(writeBoxElem);
createComment(data.body);
initWriteBox();
},
function onCommentCreateError(data) {
console.error("onCommentCreateError", data);
}
);
};
}, 200);
}
deleteComment = function deleteComment(id) {
console.log(id);
}
commentsThingy = function CommentsThingy(commentBodyId, root) {
containerId = commentBodyId;
containerDiv = document.getElementById(commentBodyId);
commentRoot = root;
API.GET(
"/comment/thread", {root: root},
function onCommentGet(data) {
if (data.body && data.body.length) {
for (var i = 0; i < data.body.length; i++) {
createComment(data.body[i]);
}
}
initWriteBox();
},
function onCommentGetError(data) {
console.error("onCommentGetError", data);
}
);
};
})();
|
JavaScript
| 0 |
@@ -1148,16 +1148,45 @@
entItem%22
+ id=%22comment_' + data.id + '%22
%3E',%0A%09%09%09'
@@ -4384,22 +4384,265 @@
%7B%0A%09%09
-console.log(id
+API.DELETE(%22/comment/%22 + id, %7B%7D,%0A%09%09%09function Success()%7B%0A%09%09%09%09var element = document.getElementById(%22comment_%22 + id);%0A%09%09%09%09element.parentNode.removeChild(element);%0A%0A%09%09%09%7D,%0A%09%09%09function Error()%7B%0A%09%09%09%09console.error(%22Failed to delete comment with ID %22 + id);%0A%09%09%09%7D%0A%09%09
);%0A%09
|
7c99f8eb8c0d249176f01429e8fbdc270ee45896
|
Remove tmp scaffolding
|
lib/buster-test-cli/browser/wiring.js
|
lib/buster-test-cli/browser/wiring.js
|
(function (B) {
function catchUncaughtErrors(emitter) {
window.onerror = function (message) {
emitter.emit("uncaughtException", {
name: "UncaughtError", message: message
});
return true;
};
}
function connectLogger(emitter) {
buster.console.on("log", function (msg) {
emitter.emit("log", msg);
});
}
function collectTestCases() {
var contexts = [];
B.addTestContext = function (context) { contexts.push(context); };
B.testCase.onCreate = B.addTestContext;
B.spec.describe.onCreate = B.addTestContext;
return contexts;
}
// Some test contexts may not be ready to run at create time
// Make sure these get parsed before running them
function parsedContexts(testContexts) {
var ctxs = [];
for (var i = 0, l = testContexts.length; i < l; ++i) {
if (!testContexts[i].tests &&
typeof testContexts[i].parse == "function") {
ctxs.push(testContexts[i].parse());
} else {
ctxs.push(testContexts[i]);
}
}
return ctxs;
}
function connectTestRunner(emitter) {
var contexts = collectTestCases();
emitter.on("tests:run", function (msg) {
var runner = B.testRunner.create(msg.data);
var reporter = B.reporters.jsonProxy.create(emitter);
reporter.listen(runner);
runner.runSuite(parsedContexts(contexts));
});
}
B.configureTestClient = function (emitter) {
emitter.connect(function () {
emitter.emit("ready", navigator.userAgent);
});
catchUncaughtErrors(emitter);
connectLogger(emitter);
connectTestRunner(emitter);
buster.env = buster.env || {};
buster.env.path = window.location.href;
};
}(buster));
// !!!!!!!!!
if (!buster.publish) {
buster.publish = function () {
return buster.bayeuxClient.publish.apply(buster.bayeuxClient, arguments);
};
}
if (!buster.subscribe) {
buster.subscribe = function () {
return buster.bayeuxClient.subscribe.apply(buster.bayeuxClient, arguments);
};
}
// !!!!!!!!!
if (buster.publish && buster.subscribe) {
buster.configureTestClient(buster.bayeuxEmitter.create(buster));
}
// TMP Performance fix
(function () {
var i = 0;
buster.nextTick = function (cb) {
i += 1;
if (i == 10) {
setTimeout(function () {
cb();
}, 0);
i = 0;
} else {
cb();
}
};
}());
|
JavaScript
| 0 |
@@ -1944,340 +1944,8 @@
);%0A%0A
-// !!!!!!!!!%0Aif (!buster.publish) %7B%0A buster.publish = function () %7B%0A return buster.bayeuxClient.publish.apply(buster.bayeuxClient, arguments);%0A %7D;%0A%7D%0A%0Aif (!buster.subscribe) %7B%0A buster.subscribe = function () %7B%0A return buster.bayeuxClient.subscribe.apply(buster.bayeuxClient, arguments);%0A %7D;%0A%7D%0A// !!!!!!!!!%0A%0A
if (
|
08d779f7b2bf39da5a35e0842beac82e31e69cbd
|
check whether the provided header is not empty
|
common/services/request.js
|
common/services/request.js
|
app.factory('Request', function () {
return {
execute: function (request) {
return $.ajax({
method: request.method,
url: request.uri,
beforeSend: function (xhr) {
var headers = request.headers;
for (var idx = 0; idx < headers.length; idx++) {
var header = headers[idx];
xhr.setRequestHeader(header.name, header.value);
}
}
});
}
}
});
|
JavaScript
| 0.00012 |
@@ -401,16 +401,101 @@
s%5Bidx%5D;%0A
+ if (header.name.length %3E 0 && header.value.length %3E 0) %7B%0A
@@ -559,16 +559,42 @@
value);%0A
+ %7D%0A
|
cf7b57c0fea2205802452e6ebc3dc43b5cf4da5c
|
Use void 0 instead of undefined
|
lib/node_modules/@stdlib/utils/homedir/test/test.js
|
lib/node_modules/@stdlib/utils/homedir/test/test.js
|
'use strict';
// MODULES //
var tape = require( 'tape' );
var proxyquire = require( 'proxyquire' );
// VARIABLES //
var mpath = './../lib/';
// TESTS //
tape( 'main export is a function', function test( t ) {
var homedir;
t.ok( true, __filename );
homedir = require( mpath );
t.strictEqual( typeof homedir, 'function', 'main export is a function' );
t.end();
});
tape( 'the function aliases `os.homedir` if available', function test( t ) {
var homedir;
var opts;
opts = {
'os': {
'homedir': mock
}
};
homedir = proxyquire( mpath, opts );
t.strictEqual( homedir, mock, 'equals `os.homedir`' );
t.end();
function mock(){}
});
tape( 'the function supports older Node versions', function test( t ) {
var homedir;
var opts;
var env;
opts = {
'os': {
'homedir': undefined
}
};
homedir = proxyquire( mpath, opts );
env = process.env;
process.env = {
'HOME': '/Users/beep'
};
t.strictEqual( homedir(), '/Users/beep', 'returns home directory' );
process.env = env;
t.end();
});
|
JavaScript
| 0.001261 |
@@ -796,17 +796,14 @@
r':
-undefined
+void 0
%0A%09%09%7D
|
43b8c4cdfb4a2a6f05f4f57f7ce9c4dfe537bf49
|
Check column arg is a string in AppView.addOne()
|
public/javascripts/views/app_view.js
|
public/javascripts/views/app_view.js
|
var AppView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'addOne', 'addAll', 'render');
window.Project.stories.bind('add', this.addOne);
window.Project.stories.bind('reset', this.addAll);
window.Project.stories.bind('all', this.render);
window.Project.stories.fetch();
},
addOne: function(story, column) {
if (typeof column === 'undefined') {
column = story.column();
}
var view = new StoryView({model: story});
$(column).append(view.render().el);
},
addAll: function() {
$('#done').html("");
$('#in_progress').html("");
$('#backlog').html("");
$('#chilly_bin').html("");
//
// Done column
//
var that = this;
var done_iterations = _.groupBy(window.Project.stories.column('#done'),
function(story) {
return story.iterationNumber();
});
// There will sometimes be gaps in the done iterations, i.e. no work
// may have been accepted in a given iteration, and it will therefore
// not appear in the set. Store this to iterate over those gaps and
// insert empty iterations.
var last_iteration = new Iteration({'number': 0});
_.each(done_iterations, function(stories, iterationNumber) {
var iteration = new Iteration({
'number': iterationNumber, 'stories': stories, column: '#done'
});
window.Project.iterations.push(iteration);
that.fillInEmptyIterations('#done', last_iteration, iteration);
last_iteration = iteration;
$('#done').append(that.iterationDiv(iteration));
_.each(stories, function(story) {that.addOne(story)});
});
// Fill in any remaining empty iterations in the done column
var currentIteration = new Iteration({
'number': window.Project.currentIterationNumber(),
'stories': window.Project.stories.column('#in_progress')
});
this.fillInEmptyIterations('#done', last_iteration, currentIteration);
//
// In progress column
//
// FIXME - Show completed/total points
$('#in_progress').append(that.iterationDiv(currentIteration));
_.each(window.Project.stories.column('#in_progress'), function(story) {
that.addOne(story);
});
//
// Backlog column
//
var backlogIteration = new Iteration({
'number': currentIteration.get('number') + 1,
'rendered': false,
'maximum_points': window.Project.velocity()
});
_.each(window.Project.stories.column('#backlog'), function(story) {
if (currentIteration.canTakeStory(story)) {
currentIteration.get('stories').push(story);
that.addOne(story, '#in_progress');
return;
}
if (!backlogIteration.canTakeStory(story)) {
// The iteration is full, render it
$('#backlog').append(that.iterationDiv(backlogIteration));
_.each(backlogIteration.get('stories'), function(iterationStory) {
that.addOne(iterationStory);
});
backlogIteration.set({'rendered': true});
var nextNumber = backlogIteration.get('number') + 1 + Math.ceil(backlogIteration.overflowsBy() / window.Project.velocity());
var nextIteration = new Iteration({
'number': nextNumber,
'rendered': false,
'maximum_points': window.Project.velocity()
});
// If the iteration overflowed, create enough empty iterations to
// accommodate the surplus. For example, if the project velocity
// is 1, and the last iteration contained 1 5 point story, we'll
// need 4 empty iterations.
//
that.fillInEmptyIterations('#backlog', backlogIteration, nextIteration);
backlogIteration = nextIteration;
}
backlogIteration.get('stories').push(story);
//that.addOne(story);
});
// Render the backlog final backlog iteration if it isn't already
$('#backlog').append(that.iterationDiv(backlogIteration));
_.each(backlogIteration.get('stories'), function(story) {
that.addOne(story);
});
backlogIteration.set({'rendered': true});
_.each(window.Project.stories.column('#chilly_bin'), function(story) {
that.addOne(story)
});
},
// Creates a set of empty iterations in column, with iteration numbers
// starting at start and ending at end
fillInEmptyIterations: function(column, start, end) {
var el = $(column);
var missing_range = _.range(
parseInt(start.get('number')) + 1,
parseInt(end.get('number'))
);
var that = this;
_.each(missing_range, function(missing_iteration_number) {
var iteration = new Iteration({
'number': missing_iteration_number, 'column': column
});
window.Project.iterations.push(iteration);
el.append(that.iterationDiv(iteration));
});
},
scaleToViewport: function() {
var storyTableTop = $('table.stories tbody').offset().top;
// Extra for the bottom padding and the
var extra = 100;
var height = $(window).height() - (storyTableTop + extra);
$('.storycolumn').css('height', height + 'px');
},
// FIXME - Make a view
iterationDiv: function(iteration) {
// FIXME Make a model method
var iteration_date = window.Project.getDateForIterationNumber(iteration.get('number'));
var points_markup = '<span class="points">' + iteration.points() + ' points</span>';
return '<div class="iteration">' + iteration.get('number') + ' - ' + iteration_date.toDateString() + points_markup + '</div>'
},
notice: function(message) {
$.gritter.add(message);
}
});
|
JavaScript
| 0.000022 |
@@ -346,24 +346,276 @@
, column) %7B%0A
+ // If column is blank determine it from the story. When the add event%0A // is bound on a collection, the callback send the collection as the%0A // second argument, so also check that column is a string and not an%0A // object for those cases.%0A
if (type
@@ -639,16 +639,46 @@
defined'
+ %7C%7C typeof column !== 'string'
) %7B%0A
|
7d43f676475ecebabed9cba40d0d7477a67ee25b
|
add feature flag for blackbox icon (#437) (#477)
|
public/js/components/SourceFooter.js
|
public/js/components/SourceFooter.js
|
const React = require("react");
const { DOM: dom } = React;
const { connect } = require("react-redux");
const { bindActionCreators } = require("redux");
const actions = require("../actions");
const { getSelectedSource } = require("../selectors");
function debugBtn(onClick, type, className = "active") {
className = `${type} ${className}`;
return dom.span(
{ onClick, className, key: type },
dom.img({ src: `images/${type}.svg` })
);
}
function SourceFooter({ togglePrettyPrint, selectedSource }) {
const commandsEnabled = selectedSource ? "" : "disabled";
return dom.div(
{
className: "source-footer"
},
dom.div({ className: "command-bar" },
debugBtn(
() => {},
"blackBox",
commandsEnabled
),
debugBtn(
() => togglePrettyPrint(selectedSource.get("id")),
"prettyPrint",
commandsEnabled
)
)
);
}
module.exports = connect(
state => ({
selectedSource: getSelectedSource(state),
}),
dispatch => bindActionCreators(actions, dispatch)
)(SourceFooter);
|
JavaScript
| 0 |
@@ -181,24 +181,69 @@
/actions%22);%0A
+const %7B isEnabled %7D = require(%22../feature%22);%0A
const %7B getS
@@ -722,24 +722,57 @@
ar%22 %7D,%0A
+ isEnabled(%22features.blackbox%22) ?
debugBtn(%0A
@@ -839,16 +839,23 @@
%0A )
+ : null
,%0A
|
0b43830f79e7ad756e98b61e18123d4030d98837
|
add back missing export
|
packages/spark-core/src/plugins/credentials/index.js
|
packages/spark-core/src/plugins/credentials/index.js
|
/**!
*
* Copyright (c) 2015 Cisco Systems, Inc. See LICENSE file.
* @private
*/
import {registerPlugin} from '../../spark-core';
import AuthInterceptor from './auth-interceptor';
import Credentials from './credentials';
registerPlugin(`credentials`, Credentials, {
proxies: [
`isAuthenticated`,
`isAuthenticating`
],
interceptors: {
AuthInterceptor: AuthInterceptor.create
}
});
export {Credentials as Credentials};
export {default as Authorization} from './authorization';
export {default as grantErrors} from './grant-errors';
export {AuthInterceptor as AuthInterceptor};
|
JavaScript
| 0.000001 |
@@ -399,16 +399,49 @@
%7D%0A%7D);%0A%0A
+export %7BCredentials as default%7D;%0A
export %7B
|
854a44a289757c953859553310cdf773e167f597
|
add tests for weekday formatting
|
management_frontend/src/l10n/__tests__/l10n.test.js
|
management_frontend/src/l10n/__tests__/l10n.test.js
|
/*jshint ignore:start */
'use strict';
var rewire = require('rewire');
describe('l10n', function() {
var l10n;
beforeAll(function() {
l10n = rewire('../index');
});
it('should return month name in nominative when formatting without specifying form',
() => {
expect(l10n.formatMonth(1)).toEqual('janvāris');
expect(l10n.formatMonth(7)).toEqual('jūlijs');
});
it('should return month name in specified form when asked to nicely', () => {
expect(l10n.formatMonth(4, 'genitivs')).toEqual('aprīļa');
expect(l10n.formatMonth(10, 'akuzativs')).toEqual('oktobri');
});
it('should return nothing when asked to format nonexisting month or to an undefined form',
() => {
expect(l10n.formatMonth(16)).not.toBeDefined();
expect(l10n.formatMonth(4, 'deklinativs')).not.toBeDefined();
});
it('should format dates without a leading zero', () => {
expect(l10n.formatDate('6-12-01')).toEqual('6.gada 1.decembris');
expect(l10n.formatDate('2015-12-01')).toEqual('2015.gada 1.decembris');
expect(l10n.formatDate('2015-12-11')).toEqual('2015.gada 11.decembris');
})
it('should format proper ISO8601-compliant dates to specified form', () => {
expect(l10n.formatDate('2015-12-01', 'dativs')).toEqual('2015.gada 1.decembrim');
expect(l10n.formatDate('2000-03-16', 'lokativs')).toEqual('2000.gada 16.martā');
});
it('should return "unknown date" when asked to format dates not complying to ISO8601, using the specified form',
() => {
expect(l10n.formatDate('03/04/2010')).toEqual('nezināms datums');
expect(l10n.formatDate('2010.14.21', 'genitivs')).toEqual('nezināma datuma');
expect(l10n.formatDate('garbageDate', 'akuzativs')).toEqual('nezināmu datumu');
});
it('should return nominative form dates when form is not specified', () => {
expect(l10n.formatDate('2010-01-01')).toEqual('2010.gada 1.janvāris');
expect(l10n.formatDate('2011-04-04')).toEqual('2011.gada 4.aprīlis');
});
it('should return "unknown date" in nominative when an undefined form is specified', () => {
expect(l10n.formatDate('2015-12-01', 'deklinativs')).toEqual('nezināms datums');
});
it('should not accept invalid months, returning "unknown date" instead, in specified form', () => {
expect(l10n.formatDate('2015-15-01')).toEqual('nezināms datums');
expect(l10n.formatDate('2015-15-01', 'genitivs')).toEqual('nezināma datuma');
});
});
|
JavaScript
| 0.000001 |
@@ -267,37 +267,42 @@
ying form',%0A
-() =%3E
+function()
%7B%0A expec
@@ -483,21 +483,26 @@
icely',
-() =%3E
+function()
%7B%0A
@@ -733,37 +733,42 @@
ined form',%0A
-() =%3E
+function()
%7B%0A expec
@@ -943,21 +943,26 @@
zero',
-() =%3E
+function()
%7B%0A
@@ -1264,37 +1264,42 @@
pecified form',
-() =%3E
+function()
%7B%0A expec
@@ -1594,21 +1594,26 @@
m',%0A
-() =%3E
+function()
%7B%0A
@@ -1929,37 +1929,42 @@
not specified',
-() =%3E
+function()
%7B%0A expec
@@ -2205,21 +2205,26 @@
ified',
-() =%3E
+function()
%7B%0A
@@ -2416,13 +2416,18 @@
m',
-() =%3E
+function()
%7B%0A
@@ -2594,12 +2594,752 @@
%7D);%0A%0A
+ it('should return weekday in an adverb form when asked to format it without specifying a form', function() %7B%0A expect(l10n.formatWeekday(1)).toEqual('pirmdien');%0A expect(l10n.formatWeekday(3)).toEqual('tre%C5%A1dien');%0A %7D);%0A%0A it('should return weekday in an adverb form when asked to format it with an invalid form', function() %7B%0A expect(l10n.formatWeekday(1, 'deklinativs')).toEqual('pirmdien');%0A expect(l10n.formatWeekday(3, 'deklinativs')).toEqual('tre%C5%A1dien');%0A %7D);%0A%0A it('should treat the weekday as a noun when changing its case', function() %7B%0A expect(l10n.formatWeekday(1, 'dativs')).toEqual('pirmdienai');%0A expect(l10n.formatWeekday(4, 'genitivs')).toEqual('ceturtdienas');%0A %7D);%0A
%7D);%0A
|
3b30335fa930964611df647cb5380f7a368f3522
|
Update customer.service-spec.js
|
customer/service/customer.service-spec.js
|
customer/service/customer.service-spec.js
|
describe('customerServiceTest', function(API_URL) {
var url=API_URL + "/user";
beforeEach(function(){
module('ecDesktopApp.customer');
});
it("Les données du formulaire de creation de client doivent être postées", inject(function(customerService, $httpBackend){
var customer = {name : "Dendooven", firstname :"Remi", address : "rue de la paix", login :"login"};
$httpBackend.expectPOST(url,customer).respond(404,'');
//$httpBackend.whenPOST('http://localhost:9001/#/customer/createCustomer',customer).respond(201,'');
customerService.addCustomer(customer).then(function(response){
}, function(error){
});
$httpBackend.flush();
}));//fin du 1er it
it("Test sur la suppression d'un client", inject(function(customerService, $httpBackend){
var id = 1;
$httpBackend.expectDELETE(url+id).respond(200,'');
customerService.deleteCustomer(id);
$httpBackend.flush();
}));//fin du 2eme it
//test modification des clients
it('test modification client', inject(function(_$httpBackend_, customerService) {
var mockBackend = _$httpBackend_;
mockBackend.expectPUT(url,
{
"id": 1,
"nom": "Dillon",
"prenom": "Gladice",
"login": "Hammond",
"email": "[email protected]",
"address": {"number":12, "street":"rue Jean-Jean", "city":"Tomtom"}
}).respond({});
// modified device name test
var item = {
id: 1,
nom: "Dillon",
prenom: "Gladice",
login: "Hammond",
email: "[email protected]",
address: {"number":12, "street":"rue Jean-Jean", "city":"Tomtom"}
};
customerService.updateCustomer(item);
mockBackend.flush();
}));
it("est ce que la fonction cherche la liste des clients? ", inject(function(customerService,$httpBackend){
//code du test de vérification
//simulation de la réponse que l'on recevra
var reponseSimule= {
id: 1,
nom: "Dillon",
prenom: "Rosalie",
login: "Hammond",
email: "[email protected]",
adress: "12 rue tomtom"
};
//l'adresse sur laquelle on récupère les données
$httpBackend.when("GET", url).respond(reponseSimule);
//récupération des données
var reponsePromesse=customerService.getCustomers();
// vérification du résultat
reponsePromesse.then(function(response){
var customer = response;
expect(customer.id).toEqual(1);
expect(customer.nom).toEqual("Dillon");
expect(customer.prenom).toEqual("Rosalie");
expect(customer.login).toEqual("Hammond");
expect(customer.email).toEqual("[email protected]");
expect(customer.adress).toEqual("12 rue tomtom");
});
//pour déclencher les réponses des requêtes faites avec $http.
$httpBackend.flush();
})); // fin du test
});
|
JavaScript
| 0.000001 |
@@ -70,16 +70,17 @@
+ %22/user
+/
%22;%0A%09befo
|
3624cce4cefdfe7f9f2667ee4b7c49539a7f47df
|
add watchgetfiletransfers to root saga
|
plugins/Files/js/sagas/index.js
|
plugins/Files/js/sagas/index.js
|
import * as sagas from './files.js'
import { fork } from 'redux-saga/effects'
export default function* rootSaga() {
yield [
fork(sagas.watchGetWalletLockstate),
fork(sagas.watchGetFiles),
fork(sagas.watchSetAllowance),
fork(sagas.watchGetMetrics),
fork(sagas.watchGetWalletBalance),
fork(sagas.watchStorageSizeChange),
fork(sagas.watchSetAllowanceProgress),
fork(sagas.watchSetPath),
fork(sagas.watchSetSearchText),
fork(sagas.watchUploadFile),
]
}
|
JavaScript
| 0 |
@@ -460,13 +460,50 @@
dFile),%0A
+%09%09fork(sagas.watchGetFileTransfers),%0A
%09%5D%0A%7D%0A
|
55e2e8c7a40edc650afb0cf3693d093033272ad4
|
increase timeout for jest
|
plugins/astroturf/index.test.js
|
plugins/astroturf/index.test.js
|
const createProject = require('@poi/test-utils/createProject')
test('astroturf', async () => {
const project = await createProject({ name: 'astroturf' })
await project.write(
'.poirc',
JSON.stringify({
plugins: [require.resolve('.')],
output: {
format: 'cjs',
target: 'node'
}
})
)
await project.write(
'index.js',
`
import { css } from 'astroturf';
const margin = 10;
const height = 50;
const bottom = height + margin;
const styles = css\`
.box {
height: \${height}px;
margin-bottom: \${margin}px;
}
.footer {
position: absolute;
top: \${bottom}px;
}
\`;
export default styles;
`
)
await project.run('poi')
expect(project.require('dist/index.js')).toEqual({
default: {
box: 'index-styles-module_box_1SCdY',
footer: 'index-styles-module_footer_1xrFU'
}
})
})
|
JavaScript
| 0.008138 |
@@ -57,16 +57,40 @@
ject')%0A%0A
+jest.setTimeout(60000)%0A%0A
test('as
|
22a00cd08e38b16bb47bd9191a32c4f90eeb7f41
|
stop keydown event propagation when ESC pressed to discard matches
|
src/typeahead/typeahead.js
|
src/typeahead/typeahead.js
|
angular.module('ui.bootstrap.typeahead', [])
/**
* A helper service that can parse typeahead's syntax (string provided by users)
* Extracted to a separate service for ease of unit testing
*/
.factory('typeaheadParser', ['$parse', function ($parse) {
// 00000111000000000000022200000000000000003333333333333330000000000044000
var TYPEAHEAD_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+(.*)$/;
return {
parse:function (input) {
var match = input.match(TYPEAHEAD_REGEXP), modelMapper, viewMapper, source;
if (!match) {
throw new Error(
"Expected typeahead specification in form of '_modelValue_ (as _label_)? for _item_ in _collection_'" +
" but got '" + input + "'.");
}
return {
itemName:match[3],
source:$parse(match[4]),
viewMapper:$parse(match[2] || match[1]),
modelMapper:$parse(match[1])
};
}
};
}])
//options - min length
.directive('typeahead', ['$compile', '$q', '$document', 'typeaheadParser', function ($compile, $q, $document, typeaheadParser) {
var HOT_KEYS = [9, 13, 27, 38, 40];
return {
require:'ngModel',
link:function (originalScope, element, attrs, modelCtrl) {
var selected = modelCtrl.$modelValue;
//minimal no of characters that needs to be entered before typeahead kicks-in
var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 1;
//expressions used by typeahead
var parserResult = typeaheadParser.parse(attrs.typeahead);
//create a child scope for the typeahead directive so we are not polluting original scope
//with typeahead-specific data (matches, query etc.)
var scope = originalScope.$new();
originalScope.$on('$destroy', function(){
scope.$destroy();
});
var resetMatches = function() {
scope.matches = [];
scope.activeIdx = -1;
};
var getMatchesAsync = function(inputValue) {
var locals = {$viewValue: inputValue};
$q.when(parserResult.source(scope, locals)).then(function(matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
if (inputValue === modelCtrl.$viewValue) {
if (matches.length > 0) {
scope.activeIdx = 0;
scope.matches.length = 0;
//transform labels
for(var i=0; i<matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
} else {
resetMatches();
}
}
}, resetMatches);
};
resetMatches();
//we need to propagate user's query so we can higlight matches
scope.query = undefined;
//plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
//$parsers kick-in on all the changes coming from the vview as well as manually triggered by $setViewValue
modelCtrl.$parsers.push(function (inputValue) {
resetMatches();
if (selected) {
return inputValue;
} else {
if (inputValue && inputValue.length >= minSearch) {
getMatchesAsync(inputValue);
}
}
return undefined;
});
modelCtrl.$render = function () {
var locals = {};
locals[parserResult.itemName] = selected;
element.val(parserResult.viewMapper(scope, locals) || modelCtrl.$viewValue);
selected = undefined;
};
scope.select = function (activeIdx) {
//called from within the $digest() cycle
var locals = {};
locals[parserResult.itemName] = selected = scope.matches[activeIdx].model;
modelCtrl.$setViewValue(parserResult.modelMapper(scope, locals));
modelCtrl.$render();
};
//bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(9)
element.bind('keydown', function (evt) {
//typeahead is open and an "interesting" key was pressed
if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
return;
}
evt.preventDefault();
if (evt.which === 40) {
scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
scope.$digest();
} else if (evt.which === 38) {
scope.activeIdx = (scope.activeIdx ? scope.activeIdx : scope.matches.length) - 1;
scope.$digest();
} else if (evt.which === 13 || evt.which === 9) {
scope.$apply(function () {
scope.select(scope.activeIdx);
});
} else if (evt.which === 27) {
scope.matches = [];
scope.$digest();
}
});
$document.find('body').bind('click', function(){
scope.matches = [];
scope.$digest();
});
var tplElCompiled = $compile("<typeahead-popup matches='matches' active='activeIdx' select='select(activeIdx)' "+
"query='query'></typeahead-popup>")(scope);
element.after(tplElCompiled);
}
};
}])
.directive('typeaheadPopup', function () {
return {
restrict:'E',
scope:{
matches:'=',
query:'=',
active:'=',
select:'&'
},
replace:true,
templateUrl:'template/typeahead/typeahead.html',
link:function (scope, element, attrs) {
scope.isOpen = function () {
return scope.matches.length > 0;
};
scope.isActive = function (matchIdx) {
return scope.active == matchIdx;
};
scope.selectActive = function (matchIdx) {
scope.active = matchIdx;
};
scope.selectMatch = function (activeIdx) {
scope.select({activeIdx:activeIdx});
};
}
};
})
.filter('typeaheadHighlight', function() {
return function(matchItem, query) {
return (query) ? matchItem.replace(new RegExp(query, 'gi'), '<strong>$&</strong>') : query;
};
});
|
JavaScript
| 0 |
@@ -4372,17 +4372,18 @@
9), esc(
-9
+27
)%0D%0A
@@ -5134,24 +5134,58 @@
=== 27) %7B%0D%0A
+ evt.stopPropagation();%0D%0A
sc
|
4af9c39471c60535f1155216683251908e3651b7
|
Remove accidental console.log
|
Expression.js
|
Expression.js
|
/**
* View code for expressions.
*
* @flow
*/
'use strict';
import React, {
Image,
Text,
View,
DeviceEventEmitter,
} from 'react-native';
import StatelessComponent from './StatelessComponent'
import {TrackedText, TrackedView} from './TrackedViews'
import type {
DisplayExpression,
DisplayLambda,
DisplayFuncCall,
DisplayVariable,
DisplayReference,
ViewKey,
} from './types'
import * as t from './types'
// This is the type returned by RelativeImageStub.
type AssetId = number;
type ExpressionPropTypes = {
expr: DisplayExpression,
}
class Expression extends StatelessComponent<ExpressionPropTypes> {
render() {
console.log("called 2");
const {expr} = this.props;
return t.matchDisplayExpression(expr, {
displayLambda: (expr) => <Lambda expr={expr} />,
displayFuncCall: (expr) => <FuncCall expr={expr} />,
displayVariable: (expr) => <Variable expr={expr} />,
displayReference: (expr) => <Reference expr={expr} />,
});
}
}
type LambdaPropTypes = {
expr: DisplayLambda,
}
class Lambda extends StatelessComponent<LambdaPropTypes> {
render() {
const {exprKey, varKey, emptyBodyKey, varName, body} = this.props.expr;
var bodyElement;
if (body != null) {
bodyElement = <Expression expr={body} />;
} else {
bodyElement = <EmptyBody viewKey={emptyBodyKey} />;
}
return <ExprContainer viewKey={exprKey}>
<ExprText>λ</ExprText>
<ExprText viewKey={varKey}>{varName}</ExprText>
<Bracket source={require('./img/left_bracket.png')}/>
{bodyElement}
<Bracket source={require('./img/right_bracket.png')}/>
</ExprContainer>;
}
}
type FuncCallPropTypes = {
expr: DisplayFuncCall,
}
class FuncCall extends StatelessComponent<FuncCallPropTypes> {
render() {
const {exprKey, func, arg} = this.props.expr;
return <ExprContainer viewKey={exprKey}>
<Expression expr={func} />
<Bracket source={require('./img/left_paren.png')}/>
<Expression expr={arg} />
<Bracket source={require('./img/right_paren.png')}/>
</ExprContainer>;
}
}
type VariablePropTypes = {
expr: DisplayVariable,
}
class Variable extends StatelessComponent<VariablePropTypes> {
render() {
const {exprKey, varName} = this.props.expr;
return <ExprContainer viewKey={exprKey}>
<ExprText>{varName}</ExprText>
</ExprContainer>;
}
}
type ReferencePropTypes = {
expr: DisplayReference,
}
class Reference extends StatelessComponent<ReferencePropTypes> {
render() {
const {exprKey, defName} = this.props.expr;
return <ExprContainer viewKey={exprKey}>
<ExprText>{defName}</ExprText>
</ExprContainer>
}
}
type ExprContainerPropTypes = {
children: any,
viewKey: ?ViewKey,
}
class ExprContainer extends StatelessComponent<ExprContainerPropTypes> {
render() {
const {children, viewKey} = this.props;
return <TrackedView viewKey={viewKey} style={{
flexDirection: 'row',
backgroundColor: "white",
elevation: 5,
paddingTop: 1,
alignItems: "center",
paddingBottom: 1,
paddingLeft: 2,
paddingRight: 2,
marginTop: 1,
marginBottom: 1,
marginLeft: 2,
marginRight: 2,
}}>
{children}
</TrackedView>
}
}
type ExprTextPropTypes = {
children: any,
viewKey: ?ViewKey,
}
class ExprText extends StatelessComponent<ExprTextPropTypes> {
render() {
const {children, viewKey} = this.props;
return <TrackedText viewKey={viewKey} style={{
paddingLeft: 6,
paddingRight: 6,
fontSize: 28,
color: "black",
textAlign: "center",
textAlignVertical: "center",
}}>
{children}
</TrackedText>;
}
}
type EmptyBodyPropTypes = {
viewKey: ?ViewKey,
}
class EmptyBody extends StatelessComponent<EmptyBodyPropTypes> {
render() {
return <TrackedView viewKey={this.props.viewKey} style={{
backgroundColor: "#FFBBBB",
padding: 2,
width: 20,
height: 40,
margin: 1,
alignSelf: "center",
}}>
</TrackedView>;
}
}
type BracketPropTypes = {
source: AssetId,
}
class Bracket extends StatelessComponent<BracketPropTypes> {
render() {
// We want the width of the bracket to be fixed, but for the height to
// match the available space. We can accomplish this by wrapping it in a
// vertical flexbox and setting flex to 1, then setting the height of
// the image itself to 0. This causes the flexbox to use the enclosing
// height, and the image is stretched to 100%.
const {source} = this.props;
return <View style={{flexDirection: "column", alignSelf: "stretch"}}>
<Image source={source} style={{
width: 6,
height: 0,
resizeMode: "stretch",
flex: 1,
marginTop: 0.5,
marginBottom: 0.5,
}}/>
</View>;
}
}
export default Expression;
|
JavaScript
| 0.000005 |
@@ -666,41 +666,8 @@
) %7B%0A
- console.log(%22called 2%22);%0A
|
dc51384a1a3a05bbac29c2ca169a6199d0332322
|
Allow CanvasProvider to receive sizes too.
|
src/util/CanvasProvider.js
|
src/util/CanvasProvider.js
|
CanvasProvider = {
canvases: [],
getCanvas: function(width, height) {
var canvas = this.canvases.length
? this.canvases.pop()
: document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
},
returnCanvas: function(canvas) {
this.canvases.push(canvas);
}
};
|
JavaScript
| 0 |
@@ -52,24 +52,46 @@
ion(
-width, height) %7B
+) %7B%0A%09%09var size = Size.read(arguments);
%0A%09%09v
@@ -204,16 +204,21 @@
width =
+size.
width;%0A%09
@@ -234,16 +234,21 @@
eight =
+size.
height;%0A
@@ -303,16 +303,66 @@
nvas) %7B%0A
+%09%09// reset canvas:%0A%09%09canvas.width = canvas.width;%0A
%09%09this.c
|
16ab401eeaae3ae04b15e76008ea8188b38a057d
|
use de-normalize `aria-hidden`
|
src/util/hidden-from-at.js
|
src/util/hidden-from-at.js
|
import trueish from './trueish'
export default function (props) {
return trueish(props, 'ariaHidden')
}
|
JavaScript
| 0.000097 |
@@ -1,8 +1,41 @@
+import hasProp from './has-prop'%0A
import t
@@ -126,9 +126,10 @@
aria
-H
+-h
idde
|
70797c54140f9b419f9242c393c2cefb4e3dfd28
|
Update app.js
|
js/app.js
|
js/app.js
|
function encrypt(text, pass) {
//console.log('pass:' + pass + ' encrypt IN:' + text);
var key = Sha256.hash(pass);
var encrypted = Aes.Ctr.encrypt(text, key, 256);
//console.log('encrypt OUT:' + encrypted);
return encrypted;
}
function decrypt (text, pass) {
//console.log('pass:' + pass + ' decrypt IN:' + text);
var key = Sha256.hash(pass);
var decrypted = Aes.Ctr.decrypt(text, key, 256);
//console.log('decrypt OUT:' + decrypted);
return decrypted;
}
function backToTop() {
$("html, body").animate({ scrollTop: 0 }, "slow");
}
function passwordsMatch() {
console.log("passwordsMatch()");
if( $('#password').val() == $('#password2').val() ) {
$('#passGroup').removeClass("has-error");
$('#passwordError').addClass("hidden");
return true;
}
$('#passGroup').addClass("has-error");
$('#passwordError').removeClass("hidden");
backToTop();
return false;
}
function onMessageChange() {
console.log("onMessageChange()");
var m = $('#message');
$("#count").text( m.val().length );
m.autosize({ append: '\n'});
m.trigger('autosize.resize');
}
function messageUpdated() {
$('#message').select();
onMessageChange();
}
function clearMessage() {
$('#message').val('');
onMessageChange();
}
function pageEncrypt() {
console.log("pageEncrypt()");
if ( passwordsMatch() ) {
$('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
messageUpdated();
}
}
function pageDecrypt() {
console.log("pageDecrypt()");
if( passwordsMatch() ) {
$('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
messageUpdated();
}
}
$( function() {
$("#message").change( onMessageChange );
$("#message").keyup( onMessageChange );
$('#encrypt').click( pageEncrypt );
$('#decrypt').click( pageDecrypt );
$('#backToTop').click( backToTop );
$('#reset').click( clearMessage );
onMessageChange();
$('.page').show();
$('#splashscreen').fadeOut('slow')
console.log('Page loaded');
});
|
JavaScript
| 0.000002 |
@@ -1961,29 +1961,8 @@
%0A %0A
- $('.page').show();%0A
$(
|
228ac96179303d83301bea0d3ea3d92a978e3424
|
Test all now
|
js/app.js
|
js/app.js
|
'use strict';
var main = require('./main');
main.debug = true;
require('./StoneConstants');
require('./rb');
require('./test/TestAi');
require('./test/TestGameLogic');
require('./test/TestGroup');
require('./test/TestStone');
main.tests.run();
|
JavaScript
| 0 |
@@ -129,100 +129,10 @@
estA
-i');%0Arequire('./test/TestGameLogic');%0Arequire('./test/TestGroup');%0Arequire('./test/TestStone
+ll
');%0A
|
1820246d3c54c97cf3216ca3890dde14265d1df6
|
Remove / in URL
|
js/app.js
|
js/app.js
|
var deps = [
'ui.router',
'ngAnimate',
'ngMaterial',
'mdl',
'ngIntercom',
'ngStorage',
'MinecraftlyAppControllers',
'MinecraftlyAppServices'
];
angular.module("MinecraftlyAppControllers", []);
angular.module("MinecraftlyAppServices", []);
angular.module('MinecraftlyApp', deps)
.run(function ($window) {
})
.config(function ($stateProvider, $locationProvider, $urlRouterProvider, IntercomProvider) {// $mdThemingProvider, $mdIconProvider,
IntercomProvider.init('t02jhyr0');
// $mdThemingProvider.theme('MinecraftlyTheme')
// .primaryPalette('blue')
// .accentPalette('purple')
// .warnPalette('deep-purple');
// $mdThemingProvider.setDefaultTheme('MinecraftlyTheme');
// $mdIconProvider
// .defaultIconSet('/img/mdi.svg');
// $locationProvider.html5Mode(true);
$stateProvider
.state('app', {
url: "",
abstract: true,
templateUrl: "templates/app.html",
controller: 'AppCtrl'
})
.state('app.home', {
cache: false,
url: "/",
views: {
'appContent': {
templateUrl: "templates/home.html",
controller: 'HomeCtrl'
}
}
})
.state('app.play', {
cache: false,
url: "/play",
views: {
'appContent': {
templateUrl: "templates/play.html",
controller: 'HomeCtrl'
}
}
})
.state('app.vote', {
cache: false,
url: "/vote",
views: {
'appContent': {
templateUrl: "templates/vote.html",
controller: 'HomeCtrl'
}
}
})
.state('app.team', {
cache: false,
url: "/team",
views: {
'appContent': {
templateUrl: "templates/team.html",
controller: 'HomeCtrl'
}
}
})
.state('app.about', {
cache: false,
url: "/about",
views: {
'appContent': {
templateUrl: "templates/about.html",
controller: 'HomeCtrl'
}
}
})
.state('app.education', {
cache: false,
url: "/education",
views: {
'appContent': {
templateUrl: "templates/education.html",
controller: 'HomeCtrl'
}
}
})
.state('app.jobs', {
cache: false,
url: "/jobs",
views: {
'appContent': {
templateUrl: "templates/jobs.html",
controller: 'HomeCtrl'
}
}
})
.state('app.features', {
cache: false,
url: "/features",
views: {
'appContent': {
templateUrl: "templates/features.html",
controller: 'HomeCtrl'
}
}
});
$urlRouterProvider.otherwise('/');
});
|
JavaScript
| 0 |
@@ -1308,17 +1308,20 @@
url: %22
-/
+home
%22,%0A
@@ -1686,17 +1686,16 @@
url: %22
-/
play%22,%0A
@@ -2064,17 +2064,16 @@
url: %22
-/
vote%22,%0A
@@ -2442,17 +2442,16 @@
url: %22
-/
team%22,%0A
@@ -2821,17 +2821,16 @@
url: %22
-/
about%22,%0A
@@ -3206,17 +3206,16 @@
url: %22
-/
educatio
@@ -3594,17 +3594,16 @@
url: %22
-/
jobs%22,%0A
@@ -3979,17 +3979,16 @@
url: %22
-/
features
@@ -4316,17 +4316,20 @@
erwise('
-/
+home
');%0A
|
6018a2af3750adabddb7249343538074ef8b6b33
|
Remove useless code
|
src/utils/storage/index.js
|
src/utils/storage/index.js
|
import {
setValueToSessionStorage,
getValueFromSessionStorage,
} from './sessionStorage'
import {
setValueToLocalStorage,
getValueFromLocalStorage,
} from './localStorage'
const SESSION_STORAGE_KEY = '__felog_session_storage_key__'
const LOCAL_STORAGE_KEY = '__felog_local_storage_key__'
export function getCount(defaultValue) {
return (
getValueFromSessionStorage(`${SESSION_STORAGE_KEY}/count`) || defaultValue
)
}
export function setCount(val) {
return setValueToSessionStorage(`${SESSION_STORAGE_KEY}/count`, val)
}
export function getCategory(defaultValue) {
return (
getValueFromSessionStorage(`${SESSION_STORAGE_KEY}/category`) ||
defaultValue
)
}
export function setCategory(val) {
return setValueToSessionStorage(`${SESSION_STORAGE_KEY}/category`, val)
}
export function getData() {
return getValueFromLocalStorage(LOCAL_STORAGE_KEY)
}
export function setData(val) {
return setValueToLocalStorage(LOCAL_STORAGE_KEY, val)
}
|
JavaScript
| 0.000548 |
@@ -539,268 +539,8 @@
%0A%7D%0A%0A
-export function getCategory(defaultValue) %7B%0A return (%0A getValueFromSessionStorage(%60$%7BSESSION_STORAGE_KEY%7D/category%60) %7C%7C%0A defaultValue%0A )%0A%7D%0A%0Aexport function setCategory(val) %7B%0A return setValueToSessionStorage(%60$%7BSESSION_STORAGE_KEY%7D/category%60, val)%0A%7D%0A%0A
expo
|
7c553177abab242a29c6fe8bc351cf6bce52e774
|
Update app.js
|
js/app.js
|
js/app.js
|
/*
UScan Technologies RFID Management System v0.1.0
Simplistic, elegant, and efficient RFID Management System
uscantechnologies.com
License: Attribution-NonCommercial-ShareAlike 4.0 International
*/
/* doesn't work
$(document).ready(function() {
$('.bar2').click(function() {
$(".tablez").animate({
left: "-500px"
}, 200);
});
});// end ready
*/
// Define spreadsheet URL.
//Sales Floor
var mySalesFloor = 'https://docs.google.com/spreadsheet/ccc?key=11x3_5BinmTr4sxeH4TiQrgvwp6OPKmERSOSuFrTPTH4#gid=1246466600';
//Data Analysis
var myDataAnalysis = "https://docs.google.com/spreadsheet/ccc?key=11x3_5BinmTr4sxeH4TiQrgvwp6OPKmERSOSuFrTPTH4#gid=1813653491";
//Stock Room
var myStockRoom = "https://docs.google.com/spreadsheet/ccc?key=11x3_5BinmTr4sxeH4TiQrgvwp6OPKmERSOSuFrTPTH4#gid=1784404855";
//Purchased
var myPurchase = "https://docs.google.com/spreadsheet/ccc?key=11x3_5BinmTr4sxeH4TiQrgvwp6OPKmERSOSuFrTPTH4#gid=783548062";
// real sheet => https://docs.google.com/spreadsheet/ccc?key=11x3_5BinmTr4sxeH4TiQrgvwp6OPKmERSOSuFrTPTH4#gid=0
// testing sheet => https://docs.google.com/spreadsheet/ccc?key=1G2xjX66QgIro6B9yV3A9E5CNINHYAp2gFjrXnfOdjHw#gid=0
/* FORMAT ROWS HAS TO DO IT'S THING AFTER SHEETS IS LOADED!*/
var threshold = 5;
var thresholdColName = "Amount";
var formatRows = function (row) {
var header = "<tr>",
footer = "</tr>";
var html = "";
for (var key in row.cells) {
var cellHtml;
if (key == thresholdColName && row.cells[key] < threshold) {
header = "<tr class='warning'>";
}
html += "<td>" + row.cells[key] + "</td>";;
}
return header + html + footer;
};
/* Thank You Michael => http://jsfiddle.net/qb26phrv/2/ */
// Method that takes a spreadsheet URL and loads it into the provided jQuery element.
function load(url, el) {
el.sheetrock({
url: url,
resetStatus: true,
rowHandler: formatRows
});
}
// Method that clears out the provided jQuery element and loads a spreadsheet back in.
function reload(url, el) {
el.empty();
load(url, el);
}
// Provides click functionality to the reload link.
//ADD RELOAD TAB IN HTML SOON
$('#reloadLink').click(function() {
reload(sheet, $('#exampleTable'));
});
// Sets a timer that will call the reload method on our second table every 15 seconds.
setInterval(function() {
reload(myStockRoom, $('#StockRoom'));
reload(mySalesFloor, $('#SalesFloor'));
reload(myDataAnalysis, $('#DataAnalysis'));
reload(myPurchase, $('#Purchase'));
reload($('GoogleGraph'));
}, 15000);
//Load Data Analysis
$('#DataAnalysis').sheetrock({
url: myDataAnalysis,
rowHandler: formatRows
});
//Load Stock Room
$('#StockRoom').sheetrock({
url: myStockRoom,
rowHandler: formatRows
});
// Load Sales Floor
$('#SalesFloor').sheetrock({
url: mySalesFloor,
rowHandler: formatRows,
/*sql:"select B,C,D,E,F,G,H,I,J" */
});
//Load Purchase
$('#Purchase').sheetrock({
url: myPurchase,
rowHandler: formatRows,
/*sql:"select B,C,D,E,F,G,H,I,J" */
});
/*
$('#runing_low').sheetrock({
url: mySpreadsheet,
sql: "select * order by C asc",
chunkSize: 10
});
*/
/* bar clicking stuff */
$('#bar1').click(function() {
$('#StockRoom').fadeIn();
$('#SalesFloor').slideUp();
/*$('#DataAnalysis').slideUp(); */
$('#Purchase').slideUp();
});
$('#bar2').click(function() {
$('#SalesFloor').fadeIn();
$('#StockRoom').slideUp();
/*$('#DataAnalysis').slideUp(); */
$('#Purchase').slideUp();
});
$('#bar3').click(function() {
$('#Purchase').fadeIn();
$('#StockRoom').slideUp();
/*$('#DataAnalysis').slideUp();*/
$('#SalesFloor').slideUp();
});
$('#bar4').click(function() {
/*$('#DataAnalysis').fadeIn(); */
$('#StockRoom').fadeIn();
$('#Purchase').fadeIn();
$('#SalesFloor').fadeIn();
});
/*
$('#bar5').click(function() {
$('#DataAnalysis').fadeIn();
$('#Inventory').slideUp();
$('#Purchase').slideUp();
$('#SalesFloor').slideUp();
});
*/
|
JavaScript
| 0.000002 |
@@ -4038,17 +4038,152 @@
deUp();%0A%7D);%0A*/%0A%0A
+/*CHART STUFF */%0Avar myBarChart = new Chart(ctx).Bar(mySalesFloor, options);%0A%0Anew Chart(ctx).Bar(data, %7B%0A barShowStroke: false%0A%7D);%0A%0A
%0A
|
a62061bd557558b7319aa297e3c024d82f91e160
|
Improve validation error message
|
src/validation/messages.js
|
src/validation/messages.js
|
'use strict';
const pluralize = require('pluralize');
const { getWordsList } = require('../utilities');
// List of custom error messages getters
const errorMessages = {
// JSON schema keywords for any type
type: ({ params: { type } }) => {
const types = type.split(',');
const typesA = getWordsList(types, { op: 'or' });
return ` must be ${typesA}`;
},
format: ({ params: { format } }) =>
` must match format '${format}'`,
enum: ({ params: { allowedValues } }) => {
const values = getWordsList(allowedValues, { quotes: true });
return ` must be ${values}`;
},
const: ({ schema }) =>
` must be equal to '${schema}'`,
// JSON schema keywords for `number|integer` type
multipleOf: ({ params: { multipleOf } }) =>
` must be multiple of ${multipleOf}`,
maximum: ({ params: { limit, comparison } }) => {
const orEqualTo = comparison === '<=' ? 'or equal to ' : '';
return ` must be less than ${orEqualTo}${limit}`;
},
minimum: ({ params: { limit, comparison } }) => {
const orEqualTo = comparison === '>=' ? 'or equal to ' : '';
return ` must be greater than ${orEqualTo}${limit}`;
},
// JSON schema keywords for `string` type
minLength: ({ params: { limit } }) =>
` must be at least ${pluralize('character', limit, true)} long`,
maxLength: ({ params: { limit } }) =>
` must be at most ${pluralize('character', limit, true)} long`,
pattern: ({ params: { pattern } }) =>
` must match pattern '${pattern}'`,
// JSON schema keywords for `array` type
contains: () =>
' must contain at least one valid item',
minItems: ({ params: { limit } }) =>
` must contains at least ${pluralize('item', limit, true)}`,
maxItems: ({ params: { limit } }) =>
` must contains at most ${pluralize('item', limit, true)}`,
uniqueItems: ({ params }) =>
` must not contain any duplicated item, but items number ${params.j} and ${params.i} are identical`,
// JSON schema keywords for `object` type
minProperties: ({ params: { limit } }) =>
` must have ${limit} or more ${pluralize('property', limit)}`,
maxProperties: ({ params: { limit } }) =>
` must have ${limit} or less ${pluralize('property', limit)}`,
required: ({ params: { missingProperty } }) =>
`.${missingProperty} must be defined`,
additionalProperties: ({ params: { additionalProperty } }) =>
`.${additionalProperty} is an unknown parameter`,
propertyNames: ({ params: { propertyName } }) =>
` property '${propertyName}' name must be valid`,
dependencies: ({ params: { missingProperty, property } }) =>
`.${missingProperty} must be defined when property '${property} is defined`,
// Special keyword for schema that are `false`,
// e.g. `patternProperties: { pattern: false }`
'false schema': () =>
' must not be defined',
};
module.exports = {
errorMessages,
};
|
JavaScript
| 0.000004 |
@@ -604,22 +604,40 @@
nst: (%7B
-schema
+params: %7B allowedValue %7D
%7D) =%3E%0A
@@ -661,22 +661,28 @@
l to '$%7B
-schema
+allowedValue
%7D'%60,%0A%0A
|
15e415c20f0df4b9d518ce207544d36870434992
|
copy html and css files to dist directory
|
config/gulp/tasks/build.js
|
config/gulp/tasks/build.js
|
/*global require*/
var gulp = require('gulp'),
clean = require('gulp-clean'),
usemin = require('gulp-usemin'),
rev = require('gulp-rev'),
minifyHtml = require('gulp-minify-html'),
runSequence = require('run-sequence'),
Builder = require('systemjs-builder');
gulp.task('build', function (callback) {
'use strict';
runSequence(
'clean',
'build:systemjs',
'usemin',
callback
);
});
gulp.task('clean', function () {
'use strict';
return gulp.src(['dist/', 'build/'], { read: false })
.pipe(clean({ force: true }));
});
gulp.task('build:systemjs', function (done) {
'use strict';
runSequence('typescript', function () {
var builder = new Builder();
builder.loadConfig('src/systemjs.config.js')
.then(function () {
return builder.buildStatic('src/app/main.js', 'build/app/bundle.js', {
normalize: true,
minify: true,
mangle: true,
runtime: false,
globalDefs: { DEBUG: false, ENV: 'production' }
});
})
.then(function () {
done();
});
});
});
gulp.task('usemin', function () {
'use strict';
return gulp.src('src/index.html')
.pipe(usemin(
{
html: [minifyHtml({ empty: true })],
js: [rev()],
jsApp: [rev()],
jsLib: [rev()]
}
))
.pipe(gulp.dest('dist/'));
});
|
JavaScript
| 0 |
@@ -412,24 +412,44 @@
'usemin',%0A
+ 'copy:app',%0A
call
@@ -1593,16 +1593,159 @@
('dist/'));%0A%7D);%0A
+%0Agulp.task('copy:app', function() %7B%0A 'use strict';%0A%0A return gulp.src('src/app/**/*.%7Bcss,html%7D')%0A .pipe(gulp.dest('dist/app'))%0A%7D);%0A
|
8d69b524f7fd89deb742589a186e6ffab367b551
|
handle arrays
|
js/app.js
|
js/app.js
|
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#maplist tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
var table = $('#maplist').DataTable( {
"ajax": "data/maps.json",
"lengthMenu": [[50, 100, 250, 500, 1000], [50, 100, 250, 500, 1000]],
"pageLength": 500,
"colReorder": true,
"stateSave": true,
"fixedHeader": true,
"processing": true,
"buttons": [
'colvis'
],
"dom": "<'row'<'col-sm-6'l><'col-sm-6'<'pull-right'B>>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
"columns": [
{ "data": "pk3" },
{ "data": "bsp[, ]" },
{ "data": "filesize" },
{ "data": "filesize" },
{ "data": "shasum" },
{ "data": "title" },
{ "data": "author" },
{ "data": "mapshot[, ]" },
{ "data": "gametypes[, ]" },
{ "data": "map" },
{ "data": "radar" },
{ "data": "waypoints" }
],
"columnDefs": [
{ // pk3
"targets": 0,
"render": function ( data, type, full, meta ) {
return type === 'display' && data.length > 40 ?
'<span title="'+data+'">'+data.substr( 0, 38 )+'...</span>' :
data;
}
},
{ // bsp
"targets": 1,
"render": function ( data, type, full, meta ) {
if (data != false) {
data = data.replace(/maps\//g,'');
if (data.length > 40 && data.indexOf(',') == -1) {
data = '<span title="'+data+'">'+data.substr( 0, 38 )+'...</span>';
}
}
return data;
}
},
{ // filesize
"targets": 2,
"orderData": 3,
"render": function ( data, type, full, meta ) {
return(bytesToSize(data));
}
},
{ // filesize for sorting
"targets": 3,
"visible": false,
"searchable": false
},
{ // mapshot file
"targets": 7,
"render": function ( data, type, full, meta ) {
return (data != false) ? true : false;
}
},
{ // map file
"targets": 9,
"render": function ( data, type, full, meta ) {
return (data != false) ? true : false;
}
},
{ // radar file
"targets": 10,
"render": function ( data, type, full, meta ) {
return (data != false) ? true : false;
}
},
{ // waypoints file
"targets": 11,
"render": function ( data, type, full, meta ) {
return (data != false) ? true : false;
}
}
]
} );
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
} );
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};
|
JavaScript
| 0.000007 |
@@ -1713,16 +1713,35 @@
!= false
+ && data.length %3E 0
) %7B%0A
|
b4e77734dd65f54a3c51ff5f6373488b4396e7ff
|
Fix bug when computing Opensearch's total number of pages
|
js/app.js
|
js/app.js
|
angular.module('app', ['app.filters', 'app.atom2json', 'app.settings'])
.config(function($routeProvider, $locationProvider, $httpProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({controller:FeedCtrl, templateUrl:'partial/feed.html'});
});
function MainCtrl($scope, $location, $settings) {
document.title = $scope.title = $settings.title;
$scope.placeholder = $settings.search_placeholder;
$scope.search = function() {
$location.url( $settings.search_service.replace('{term}', $scope.query) );
};
$scope.$watch(function() { return $location.search(); },
function(querystring) { $scope.query = querystring.q; });
}
function FeedCtrl($rootScope, $scope, $location, $atom2json, $http, $settings) {
$scope.toggleView = function() {
$rootScope.tableview = !$rootScope.tableview;
};
if ($location.url() !== "") {
$scope.settings = $settings;
$scope.loading="true";
$http.get( $settings.hostname+$location.url(), {headers: $settings.http_headers} )
.success( function(data) {
delete $scope.loading;
$scope.feed = $atom2json(data).feed;
document.title = $scope.feed.title;
if (typeof $scope.feed._modules.opensearch !== "undefined") {
var os = $scope.feed._modules.opensearch;
$scope.opensearch = {
current: os.startIndex,
results: os.totalResults,
total: 1^os.totalResults/os.itemsPerPage,
offset: (os.startIndex-1) * os.itemsPerPage,
perpage: os.itemsPerPage
};
}
})
.error( function(err, status) {
delete $scope.loading;
document.title = "Euh...";
$scope.err = {
msg: {'404': 'Not found', '403': 'Forbidden'}[''+status] || "Unexpected error",
url: $location.url()
};
} );
}
}
|
JavaScript
| 0.00002 |
@@ -1353,16 +1353,78 @@
ensearch
+,%0A total = os.totalResults / os.itemsPerPage
;%0A
@@ -1569,41 +1569,67 @@
al:
-1%5Eos.totalResults/os.itemsPerPage
+Math.floor(total) === total ? total : Math.floor(total) + 1
,%0A
|
45f685f06095948affb0156ff07618ce5d0984f0
|
Refactor AJAX Request
|
js/app.js
|
js/app.js
|
$('#key').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
$("#urigen").click(function(e)
{
e.preventDefault();
var u = $("#u").val();
var k = $("#key").val();
$("#loader").show();
$.ajax({
type: 'GET',
url: 'http://uri.im/api/v1',
crossDomain: true,
data: 'u='+u+'&key='+k,
dataType: 'text',
success: function(r, t, j)
{
$("#loader").hide();
$("#u").hide();
$("#key").hide();
$("#urigen").hide();
$(".result").html("<a target='_blank' href='"+r+"'>"+r+"</a>");
$(".result").show();
$("#back").show();
},
error: function (r, t, e)
{
$("#u").hide();
$("#key").hide();
$("#urigen").hide();
$("#back").show();
$(".error").html('<a style="color:red;" title="Return to Previous Page" name="back" id="back" href="javascript:location.reload();">'+r.responseText+'</a>')
$(".error").show();
}
});
});
|
JavaScript
| 0.000001 |
@@ -243,19 +243,17 @@
%0A %7D%0A%7D);
-%09%09%09
+%0A
%0A$(%22#uri
@@ -403,16 +403,17 @@
'GET',%0A
+%09
%09url: 'h
@@ -434,16 +434,17 @@
pi/v1',%0A
+%09
%09crossDo
@@ -455,16 +455,17 @@
: true,%0A
+%09
%09data: '
@@ -481,16 +481,17 @@
ey='+k,%0A
+%09
%09dataTyp
@@ -503,40 +503,53 @@
ext'
-,
%0A%09
-success: function(r, t, j) %0A%09
+%7D)%0A%09.done(function(data, textStatus, jqXHR)
%7B%0A%09%09
@@ -602,37 +602,24 @@
ey%22).hide();
-%09%09%09%09%09
%0A%09%09$(%22#urige
@@ -625,37 +625,24 @@
en%22).hide();
-%09%09%09%09%09
%0A%09%09$(%22.resul
@@ -683,16 +683,22 @@
='%22+
-r
+data
+%22'%3E%22+
-r
+data
+%22%3C/
@@ -750,29 +750,30 @@
w();
+%09%09
%0A%09%7D
-,%0A%09error:
+)%0A%09.fail(
function
(r,
@@ -772,21 +772,33 @@
tion
- (r, t, e) %0A%09
+(data, textStatus, jqXHR)
%7B%0A%09%09
@@ -828,37 +828,24 @@
ey%22).hide();
-%09%09%09%09%09
%0A%09%09$(%22#urige
@@ -859,21 +859,8 @@
e();
-%09%09%09%09%09
%0A%09%09$
@@ -1012,17 +1012,20 @@
d();%22%3E'+
-r
+data
.respons
@@ -1037,20 +1037,17 @@
+'%3C/a%3E')
-%09
+;
%0A%09%09$(%22.e
@@ -1064,30 +1064,13 @@
w();
-%09%09%09%09%09 %09
%0A%09
-%7D%0A
%7D);
-%09
%0A%7D);
-%09%09%0A
|
3b2ebb49747efb2518ed7b65cb69001972fb8edd
|
add button show, hide
|
js/app.js
|
js/app.js
|
// $(document).ready(function() {
'use strict';
// Waiting for vote state
var Photo = function(fileLocation) { //constructor
this.fileLocation = fileLocation;
this.votes = 1;
this.index = [];
};
var Tracker = function() {
this.photoArray = [];
this.leftPhoto = '';
this.rightPhoto = '';
};
Tracker.prototype.getPhoto = function() {
this.leftPhoto = this.photoArray[Math.floor(Math.random() * (this.photoArray.length - 1))];
this.rightPhoto = this.photoArray[Math.floor(Math.random() * (this.photoArray.length - 1))];
console.log(this.rightPhoto);
while (this.rightPhoto === this.leftPhoto) {
this.leftPhoto = this.photoArray[Math.floor(Math.random() * (this.photoArray.length - 1))];
}
};
Tracker.prototype.renderPhotos = function() {
rphoto.attributes[1].value = this.rightPhoto.fileLocation;
lphoto.attributes[1].value = this.leftPhoto.fileLocation;
};
Tracker.prototype.leftphoto = function() {
console.log ("left was clicked");
console.log("left is " + vote.leftPhoto.fileLocation);
vote.leftPhoto.votes++;
console.log("left has " + vote.leftPhoto.votes);
results.innerHTML = ('Left has ' + vote.leftPhoto.votes + ' and right has '
+ vote.rightPhoto.votes);
};
Tracker.prototype.rightphoto = function() {
console.log ("right was clicked");
console.log("right is " + vote.rightPhoto.fileLocation);
vote.rightPhoto.votes++;
console.log("right has " + vote.rightPhoto.votes);
};
Tracker.prototype.incrementKittens = function(photo) {
var index = this.leftphoto(photo);
var index = this.rightphoto(photo);
this.photoArray[index][1]++;
};
$('div[#highlight]').hide();
var vote = new Tracker();
vote.photoArray.push(new Photo('img/kittens/cat1.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat2.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat3.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat4.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat5.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat6.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat7.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat8.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat9.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat10.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat11.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat12.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat13.jpg'));
vote.photoArray.push(new Photo('img/kittens/cat14.jpg'));
var lphoto = document.getElementById('leftphoto');
var rphoto = document.getElementById('rightphoto');
var results = document.getElementById('results');
var nextbutton = document.getElementById('nextbutton');
rphoto.addEventListener('click', vote.rightphoto);
lphoto.addEventListener('click', vote.leftphoto);
nextbutton.addEventListener('click', function (){
vote.getPhoto();
vote.renderPhotos();
});
vote.getPhoto();
vote.renderPhotos();
// vote.waitingForVote();
// console.dir(vote);
// voteButton.addEventListener('click', waitingForVote);
// });
// Photo.prototype.highlight = function() {
// var getPhoto = document.getElementById('photos');
// newDiv.
// };
// // highlight() // CSS for highlight later
// }
// // drawTheChart()?
// // giveUserOptionToVoteAgain()?
// };
// function Tally() {
// var Vote document.getElementById("leftphoto");
// var Vote document.getElementById("rightphoto");
// // return running tally
// }
// Tracker.prototype.getRandomInt = function() {
// return Math.floor(Math.random() * (this.Photo));
// };
// Tracker.prototype.displayPhotos = function() {
// //display random photos
// //prevent same photo displayed for both choices
// //if photo1 === photo2 then re-roll
// }
// Display Winner State
// Tracker.prototype.displayWinner = function() {
// action4()
// action5()
// action6()
// }
//some 'document.getElementById' variables to access and manipulate document
|
JavaScript
| 0 |
@@ -1172,32 +1172,58 @@
htPhoto.votes);%0A
+%09$('#nextbutton').show();%0A
%7D;%0A%0ATracker.prot
@@ -1426,16 +1426,42 @@
votes);%0A
+%09$('#nextbutton').show();%0A
%7D;%0A%0ATrac
@@ -1622,38 +1622,8 @@
%7D;%0A%0A
-$('div%5B#highlight%5D').hide();%0A%0A
var
@@ -2850,16 +2850,42 @@
otos();%0A
+%09$('#nextbutton').hide();%0A
%7D); %0A%0Avo
@@ -2919,16 +2919,41 @@
hotos();
+%0A$('#nextbutton').hide();
%0A%0A// vot
|
58c86181c3c21a551b9f33ddbb91f5dbaf1cb145
|
Update client script to handle reconnecting better
|
public/js/scripts.js
|
public/js/scripts.js
|
var ws = new WebSocket('ws://cfc.jmgpena.net/ws');
function renderMsg(message) {
var div = document.createElement("div");
var content = document.createTextNode(message);
div.appendChild(content);
document.body.appendChild(div);
}
ws.onopen = function(evt) {
console.log('Websocket connection opened');
};
ws.onclose = function(evt) {
console.log('Websocket connection closed');
setTimeout(function() {
ws = new WebSocket('ws://cfc.jmgpena.net/ws');
}, 1000);
};
ws.onmessage = function(evt) {
console.log('Message: ',evt.data);
renderMsg(evt.data);
};
ws.onerror = function(evt) {
console.log('Error: ', evt.data);
};
|
JavaScript
| 0 |
@@ -3,51 +3,8 @@
r ws
- = new WebSocket('ws://cfc.jmgpena.net/ws')
;%0A%0Af
@@ -204,27 +204,22 @@
%0A%7D%0A%0A
-ws.onopen =
functio
+n onope
n(ev
@@ -276,32 +276,18 @@
);%0A%7D
-;
%0A%0A
-ws.onclose =
function
(evt
@@ -274,32 +274,40 @@
d');%0A%7D%0A%0Afunction
+ onclose
(evt) %7B%0A cons
@@ -386,52 +386,21 @@
-ws = new WebSocket('ws://cfc.jmgpena.net/ws'
+createWsConn(
);%0A
@@ -417,34 +417,28 @@
);%0A%7D
-;
%0A%0A
-ws.onmessage = function
+function onmessage
(evt
@@ -510,32 +510,18 @@
);%0A%7D
-;
%0A%0A
-ws.onerror =
function
(evt
@@ -516,16 +516,24 @@
function
+ onerror
(evt) %7B%0A
@@ -528,32 +528,36 @@
rror(evt) %7B%0A
+
+
console.log('Err
@@ -575,11 +575,215 @@
data);%0A%7D
-;
%0A
+%0Afunction createWsConn() %7B%0A ws = new WebSocket('ws://cfc.jmgpena.net/ws');%0A%0A ws.onopen = onopen;%0A ws.onclose = onclose;%0A%0A ws.onmessage = onmessage;%0A%0A ws.onerror = onerror;%0A%7D%0A%0AcreateWsConn();
%0A
|
fd7813fd62890da1df1216618ead48d0ba3b1961
|
Use landed option in app.js
|
js/app.js
|
js/app.js
|
;(function(lander){
console.log('Moon Lander Visualisation');
var display = document.getElementById('display');
var horizon = new Array(display.width);
horizon[0] = 50;
for (var index = 1; index < display.width; index++){
horizon[index] = horizon[index - 1] + 2 * (Math.random() - 0.5);
}
var model = {
"lander": {
"x": 37, "y": 251,
"vx": 1, "vy": 0,
"orientation": Math.PI/4, "angular-velocity": 0.05,
"radius": 10,
"fuel": 100,
"thrusting": true,
"crashed": false
},
"horizon": horizon
};
var view = new lander.View(model, display);
function tick(){
model.lander.x += model.lander.vx;
if (model.lander.x > display.width) {
model.lander.x -= display.width;
}
view.update();
requestAnimationFrame(tick);
};
tick();
})(lander);
|
JavaScript
| 0.000001 |
@@ -583,16 +583,45 @@
rashed%22:
+ false,%0A %22landed%22:
false%0A
|
6a67159929123a0e8ef908c33526680df4fa0467
|
Update app.js
|
js/app.js
|
js/app.js
|
//RedditApp Module
var redditApp = angular.module('redditApp', ['ngRoute']);
redditApp.controller('mainController', ['$scope', '$http', '$rootElement', '$timeout', function($scope, $http, $rootElement, $timeout){
$scope.next = null;
$scope.count = 0;
$scope.page = 1;
$scope.redditify = function(){
$scope.sr;
$scope.success = false;
$http.get('http://www.reddit.com/r/' + $scope.sr + '.json?count=' + $scope.count + '&limit=25' + $scope.next)
.success(function (data){
$scope.success = true;
$scope.subreddits = [];
$scope.next = null;
for(var i = 0; i < data.data.children.length; i++)
{
//Hide placeholder div
//Show page nav.
if(data.data.children.length > 0)
{
$('.previouspage, .nextpage').removeClass('hidden');
$('#placeholderdiv').addClass('hidden');
}
//Dealing with .gifs
var str = data.data.children[i].data.url;
var rest = str.substring(0, str.lastIndexOf("/") + 1);
var last = str.substring(str.lastIndexOf("/") + 1, str.length);
var split = last.split(".");
var fileformat = split[1];
//Check if .gifv format. Not supporting that.
if(fileformat == "gifv")
data.data.children[i].data.url = "http://" + data.data.children[i].data.domain + "/" + split[0] + ".gif";
if(fileformat == "jpg" || fileformat == "png" || fileformat == "bmp" || fileformat =="tif")
{
$scope.subreddits.push(data.data.children[i].data);
}
$scope.after = data.data.after;
$scope.before = data.data.before;
$scope.subreddit = data.data.children[i].data.subreddit;
}
});
}
}]);
//Directive for showing the info qtip.
redditApp.directive('ngHover', function() {
return {
link: function(scope, element) {
element.qtip
({
position: {
my: 'bottom center', // Position it where the click was...
at: 'top center',
target: element,
adjust: { mouse: false } // ...but don't follow the mouse
},
style: { classes: 'qtip-youtube' },
content:
{
text: scope.subreddit.title
}
})
element.on('click', function(){
$('.modal-body', '.modal-title').empty();
$('#myModal p a').remove();
$('.modal-title').append('<a href="http://reddit.com' + scope.subreddit.permalink + '" target="_blank">' + scope.subreddit.title + '</a>');
$('.modal-body').append('<img id="mimg" src="' + scope.subreddit.url + '">');
$('#myModal').modal('show');
setTimeout( function () {
$('#myModal').data('bs.modal').handleUpdate();
} , 800 );
});
}
}
});
//Directive ends
//Next Page
redditApp.directive('nextPage', function(){
return {
link: function(scope, element) {
element.on('click', function() {
scope.next = "&after=" + scope.after;
scope.count = scope.count + 25;
scope.redditify();
});
}
}
});
//Previous Page
redditApp.directive('previousPage', function(){
return {
link: function(scope, element){
element.on('click', function(){
scope.next = "&before=" + scope.before;
scope.count = scope.count - 25;
scope.redditify();
});
}
}
});
|
JavaScript
| 0.000002 |
@@ -2783,18 +2783,38 @@
al-body'
-,
+).empty();%0D%0A $(
'.modal-
|
2b6f0b8ec9d5c9e02c4fc9625847d58b6d676e68
|
fix decrypt bug
|
js/app.js
|
js/app.js
|
/*global MozSmsFilter*/
$(function() {
'use strict';
/*
function logObject(obj) {
$("#response").append("<br> New Object: " + obj);
Object.keys(obj).forEach(function (key) {
$("#response").append("<br> " + key + ": " + obj[key]);
});
}
*/
function logMsg(msg) {
[
'type', 'id', 'threadId', 'body', 'delivery', 'deliveryStatus', 'read'
, 'receiver', 'sender', 'timestamp', 'messageClass'
].forEach(function (key) {
$("#response").append("<br> " + key + ": " + msg[key]);
});
}
$('form#sms-form').on("submit", function (ev) {
$("#response").html("submit form");
ev.preventDefault();
ev.stopPropagation();
//var crypto = crypto.subtle;
var message = $('[name=msg]').val();
var pwUtf8 = new TextEncoder().encode(message);
var pwHash = crypto.subtle.digest('SHA-256', pwUtf8);
var iv = crypto.getRandomValues(new Uint8Array(20));
var alg = { name: 'AES-GCM', iv: iv };
var key = crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']);
var cryptedMessage = crypto.subtle.encrypt(alg, key, cryptedMessage);
var decryptedMessage = crypto.subtle.decrypt(alg, key, data);
var msg = decryptedMessage
, phone = $('[name=phone]').val()
, request;
$("#response").html("got values");
request = navigator.mozMobileMessage.send(phone, msg);
$("#response").html("tried to send message");
$("#response").html("iterate through requests");
request.onsuccess = function () {
window.thing = this;
console.error(this.result);
$("#response").html("Sent to <br>" + this.result);
logMsg(this.result);
};
request.onerror = function () {
window.thing = this;
console.error(this.error.name);
console.error(this.error.message);
$("#response").html(this.error.name + ':' + this.error.message);
};
//});
});
function showMessages(id) {
var filter = new MozSmsFilter() // https://developer.mozilla.org/en-US/docs/Web/API/MozSmsFilter
, cursor
;
filter.read = false;
if ('undefined' !== typeof id) {
filter.threadId = id;
}
// Get the messages from the latest to the first
cursor = navigator.mozMobileMessage.getMessages(filter, true);
cursor.onsuccess = function () {
logMsg(this.result);
/*
var message = this.result
, time = message.timestamp.toDateString()
;
console.log(time + ': ' + (message.body || message.subject)); // SMS || MMS
$("#response").append("<div>Got new message [" + time + "]"
+ "<br>" + (message.body || message.subject)
+ "</div>"
);
if (!this.done) {
this.continue();
}
*/
};
}
// 'received' seems to only activate after a message is sent
navigator.mozMobileMessage.addEventListener('received', function (msg) {
// https://developer.mozilla.org/en-US/docs/Web/API/MozSmsMessage
$("#response").html("Got a message");
$("#response").append("<br>" + msg);
logMsg(msg);
showMessages(msg.id);
});
navigator.mozSetMessageHandler("alarm", function (mozAlarm) {
// var directive = alorms[mozAlarm.data.id]; doStuff(directive);
$("#alarms").append("<li>Alarm Fired: " + new Date().toString().replace(/GMT.*/, ''));
//+ " : " + JSON.stringify(mozAlarm.data) + "</li>");
showMessages();
//setAlarm(7 * 1000);
setAlarm(7 * 60 * 1000);
});
function setAlarm(offset) {
var alarmId
, date
, request
;
$("#response").append("<br><br> setting alarm for " + (offset / 1000) + "s in the future");
date = new Date(Date.now() + offset);
$("#response").append("<br> will fire at " + " for " + date.toString().replace(/GMT.*/, ''));
// Set an alarm and store it's id
//request = navigator.mozAlarms.add(date, "ignoreTimezone", { foo: "bar" });
request = navigator.mozAlarms.add(date, "honorTimezone", { foo: "bar" });
request.onsuccess = function () {
// alarms[this.result] = { type: 'thingy', params: ['do', 'stuff'] };
alarmId = this.result;
if (this.result) {
$("#response").append("<br> set alarm " + this.result + " for " + date.toString().replace(/GMT.*/, ''));
} else {
$("#response").append("<br><br> error setting alarm: " + this.error);
}
};
// ...
// Later on, removing the alarm if it exists
if (alarmId) {
navigator.mozAlarms.remove(alarmId);
}
}
if (!navigator.mozHasPendingMessage("alarm")) {
setAlarm(5 * 1000);
}
});
|
JavaScript
| 0.000011 |
@@ -681,35 +681,19 @@
%0A%09//
-var crypto = crypto.subtle;
+ Encryption
%0A%09va
@@ -1063,26 +1063,35 @@
ey,
-cryptedMessage);%0A%09
+ptUtf8);%0A%09%0A%09%0A%09// decryption
%0A%09va
@@ -1143,20 +1143,30 @@
g, key,
-data
+cryptedMessage
);%0A%0A
|
d7cd478e860f62b9f7bc4b5088f50a028ea1b2fa
|
move call to addSearchBox() out of initMap()
|
js/map.js
|
js/map.js
|
/*-----------------------------------------------------------------------------------------*/
/* CONTROLLER */
// map in global scope for access
var map;
function initMap() {
// Create a new map object and add to #map div
map = new google.maps.Map(document.getElementById('map'), initOptions);
// add search box
addSearchBox();
}
function addSearchBox() {
// create new search box object and assign to #searchbox <input>
var input = document.getElementById('searchbox');
// (searchBox in global scope)
searchBox = new google.maps.places.SearchBox(input);
// move search box to top left of map (COMMENTED OUT FOR NOW)
// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// bias searchbox results towards current map bounds
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
addSearchListener(searchBox);
}
function addSearchListener(searchBox) {
// listen for user selecting place
searchBox.addListener('places_changed', function() {
// getPlaces() return an ARRAY of possible matches
// so "li" returns array of possibles
var places = searchBox.getPlaces();
// just select 1st place in array
var place = places[0];
// create new marker
var newMarkOptions = {
map : map,
title : place.formatted_address,
position : place.geometry.location
};
addMarker(newMarkOptions);
// centre screen on marker
var bounds = new google.maps.LatLngBounds();
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
}
else {
bounds.extend(place.geometry.location);
}
// fit map to bounds selected by place search
map.fitBounds(bounds);
// set zoom to street level
map.setZoom(15);
// get stop/search data from api
getStopsData();
});
}
function addMarker(markerOptions) {
marker = new google.maps.Marker(markerOptions);
var marker = new google.maps.Marker(markerOptions);
// add info window for each stop
// format date/time
var date = new Date(stop.datetime);
var formattedDate = date.toString();
var infoContent = "<div id='infowindow'>"
+ '<p>' + formattedDate + '</p>'
+ '<p>' + stop.legislation + '</p>'
+ '<p>' + stop.gender + ', ' + stop.age_range + ', ' + stop.self_defined_ethnicity + '</p>'
+ '<p>' + 'result: ' + stop.outcome + '</p>'
+ '</div>';
// test
console.log(infoContent);
var infowindow = new google.maps.InfoWindow({
content: infoContent
});
marker.addListener('click', function() {
infowindow.open(map, marker);
})
};
function getStopsData() {
// get current bounds from getBounds object
var current_bounds = map.getBounds();
var min_lat = current_bounds.R.R;
var min_lng = current_bounds.j.j;
var max_lat = current_bounds.R.j;
var max_lng = current_bounds.j.R;
// get police.uk stop-search data for current bounds (https://data.police.uk/docs/method/stops-street/)
var poly_1 = min_lat.toString() + ',' + min_lng.toString() + ':';
var poly_2 = min_lat.toString() + ',' + max_lng.toString() + ':';
var poly_3 = max_lat.toString() + ',' + max_lng.toString(); // 4th poly not required as per documentation
var query = 'https://data.police.uk/api/stops-street?poly=' + poly_1 + poly_2 + poly_3;
var stops;
var request = new XMLHttpRequest();
request.open("GET", query); // async by default
request.addEventListener("load", function() {
// once loaded, do this..
stops = JSON.parse(request.responseText);
// test
// console.log(stops);
addStopsMarkers(stops);
});
request.send(null);
}
function addStopsMarkers(stops) {
//test
console.log(stops);
for (stop of stops) {
// test
console.log(stop);
var markerOptions = {};
markerOptions.position = {
lat: Number(stop.location.latitude),
lng: Number(stop.location.longitude)
};
markerOptions.animation = google.maps.Animation.DROP;
markerOptions.map = map;
addMarker(markerOptions);
}
}
/*-----------------------------------------------------------------------------------------*/
/* MODEL */
var initOptions = {
center : {lat : 53.328, lng: -3.101995},
zoom : 8
};
/*---------------------------------------------------------------------------------------*/
/* VIEW */
initMap();
/*---------------------------------*/
/* TEST: can we use this later for recalculating not just when user searches,
but when user moves map bounds? */
map.addListener('bounds_changed', function() {
console.log(searchBox.getBounds());
})
|
JavaScript
| 0 |
@@ -302,48 +302,9 @@
ns);
-%0D%0A%0D%0A%09// add search box%0D%0A%09addSearchBox();
+%09
%0D%0A%7D%0D
@@ -4405,24 +4405,41 @@
initMap();%0D%0A
+addSearchBox();%0D%0A
%0D%0A%0D%0A%0D%0A%0D%0A/*--
|
bbcf737e7dbb4f11e41ccb26bb8c34c8d36cd96f
|
Remove strikethrough on successful recipe
|
js/rrg.js
|
js/rrg.js
|
var recipe_id;
function fetchInsane() {
fetchRecipe(true);
}
function fetchRecipe(insane=false) {
var api_url = "https://rrg.jamesoff.net/recipe";
if (insane) {
api_url += '-insane'
}
$.getJSON(api_url, function(data) {
$("div#recipe").replaceWith(
formatRecipe(data)
);
$("div#share").replaceWith(
"<div id='share'><input id='share' type='button' value='Get share link' onclick='shareRecipe()' /></div>"
);
recipe_id = data.metadata.recipe_id;
location.hash = '';
} )
.fail(function() {
formatRecipeError();
$("div#share").replaceWith(
"<div id='share'></div>"
);
recipe_id = '';
} );
}
function formatRecipeError() {
$("div#recipe").replaceWith("<div id='recipe'>Oh no, dropped all the ingredients on the floor, sorry :(<br /></div>");
$("div#yum").replaceWith("<div id='yum' style='text-decoration: line-through'>Yum.</div>");
}
function formatRecipe(data) {
var HTML = '<div id="recipe">';
HTML += '<div style="float: right">Serves ' + data.serves + '</div>';
HTML += '<h2>' + data.title + '</h2>';
HTML += 'You will need:<ul class="recipe_needs">';
data.ingredients.forEach(function(i) {
HTML += "<li>" + i + "</li>";
});
HTML += "</ul>";
HTML += "Instructions:";
HTML += "<ol class='recipe_instr'>";
data.steps.forEach(function(s) {
HTML += "<li>" + s + "</li>";
});
HTML + "</ol>";
HTML += "</div>";
return HTML;
}
function writeSharebutton() {
$("div#share").replaceWith(
"<div id='share'><input id='share' type='button' value='Get share link' onclick='shareRecipe()' /></div>"
);
}
function clearShareButton() {
$("div#share").replaceWith(
"<div id='share'></div>"
);
}
function fetchSpecificRecipe(rid) {
$.getJSON("https://rrg.jamesoff.net/" + rid + ".json", function(data) {
$("div#recipe").replaceWith(
formatRecipe(data)
);
recipe_id = rid;
giveShareLink()
} )
.fail(function() {
formatRecipeError();
clearShareButton();
recipe_id = '';
} );
}
function shareRecipe() {
if (recipe_id == '') {
return false;
}
$.getJSON("https://rrg.jamesoff.net/recipe-persist/" + recipe_id, function(data) {
giveShareLink();
} )
.fail(function() {
giveShareFailure();
} );
}
function giveShareLink() {
var share_url = 'https://jamesoff.net/rrg/' + recipe_id;
$("div#share").replaceWith(
"<div id='share'>Sharable link: <a href='" + share_url + "'>" + share_url + "</a></div>"
);
}
function giveShareFailure() {
$("div#share").replaceWith(
"<div id='share'><input id='share' type='button' value='Get share link' onclick='shareRecipe()' /> An error occurred while generating the share link.</div>"
);
}
function loadHandler() {
var recipe_id = window.location.hash.substr(1);
if (recipe_id == "") {
fetchRecipe();
}
else {
fetchSpecificRecipe(recipe_id);
}
}
$(window).load(loadHandler());
$(document).keydown(function (e) {
if (e.which == 82) {
// r
fetchRecipe();
return false;
}
if (e.which == 73) {
// i
fetchInsane();
return false;
}
});
|
JavaScript
| 0.000001 |
@@ -480,32 +480,94 @@
iv%3E%22%0A );%0A
+ $(%22div#yum%22).replaceWith(%22%3Cdiv id='yum'%3EYum.%3C/div%3E%22);%0A
recipe_i
|
ed37b715f75d1ecfa288f9b17e6cf68690ad89a8
|
make some Square react things
|
js/web.js
|
js/web.js
|
import React from "react";
const board = require("./board.js")
console.log("white = " + board.WHITE)
// TODO: render a pieceless chessboard
const App = React.createClass({
getInitialState() {
return { board: new board.Board() }
},
render() {
return (
<div>
hello react world!
</div>
);
}
})
const Square = React.createClass({
render() {
const size = 50
let style = {
left: this.props.x * size,
bottom: this.props.y * size,
}
if ((this.props.x + this.props.y) % 2 == 0) {
// Dark square
} else {
// Light square
}
}
})
React.render(<App/>, document.body);
|
JavaScript
| 0.000003 |
@@ -261,55 +261,213 @@
-return (%0A %3Cdiv%3E%0A hello react world!
+let squares = %5B%5D%0A for (let x = 0; x %3C 8; x++) %7B%0A for (let y = 0; y %3C 8; y++) %7B%0A squares.push(%3CSquare x=%7Bx%7D y=%7By%7D /%3E)%0A %7D%0A %7D%0A%0A return (%0A %3Cdiv className=%22board%22%3E%0A %7Bsquares%7D
%0A
|
06dd1106c635228fa21bad70db090a26b890da76
|
Move audio from view to controller
|
scripts/explore/ExploreJointSourceController.js
|
scripts/explore/ExploreJointSourceController.js
|
var ExploreJointSourceController = JointSourceController.createComponent("ExploreJointSourceController");
ExploreJointSourceController.createViewFragment = function () {
return cloneTemplate("#template-explore-jointsource");
};
ExploreJointSourceController.defineAlias("model", "jointSource");
ExploreJointSourceController.defineMethod("initView", function initView() {
if (!this.view) return;
setElementProperty(this.view, "jointsource-id", this.jointSource.jointSourceId);
this.view.style.order = - this.jointSource.jointSourceId;
this.view.querySelector("[data-ica-action='edit-jointsource']").addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
var fragment = PublisherJointSourceController.createViewFragment();
var element = fragment.querySelector(".publisher");
document.body.appendChild(fragment);
new PublisherJointSourceController(this.controller.jointSource, element);
}.bind(this.view));
this.view.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
var map = new Map([this.controller.jointSource]);
var fragment = MapController.createViewFragment();
var element = fragment.querySelector(".map");
document.body.appendChild(fragment);
new MapController(map, element);
}.bind(this.view));
this.view.addEventListener("mouseover", function mouseOver() {
if (this.audio) {
this.audio.play();
}
}.bind(this.view));
this.view.addEventListener("mouseout", function mouseOver() {
if (this.audio) {
this.audio.pause();
this.audio.currentTime = 0;
}
}.bind(this.view));
});
ExploreJointSourceController.defineMethod("updateView", function updateView() {
if (!this.view) return;
// Reset view
var parentNode = this.view.parentNode;
var fragment = this.constructor.createViewFragment();
var element = fragment.querySelector(".jointsource");
parentNode.replaceChild(fragment, this.view);
this.uninitView();
this._view = element;
this.initView(false);
this.view.querySelectorAll("[data-ica-jointsource-meta]").forEach(function (element) {
element.textContent = this.jointSource.meta[getElementProperty(element, "jointsource-meta")];
}.bind(this));
var imageSources = this.jointSource.imageSources;
if (imageSources.length > 0) {
var imageSource = imageSources[0];
if (imageSource.content) {
this.view.classList.add("dark");
this.view.querySelector(".jointsource-backdrop-image").style.backgroundImage = imageSource.content
? "url(" + (
imageSource.blobHandler.blob instanceof Blob
? imageSource.blobHandler.url
: imageSource.blobHandler.url + "?width=" + (2 * this.view.offsetWidth * this.devicePixelRatio)
) + ")"
: "";
}
}
var audioSources = this.jointSource.audioSources;
if (audioSources.length > 0) {
var audioSource = audioSources[0];
if (audioSource.content) {
var audio = new Audio(audioSource.blobHandler.url);
this.view.audio = audio;
}
}
});
ExploreJointSourceController.defineMethod("uninitView", function uninitView() {
if (!this.view) return;
removeElementProperty(this.view, "jointsource-id");
});
/*****/
function empty(value) {
if (Array.isArray(value)) return value.length == 0;
return !value;
}
|
JavaScript
| 0 |
@@ -1398,32 +1398,43 @@
%7B%0A if (this.
+controller.
audio) %7B%0A t
@@ -1433,24 +1433,35 @@
%0A this.
+controller.
audio.play()
@@ -1564,24 +1564,35 @@
if (this.
+controller.
audio) %7B%0A
@@ -1595,24 +1595,35 @@
%0A this.
+controller.
audio.pause(
@@ -1636,16 +1636,27 @@
this.
+controller.
audio.cu
@@ -3096,21 +3096,16 @@
this.
-view.
audio =
|
df09f1a85e335f6282bf9393683b5c0513349933
|
fix order of entries after sort
|
scripts/magickartenmarkt.de/browse-view.user.js
|
scripts/magickartenmarkt.de/browse-view.user.js
|
// ==UserScript==
// @name browse view: cleaner view by hiding duplicate name information
// @description magiccardmarket.eu, magickartenmarkt.de
// @version 0.0.1
// @namespace https://github.com/solygen/userscripts
// @repository https://github.com/solygen/userscripts.git
// @license MIT
// @require https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js
//
// @include https://www.magickartenmarkt.de/?mainPage=browseUserProducts*
// @include https://www.magiccardmarket.eu/?mainPage=browseUserProducts*
// @include https://fr.magiccardmarket.eu/?mainPage=browseUserProducts*
// @include https://es.magiccardmarket.eu/?mainPage=browseUserProducts*
// @include https://id.magiccardmarket.eu/?mainPage=browseUserProducts*
//
// @updateURL https://rawgithub.com/solygen/userscripts/master/scripts-min/magickartenmarkt.de/browse-view-min.user.js
// @downloadURL https://rawgithub.com/solygen/userscripts/master/scripts-min/magickartenmarkt.de/browse-view-min.user.js
// @homepage https://github.com/solygen/userscripts
// ==/UserScript==
(function () {
'use strict';
var $summary = $('.navBarTopText').length ? $($('.navBarTopText').children()[0]) : $($('#siteContents').children()[2]),
$table = $('tbody'),
$rows = $('tbody').find('tr'),
list = $($.find('.col_2')).find('a'),
hits = 0,
//flag green
tolerance = 0.1,
pricelevel = [],
lastname;
//sort cards (name, price)
(function sortCards() {
$rows.sort(function(a, b){
//hack: +1000 to get right sort order (e.g. 8, 12, 102)
var keyA = $(a).find('.col_2').text() + parseFloat($(a).find('.col_9').text().trim(), 10) + 1000,
keyB = $(b).find('.col_2').text() + parseFloat($(b).find('.col_9').text().trim(), 10) + 1000;
return keyA.localeCompare(keyB);
});
}());
//apply order
(function applyOrder() {
$table.empty();
$.each($rows, function (index, row){
$table.append(row);
});
}());
//add column header
(function addColumnHeader() {
var header = $('.col_price').clone();
header
.removeClass('col_price')
.addClass('col_price_sold')
.html('∅')
.insertBefore($('.col_price'));
//expand footer row
$('.footerCell_0').attr('colspan', 13);
}());
function addCell(row) {
var cell = row.find('.col_9').clone();
cell
.removeClass('col_9')
.addClass('col_9a')
.insertBefore(row.find('.col_9'));
}
function colorizePrice(price, saleprice, row) {
if (!price) {
return;
} else if (saleprice <= parseFloat(price, 10) + tolerance) {
row.find('.col_9').css('color', 'green');
} else {
row.find('.col_9').css('color', 'red');
}
}
function getSalePrice($row) {
var salesprice = $row
.find('.col_9')
.text()
.replace(',', '.')
.replace('€', '')
.trim();
return parseFloat(salesprice, 10);
}
function setLevel() {
var level,
sum = 0;
//sum
$.each(pricelevel, function() {
sum += parseFloat(this) || 0;
});
//average
level = Math.round(sum/pricelevel.length*100)/100;
//add level to dom
$('.H1_PageTitle').text($('.H1_PageTitle').text() + ' (' + level + ')')
}
//process entries
$.each(list, function (index, value) {
var $namecell = $(value),
$row = $($namecell.parent().parent()),
name = $namecell.text(),
price = localStorage.getItem(name),
salesprice = getSalePrice($row);
//average price (sold)
addCell($row);
colorizePrice(price, salesprice, $row);
//set content of new cell and apply style
if (name === lastname) {
$namecell.empty();
$row.css('font-weight', 100)
.find('.col_9a').empty();
} else {
hits++;
pricelevel.push(salesprice / (price || salesprice));
$row.find('.col_9a')
.text(price ? (price + ' €')
.replace('.', ',') : '');
}
//remember name
lastname = name;
});
//show price level
setLevel();
//update hits value
$summary.text(hits + ' hits');
})();
|
JavaScript
| 0.000005 |
@@ -1348,40 +1348,8 @@
list
- = $($.find('.col_2')).find('a')
,%0A
@@ -3660,16 +3660,58 @@
entries%0A
+ list = $($.find('.col_2')).find('a');%0A
$.ea
|
e4c987b2720f54504b88e2c5d9e8fe166465dde1
|
use UUID
|
GPIOBridge.js
|
GPIOBridge.js
|
/*
* GPIOBridge.js
*
* David Janes
* IOTDB.org
* 2014-04-30
*
* Copyright [2013-2016] [David P. Janes]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
var fs = require('fs')
var child_process = require('child_process')
var rpi = require('./rpi');
var iotdb = require('iotdb');
var _ = iotdb._;
var logger = iotdb.logger({
name: 'homestar-gpio',
module: 'GPIOBridge',
});
/* --- constructor --- */
/**
* See {iotdb.bridge.Bridge#Bridge} for documentation.
* <p>
* @param {object|undefined} native
* only used for instances, should be
*/
var GPIOBridge = function (initd, native) {
var self = this;
self.initd = _.defaults(
initd,
iotdb.keystore().get("bridges/GPIOBridge/initd"),
{}
);
self.native = native;
self.istate = {};
};
GPIOBridge.prototype = new iotdb.Bridge();
GPIOBridge.prototype.name = function () {
return "GPIOBridge";
};
/* --- lifecycle --- */
/**
* See {iotdb.bridge.Bridge#discover} for documentation.
*/
GPIOBridge.prototype.discover = function () {
var self = this;
if (!self.initd.init) {
console.log(self.initd);
logger.error({
method: "discover",
cause: "you must define 'init' for the Thing - otherwise how would we know?",
}, "no 'pins'");
}
logger.info({
method: "discover",
init: self.initd.init,
}, "called");
var bridge;
var native;
if (rpi.check()) {
native = new rpi.Delegate();
bridge = new GPIOBridge(self.initd, native);
} else {
return;
}
/* complex but it works - we want to do setup before the offical discovery */
bridge._setup(function(error) {
if (error) {
logger.error({
method: "discover/_setup",
error: error,
}, "error while setting up pins");
return;
}
logger.info({
method: "_setup",
}, "discovered");
self.discovered(bridge);
});
};
/**
*/
GPIOBridge.prototype._setup = function (done) {
this.native.setup(this, done);
};
/**
* See {iotdb.bridge.Bridge#connect} for documentation.
*/
GPIOBridge.prototype.connect = function (connectd) {
var self = this;
if (!self.native) {
return;
}
self._validate_connect(connectd);
self.native.connect(self, connectd);
process.nextTick(function() {
self.pull();
});
};
GPIOBridge.prototype._forget = function () {
var self = this;
if (!self.native) {
return;
}
logger.info({
method: "_forget"
}, "called");
self.native = null;
self.pulled();
};
/**
* See {iotdb.bridge.Bridge#disconnect} for documentation.
*/
GPIOBridge.prototype.disconnect = function () {
var self = this;
if (!self.native || !self.native) {
return;
}
self._forget();
};
/* --- data --- */
/**
* See {iotdb.bridge.Bridge#push} for documentation.
*/
GPIOBridge.prototype.push = function (pushd, done) {
var self = this;
if (!self.native) {
done(new Error("not connected", pushd));
return;
}
self._validate_push(pushd, done);
logger.info({
method: "push",
pushd: pushd
}, "push");
self.native.push(self, pushd, done);
};
/**
* See {iotdb.bridge.Bridge#pull} for documentation.
*/
GPIOBridge.prototype.pull = function () {
var self = this;
if (!self.native) {
return;
}
// self.native.pull(self);
};
/* --- state --- */
/**
* See {iotdb.bridge.Bridge#meta} for documentation.
*/
GPIOBridge.prototype.meta = function () {
var self = this;
if (!self.native) {
return;
}
return {
"iot:thing-id": _.id.thing_urn.unique("GPIO", self.native.uuid, self.initd.number),
"schema:name": self.native.name || "GPIO",
// "iot:thing-number": self.initd.number,
// "iot:device-id": _.id.thing_urn.unique("GPIO", self.native.uuid),
// "schema:manufacturer": "",
// "schema:model": "",
};
};
/**
* See {iotdb.bridge.Bridge#reachable} for documentation.
*/
GPIOBridge.prototype.reachable = function () {
return this.native !== null;
};
/**
* See {iotdb.bridge.Bridge#configure} for documentation.
*/
GPIOBridge.prototype.configure = function (app) {};
/*
* API
*/
exports.Bridge = GPIOBridge;
|
JavaScript
| 0.999847 |
@@ -1283,65 +1283,442 @@
%7B
-%7D%0A );%0A%0A self.native = native;%0A self.istate = %7B%7D;
+%0A uuid: null, %0A %7D,%0A );%0A%0A self.native = native;%0A%0A if (self.native) %7B%0A self.istate = %7B%7D;%0A if (!self.initd.uuid) %7B%0A logger.error(%7B%0A method: %22GPIOBridge%22,%0A initd: self.initd,%0A cause: %22caller should initialize with an 'uuid', used to uniquely identify things over sessions%22,%0A %7D, %22missing initd.uuid - problematic%22);%0A %7D%0A %7D
%0A%7D;%0A
@@ -4719,287 +4719,19 @@
elf.
-native.uuid, self.initd.number),%0A %22schema:name%22: self.native.name %7C%7C %22GPIO%22,%0A%0A // %22iot:thing-number%22: self.initd.number,%0A // %22iot:device-id%22: _.id.thing_urn.unique(%22GPIO%22, self.native.uuid),%0A // %22schema:manufacturer%22: %22%22,%0A // %22schema:model%22: %22%22
+initd.uuid)
,%0A
|
bdb35a5e3cc4e10edc6ebdd4d48214177c474e5b
|
Optimize QOR Fixer
|
admin/views/assets/javascripts/qor/qor-fixer.js
|
admin/views/assets/javascripts/qor/qor-fixer.js
|
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node / CommonJS
factory(require('jquery'));
} else {
// Browser globals.
factory(jQuery);
}
})(function ($) {
'use strict';
var $window = $(window);
var NAMESPACE = 'qor.fixer';
var EVENT_ENABLE = 'enable.' + NAMESPACE;
var EVENT_DISABLE = 'disable.' + NAMESPACE;
var EVENT_RESIZE = 'resize.' + NAMESPACE;
var EVENT_SCROLL = 'scroll.' + NAMESPACE;
function QorFixer(element, options) {
this.$element = $(element);
this.options = $.extend({}, QorFixer.DEFAULTS, $.isPlainObject(options) && options);
this.$clone = null;
this.init();
}
QorFixer.prototype = {
constructor: QorFixer,
init: function () {
var $this = this.$element;
if ($this.is(':hidden') || $this.find('tbody:visible > tr:visible').length <= 1) {
return;
}
this.$thead = $this.find('thead:first');
this.$tbody = $this.find('tbody:first');
this.$tfoot = $this.find('tfoot:first');
this.resize();
this.bind();
},
bind: function () {
$window
.on(EVENT_SCROLL, $.proxy(this.toggle, this))
.on(EVENT_RESIZE, $.proxy(this.resize, this));
},
unbind: function () {
$window
.off(EVENT_SCROLL, this.toggle)
.off(EVENT_RESIZE, this.resize);
},
build: function () {
var $this = this.$element;
var $thead = this.$thead;
var $tbody = this.$tbody;
var $tfoot = this.$tfoot;
var $clone = this.$clone;
var $items = $thead.find('> tr').children();
this.offsetTop = $this.offset().top;
this.maxTop = $this.outerHeight() - $thead.height() - $tbody.find('> tr:last').height() - $tfoot.height();
if (!$clone) {
this.$clone = $clone = $thead.clone().prependTo($this);
}
$clone.
css({
position: 'fixed',
top: 0,
zIndex: 1,
display: 'none',
width: $thead.width()
}).
find('> tr').
children().
each(function (i) {
$(this).width($items.eq(i).width());
});
},
unbuild: function () {
this.$clone.remove();
},
toggle: function () {
var $clone = this.$clone;
var top = $window.scrollTop() - this.offsetTop;
if (top > 0 && top < this.maxTop) {
$clone.show();
} else {
$clone.hide();
}
},
resize: function () {
this.build();
this.toggle();
},
destroy: function () {
this.unbind();
this.unbuild();
this.$element.removeData(NAMESPACE);
},
};
QorFixer.DEFAULTS = {};
QorFixer.plugin = function (options) {
return this.each(function () {
var $this = $(this);
var data = $this.data(NAMESPACE);
var fn;
if (!data) {
$this.data(NAMESPACE, (data = new QorFixer(this, options)));
}
if (typeof options === 'string' && $.isFunction(fn = data[options])) {
fn.call(data);
}
});
};
$(function () {
var selector = '.qor-list';
$(document)
.on(EVENT_DISABLE, function (e) {
QorFixer.plugin.call($(selector, e.target), 'destroy');
})
.on(EVENT_ENABLE, function (e) {
QorFixer.plugin.call($(selector, e.target));
})
.triggerHandler(EVENT_ENABLE);
});
return QorFixer;
});
|
JavaScript
| 0.000001 |
@@ -942,24 +942,16 @@
d('tbody
-:visible
%3E tr:vi
@@ -1566,72 +1566,8 @@
ad;%0A
- var $tbody = this.$tbody;%0A var $tfoot = this.$tfoot;%0A
@@ -1650,165 +1650,8 @@
);%0A%0A
- this.offsetTop = $this.offset().top;%0A this.maxTop = $this.outerHeight() - $thead.height() - $tbody.find('%3E tr:last').height() - $tfoot.height();%0A%0A
@@ -2162,81 +2162,383 @@
ar $
-clone = this.$clone;%0A var top = $window.scrollTop() - this.offsetTop
+this = this.$element;%0A var $clone = this.$clone;%0A var offset = $this.offset();%0A var top = $window.scrollTop() - offset.top;%0A var theadHeight = this.$thead.height();%0A var tbodyHeight = this.$tbody.find('%3E tr:last').height();%0A var tfootHeight = this.$tfoot.height();%0A var maxTop = $this.outerHeight() - theadHeight - tbodyHeight - tfootHeight
;%0A%0A
@@ -2563,21 +2563,16 @@
& top %3C
-this.
maxTop)
|
729cbf384f9d9ba37947f593d3386e640bc3a8ee
|
improve code readability
|
administration/static/js/courses/controllers.js
|
administration/static/js/courses/controllers.js
|
(function(angular){
'use strict';
var app = angular.module('courses');
app.controller('CourseListController', [
'$scope', 'Course',
function ($scope, Course) {
$scope.courseList = [];
$scope.ordering = 'id';
$scope.reverse = false;
$scope.filters = {
all: false,
published : true,
listed : true,
draft : true,
textsearch: '',
check : function(course){
return (
$scope.filters.all || ($scope.filters[course.status])
) && (
!$scope.filters.textsearch ||
course.name.toLowerCase().indexOf($scope.filters.textsearch.toLowerCase()) >= 0
);
}
};
Course.query(function(list){
$scope.courseList = list;
});
}
]);
})(window.angular);
|
JavaScript
| 0.001398 |
@@ -542,94 +542,153 @@
-return (%0A $scope.filters.all %7C%7C ($scope.filters%5Bcourse.status%5D)
+var f = $scope.filters;%0A var search = f.textsearch.toLowerCase();%0A var target = course.name.toLowerCase();%0A
%0A
@@ -708,12 +708,14 @@
-) &&
+return
(%0A
@@ -741,141 +741,116 @@
-!$scope.filters.textsearch %7C%7C%0A course.name.toLowerCase().indexOf($scope.filters.textsearch.toLowerCase()) %3E= 0
+f.all %7C%7C f%5Bcourse.status%5D%0A ) && (%0A !search %7C%7C target.match(search)
%0A
|
06e5ff50186714f5aa1116cd19f61d7c98f9c252
|
revise some comments
|
GulpConfig.js
|
GulpConfig.js
|
/**
* + Project Config
* =====================================================================
*/
module.exports = (function(config) {
var path = require('path');
// project paths
config.paths = (function(p) {
p.root = process.cwd();
p.bower = path.join(p.root, 'bower_components');
p.node = path.join(p.root, 'node_modules');
p.app = path.join(p.root, 'app');
p.src = path.join(p.root, 'src');
p.web = path.join(p.root, 'web');
p.site = path.join(p.src, 'site');
p.templates = path.join(p.src, 'templates');
p.assetsSrc = path.join(p.site, 'assets');
p.assetsDev = path.join(p.src, 'assets-dev');
p.assets = path.join(p.web, 'assets');
return p;
})({});
// metadata
config.metadata = {
siteTitle: 'simbo.ninja',
siteDescription: 'Some informative description for search engine results.',
baseUrl: '//simbo.ninja/',
styles: [
'assets/css/main.css'
],
scripts: [
'assets/js/main.js'
],
dateLocale: 'de',
dateFormat: 'Do MMM YYYY',
dateFormatShort: 'DD.MM.YY',
dateFormatLong: 'dddd, Do MMMM YYYY'
};
// metadata changes depending on environment
config.metadata.environments = {
development: {
baseUrl: '//localhost:8080/',
googleAnalytics: false
}
};
// get jQuery version from package.json
config.metadata.jqueryVersion = (function() {
var pkg = require(process.cwd() + '/package.json');
return pkg.devDependencies.hasOwnProperty('jquery') ? pkg.devDependencies.jquery.replace(/[^.0-9]/g, '') : '';
})();
// template function to get the hash of a file
config.metadata.hash = function(file, algorithm) {
var crypto = require('crypto');
if (!algorithm || crypto.getHashes().indexOf(algorithm)===-1) {
algorithm = 'md5';
}
var fs = require('fs'),
fileContents = fs.readFileSync(path.join(config.paths.root, file));
return crypto
.createHash(algorithm)
.update(fileContents, 'utf8')
.digest('hex');
}
// gulp default params
config.gulpParams = {
environment: 'production'
};
// global watch task options
config.watch = {
mode: 'auto'
};
// marked options
config.marked = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false
};
// stylus options
config.stylus = {
// add imports and vendor folders to @import path
paths: [
path.join(config.paths.assetsDev, 'stylus/imports'),
path.join(config.paths.assetsDev, 'vendor'),
path.join(config.paths.assetsSrc, 'img')
],
// function for generating base64 data-uris
url: {
name: 'inline-url',
limit: false
},
// create sourcemaps containing inline sources
sourcemap: {
inline: true,
sourceRoot: '.',
basePath: path.join(path.relative(config.paths.web, config.paths.assets), 'css')
}
};
// autoprefixer options
config.autoprefixer = {
browsers: [
'last 2 versions',
'> 2%',
'Opera 12.1',
'Firefox ESR'
]
};
// csslint options
// https://github.com/CSSLint/csslint/wiki/Rules-by-ID
config.csslint = {
'box-sizing': false,
'bulletproof-font-face': false,
'font-faces': false,
'compatible-vendor-prefixes': false
};
// config sync options
// https://github.com/danlevan/gulp-config-sync
config.configSync = {
fields: [
'name',
'version',
'description',
'keywords',
'version',
'private'
],
space: 2
};
return config;
})({});
/* = Project Config */
|
JavaScript
| 0 |
@@ -2,23 +2,20 @@
**%0A * +
-Project
+Gulp
Config%0A
@@ -4299,15 +4299,12 @@
* =
-Project
+Gulp
Con
|
d9d737a14c16279779f2fe9066925aca381296b6
|
Update task reducer
|
desktop/reactified/client/src/reducers/task.js
|
desktop/reactified/client/src/reducers/task.js
|
const taskReducer = (state=[], action) => {
switch (action.type) {
case 'ADD_TASK':
return [
...state,
action.task
];
case 'DO_TASK':
return [
...state.slice(0, action.index),
{
...state[action.index],
done: true,
},
...state.slice(action.index + 1),
];
case 'EDIT_TASK':
return [
...state.slice(0, action.index),
action.newTask,
...state.slice(action.index + 1),
];
case 'DELETE_TASK':
return [
...state.slice(0, action.index),
...state.slice(action.index + 1),
];
default:
return state;
}
};
export default taskReducer;
|
JavaScript
| 0.000002 |
@@ -439,22 +439,89 @@
-action.newTask
+%7B%0A ...state%5Baction.index%5D,%0A task: action.newTask.task%0A %7D
,%0A
|
a25b25524046c9318b3fee7ddb1519237d2f4231
|
fix start gold
|
clickingsagajavascript.js
|
clickingsagajavascript.js
|
var progress = 0
var pps = 1
var goldpertick = 1
var goldcount = 2
var increasegoldproductionrateprice = 1
var increasegoldamountrateprice = 10
var pbar = document.getElementById("progressbar");
var golddisplay = document.getElementById("gold");
var clickcollectgold = document.getElementById("collectgold");
golddisplay.innerHTML = "Gold: " + goldcount;
function updateprogress() {
pbar.value = progress;
}
document.getElementById('collectgold').onclick = function() {
if (progress > 999) {
progress = 0
goldcount += goldpertick
golddisplay.innerHTML = "Gold: " + goldcount;
updateprogress()
}
}
document.getElementById('speed').onclick = function() {
if (goldcount > increasegoldproductionrateprice - 1) {
goldcount -= increasegoldproductionrateprice
golddisplay.innerHTML = "Gold: " + goldcount;
increasegoldproductionrateprice = Math.ceil(increasegoldproductionrateprice = Math.pow(pps,2) * 0.4)
document.getElementById('speed').innerHTML = "Increase Production Rate for " + increasegoldproductionrateprice + " gold"
pps += 1;
}
}
document.getElementById('amount').onclick = function() {
if (goldcount > increasegoldamountrateprice - 1) {
goldcount -= increasegoldamountrateprice
golddisplay.innerHTML = "Gold: " + goldcount;
increasegoldamountrateprice += increasegoldamountrateprice * 2
goldpertick = goldpertick * 2
document.getElementById('amount').innerHTML = "Increase Amount Found for " + increasegoldamountrateprice + " gold";
}
}
setInterval(function() {
progress += pps;
updateprogress()
},10);
|
JavaScript
| 0.000001 |
@@ -58,17 +58,17 @@
count =
-2
+0
%0A%0A%0Avar i
|
e0951a60f6bc0abf9651f6be72ed6d4bd7bfc95d
|
Change button styles to flat button
|
client/components/Book.js
|
client/components/Book.js
|
import React from 'react';
import { Link } from 'react-router-dom';
const Book = (props) => {
const { book } = props;
return (
<div className="col s12 m6 l4">
<div className="card">
<div className="card-image">
<img src = { book.imageURL } className="responsive-img" />
<Link to= { `/books/${book.id}`} className="btn-floating halfway-fab waves-effect waves-light small red">
<i className="material-icons">chevron_right</i>
</Link>
</div>
<div className="card-content">
<span className="card-title truncate grey-text text-darken-4"> { book.title } </span>
<p> Author| <span className="red-text text-darken-4 bold"> { book.author} </span></p>
<p> Genre| <span className="red-text text-darken-4 bold"> {book.subject} </span></p>
<p> Quantity| <span className="red-text text-darken-4 bold"> { book.quantity} </span></p>
<div className="divider"></div>
<div className="row">
<div className="col s3 btn btn-small white teal-text book-icon"><i className="material-icons prefix">thumb_up</i><span>{book.upvotes}</span></div>
<div className="col s3 btn btn-small white teal-text book-icon"><i className="material-icons prefix">favorite_border</i><span>{book.favCount}</span></div>
<div className="col s3 btn btn-samll white teal-text book-icon"><i className="material-icons prefix">comment</i><span>{book.bookReviews.length}</span></div>
</div>
</div>
</div>
</div>
);
};
export default Book;
|
JavaScript
| 0.000001 |
@@ -1194,32 +1194,41 @@
3 btn btn-small
+btn-flat
white teal-text
@@ -1382,16 +1382,25 @@
n-small
+btn-flat
white te
@@ -1570,16 +1570,25 @@
n-samll
+btn-flat
white te
|
6ca975fde5c70746fee59223ed0588f220613b7f
|
fix add/rm lines and check empty val
|
client/contents/styles.js
|
client/contents/styles.js
|
var ace = AceEditor.instance();
angular.module('domegis')
.directive('domegisStyles', [
function() {
return {
restrict: 'E',
templateUrl: 'client/contents/styles.html',
scope: {
content: '='
},
controller: [
'$scope',
'$reactive',
'$compile',
function($scope, $reactive, $compile) {
$scope.aceOption = {
mode: 'css',
useWrapMode: false,
showGutter: false,
theme: 'github'
};
$scope.table = {
title: 'table'
};
$scope.styles = {
polygon: {
composite: '',
fill: {
color: '#f00',
opacity: .8,
},
stroke: {
color: '#0f0',
width: 1,
opacity: .8
}
},
marker: {
composite: '',
fill: {
width: 10,
color: '#00f',
opacity: 1
},
stroke: {
color: '#0f0',
width: .5,
opacity: .8
}
}
};
var mapCarto = {
'polygon': {
'polygon-fill': 'fill.color',
'polygon-opacity': 'fill.opacity',
'polygon-comp-op': 'composite',
'line-color': 'stroke.color',
'line-width': 'stroke.width',
'line-opacity': 'stroke.opacity'
},
'marker': {
'marker-width': 'fill.width',
'marker-fill': 'fill.color',
'marker-fill-opacity': 'fill.opacity',
'marker-comp-op': 'composite',
'marker-line-color': 'stroke.color',
'marker-line-width': 'stroke.width',
'marker-line-opacity': 'stroke.opacity'
}
};
var getProp = function(type, name) {
var val = '';
if(mapCarto[type][name]) {
return eval('$scope.styles.' + type + '.' + mapCarto[type][name]);
}
return val;
}
function regexEscape(str) {
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
$scope.cartocss = '';
var tableRegex = new RegExp(regexEscape('#' + $scope.table.title + ' {') + '([\\s\\S]*?)}');
// Update styles object from raw CartoCSS
$scope.$watch('cartocss', function(cartocss) {
var tableMatch = cartocss.match(tableRegex);
if(tableMatch != null && tableMatch[1]) {
for(var type in mapCarto) {
if($scope.isType(type)) {
for(var prop in mapCarto[type]) {
var propRegex = new RegExp(regexEscape(prop) + ':(.*?);');
var propMatch = cartocss.match(propRegex);
if(propMatch != null) {
eval('$scope.styles.' + type + '.' + mapCarto[type][prop] + ' = propMatch[1].trim().toLowerCase()');
}
}
}
}
}
});
// Update CartoCSS output from styles object
$scope.$watch('styles', function(styles, prevStyles) {
var tableMatch = $scope.cartocss.match(tableRegex);
var cartocss = '';
if(tableMatch != null && tableMatch[1]) {
cartocss = tableMatch[1];
}
for(var type in mapCarto) {
if($scope.isType(type)) {
for(var prop in mapCarto[type]) {
var propRegex = new RegExp(regexEscape(prop) + ':(.*?);');
var propMatch = cartocss.match(propRegex);
var val = getProp(type, prop);
if(propMatch != null) {
if(propMatch[1].trim().toLowerCase() != val) {
cartocss = cartocss.replace(propRegex, prop + ': ' + val + ';');
}
} else {
cartocss += '\t' + prop + ': ' + val + ';\n';
}
}
}
}
if(tableMatch != null && tableMatch[1]) {
$scope.cartocss = $scope.cartocss.replace(tableRegex, '#' + $scope.table.title + ' {' + cartocss + '}');
} else {
$scope.cartocss = '#' + $scope.table.title + ' {\n' + cartocss + '}';
}
}, true);
$scope.composites = {
'': 'None',
'multiply': 'Multiply',
'screen': 'Screen',
'overlay': 'Overlay',
'darken': 'Darken',
'lighten': 'Lighten',
'color-dodge': 'Color dodge',
'color-burn': 'Color burn'
};
$scope.types = ['polygon', 'marker'];
$scope.isType = function(type) {
return $scope.types.indexOf(type) !== -1;
};
$scope.properties = [
{
key: 'amount',
type: 'number',
values: [1,2,3,4,5,6,7,8,9,10]
},
{
key: 'category',
type: 'string',
values: ['category 1', 'category 2', 'category 3']
}
];
}
]
}
}
])
|
JavaScript
| 0 |
@@ -3728,32 +3728,39 @@
ex = new RegExp(
+'%5Ct' +
regexEscape(prop
@@ -3763,32 +3763,34 @@
prop) + ':(.*?);
+%5Cn
');%0A
@@ -3921,32 +3921,163 @@
atch != null) %7B%0A
+ var rep = '';%0A if(val !== '')%0A rep = '%5Ct' + prop + ': ' + val + ';%5Cn';%0A
@@ -4192,31 +4192,11 @@
ex,
-prop + ': ' + val + ';'
+rep
);%0A
@@ -4235,32 +4235,69 @@
%7D else %7B%0A
+ if(val !== '')%0A
|
5b7b5fc32729c7b27029f584a745ce2bea49ca81
|
Fix typo
|
client/lib/audioplayer.js
|
client/lib/audioplayer.js
|
AudioPlayer = {
audioElement: new Audio(),
canPlay: function(song) {
var self = this;
return self.audioElement.canPlayType(song.mime);
},
load: function(song, successCallback, errorCallback, options) {
var self = this;
if(self.audioElement.currentSrc) {
self.audioElement.pause();
Session.set('currentSong', undefined);
}
var successCallback2 = function() {
Session.set('currentSong', song);
if(successCallback) {
successCallback();
}
};
var errorCallback2 = function(error) {
if(!(error instanceof Error)) {
error = new Error(error);
}
if(errorCallback) {
errorCallback(error);
}
};
if(song.owner == Meteo.userId()) {
self.loadFromUrl(MusicManager.localCollection.findOne({ _id: song._id }).url, successCallback2, errorCallback2);
} else if(song.url) {
self.loadFromUrl(song.url, successCallback2, errorCallback2);
} else {
MusicManager.requestSong(song.owner, song._id, function(url) {
self.loadFromUrl(url, successCallback2, errorCallback2);
}, errorCallback2, options);
}
},
loadFromUrl: function(url, successCallback, errorCallback) {
var self = this;
var loadCallback = function(url) {
self.audioElement.src = url;
self.audioElement.load();
if(successCallback) {
successCallback();
}
}
if(url.indexOf('indexeddb:') != 0) {
loadCallback(url);
} else {
MusicManager.localStorage.readFileFromUrl(url, function(fileEntry) {
loadCallback(URL.createObjectURL(fileEntry));
}, errorCallback);
}
}
}
|
JavaScript
| 0.999999 |
@@ -852,16 +852,17 @@
== Meteo
+r
.userId(
|
2560290cf8c1494102321ca2d8a36adf60e2ce16
|
Fix issue where gulp watch sass was not looking at correct files.
|
NetCore.Angular/gulpfile.js
|
NetCore.Angular/gulpfile.js
|
/// <binding BeforeBuild='moveToLibs, sass, typescript' Clean='clean' ProjectOpened='sass:watch, watch:ts' />
var gulp = require('gulp'),
ts = require('gulp-typescript'),
dest = require('gulp-dest'),
sass = require('gulp-sass'),
merge = require('merge2'),
del = require('del'),
tsProject = ts.createProject('tsconfig.json'),
paths = {
target: {
webroot: 'wwwroot',
js: 'wwwroot/js',
css: 'wwwroot/css',
lib: 'wwwroot/lib'
},
source: {
typescript: 'App/**/*.ts',
packages: [
'@angular/core/bundles',
'@angular/compiler/bundles',
'@angular/common/bundles',
'@angular/platform-browser/bundles',
'@angular/forms/bundles',
'@angular/http/bundles',
'@angular/router/bundles',
'@angular/platform-browser-dynamic/bundles',
'systemjs',
'reflect-metadata',
'rxjs',
'zone.js'
],
sass: [
'CSS/home.scss'
]
}
};
gulp.task('typescript', function () {
var result = gulp.src(paths.source.typescript)
.pipe(tsProject());
return result.js.pipe(gulp.dest(paths.target.js));
});
gulp.task('watch:ts', ['typescript'], function () {
gulp.watch(paths.source.typescript, ['typescript']);
});
gulp.task('sass', function () {
return gulp.src(paths.source.sass)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(paths.target.css));
});
gulp.task('sass:watch', function () {
gulp.watch(paths.sass, ['sass']);
});
gulp.task('moveToLibs', function () {
var merges = [];
for (var i = 0; i < paths.source.packages.length; i++) {
var to = paths.source.packages[i].replace('@', '');
merges.push(gulp.src('node_modules/' + paths.source.packages[i] + '/**/*.js').pipe(gulp.dest(paths.target.lib + '/' + to)));
merges.push(gulp.src('node_modules/' + paths.source.packages[i] + '/**/*.min.js').pipe(gulp.dest(paths.target.lib + '/' + to)));
}
return merge(merges);
});
gulp.task('clean', function () {
return del([paths.target.lib + '/*', paths.target.js + '/*', paths.target.css + '/*']);
})
|
JavaScript
| 0 |
@@ -1707,16 +1707,23 @@
h(paths.
+source.
sass, %5B'
|
c4cd57c5a2253061a3772777dd2355fa87ecb270
|
use itemsPerPage in PeopleView.js
|
PeopleView.js
|
PeopleView.js
|
/* global MainGame */
// shows FirstName, LastName, Health, Edu, Shelter
var PeopleRightView={
style: {font:"30px myKaiti", fill:"black"},
createNew: function(data){
var v=MainGame.game.make.sprite(0,0,"peopleViewRightBg");
// name, health, edu, shelter
v.data=JSON.parse(JSON.stringify(data));
// ListView: 10 items (slots)
// createNew(textures, margin, itemSize, itemCallback, isHorizontal)
v.listView=DListView.createNew(
{},
{},
{w:400, h:45},
function(index){PeopleRightView.onPersonSelected(v,index)}
);
v.addChild(v.listView);
// PageIndicator: N pages
var pageCount=Math.ceil(data.length/10);
v.pageIndicator=DPageIndicator.createNew(
pageCount,
{width:400,textPos:{x:200,y:0}},
function(index){PeopleRightView.onPageChanged(v,index)}
);
v.pageIndicator.y=440;
v.addChild(v.pageIndicator);
// setup the init page
PeopleRightView._setupPage_(v,0);
return v;
},
onPersonSelected: function(view,index){
console.log("PeopleRightView: person selected:",index);
// TODO: center the person's housing unit
},
onPageChanged: function(view,index){
console.log("PeoplePageChanged: ",index);
PeopleRightView._setupPage_(view,index);
},
_makeEntry_: function(oneEntryData){
var entrySprite=MainGame.game.make.sprite(0,0);
var entryString=""+oneEntryData.name+" | Hth:"+oneEntryData.health+" | Edu:"
+oneEntryData.edu+" | Sht:"+oneEntryData.shelter;
var entryText=MainGame.game.make.text(0,0,entryString,PeopleRightView.style);
entrySprite.addChild(entryText);
return entrySprite;
},
_setupPage_: function(view,pageIndex){
view.listView.removeAll();
var startIndex=pageIndex*10;
var endIndex=Math.min(startIndex+10,view.data.length);
for(var i=startIndex;i<endIndex;i++)
view.listView.add(PeopleRightView._makeEntry_(view.data[i]));
},
};
var PeopleView={
createNew: function(){
var pv=MainGame.game.add.sprite(0,0,'peopleViewBg');
pv.x=100, pv.y=100;
// create low people view (right)
// create low people data
var lowData=[
{name:"Sam Reha",health:50,edu:50,shelter:50},
{name:"A Math",health:20,edu:50,shelter:50},
{name:"B Dee",health:30,edu:50,shelter:50},
{name:"C Eee",health:40,edu:50,shelter:50},
{name:"D FFF",health:50,edu:50,shelter:50},
{name:"Sam2",health:50,edu:50,shelter:50},
{name:"A2 Math",health:20,edu:50,shelter:50},
{name:"B2 Dee",health:30,edu:50,shelter:50},
{name:"C2 Eee",health:40,edu:50,shelter:50},
{name:"D2 FFF",health:50,edu:50,shelter:50},
{name:"Sam3Reha",health:50,edu:50,shelter:50},
{name:"A3Math",health:20,edu:50,shelter:50},
{name:"B Dee",health:30,edu:50,shelter:50},
{name:"C3 ee",health:40,edu:50,shelter:50},
{name:"D3FFF",health:50,edu:50,shelter:50},
{name:"Sa4 Reha",health:50,edu:50,shelter:50},
{name:"A4Math",health:20,edu:50,shelter:50},
{name:"B4Dee",health:30,edu:50,shelter:50},
{name:"C4Eee",health:40,edu:50,shelter:50},
{name:"D4FFF",health:50,edu:50,shelter:50},
];
pv.right=PeopleRightView.createNew(lowData);
pv.right.x=450, pv.right.y=0;
// TBD: set a precise x
pv.addChild(pv.right);
// Class funcs
pv.setVisible=function(value){pv.visible=value};
return pv;
},
};
|
JavaScript
| 0 |
@@ -16,16 +16,68 @@
ame */%0A%0A
+// change item per page here!%0Avar itemsPerPage=10;%0A%0A
// shows
@@ -119,16 +119,16 @@
Shelter%0A
-
var Peop
@@ -364,18 +364,30 @@
stView:
-10
+%5BitemsPerPage%5D
items (
@@ -690,18 +690,28 @@
.length/
-10
+itemsPerPage
);%0A%09%09v.p
@@ -1029,32 +1029,97 @@
on(view,index)%7B%0A
+%09%09var globalIndex=view.pageIndicator.curPage*itemsPerPage+index;%0A
%09%09console.log(%22P
@@ -1152,17 +1152,23 @@
ected:%22,
-i
+globalI
ndex);%0A%09
@@ -1802,18 +1802,28 @@
geIndex*
-10
+itemsPerPage
;%0A%09%09var
@@ -1851,18 +1851,28 @@
rtIndex+
-10
+itemsPerPage
,view.da
@@ -3077,32 +3077,32 @@
50,shelter:50%7D,%0A
-
%09%09%7Bname:%22D4FFF%22,
@@ -3131,16 +3131,66 @@
er:50%7D,%0A
+%09%09%7Bname:%22Json File%22,health:50,edu:50,shelter:10%7D,%0A
%09%09%5D;%0A%0A%09%09
|
5c5769bab227dd8f1cc8f1dd58471263038ee735
|
Change file tree when changing submission
|
app/assets/javascripts/submission_statistics.js
|
app/assets/javascripts/submission_statistics.js
|
$(function() {
var ACE_FILES_PATH = '/assets/ace/';
var THEME = 'ace/theme/textmate';
var active_file = undefined;
var showFirstFile = function() {
var frame = $('.frame[data-role="main_file"]').isPresent() ? $('.frame[data-role="main_file"]') : $('.frame').first();
var file_id = frame.find('.editor').data('file-id');
$('#files').jstree().select_node(file_id);
showFrame(frame);
};
var showFrame = function(frame) {
$('.frame').hide();
frame.show();
};
var initializeFileTree = function() {
$('#files').jstree($('#files').data('entries'));
$('#files').on('click', 'li.jstree-leaf', function() {
active_file = {
filename: $(this).text(),
id: parseInt($(this).attr('id'))
};
var frame = $('[data-file-id="' + active_file.id + '"]').parent();
showFrame(frame);
});
};
if ($.isController('exercises') && $('#timeline').isPresent()) {
_.each(['modePath', 'themePath', 'workerPath'], function(attribute) {
ace.config.set(attribute, ACE_FILES_PATH);
});
var editors = $('.editor');
var slider = $('#slider>input');
var submissions = $('#data').data('submissions');
var files = $('#data').data('files');
editors.each(function(index, element) {
currentEditor = ace.edit(element);
var file_id = $(element).data('file-id');
var content = $('.editor-content[data-file-id=' + file_id + ']');
currentEditor.setShowPrintMargin(false);
currentEditor.setTheme(THEME);
currentEditor.$blockScrolling = Infinity;
currentEditor.setReadOnly(true);
var session = currentEditor.getSession();
session.setMode($(element).data('mode'));
session.setTabSize($(element).data('indent-size'));
session.setUseSoftTabs(true);
session.setUseWrapMode(true);
session.setValue(content.text());
});
slider.on('change', function(event) {
var currentSubmission = slider.val();
var currentFiles = files[currentSubmission];
editors.each(function(index, editor) {
currentEditor = ace.edit(editor);
fileContent = "";
if (currentFiles[index]) {
fileContent = currentFiles[index].content
}
currentEditor.getSession().setValue(fileContent);
});
});
initializeFileTree();
showFirstFile();
}
});
|
JavaScript
| 0 |
@@ -85,16 +85,45 @@
mate';%0A%0A
+ var currentSubmission = 0;%0A
var ac
@@ -144,16 +144,37 @@
defined;
+%0A var fileTrees = %5B%5D
%0A%0A var
@@ -384,32 +384,52 @@
id');%0A $(
-'#
file
-s'
+Trees%5BcurrentSubmission%5D
).jstree().s
@@ -471,16 +471,53 @@
frame);%0A
+ showFileTree(currentSubmission);%0A
%7D;%0A%0A
@@ -645,25 +645,25 @@
%0A $('
-#
+.
files').
jstree($
@@ -654,16 +654,76 @@
files').
+each(function(index, element) %7B%0A fileTree = $(element).
jstree($
@@ -723,24 +723,23 @@
stree($(
-'#files'
+element
).data('
@@ -758,19 +758,18 @@
-$('#files')
+ fileTree
.on(
@@ -814,16 +814,18 @@
%7B%0A
+
active_f
@@ -832,16 +832,18 @@
ile = %7B%0A
+
@@ -876,16 +876,18 @@
+
id: pars
@@ -917,19 +917,23 @@
)%0A
+
+
%7D;%0A
+
va
@@ -999,24 +999,26 @@
nt();%0A
+
showFrame(fr
@@ -1031,16 +1031,166 @@
-%7D);%0A %7D;
+ %7D);%0A fileTrees.push(fileTree);%0A %7D);%0A %7D;%0A%0A var showFileTree = function(index) %7B%0A $('.files').hide();%0A $(fileTrees%5Bindex%5D.context).show();%0A %7D
%0A%0A
@@ -2251,28 +2251,24 @@
nt) %7B%0A
-var
currentSubmi
@@ -2285,24 +2285,63 @@
ider.val();%0A
+ showFileTree(currentSubmission);%0A
var cu
|
36adec99bc47bb754ffabb7a296bd4f9f7554d54
|
remove deprecated Vue resource method
|
app/installer/app/components/package-manager.js
|
app/installer/app/components/package-manager.js
|
module.exports = {
mixins: [
require('../lib/package')
],
data: function () {
return _.extend({
package: {},
view: false,
updates: null,
search: '',
status: ''
}, window.$data);
},
ready: function () {
this.load();
},
methods: {
load: function () {
this.$set('status', 'loading');
this.queryUpdates(this.packages, function (res) {
var data = res.data;
this.$set('updates', data.packages.length ? _.indexBy(data.packages, 'name') : null);
this.$set('status', '');
}).error(function () {
this.$set('status', 'error');
});
},
icon: function (pkg) {
if (pkg.extra && pkg.extra.icon) {
return pkg.url + '/' + pkg.extra.icon;
} else {
return this.$url('app/system/assets/images/placeholder-icon.svg');
}
},
image: function (pkg) {
if (pkg.extra && pkg.extra.image) {
return pkg.url + '/' + pkg.extra.image;
} else {
return this.$url('app/system/assets/images/placeholder-800x600.svg');
}
},
details: function (pkg) {
this.$set('package', pkg);
this.$refs.details.open();
},
settings: function (pkg) {
if (!pkg.settings) {
return;
}
var view, options;
_.forIn(this.$options.components, function (component, name) {
options = component.options || {};
if (options.settings && pkg.settings === name) {
view = name;
}
});
if (view) {
this.$set('package', pkg);
this.$set('view', view);
this.$refs.settings.open();
} else {
window.location = pkg.settings;
}
},
update: function (pkg) {
var vm = this;
this.install(pkg, this.packages, function (output) {
if (output.status === 'success') {
vm.updates.$delete(pkg.name);
}
setTimeout(function () {
location.reload();
}, 300);
});
}
},
filters: {
empty: function (packages) {
return Vue.filter('filterBy')(packages, this.search, 'title').length === 0;
}
},
components: {
'package-upload': require('./package-upload.vue')
}
};
|
JavaScript
| 0.000002 |
@@ -455,34 +455,39 @@
es(this.packages
-,
+).then(
function (res) %7B
@@ -684,16 +684,10 @@
%7D
-).error(
+,
func
|
05acdf3a05e596829e3bba87bc6b7bbe0f3a6a3e
|
change orders screen to have currentPaidAmount
|
app/pods/events/show/orders/index/controller.js
|
app/pods/events/show/orders/index/controller.js
|
import Ember from 'ember';
import ENV from 'aeonvera/config/environment';
export default Ember.Controller.extend({
columns: [
{ property: 'userName', title: 'Name' },
{ property: 'total', title: 'Total' },
{ property: 'paid', title: 'Paid' },
{ property: 'createdAt', title: 'Created At' },
{ property: '', title: 'Registration', sort: false }
],
eventId: Ember.computed.alias('model.eventId'),
orders: Ember.computed.alias('model.orders'),
paramsForDownload: Ember.computed('model.eventId', {
get(key) {
return {
event_id: this.get('model.eventId')
};
}
}),
path: Ember.computed('model.eventId', {
get(key) {
return `${ENV.host}/api/orders.csv?`;
}
})
});
|
JavaScript
| 0 |
@@ -188,29 +188,47 @@
y: '
-total', title: 'Total
+currentPaidAmount', title: 'Paid Amount
' %7D,
|
682045e815afc473bee2dcabe5fdc11512996ad8
|
Increase colspan to align pagination footer to the right
|
app/src/Components/ListTable/ListTableFooter.js
|
app/src/Components/ListTable/ListTableFooter.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import TableRow from '@material-ui/core/TableRow';
import IconButton from '@material-ui/core/IconButton';
import FirstPageIcon from '@material-ui/icons/FirstPage';
import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight';
import LastPageIcon from '@material-ui/icons/LastPage';
import TableFooter from '@material-ui/core/TableFooter';
import TablePagination from '@material-ui/core/TablePagination';
const actionsStyles = theme => ({
root: {
flexShrink: 0,
color: theme.palette.text.secondary,
marginLeft: theme.spacing.unit * 2.5,
},
});
class TablePaginationActions extends React.Component {
handleFirstPageButtonClick = () => {
this.props.onChangePage(0);
};
handleBackButtonClick = () => {
this.props.onChangePage(this.props.page - 1);
};
handleNextButtonClick = () => {
this.props.onChangePage(this.props.page + 1);
};
handleLastPageButtonClick = () => {
this.props.onChangePage(
Math.max(0, Math.ceil(this.props.count / this.props.rowsPerPage) - 1),
);
};
render() {
const { classes, theme } = this.props;
let count = this.props.count;
let page = this.props.page;
let rowsPerPage = this.props.rowsPerPage;
return (
<div className={classes.root}>
<IconButton
onClick={this.handleFirstPageButtonClick}
disabled={page === 0}
aria-label="First Page"
>
{theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />}
</IconButton>
<IconButton
onClick={this.handleBackButtonClick}
disabled={page === 0}
aria-label="Previous Page"
>
{theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
</IconButton>
<IconButton
onClick={this.handleNextButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="Next Page"
>
{theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
</IconButton>
<IconButton
onClick={this.handleLastPageButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="Last Page"
>
{theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />}
</IconButton>
</div>
);
}
}
TablePaginationActions.propTypes = {
classes: PropTypes.object.isRequired,
onChangePage: PropTypes.func.isRequired,
theme: PropTypes.object.isRequired,
};
const TablePaginationActionsWrapped = withStyles(actionsStyles, { withTheme: true })(
TablePaginationActions,
);
class ListTableFooter extends React.Component {
constructor() {
super();
this.handleChangePage = this.handleChangePage.bind(this);
this.handleChangeRowsPerPage = this.handleChangeRowsPerPage.bind(this);
}
render() {
return (<TableFooter>
<TableRow>
<TablePagination
colSpan={3}
count={this.props.params.rowTotal}
rowsPerPage={this.props.params.rowsPerPage}
page={this.props.params.page}
onChangePage={this.handleChangePage}
onChangeRowsPerPage={(event) => this.handleChangeRowsPerPage(event)}
ActionsComponent={TablePaginationActionsWrapped}
/>
</TableRow>
</TableFooter>);
}
handleChangePage(page) {
this.props.params.setPage(page);
};
handleChangeRowsPerPage(event) {
this.props.params.setRowsPerPage(event.target.value);
};
}
export default ListTableFooter;
|
JavaScript
| 0 |
@@ -3137,9 +3137,10 @@
an=%7B
-3
+10
%7D%0A
|
c2b89e22143259c26e286e7516d300be47b1ba30
|
Make sure to repear ident after each reconnect
|
TURTED.js
|
TURTED.js
|
var TURTED = function (sockjs_url) {
var me = this;
this.callbacks = {};
this.nativeConnection = {};
this.callbackQueue = [];
this.reconnectQueue = [];
this.isConnected = false;
this.connect = function (isReconnect) {
var sockjs = new SockJS(sockjs_url);
sockjs.onopen = function () {
//fire queued events here
me.isConnected = true;
me.processQueue();
if (isReconnect) {
me.processReconnectQueue()
}
}
sockjs.onmessage = function (e) {
//console.log("Sock gives me ", e);
data = JSON.parse(e.data);
//console.log("After parsing I have ", data);
var type = data.type;
var data = data.data;
//console.log(type, data);
if (typeof me.callbacks[type] === "object") {
var l = me.callbacks[type].length;
console.log("Triggering callbacks on ", type);
for (var i = 0; i < l; i++) {
me.callbacks[type][i].call(me, data);
}
}
};
sockjs.onerror = function (e) {
console.log("Error", e)
}
sockjs.onclose = function () {
this.isConnected = false;
setTimeout(this.reconnect.bind(this), 1000);
}.bind(this);
;
this.nativeConnection = sockjs;
}
this.reconnect = function() {
this.connect(true);
}.bind(this);
this.connect();
}
TURTED.prototype.on = function (on, f) {
if (typeof this.callbacks[on] === "undefined") {
this.callbacks[on] = [];
}
this.callbacks[on].push(f);
};
TURTED.prototype.ident = function (id, username, token) {
//enqueue the "ident" action until connected
var f = function () {
this.nativeConnection.send(this.encode("ident", {
id: id,
username: username,
token: token
}));
}.bind(this);
this.enqueue(f);
this.enqueueReconnect(f);
//in case the call was made on an open connection, immediately process the queue again
if (this.isConnected) {
this.processQueue();
}
}
TURTED.prototype.join = function (channel) {
//enqueue the "join" action until connected
this.enqueue(function () {
this.nativeConnection.send(this.encode("join", {
channel: channel
}));
}.bind(this));
//in case the call was made on an open connection, immediately process the queue again
if (this.isConnected) {
this.processQueue();
}
}
TURTED.prototype.send = function (message) {
this.nativeConnection.send(this.encode("message", message));
console.log(this.encode("message", message));
}
TURTED.prototype.echo = function (message) {
this.nativeConnection.send(this.encode("echo", message));
}
TURTED.prototype.encode = function (type, data) {
return JSON.stringify({
type: type,
data: data
});
}
TURTED.prototype.enqueue = function (f) {
//store the callback
this.callbackQueue.push(f);
}
TURTED.prototype.enqueueReconnect = function (f) {
//store the callback
this.reconnectQueue.push(f);
}
TURTED.prototype.processQueue = function () {
var emergency = 100;
while ((this.callbackQueue.length > 0) && (emergency > 0)) {
var f = this.callbackQueue.shift();
if (typeof f === "function") {
f();
}
emergency--;
}
}
TURTED.prototype.processReconnectQueue = function () {
var emergency = 100;
while ((this.reconnectQueue.length > 0) && (emergency > 0)) {
var f = this.reconnectQueue.shift();
if (typeof f === "function") {
f();
}
emergency--;
}
}
|
JavaScript
| 0 |
@@ -3592,32 +3592,39 @@
= 100;%0A
-while ((
+for (var i=0;i%3C
this.reconne
@@ -3641,32 +3641,12 @@
ngth
- %3E 0) && (emergency %3E 0)
+;i++
) %7B%0A
@@ -3676,32 +3676,27 @@
connectQueue
-.shift()
+%5Bi%5D
;%0A if
|
f765759573e5ed299c0f977b8099631f01411b57
|
Apply scope and scopeId when Role.prototype.resolveParents
|
common/models/sec-role.js
|
common/models/sec-role.js
|
'use strict';
const _ = require('lodash');
const Promise = require('bluebird');
const shortid = require('shortid');
const arrify = require('arrify');
const utils = require('../../src/utils');
/* eslint-disable */
/**
* @class Role
*/
function Role() {
// this is a dummy placeholder for jsdox
}
/* eslint-enable */
module.exports = function (Role) {
Role.definition.rawProperties.id.default =
Role.definition.properties.id.default = function () {
return shortid();
};
Role.prototype.resolveParents = function (parents) {
return Role.resolve(parents, p => p.id !== this.id);
};
Role.prototype.resolveParentIds = function (parents) {
return this.resolveParents(parents).map(p => p.id);
};
/**
* Inherit from parents
*
* @param {Role|String} parents
* @return {Promise.<Role>}
*/
Role.prototype.inherit = function (parents) {
return this.resolveParentIds(parents)
.then(parentIds => this.parentIds = _.union(this.parentIds, parentIds))
.then(() => this.save());
};
/**
* Uninherit form parents
*
* @param parents
* @return {Promise.<Role>}
*/
Role.prototype.uninherit = function (parents) {
return this.resolveParentIds(parents)
.then(parentIds => this.parentIds = _.without(this.parentIds, ...parentIds))
.then(() => this.save());
};
/**
* Set parents to role's inherits
*
* @param parents
* @return {Promise.<Role>}
*/
Role.prototype.setInherits = function (parents) {
return this.resolveParentIds(parents)
.then(parents => this.parentIds = parents)
.then(() => this.save());
};
/**
* Resolve roles with filter function or scope
*
* @param {[Object]|[String]|Object|String} roles
* @param {Function|String| Object} [filter]
* @return {Promise.<[Role]>}
*/
Role.resolve = function (roles, filter) {
let scope;
let scopeId;
if (!_.isFunction(filter)) {
if (_.isString(filter) || _.isNull(filter)) {
const {type, id} = utils.typeid(filter);
scope = type;
scopeId = id;
}
if (_.isObject(filter)) {
scope = filter.scope;
scopeId = filter.scopeId;
filter = (role => {
return (_.isUndefined(scope) ||role.scope === scope) && (_.isUndefined(scopeId) || role.scopeId === scopeId)
});
} else {
filter = _.identity;
}
}
const ids = [];
roles = arrify(roles).filter(p => {
if (!p) {
return false;
}
if (typeof p === 'string') {
ids.push(p);
return false;
}
if (p.inherit && p.uninherit) {
return filter(p);
}
console.warn('Invalid object:', p);
return false;
});
const promise = Promise.resolve(_.isEmpty(ids) ? [] : Role.find({
where: {
scope,
scopeId,
or: [{
id: {inq: ids}
}, {
name: {inq: ids}
}]
}
}));
return promise.then(found => _(roles).concat(found).uniqBy('id').filter(filter).value());
};
return Role;
};
|
JavaScript
| 0 |
@@ -561,16 +561,59 @@
arents,
+_.pick(this, %5B'scope', 'scopeId'%5D)).filter(
p =%3E p.i
@@ -2134,30 +2134,15 @@
r =
-(
role =%3E
- %7B%0A%09%09%09%09%09return
(_.
@@ -2162,16 +2162,17 @@
cope) %7C%7C
+
role.sco
@@ -2244,15 +2244,8 @@
eId)
-%0A%09%09%09%09%7D)
;%0A%09%09
|
6bc2d0ec344a8e8b77aa93a7bd49ea69a1a697e7
|
update winner bug fix
|
job/realtime/update_schdule.js
|
job/realtime/update_schdule.js
|
/**
* 更新比赛状态
* */
var query = require("../../service/common/connection").query;
var request = require("request");
//var dom = require("jsdom");
var cheerio = require("cheerio");
module.exports = function () {
var today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
var tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
query("select * from playball.Game where Time between ? and ? and Status<2", [today, tomorrow], function (error, results) {
if (!error && results && results.length) {
results.forEach(function (game) {
if (game.Status == 0 && new Date(game.Time) < new Date()) {
//已经开始
updateStatus(game.GameID, 1);
}
if (game.Status == 1) {
findScore("http://g.hupu.com/nba/daily/boxscore_" + game.ThirdID + ".html", game.GameID, game);
}
});
}
});
};
function findScore(liveUrl, id, game) {
console.log("request hupu game page " + liveUrl + " to get score.. ");
request(liveUrl, function (errors, response, body) {
if (!errors && response && response.statusCode == 200) {
var $ = cheerio.load(body);
//比分
var hs = "0" , vs = "0";
var HostScoreBox = $(".team_vs_box .team_a h2").eq(0);
var VisitingScoreBox = $(".team_vs_box .team_b h2").eq(0);
if (HostScoreBox.length) {
hs = HostScoreBox.text();
}
if (VisitingScoreBox.length) {
vs = VisitingScoreBox.text();
}
if (/^\d+$/.test(hs) && /^\d+$/.test(vs)) {
updateScore(id, hs, vs);
}
//状态
var status;
var statusBox = $(".table_list .table_list_c li.on p").eq(0);
if (statusBox.length) {
var text = statusBox.text().trim();
if (text == "已结束") {
status = 2;
}
}
if (status) {
updateStatus(id, status, hs > vs ? game.HostID : game.VisitID, game);
}
}
});
}
function updateScore(id, hs, vs) {
query("update playball.Game set ? where GameID=" + id, {
HostScore: hs,
VisitScore: vs
}, function (err) {
if (err) {
console.log(err);
}
});
}
function updateStatus(id, status, winnerID, game) {
query("update playball.Game set ? where GameID=" + id, {
Status: status,
WinnerID: winnerID || 0
}, function (err) {
if (err) {
console.log(err);
} else {
if (status == 2 && game && game.IsPlayOff == 1 && game.RoundID) {
query('select * from playball.PlayOff where RoundID = ?', [game.RoundID], function (err, round) {
if (!err && round && round.length) {
round = round[0];
var key = winnerID == round.HostID ? 'HostWin' : 'VisitWin';
query('update playball.PlayOff set ' + key + '= ' + key + '+1 where RoundID= ?', [game.RoundID], function (e) {
if (e) {
console.log(e);
}
});
}
});
}
}
});
}
|
JavaScript
| 0 |
@@ -2188,13 +2188,15 @@
us,
++
hs %3E
++
vs ?
@@ -2552,24 +2552,71 @@
ID, game) %7B%0A
+ if(status!=2)%7B%0A winnerID = 0;%0A %7D%0A
query(%22u
|
aeb25276d3b2c66c7a5daa0bf1f915a443cdd7a8
|
Rename data-role attribute in the JQM plugin
|
js/jquery.mobile.mobiscroll.js
|
js/jquery.mobile.mobiscroll.js
|
/*
Copyright (c) 2012 Sergio Gabriel Teves
All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function($, undefined ) {
$.widget( "mobile.datebox", $.mobile.widget, {
options: {
theme: 'jqm',
preset: 'date'
},
_create: function() {
var o = $.extend(this.options, this.element.data('options')),
input = $(this.element);
input.scroller(o);
}
});
$(document).bind("pagebeforecreate", function(c) {
// Convert date inputs to normal inputs
$('input[type="date"]:jqmData(role="datebox")', c.target).prop('type', 'text');
});
$(document).bind("pagecreate create", function(c) {
$(document).trigger("dateboxbeforecreate");
$(':jqmData(role="datebox")', c.target).each(function() {
if (typeof ($(this).data("datebox")) === "undefined") {
$(this).datebox();
}
})
});
})( jQuery );
|
JavaScript
| 0 |
@@ -724,23 +724,26 @@
%22mobile.
-datebox
+mobiscroll
%22, $.mob
@@ -827,16 +827,44 @@
: 'date'
+,%0A animate: 'pop'
%0A
@@ -917,104 +917,97 @@
var
-o = $.extend(this.options, this.element.data('options')),%0A input = $(this.element
+input = this.element,%0A o = $.extend(this.options, input.jqmData('options')
);%0A
@@ -1194,39 +1194,42 @@
%5D:jqmData(role=%22
-datebox
+mobiscroll
%22)', c.target).p
@@ -1343,23 +1343,26 @@
rigger(%22
-datebox
+mobiscroll
beforecr
@@ -1396,23 +1396,26 @@
a(role=%22
-datebox
+mobiscroll
%22)', c.t
@@ -1477,23 +1477,26 @@
).data(%22
-datebox
+mobiscroll
%22)) ===
@@ -1538,15 +1538,18 @@
is).
-datebox
+mobiscroll
();%0A
|
c9f05f5eae221c45f7b8b09709e758180cfaf754
|
Add todos
|
app/ui.js
|
app/ui.js
|
/**
* TODO: #timeline -> event page -> history back (and reverse), no view data is cached
* TODO: which table columns are always shown (how to render various event types)
* TODO: Add file logging for 404/500 (http://expressjs.com/guide.html#error-handling)
*/
var _ = require('underscore');
var express = require('express');
var app = express.createServer();
var storage = require(__dirname + '/modules/storage/mongodb.js');
var config = require(__dirname + '/../config/config.js').read();
// http://stackoverflow.com/questions/6825325/example-of-node-js-express-registering-underscore-js-as-view-engine
app.register('.html', {
compile: function (str, options) {
var template = _.template(str);
return function (locals) {
return template(locals);
};
}
});
// http://japhr.blogspot.com/2011/10/underscorejs-templates-in-backbonejs.html
_.templateSettings = {
evaluate : /\{\[([\s\S]+?)\]\}/g,
interpolate : /\{\{([\s\S]+?)\}\}/g
};
// NODE_ENV=development node app/ui.js
app.configure('development', function() {
console.log('environment: dev');
var path = require('path');
var dust = require('dust');
var fs = require('fs');
var templates = fs.readdirSync(__dirname + '/views');
var fd = fs.openSync(__dirname + '/../public/templates/compiled.js', 'a');
_.each(templates, function(template) {
console.log('template: ' + template);
var templateName = path.basename(template, '.html');
var compiled = dust.compile(fs.readFileSync(__dirname + '/views/' + template, 'UTF-8'), templateName);
dust.loadSource(compiled);
fs.writeSync(fd, compiled, null, 'utf8');
//fs.writeFileSync(path.join(__dirname + '/../public/templates', templateName + '.js'), compiled);
//fs.writeFileSync(path.join(__dirname + '/../public/templates/compiled.js'), compiled);
});
});
app.use(express.static(__dirname + '/../public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.set('view options', { layout: false });
app.get('/', function(req, res) {
res.render('index');
});
app.get('/timeline', function(req, res) {
storage.get_timeline(req.query, function(err, documents) {
res.send(documents);
});
});
app.get('/event/:id', function(req, res) {
if (!req.params.id.match(/^[a-z0-9]{24}$/)) {
res.send(null);
}
storage.get_log(req.params.id, function(err, document) {
res.send(document);
});
});
app.listen(8080, '127.0.0.1');
|
JavaScript
| 0.000097 |
@@ -10,85 +10,72 @@
DO:
-#timeline -%3E event page -%3E history back (and reverse), no view data is cached
+import.js hangs on /tmp/php.log -- need way to mass-insert async
%0A *
@@ -240,16 +240,58 @@
ndling)%0A
+ * TODO: Add 'err' handling to mongodb.js%0A
*/%0A%0Avar
|
2efa259620a685eb41fe8bf0645096fb4254106c
|
Use the label prop instead of the children
|
components/toast/Toast.js
|
components/toast/Toast.js
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Transition from 'react-transition-group/Transition';
import cx from 'classnames';
import { IconButton, LinkButton } from '../button';
import { TextSmall } from '../typography';
import LoadingSpinner from '../loadingSpinner';
import { createPortal } from 'react-dom';
import { IconCloseMediumOutline } from '@teamleader/ui-icons';
import theme from './theme.css';
const factory = (LinkButton, IconButton) => {
class Toast extends PureComponent {
static propTypes = {
action: PropTypes.string,
active: PropTypes.bool,
children: PropTypes.node,
className: PropTypes.string,
label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
onClose: PropTypes.func,
onTimeout: PropTypes.func,
processing: PropTypes.bool,
timeout: PropTypes.number,
};
constructor() {
super(...arguments);
this.toastRoot = document.createElement('div');
this.toastRoot.id = 'toast-root';
}
componentDidMount() {
document.body.appendChild(this.toastRoot);
if (this.props.active && this.props.timeout) {
this.scheduleTimeout(this.props);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.active && nextProps.timeout) {
this.scheduleTimeout(nextProps);
}
}
componentWillUnmount() {
clearTimeout(this.currentTimeout);
document.body.removeChild(this.toastRoot);
}
scheduleTimeout = props => {
const { onTimeout, timeout } = props;
if (this.currentTimeout) {
clearTimeout(this.currentTimeout);
}
this.currentTimeout = setTimeout(() => {
if (onTimeout) {
onTimeout();
}
this.currentTimeout = null;
}, timeout);
};
render() {
const { action, active, children, className, label, onClose, processing } = this.props;
const toast = (
<Transition in={active} timeout={{ enter: 0, exit: 1000 }}>
{state => {
if (state === 'exited') {
return null;
}
const classNames = cx(
theme['toast'],
{
[theme['is-entering']]: state === 'entering',
[theme['is-entered']]: state === 'entered',
[theme['is-exiting']]: state === 'exiting',
},
className,
);
return (
<div data-teamleader-ui="toast" className={classNames}>
{processing && <LoadingSpinner className={theme['spinner']} color="white" />}
<TextSmall className={theme['label']} color="white">
{label}
{children}
</TextSmall>
{onClose ? (
action ? (
<LinkButton className={theme['action-link']} inverse onClick={onClose}>{action}</LinkButton>
) : (
<IconButton
className={theme['action-button']}
icon={<IconCloseMediumOutline />}
color="white"
onClick={onClose}
/>
)
) : null}
</div>
);
}}
</Transition>
);
return createPortal(toast, this.toastRoot);
}
}
return Toast;
};
const Toast = factory(LinkButton, IconButton);
export default Toast;
export { factory as toastFactory, Toast };
|
JavaScript
| 0.000001 |
@@ -2930,16 +2930,31 @@
inverse
+ label=%7Baction%7D
onClick
@@ -2967,29 +2967,9 @@
ose%7D
-%3E%7Baction%7D%3C/LinkButton
+/
%3E%0A
|
186fbcd40f95526712ad7c8db0249e688caf2d81
|
move sass loader to postLoaders
|
conf/webpack-test.conf.js
|
conf/webpack-test.conf.js
|
module.exports = {
module: {
preLoaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint'
}
],
loaders: [
{
test: /\.scss$/,
loaders: [
'style',
'css',
'sass',
'postcss'
]
},
{
test: /\.js$/,
exclude: /(node_modules|.*\.spec\.js)/,
loader: 'isparta-instrumenter'
}
],
postLoaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: [
'babel'
]
}
]
},
debug: true,
devtool: 'cheap-module-eval-source-map'
};
|
JavaScript
| 0.000001 |
@@ -190,11 +190,9 @@
/%5C.
-scs
+j
s$/,
@@ -204,119 +204,191 @@
-loaders: %5B%0A 'style',
+exclude: /(node_modules%7C.*%5C.spec%5C.js)/,%0A loader: 'isparta-instrumenter'
%0A
+%7D%0A
-'css'
+%5D
,%0A
- 'sass',%0A 'postcss'%0A %5D
+postLoaders: %5B%0A %7B%0A test: /%5C.scss$/,%0A loaders: %5B
%0A
-%7D,%0A
- %7B
+'style',
%0A
@@ -396,143 +396,73 @@
-test: /%5C.js$/,%0A exclude: /(node_modules%7C.*%5C.spec%5C.js)/,%0A loader: 'isparta-instrumenter'%0A %7D%0A %5D,%0A postLoaders: %5B
+ 'css',%0A 'sass',%0A 'postcss'%0A %5D%0A %7D,
%0A
|
2338819d77512a94a4ddaffad6131282df4157fb
|
Change tasks to update once per hour by default
|
config/config.template.js
|
config/config.template.js
|
module.exports = {
port: 8000,
tasks: {
cdnjs: {hour: 1},
google: {hour: 1},
jsdelivr: {hour: 1}
}
};
|
JavaScript
| 0 |
@@ -57,20 +57,22 @@
cdnjs: %7B
-hour
+minute
: 1%7D,%0A
@@ -86,20 +86,22 @@
oogle: %7B
-hour
+minute
: 1%7D,%0A
@@ -121,12 +121,14 @@
r: %7B
-hour
+minute
: 1%7D
|
450b76c30096f1265d22c36b67a6a562a94a6eae
|
Update development.js
|
config/env/development.js
|
config/env/development.js
|
'use strict';
var defaultEnvConfig = require('./default');
module.exports = {
db: {
uri: 'mongodb://kingtsunamy:9z80dS8tRMkI48tlBSw1h4jHOWeldaBtcaI6wbMXAoEiDWgtV27YZHd8QTYywYymYzf2GZuPAbC7AEklQX5Jdg==@kingtsunamy.documents.azure.com:10255/?ssl=true&replicaSet=globaldb' ,process.env.MONGOHQ_URL || process.env.MONGODB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean-dev',
options: {
user: '',
pass: ''
},
// Enable mongoose debug mode
debug: process.env.MONGODB_DEBUG || false
},
log: {
// logging with Morgan - https://github.com/expressjs/morgan
// Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
format: 'dev',
fileLogger: {
directoryPath: process.cwd(),
fileName: 'app.log',
maxsize: 10485760,
maxFiles: 2,
json: false
}
},
app: {
title: defaultEnvConfig.app.title + ' - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/api/auth/facebook/callback'
},
twitter: {
username: '@TWITTER_USERNAME',
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/api/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/api/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/api/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/api/auth/github/callback'
},
paypal: {
clientID: process.env.PAYPAL_ID || 'CLIENT_ID',
clientSecret: process.env.PAYPAL_SECRET || 'CLIENT_SECRET',
callbackURL: '/api/auth/paypal/callback',
sandbox: true
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
},
livereload: true,
seedDB: {
seed: process.env.MONGO_SEED === 'true',
options: {
logResults: process.env.MONGO_SEED_LOG_RESULTS !== 'false',
seedUser: {
username: process.env.MONGO_SEED_USER_USERNAME || 'seeduser',
provider: 'local',
email: process.env.MONGO_SEED_USER_EMAIL || '[email protected]',
firstName: 'User',
lastName: 'Local',
displayName: 'User Local',
roles: ['user']
},
seedAdmin: {
username: process.env.MONGO_SEED_ADMIN_USERNAME || 'seedadmin',
provider: 'local',
email: process.env.MONGO_SEED_ADMIN_EMAIL || '[email protected]',
firstName: 'Admin',
lastName: 'Local',
displayName: 'Admin Local',
roles: ['user', 'admin']
}
}
}
};
|
JavaScript
| 0.000001 |
@@ -278,16 +278,19 @@
baldb' ,
+ //
process.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.