code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
export default 1;
export const [ a, b ] = [ 2, 3 ];
| quase/quasejs | packages/builder/test/fixtures/imports-exports/files/export1.js | JavaScript | mit | 53 |
var image = document.getElementById('image');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var sprite = new Sprite(image, { y: 200 });
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
TINA.onUpdate(function update(t, dt) {
// At this point, all my tweens are up to date for the current iteration
ctx.clearRect(0, 0, 400, 400);
sprite.draw(ctx);
});
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
new TINA.Tween(sprite, ['x', 'rotation'])
.relative(true)
.iterations(Infinity)
.pingpong(true)
.from({ x: 100, rotation: -3 })
.to({ x: 300, rotation: 3 }, 2000, TINA.easing.sineInOut)
.start();
new TINA.Tween(sprite, ['x', 'rotation'])
.relative(true)
.iterations(Infinity)
.pingpong(true)
.from({ x: -30, rotation: -0.5 })
.to({ x: 30, rotation: 0.5 }, 260, TINA.easing.sineInOut)
.start();
| Wizcorp/tina.js | examples/relative/index.js | JavaScript | mit | 1,085 |
/**
* Created by Xuan on 2014/11/30.
*/
defineClass('ControlBase', 'ControlPlane', {
style: 'black',
init: function (style) {
this._super();
this.style = style;
},
/**
* @return {boolean}
*/
IsPointIn: function (x, y) {
return x >= 0 && x <= this.width &&
y >= 0 && y <= this.height;
},
/**
* @return {boolean}
*/
Render: function (c) {
if (!this._super())return false;
this.startRender(c);
try {
c.fillStyle = this.style;
c.fillRect(0, 0, this.width, this.height);
} finally {
this.endRender(c);
}
return true;
}
}); | Kxuan/pchelper | js/SysControl/Plane.js | JavaScript | mit | 725 |
(function() {
'use strict';
angular
.module('vizbox')
.run(runBlock);
/** @ngInject */
function runBlock($log) {
$log.debug('runBlock end');
$log.debug('check c3', c3);
$log.debug('check topojson', topojson);
}
})();
| ronotono/vizbox | src/app/index.run.js | JavaScript | mit | 251 |
/*global GIGO, Browser, unescape */
/*jslint browser: true */
GIGO.getms = function () {
// Helper function to get the current date/time as milliseconds.
var d = new Date();
return d.getTime();
};
GIGO.slow = 5000; // milliseconds . If a test takes longer than this, it is considered "slow" (if good) or "timeout" (if error)
GIGO.max_time = 15 * 1000; // milliseconds . Max time to allow a test to try and run, before giving up on it.
GIGO.retry_until = 15 * 1000; // milliseconds. If we want multiple passes, this says to stop new passes after this time.
GIGO.retry_min = 1; // Minimum time_ms to reload images, trying to differentiate service quality.
GIGO.retry_max = 3; // Max time_ms to allow reloading, no matter how fast.
GIGO.repeat_only_if_slow = 1; // If 1: only repeat tests if at least one test was slow. If 0: always repeat until retry_min/retry_max.
GIGO.repeated = 0; // How many time_ms we've tried so far.
GIGO.results = {}; // what we want to expose as "this" to callback functions
GIGO.results.ipv4 = {
ip: "",
subtype: ""
}; // Customer IP information, per our web service call
GIGO.results.ipv6 = {
ip: "",
subtype: ""
}; // Customer IP information, per our web service call
GIGO.results.tests = {}; // Store test specific data here.
GIGO.tabhistory = ["main"]; // History of what tab we go to and when; used for GIGO.goback()
GIGO.tests_planned = 0; // As we add tests, this will be incremented. Used by progress bar.
GIGO.tests_finished = 0; // As we finish tests, this will be incremented. Used by progress bar.
GIGO.start_time = GIGO.getms(); // Starting time. Used by progress bar as well as by retry_until
GIGO.finished = 0; // When we're done with all tests, set to 1 to hide the progress bar
GIGO.slowcount = 0; // How many background jsonp we spawned so far. Used when we execute tasks in parallel to stagger load.
// If we rig the test, don't report the results to the status surver.
// This is what happens when the page is called with
// ?test=oooooooo (all "ok", and technically impossible).
// ?test=oobooooo (more likely result)
// Main purpose is to test the display logic for given patterns of
// "ok", "slow", "bad", "timeout".
GIGO.test_rigged = 0;
GIGO.tests = []; // The list of all tests we will run.
GIGO.queue = []; // If use_queue then this is the list of pending jobs to start.
GIGO.dequeued = []; // Tests we have dequeued
GIGO.use_queue = 0; // Set to 1 for force serial execution. Set to 0 to permit parallel execution.
if (Browser.firefox) {
GIGO.use_queue = 1; // Always do serial execution for Firefox and friends, due to funky socks behavior.
}
if (Browser.opera) {
GIGO.use_queue = 1; // Any blocking thread, blocks all.
GIGO.max_time = 15 * 1000; // Hmm.
}
GIGO.helpdesk = {}; // Test results will pass data to the helpdesk page
GIGO.helpdesk.other_sites = {};
GIGO.helpdesk.other_sites.finished = 0;
GIGO.helpdesk.other_sites.count = 0;
GIGO.helpdesk.other_sites.good = [];
GIGO.helpdesk.other_sites.bad = [];
// http://mootools.net/docs/core/Core/Browser
GIGO.slowcount_delay = 20; // How long (ms) to delay between backgrounding jsonp if use_queue==0
if (Browser.ie) {
GIGO.slowcount_delay = 200; // Slow down spawning of ajax queries
}
// Symbian appears to be particularly bad.
// DNS lookups for some people appear to slow things down by nearly 5 seconds
if (navigator.userAgent.match(/SymbianOS|SymbOS/)) {
GIGO.slowcount_delay = 500; // Slow down on Symbian phones
GIGO.slow = 9000;
}
GIGO.parseGetVars = function () {
var getVars, returnVars, i, newVar;
getVars = location.search.substring(1).split("&"); // From the browser URL
returnVars = [];
i = 0;
for (i = 0; i < getVars.length; i = i + 1) {
newVar = getVars[i].split("=");
returnVars[unescape(newVar[0])] = unescape(newVar[1]);
}
return returnVars;
};
GIGO.CGI = GIGO.parseGetVars(); // Parse CGI arguements
GIGO.contact_wanted = GIGO.CGI.contact; // Do we want to force the contact form?
// If we found overrides, we will set GIGO.override
// as we as prepared each override into GIGO.overrides
GIGO.override = 0;
GIGO.overrides = {};
| falling-sky/builder | templates/js/inc/init.js | JavaScript | mit | 4,184 |
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import ClosedPODateRange from '../../../components/Rpt/ClosedPO/ClosedPODateRange';
import * as Actions from '../../../actions/Rpt/Actions';
function mapStateToProps(state) {
return {
Rpt: state.Reports
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(Actions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(ClosedPODateRange);
| robogroves/Ashley | app/containers/Rpt/ClosedPO/ClosedPODateRange.js | JavaScript | mit | 475 |
const path = require('path')
const CleanCSS = require('clean-css')
const uglify = require('uglify-js')
const read = require('@lump/read')
const write = require('@lump/write')
/*
* Minify CSS/JS files with optional sourceMap
*/
module.exports = async (src, { sourceMap = false, log = false }) => {
if (!src) {
throw new Error('Missing Arguments')
}
let code
let map
const ext = path.extname(src)
const content = await read(src)
if (ext === '.css') {
const minified = await _minifyCSS(content, sourceMap)
if (minified.error) {
throw minified.error
}
code = minified.styles
map = minified.sourceMap
} else if (ext === '.js') {
const minified = await _minifyJS(content, sourceMap)
if (minified.error) {
throw minified.error
}
code = minified.code
map = minified.map
}
if (sourceMap) {
const dest = src.replace(ext, `.min${ext}.map`)
const url = path.basename(dest)
code += `\n/*# sourceMappingURL=${url}*/`
await write(dest, map, { log })
}
const dest = src.replace(ext, `.min${ext}`)
await write(dest, code, { log })
}
function _minifyCSS (content, sourceMap) {
return new CleanCSS({
sourceMap,
advanced: false,
keepSpecialComments: 0,
rebase: false,
returnPromise: true
}).minify(content)
}
function _minifyJS (content, sourceMap) {
return uglify.minify(content, {
sourceMap,
output: {
ascii_only: true
},
compress: {
pure_funcs: ['makeMap']
}
})
}
| miljan-aleksic/lump | packages/minify/index.js | JavaScript | mit | 1,521 |
#!/usr/bin/env node
// nS - No Space
// lC - Lowercase
import cheerio from 'cheerio';
import colors from 'colors';
import fs from 'fs';
import program from 'commander';
import replace from 'node-replace';
import shell from 'shelljs';
import pjson from '../package.json';
import path from 'path';
import { foldersAndFiles } from './config/foldersAndFiles';
import { filesToModifyContent } from './config/filesToModifyContent';
import { bundleIdentifiers } from './config/bundleIdentifiers';
const devTestRNProject = ''; // For Development eg '/Users/junedomingo/Desktop/RN49'
const __dirname = devTestRNProject || process.cwd();
const projectName = pjson.name;
const projectVersion = pjson.version;
const replaceOptions = {
recursive: true,
silent: true,
};
function readFile(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, (err, data) => {
if (err) reject(err);
resolve(data);
});
});
}
function replaceContent(regex, replacement, paths) {
replace({
regex,
replacement,
paths,
...replaceOptions,
});
for (const filePath of paths) {
console.log(`${filePath.replace(__dirname, '')} ${colors.green('MODIFIED')}`);
}
}
const deletePreviousBundleDirectory = ({ oldBundleNameDir, shouldDelete }) => {
if (shouldDelete) {
const dir = oldBundleNameDir.replace(/\./g, '/');
const deleteDirectory = shell.rm('-rf', dir);
Promise.resolve(deleteDirectory);
console.log('Done removing previous bundle directory.'.green);
} else {
Promise.resolve();
console.log('Bundle directory was not changed. Keeping...'.yellow);
}
};
const cleanBuilds = () => {
const deleteDirectories = shell.rm('-rf', [
path.join(__dirname, 'ios/build/*'),
path.join(__dirname, 'android/.gradle/*'),
path.join(__dirname, 'android/app/build/*'),
path.join(__dirname, 'android/build/*'),
]);
Promise.resolve(deleteDirectories);
console.log('Done removing builds.'.green);
};
const loadAppConfig = () => {
return readFile(path.join(__dirname, 'app.json')).then(data => JSON.parse(data));
}
loadAppConfig()
.then(appConfig => {
const currentAppName = appConfig.name;
const nS_CurrentAppName = currentAppName.replace(/\s/g, '');
const lC_Ns_CurrentAppName = nS_CurrentAppName.toLowerCase();
program
.version(projectVersion)
.arguments('<newName>')
.option('-b, --bundleID [value]', 'Set custom bundle identifier eg. "com.junedomingo.travelapp"')
.action(newName => {
const nS_NewName = newName.replace(/\s/g, '');
const pattern = /^([\p{Letter}\p{Number}])+([\p{Letter}\p{Number}\s]+)$/u;
const lC_Ns_NewAppName = nS_NewName.toLowerCase();
const bundleID = program.bundleID ? program.bundleID.toLowerCase() : null;
let newBundlePath;
const listOfFoldersAndFiles = foldersAndFiles(currentAppName, newName);
const listOfFilesToModifyContent = filesToModifyContent(currentAppName, newName, projectName);
if (bundleID) {
newBundlePath = bundleID.replace(/\./g, '/');
const id = bundleID.split('.');
const validBundleID = /^([a-zA-Z]([a-zA-Z0-9_])*\.)+[a-zA-Z]([a-zA-Z0-9_])*$/u;
if (id.length < 2) {
return console.log(
'Invalid Bundle Identifier. Add something like "com.travelapp" or "com.junedomingo.travelapp"'
);
}
if (!validBundleID.test(bundleID)) {
return console.log('Invalid Bundle Identifier. It must have at least two segments (one or more dots). Each segment must start with a letter. All characters must be alphanumeric or an underscore [a-zA-Z0-9_]')
}
}
if (!pattern.test(newName)) {
return console.log(
`"${newName}" is not a valid name for a project. Please use a valid identifier name (alphanumeric and space).`
);
}
if (newName === currentAppName || newName === nS_CurrentAppName || newName === lC_Ns_CurrentAppName) {
return console.log('Please try a different name.');
}
// Move files and folders from ./config/foldersAndFiles.js
const resolveFoldersAndFiles = new Promise(resolve => {
listOfFoldersAndFiles.forEach((element, index) => {
const dest = element.replace(new RegExp(nS_CurrentAppName, 'i'), nS_NewName);
let itemsProcessed = 1;
const successMsg = `/${dest} ${colors.green('RENAMED')}`;
setTimeout(() => {
itemsProcessed += index;
if (fs.existsSync(path.join(__dirname, element)) || !fs.existsSync(path.join(__dirname, element))) {
const move = shell.exec(
`git mv -k "${path.join(__dirname, element)}" "${path.join(__dirname, dest)}"`
);
if (move.code === 0) {
console.log(successMsg);
} else if (move.code === 128) {
// if "outside repository" error occured
if (shell.mv('-f', path.join(__dirname, element), path.join(__dirname, dest)).code === 0) {
console.log(successMsg);
} else {
console.log("Ignore above error if this file doesn't exist");
}
}
}
if (itemsProcessed === listOfFoldersAndFiles.length) {
resolve();
}
}, 200 * index);
});
});
// Modify file content from ./config/filesToModifyContent.js
const resolveFilesToModifyContent = () =>
new Promise(resolve => {
let filePathsCount = 0;
let itemsProcessed = 0;
listOfFilesToModifyContent.map(file => {
filePathsCount += file.paths.length;
file.paths.map((filePath, index) => {
const newPaths = [];
setTimeout(() => {
itemsProcessed++;
if (fs.existsSync(path.join(__dirname, filePath))) {
newPaths.push(path.join(__dirname, filePath));
replaceContent(file.regex, file.replacement, newPaths);
}
if (itemsProcessed === filePathsCount) {
resolve();
}
}, 200 * index);
});
});
});
const resolveJavaFiles = () =>
new Promise(resolve => {
readFile(path.join(__dirname, 'android/app/src/main/AndroidManifest.xml')).then(data => {
const $ = cheerio.load(data);
const currentBundleID = $('manifest').attr('package');
const newBundleID = program.bundleID ? bundleID : currentBundleID;
const javaFileBase = '/android/app/src/main/java';
const newJavaPath = `${javaFileBase}/${newBundleID.replace(/\./g, '/')}`;
const currentJavaPath = `${javaFileBase}/${currentBundleID.replace(/\./g, '/')}`;
if (bundleID) {
newBundlePath = newJavaPath;
} else {
newBundlePath = newBundleID.replace(/\./g, '/').toLowerCase();
newBundlePath = `${javaFileBase}/${newBundlePath}`;
}
const fullCurrentBundlePath = path.join(__dirname, currentJavaPath);
const fullNewBundlePath = path.join(__dirname, newBundlePath);
// Create new bundle folder if doesn't exist yet
if (!fs.existsSync(fullNewBundlePath)) {
shell.mkdir('-p', fullNewBundlePath);
const move = shell.exec(`git mv -k "${fullCurrentBundlePath}/"* "${fullNewBundlePath}"`);
const successMsg = `${newBundlePath} ${colors.green('BUNDLE INDENTIFIER CHANGED')}`;
if (move.code === 0) {
console.log(successMsg);
} else if (move.code === 128) {
// if "outside repository" error occured
if (shell.mv('-f', fullCurrentBundlePath + '/*', fullNewBundlePath).code === 0) {
console.log(successMsg);
} else {
console.log(`Error moving: "${currentJavaPath}" "${newBundlePath}"`);
}
}
}
const vars = {
currentBundleID,
newBundleID,
newBundlePath,
javaFileBase,
currentJavaPath,
newJavaPath,
};
resolve(vars);
});
});
const resolveBundleIdentifiers = params =>
new Promise(resolve => {
let filePathsCount = 0;
const { currentBundleID, newBundleID, newBundlePath, javaFileBase, currentJavaPath, newJavaPath } = params;
bundleIdentifiers(
currentAppName,
newName,
projectName,
currentBundleID,
newBundleID,
newBundlePath
).map(file => {
filePathsCount += file.paths.length - 1;
let itemsProcessed = 0;
file.paths.map((filePath, index) => {
const newPaths = [];
if (fs.existsSync(path.join(__dirname, filePath))) {
newPaths.push(path.join(__dirname, filePath));
setTimeout(() => {
itemsProcessed += index;
replaceContent(file.regex, file.replacement, newPaths);
if (itemsProcessed === filePathsCount) {
const oldBundleNameDir = path.join(__dirname, javaFileBase, currentBundleID);
resolve({ oldBundleNameDir, shouldDelete: !newJavaPath.includes(currentJavaPath) });
}
}, 200 * index);
}
});
});
});
const rename = () => {
resolveFoldersAndFiles
.then(resolveFilesToModifyContent)
.then(resolveJavaFiles)
.then(resolveBundleIdentifiers)
.then(deletePreviousBundleDirectory)
.then(cleanBuilds)
.then(() => console.log(`APP SUCCESSFULLY RENAMED TO "${newName}"! 🎉 🎉 🎉`.green))
.then(() => {
if (fs.existsSync(path.join(__dirname, 'ios', 'Podfile'))) {
console.log(
`${colors.yellow('Podfile has been modified, please run "pod install" inside ios directory.')}`
);
}
})
.then(() =>
console.log(
`${colors.yellow(
'Please make sure to run "watchman watch-del-all" and "npm start --reset-cache" before running the app. '
)}`
)
);
};
rename();
})
.parse(process.argv);
if (!process.argv.slice(2).length) program.outputHelp();
})
.catch(err => {
if (err.code === 'ENOENT') return console.log('Directory should be created using "react-native init"');
return console.log('Something went wrong: ', err);
});
| JuneDomingo/react-native-rename | src/index.js | JavaScript | mit | 11,241 |
module.exports = function(injectorTransform) {
'use strict';
return {
options: {
template: '<%= jqueryToolbox.folder.demo %>index.html',
transform: injectorTransform
},
files: {
'<%= jqueryToolbox.folder.demo %>index.html': [
'<%= jqueryToolbox.files.src.js %>',
'<%= jqueryToolbox.files.src.less %>',
'<%= jqueryToolbox.files.src.sass %>'
],
}
};
};
| Jimdo/grunt-jquery-toolbox | lib/config/injector/demo.js | JavaScript | mit | 422 |
var
gulp = require('gulp'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
cssnano = require('gulp-cssnano'),
sassLint = require('gulp-sass-lint'),
rename = require('gulp-rename'),
sourcemaps = require('gulp-sourcemaps'),
sassPath = 'scss/primocss-1.0.0.scss';
// Gulp help instructions triggered as Gulp default task
gulp.task('help', function() {
console.log('develop - Watch sass files and generate unminified CSS for development');
console.log('test - Lint Sass');
console.log('build - Lint Sass files and generate minified CSS for production');
});
// Provide details of Sass errors
function throwSassError(sassError) {
throw new gutil.PluginError({
plugin: 'sass',
message: util.format(
"Sass error: '%s' on line %s of %s",
sassError.message,
sassError.line,
sassError.file
)
});
}
// Lints Sass and provides errors
gulp.task('lint:sass', function() {
return gulp.src('scss/**/*.s+(a|c)ss')
.pipe(sassLint({
options: {
configFile: '.sass-lint.yml'
}
}))
.pipe(sassLint.format())
.pipe(sassLint.failOnError())
});
// Build Sass for local development
gulp.task('sass:develop', function() {
return gulp.src(sassPath)
.pipe(sourcemaps.init())
.pipe(sass({ style: 'expanded', errLogToConsole: true }))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1'))
.pipe(sourcemaps.write('maps/'))
.pipe(gulp.dest('build/css/'))
});
// Build Sass for production
gulp.task('sass:build', function() {
return gulp.src(sassPath)
.pipe(sass({
style: 'compressed',
errLogToConsole: true,
omitSourceMapUrl: true,
onError: throwSassError
}))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1'))
.pipe(gulp.dest('build/css/'))
.pipe(cssnano())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('build/css/'));
});
// Gulp default tasks
gulp.task('default', ['help']);
gulp.task('develop', ['watch', 'sass:develop']);
gulp.task('test', ['lint:sass']);
gulp.task('build', ['lint:sass', 'sass:build']);
| richmccartney/Ground-Work | gulpfile.js | JavaScript | mit | 2,131 |
// vim: set ts=2 sw=2 sts=2 et ai:
var devel = require("../src/base/devel");
var ScopingEval = require("../src/base/ScopingEval");
var expect = require("chai").expect;
describe("ScopingEval", function () {
var seval = new ScopingEval(true);
seval.add("var x = 100, y = 'outside';");
seval.add("x += 10;");
seval.add("var double = function (x) { return x * 2 };");
var se2 = seval.injectScope();
se2.add("var z = x - 1;");
se2.add("if (x > 100) z = double(z);");
it("should refer the outer `y` until the inside `y` is defined", function () {
var v = se2.eval("y");
expect(v).equals("outside");
});
it("should handle a variable in an injected scope", function () {
expect(se2.eval("z")).equals(218);
});
it("should refer the inner `y`", function () {
se2.add("var y = 'inside';");
expect(se2.eval("y")).equals("inside");
});
it("should not modify the outer `y` when the inner `y` modified", function () {
expect(seval.eval("y")).equals("outside");
});
var se3, se31;
it("should refer altered `y` from inside", function () {
se2.flush();
se3 = seval.injectScope();
se3.add("y = 'overwritten';");
expect(se3.eval("y")).equals("overwritten");
});
it("should refer altered `y` even outside", function () {
se3.flush();
expect(seval.eval("y")).equals("overwritten");
});
it("should not modify the outer `z`", function () {
se3.add("var z = 1;");
se31 = se3.injectScope();
se31.add("var z = 2;");
se31.flush();
expect(se3.eval("z")).equals(1);
});
it("should not propagate inner variable to outside", function () {
var global_z;
try {
global_z = z;
expect(seval.eval("try{ z } catch (e) { typeof e }")).equals(global_z);
} catch (e) {
expect(seval.eval("try{ z } catch (e) { typeof e }")).equals("object");
}
});
it("should refer the previously defined variable", function () {
var seval = new ScopingEval(true);
seval.add("var g = 12;");
seval.add("var s; s = 42;");
seval.injectScope().add("var s; s = 142");
expect(seval.eval("(function () { ++s; return s })()")).equals(43);
});
});
| kizz/sifon | test/test.ScopingEval.js | JavaScript | mit | 2,172 |
//-----------------------------------------------------
//
// Author: Daeren Torn
// Site: 666.io
//
//-----------------------------------------------------
"use strict";
//-----------------------------------------------------
var rAigis = require("./../index");
//-----------------------------------------------------
{
var l = 1000 * 1000 * 1;
var data = 1;
console.time("$typenize.string: number");
while(l--)
{
$typenize("float", data);
}
console.timeEnd("$typenize.string: number");
}
//---------------)>
{
var l = 1000 * 1000 * 1;
var data;
console.time("$typenize.string: undefined");
while(l--)
{
$typenize("float", data);
}
console.timeEnd("$typenize.string: undefined");
}
//------------------------------]>
{
var l = 1000 * 1000 * 1;
var data = 1;
console.time("parseFloat: nubmer");
while(l--)
{
parseFloat(data);
}
console.timeEnd("parseFloat: nubmer");
}
//---------------)>
{
var l = 1000 * 1000 * 1;
var data;
console.time("parseFloat: undefined");
while(l--)
{
parseFloat(data);
}
console.timeEnd("parseFloat: undefined");
}
//------------------------------]>
{
var l = 1000 * 1000 * 1;
var data = 1;
var fXEnd = function(in2) { return parseFloat(in2); };
var fXBegin = function(in1) { return fXEnd(in1); };
console.time("parseFloat + functions: nubmer");
while(l--)
{
fXBegin(data);
}
console.timeEnd("parseFloat + functions: nubmer");
}
//---------------)>
{
var l = 1000 * 1000 * 1;
var data = 1;
var fXEnd = function(in2) { return parseFloat(in2); };
var fXBegin = function(in1) { return fXEnd(); };
console.time("parseFloat + functions: undefined");
while(l--)
{
fXBegin(data);
}
console.timeEnd("parseFloat + functions: undefined");
} | Daeren/Aigis | test/benchmark.js | JavaScript | mit | 1,933 |
import React, { Component, PropTypes } from 'react'
import { GENRES } from '../constants/SongConstants'
import {Link} from '.'
const DAYS = [7, 30, 90]
const propTypes = {
dispatch: PropTypes.func.isRequired,
playlist: PropTypes.string.isRequired,
time: PropTypes.number
}
class Toolbar extends Component {
renderGenres () {
const { dispatch, playlist, time } = this.props
const genre = playlist.split(' - ')[0]
return GENRES.map((g) => {
const route = {
path: ['songs'],
query: {
q: g,
t: time
}
}
return (
<Link
className={`toolbar-item toolbar-genre ${(g === genre ? 'active' : '')}`}
dispatch={dispatch}
key={g}
route={route}
>
{g}
</Link>
)
})
}
renderTimes () {
const { dispatch, playlist, time } = this.props
const genre = playlist.split(' - ')[0]
return DAYS.map((t) => {
const route = {
path: ['songs'],
query: {
q: genre,
t: (t === time ? null : t)
}
}
return (
<Link
className={`toolbar-time ${(t === time ? 'active' : '')}`}
dispatch={dispatch}
key={t}
route={route}
>
{`${t} days`}
</Link>
)
})
}
render () {
return (
<div className='toolbar'>
<div className='container'>
<div className='toolbar-items'>
{this.renderGenres()}
<div className='toolbar-item toolbar-filter toolbar-times'>
<i className='icon ion-funnel' />
{this.renderTimes()}
</div>
</div>
</div>
</div>
)
}
}
Toolbar.propTypes = propTypes
export default Toolbar
| dearfrankg/soundio | app/components/Toolbar.js | JavaScript | mit | 1,807 |
var searchData=
[
['singlylinkedlist',['SinglyLinkedList',['../classsinglyLinkedList_1_1SinglyLinkedList.html',1,'singlyLinkedList']]]
];
| calebwherry/Cpp-Libraries | doc/html/search/classes_73.js | JavaScript | mit | 140 |
;(function(window) {
var svgSprite = '<svg>' +
'' +
'<symbol id="icon-add" viewBox="0 0 1024 1024">' +
'' +
'<path d="M320 473.6l384 0 0 76.8-384 0L320 473.6z" ></path>' +
'' +
'<path d="M473.6 320l76.8 0 0 384-76.8 0L473.6 320z" ></path>' +
'' +
'<path d="M512 128c-212.0704 0-384 171.9296-384 384s171.9296 384 384 384 384-171.9296 384-384S724.0704 128 512 128zM512 819.2c-169.6768 0-307.2-137.5232-307.2-307.2s137.5232-307.2 307.2-307.2 307.2 137.5232 307.2 307.2S681.6768 819.2 512 819.2z" ></path>' +
'' +
'</symbol>' +
'' +
'</svg>'
var script = function() {
var scripts = document.getElementsByTagName('script')
return scripts[scripts.length - 1]
}()
var shouldInjectCss = script.getAttribute("data-injectcss")
/**
* document ready
*/
var ready = function(fn) {
if (document.addEventListener) {
if (~["complete", "loaded", "interactive"].indexOf(document.readyState)) {
setTimeout(fn, 0)
} else {
var loadFn = function() {
document.removeEventListener("DOMContentLoaded", loadFn, false)
fn()
}
document.addEventListener("DOMContentLoaded", loadFn, false)
}
} else if (document.attachEvent) {
IEContentLoaded(window, fn)
}
function IEContentLoaded(w, fn) {
var d = w.document,
done = false,
// only fire once
init = function() {
if (!done) {
done = true
fn()
}
}
// polling for no errors
var polling = function() {
try {
// throws errors until after ondocumentready
d.documentElement.doScroll('left')
} catch (e) {
setTimeout(polling, 50)
return
}
// no errors, fire
init()
};
polling()
// trying to always fire before onload
d.onreadystatechange = function() {
if (d.readyState == 'complete') {
d.onreadystatechange = null
init()
}
}
}
}
/**
* Insert el before target
*
* @param {Element} el
* @param {Element} target
*/
var before = function(el, target) {
target.parentNode.insertBefore(el, target)
}
/**
* Prepend el to target
*
* @param {Element} el
* @param {Element} target
*/
var prepend = function(el, target) {
if (target.firstChild) {
before(el, target.firstChild)
} else {
target.appendChild(el)
}
}
function appendSvg() {
var div, svg
div = document.createElement('div')
div.innerHTML = svgSprite
svgSprite = null
svg = div.getElementsByTagName('svg')[0]
if (svg) {
svg.setAttribute('aria-hidden', 'true')
svg.style.position = 'absolute'
svg.style.width = 0
svg.style.height = 0
svg.style.overflow = 'hidden'
prepend(svg, document.body)
}
}
if (shouldInjectCss && !window.__iconfont__svg__cssinject__) {
window.__iconfont__svg__cssinject__ = true
try {
document.write("<style>.svgfont {display: inline-block;width: 1em;height: 1em;fill: currentColor;vertical-align: -0.1em;font-size:16px;}</style>");
} catch (e) {
console && console.log(e)
}
}
ready(appendSvg)
})(window) | SakuB/Individual_website | app/containers/ArticleManage/iconfont.js | JavaScript | mit | 3,295 |
// Setting up stdin and stdout
process.stdin.resume();
process.stdin.setEncoding('utf8');
/**
* fibonacci
* The Fibonacci Sequence is the series of numbers:
* 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
* The next number is found by adding up the two numbers before it
* @param string num - the user input we need to find the series for - ex: 5
* @return - return the fibonacci series - ex: 0,1,1,2,3,5
*/
function fibonacci(num) {
var first = 0,
second = 1,
next,
list = '';
for (i = 1; i <= num; i++) {
if (i <= 1) {
next = i;
} else {
next = first + second;
first = second;
second = next;
}
// if list isn't set to anything, set it to next
if (list == '') {
list = next;
} else {
list = list + ',' + next;
}
}
return list;
}
/**
* handle input
* @param string str - the user input
* @return - the user's modify input
*/
function handle_input(callback) {
var stdin = process.stdin;
stdin.resume();
stdin.once('data', function(data) {
data.toString().trim();
// this will remove all sorts of line breaks
data = data.replace(/(\r\n|\n|\r)/gm,'');
callback(fibonacci(data));
});
}
console.log("Enter the number you want to see a fibonacci series for");
handle_input(function(res) {
console.log("Fibonacci Series: ",res);
process.exit();
}); | jshemas/Projects | Numbers/node_fibonacci.js | JavaScript | mit | 1,310 |
version https://git-lfs.github.com/spec/v1
oid sha256:4e32e53cb8f80919716179336348f5500f14b247a2d481c21ace244021e68832
size 1578
| yogeshsaroya/new-cdnjs | ajax/libs/timelinejs/2.27.0/js/locale/fi.js | JavaScript | mit | 129 |
Patients = new Mongo.Collection("patients"); | chilldude/patientdb | both/collections/patients.js | JavaScript | mit | 44 |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import ReactEcharts from 'echarts-for-react';
import { updateOption } from '../../../redux/dynamicEchart/reducer';
class DynamicChartComponent extends Component {
constructor(props) {
super(props);
this.fetchNewDate = this.fetchNewDate.bind(this);
this.count = 0;
}
fetchNewDate() {
this.props.updateOption();
}
componentDidMount() {
if (this.timeTicket) {
clearInterval(this.timeTicket);
}
this.timeTicket = setInterval(this.fetchNewDate, 2500);
}
componentWillUnmount() {
if (this.timeTicket) {
clearInterval(this.timeTicket);
}
}
render() {
const option = this.props.option;
return (
<div className="examples">
<ReactEcharts
ref="echarts_react"
option={option}
style={{ height: 300 }}
/>
</div>
);
}
}
export default connect(
state => ({
...state.DynamicChartComponent.toJS(),
}),
{ updateOption },
)(DynamicChartComponent);
| EncontrAR/backoffice | src/containers/Charts/echarts/dynamicChartComponent.js | JavaScript | mit | 1,059 |
/*
* china_area.zepto
* https://github.com/sang/china_area.zepto
*
* Copyright (c) 2015 alfred sang
* Licensed under the MIT license.
*/
(function($) {
// Collection method.
$.fn.china_area_zepto = function() {
return this.each(function(i) {
// Do something awesome to each selected element.
$(this).html('awesome' + i);
});
};
// Static method.
$.china_area_zepto = function(options) {
// Override default options with passed-in options.
options = $.extend({}, $.china_area_zepto.options, options);
// Return something awesome.
return 'awesome' + options.punctuation;
};
// Static method default options.
$.china_area_zepto.options = {
punctuation: '.'
};
// Custom selector.
$.expr[':'].china_area_zepto = function(elem) {
// Is this element awesome?
return $(elem).text().indexOf('awesome') !== -1;
};
}(jQuery));
| i5ting/china_area.zepto | src/jquery.china_area.zepto.js | JavaScript | mit | 901 |
//v.3.6 build 130416
/*
Copyright DHTMLX LTD. http://www.dhtmlx.com
To use this component please contact [email protected] to obtain license
*/
/*
Limitation:
a) Width of column in px
b) Grid not autoresizable
c) Initialize grid in visible state
*/
dhtmlXGridObject.prototype._init_point_bspl=dhtmlXGridObject.prototype._init_point;
dhtmlXGridObject.prototype._init_point = function(){
if (this._split_later)
this.splitAt(this._split_later);
this._init_point=this._init_point_bspl;
if (this._init_point) this._init_point();
}
/**
* @desc: split grid in two parts, with separate scrolling
* @param: ind - index of column to split after
* @edition: Professional
* @type: public$
*/
dhtmlXGridObject.prototype.splitAt=function(ind){
if (!this.obj.rows[0]) return this._split_later=ind;
ind=parseInt(ind);
var leftBox=document.createElement("DIV");
this.entBox.appendChild(leftBox);
var rightBox=document.createElement("DIV");
this.entBox.appendChild(rightBox);
for (var i=this.entBox.childNodes.length-3; i>=0; i--)
rightBox.insertBefore(this.entBox.childNodes[i],rightBox.firstChild);
this.entBox.style.position="relative";
this.globalBox=this.entBox;
this.entBox=rightBox; rightBox.grid=this;
leftBox.style.cssText+="border:0px solid red !important;";
rightBox.style.cssText+="border:0px solid red !important;";
rightBox.style.top="0px";
rightBox.style.position="absolute";
leftBox.style.position="absolute";
leftBox.style.top="0px";
leftBox.style.left="0px";
leftBox.style.zIndex=11;
rightBox.style.height=leftBox.style.height=this.globalBox.clientHeight;
this._fake=new dhtmlXGridObject(leftBox);
this._fake.setSkin("not_existing_skin");
this.globalBox=this._fake.globalBox=this.globalBox;
this._fake._fake=this;
this._fake._realfake=true;
//copy properties
this._treeC=this.cellType._dhx_find("tree");
this._fake.delim=this.delim;
this._fake.customGroupFormat=this.customGroupFormat;
this._fake.imgURL=this.imgURL;
this._fake._customSorts=this._customSorts;
this._fake.noHeader=this.noHeader;
this._fake._enbTts=this._enbTts;
this._fake._htkebl = this._htkebl;
this._fake.clists = this.clists;
this._fake.fldSort=new Array();
this._fake.selMultiRows=this.selMultiRows;
this._fake.multiLine=this.multiLine;
if (this.multiLine || this._erspan){
this.attachEvent("onCellChanged",this._correctRowHeight);
this.attachEvent("onRowAdded",this._correctRowHeight);
var corrector=function(){
this.forEachRow(function(id){
this._correctRowHeight(id);
})
};
this.attachEvent("onPageChanged",corrector);
this.attachEvent("onXLE",corrector);
this.attachEvent("onResizeEnd",corrector);
if (!this._ads_count) //in case of distribute parsing - use special event instead
this.attachEvent("onAfterSorting",corrector);
this.attachEvent("onDistributedEnd",corrector);
//this._fake.attachEvent("onCellChanged",this._correctRowHeight);
}
this.attachEvent("onGridReconstructed",function(){
this._fake.objBox.scrollTop = this.objBox.scrollTop;
})
this._fake.loadedKidsHash=this.loadedKidsHash;
if (this._h2) this._fake._h2=this._h2;
this._fake._dInc=this._dInc;
//collect grid configuraton
var b_ha=[[],[],[],[],[],[],[]];
var b_ar=["hdrLabels","initCellWidth","cellType","cellAlign","cellVAlign","fldSort","columnColor"];
var b_fu=["setHeader","setInitWidths","setColTypes","setColAlign","setColVAlign","setColSorting","setColumnColor"];
this._fake.callEvent=function(){
this._fake._split_event=true;
if (arguments[0]=="onGridReconstructed")
this._fake.callEvent.apply(this,arguments);
return this._fake.callEvent.apply(this._fake,arguments);
this._fake._split_event=false;
}
if (this._elmn)
this._fake.enableLightMouseNavigation(true);
if (this.__cssEven||this._cssUnEven)
this._fake.attachEvent("onGridReconstructed",function(){
this._fixAlterCss();
});
this._fake._cssEven=this._cssEven;
this._fake._cssUnEven=this._cssUnEven;
this._fake._cssSP=this._cssSP;
this._fake.isEditable=this.isEditable;
this._fake._edtc=this._edtc;
if (this._sst) this._fake.enableStableSorting(true);
this._fake._sclE=this._sclE;
this._fake._dclE=this._dclE;
this._fake._f2kE=this._f2kE;
this._fake._maskArr=this._maskArr;
this._fake._dtmask=this._dtmask;
this._fake.combos=this.combos;
var width=0;
var m_w=this.globalBox.offsetWidth;
for (var i=0; i<ind; i++){
for (var j=0; j<b_ar.length; j++){
if (this[b_ar[j]])
b_ha[j][i]=this[b_ar[j]][i];
if (typeof b_ha[j][i] == "string") b_ha[j][i]=b_ha[j][i].replace(new RegExp("\\"+this.delim,"g"),"\\"+this.delim);
}
if (_isFF) b_ha[1][i]=b_ha[1][i]*1;
if ( this.cellWidthType == "%"){
b_ha[1][i]=Math.round(parseInt(this[b_ar[1]][i])*m_w/100);
width+=b_ha[1][i];
} else
width+=parseInt(this[b_ar[1]][i]);
this.setColumnHidden(i,true);
}
for (var j=0; j<b_ar.length; j++){
var str=b_ha[j].join(this.delim);
if (b_fu[j]!="setHeader"){
if (str!="")
this._fake[b_fu[j]](str);
} else
this._fake[b_fu[j]](str,null,this._hstyles);
}
this._fake._strangeParams=this._strangeParams;
this._fake._drsclmn=this._drsclmn;
width = Math.min(this.globalBox.offsetWidth, width);
rightBox.style.left=width+"px"; leftBox.style.width=width+"px";
rightBox.style.width=Math.max(this.globalBox.offsetWidth-width,0);
if (this._ecspn) this._fake._ecspn=true;
// this._fake.setNoHeader(true);
this._fake.init();
if (this.dragAndDropOff)
this.dragger.addDragLanding(this._fake.entBox, this);
this._fake.objBox.style.overflow="hidden";
this._fake.objBox.style.overflowX="scroll";
this._fake._srdh=this._srdh||20;
this._fake._srnd=this._srnd;
var selfmaster = this;
function _on_wheel(e){
var dir = e.wheelDelta/-40;
if (e.wheelDelta === window.undefined)
dir = e.detail;
var cont = selfmaster.objBox;
cont.scrollTop += dir*40;
if (e.preventDefault)
e.preventDefault();
}
dhtmlxEvent(this._fake.objBox,"mousewheel",_on_wheel);
dhtmlxEvent(this._fake.objBox,"DOMMouseScroll",_on_wheel);
//inner methods
function change_td(a,b){
b.style.whiteSpace="";
var c=b.nextSibling;
var cp=b.parentNode;
a.parentNode.insertBefore(b,a);
if (!c)
cp.appendChild(a);
else
cp.insertBefore(a,c);
var z=a.style.display;
a.style.display=b.style.display;
b.style.display=z;
}
function proc_hf(i,rows,mode,frows){
var temp_header=(new Array(ind)).join(this.delim);
var temp_rspan=[];
if (i==2)
for (var k=0; k<ind; k++){
var r=rows[i-1].cells[rows[i-1]._childIndexes?rows[i-1]._childIndexes[k]:k];
if (r.rowSpan && r.rowSpan>1){
temp_rspan[r._cellIndex]=r.rowSpan-1;
frows[i-1].cells[frows[i-1]._childIndexes?frows[i-1]._childIndexes[k]:k].rowSpan=r.rowSpan;
r.rowSpan=1;
}
}
for (i; i<rows.length; i++){
this._fake.attachHeader(temp_header,null,mode);
frows=frows||this._fake.ftr.childNodes[0].rows;
var max_ind=ind;
var r_cor=0;
for (var j=0; j<max_ind; j++){
if (temp_rspan[j]) {
temp_rspan[j]=temp_rspan[j]-1;
if (_isIE || (_isFF && _FFrv >= 1.9 ) || _isOpera) {
var td=document.createElement("TD");
if (_isFF) td.style.display="none";
rows[i].insertBefore(td,rows[i].cells[0])
}
r_cor++;
continue;
}
var a=frows[i].cells[j-r_cor];
var b=rows[i].cells[j-(_isIE?0:r_cor)];
var t=b.rowSpan;
change_td(a,b);
if (t>1){
temp_rspan[j]=t-1;
b.rowSpan=t;
}
if (frows[i].cells[j].colSpan>1){
rows[i].cells[j].colSpan=frows[i].cells[j].colSpan;
max_ind-=frows[i].cells[j].colSpan-1;
for (var k=1; k < frows[i].cells[j].colSpan; k++)
frows[i].removeChild(frows[i].cells[j+1]);
}
}
}
}
if (this.hdr.rows.length>2)
proc_hf.call(this,2,this.hdr.rows,"_aHead",this._fake.hdr.rows);
if (this.ftr){
proc_hf.call(this,1,this.ftr.childNodes[0].rows,"_aFoot");
this._fake.ftr.parentNode.style.bottom=(_isFF?2:1)+"px";
}
if (this.saveSizeToCookie){
this.saveSizeToCookie=function(name,cookie_param){
if (this._realfake)
return this._fake.saveSizeToCookie.apply(this._fake,arguments);
if (!name) name=this.entBox.id;
var z=new Array();
var n="cellWidthPX";
for (var i=0; i<this[n].length; i++)
if (i<ind)
z[i]=this._fake[n][i];
else
z[i]=this[n][i];
z=z.join(",")
this.setCookie(name,cookie_param,0,z);
var z=(this.initCellWidth||(new Array)).join(",");
this.setCookie(name,cookie_param,1,z);
return true;
}
this.loadSizeFromCookie=function(name){
if (!name) name=this.entBox.id;
var z=this._getCookie(name,1);
if (!z) return
this.initCellWidth=z.split(",");
var z=this._getCookie(name,0);
var n="cellWidthPX";
this.cellWidthType="px";
var summ2=0;
if ((z)&&(z.length)){
z=z.split(",");
for (var i=0; i<z.length; i++)
if (i<ind){
this._fake[n][i]=z[i];
summ2+=z[i]*1;
}
else
this[n][i]=z[i];
}
this._fake.entBox.style.width=summ2+"px";
this._fake.objBox.style.width=summ2+"px";
var pa=this.globalBox.childNodes[1];
pa.style.left=summ2-(_isFF?0:0)+"px";
if (this.ftr)
this.ftr.style.left=summ2-(_isFF?0:0)+"px";
pa.style.width=this.globalBox.offsetWidth-summ2+"px";
this.setSizes();
return true;
}
this._fake.onRSE=this.onRSE;
}
this.setCellTextStyleA=this.setCellTextStyle;
this.setCellTextStyle=function(row_id,i,styleString){
if (i<ind) this._fake.setCellTextStyle(row_id,i,styleString);
this.setCellTextStyleA(row_id,i,styleString);
}
this.setRowTextBoldA=this.setRowTextBold;
this.setRowTextBold = function(row_id){
this.setRowTextBoldA(row_id);
this._fake.setRowTextBold(row_id);
}
this.setRowColorA=this.setRowColor;
this.setRowColor = function(row_id,color){
this.setRowColorA(row_id,color);
this._fake.setRowColor(row_id,color);
}
this.setRowHiddenA=this.setRowHidden;
this.setRowHidden = function(id,state){
this.setRowHiddenA(id,state);
this._fake.setRowHidden(id,state);
}
this.setRowTextNormalA=this.setRowTextNormal;
this.setRowTextNormal = function(row_id){
this.setRowTextNormalA(row_id);
this._fake.setRowTextNormal(row_id);
}
this.getChangedRows = function(and_added){
var res = new Array();
function test(row){
for (var j = 0; j < row.childNodes.length; j++)
if (row.childNodes[j].wasChanged)
return res[res.length]=row.idd;
}
this.forEachRow(function(id){
var row = this.rowsAr[id];
var frow = this._fake.rowsAr[id];
if (row.tagName!="TR" || frow.tagName!="TR") return;
if (and_added && row._added)
res[res.length]=row.idd;
else{
if (!test(row)) test(frow);
}
});
return res.join(this.delim);
};
this.setRowTextStyleA=this.setRowTextStyle;
this.setRowTextStyle = function(row_id,styleString){
this.setRowTextStyleA(row_id,styleString);
if (this._fake.rowsAr[row_id])
this._fake.setRowTextStyle(row_id,styleString);
}
this.lockRowA = this.lockRow;
this.lockRow = function(id,mode){ this.lockRowA(id,mode); this._fake.lockRow(id,mode); }
this.getColWidth = function(i){
if (i<ind) return parseInt(this._fake.cellWidthPX[i]);
else return parseInt(this.cellWidthPX[i]);
};
this.getColumnLabel = function(i){
return this._fake.getColumnLabel.apply(((i<ind)?this._fake:this) ,arguments);
};
this.setColWidthA=this._fake.setColWidthA=this.setColWidth;
this.setColWidth = function(i,value){
i=i*1;
if (i<ind) this._fake.setColWidthA(i,value);
else this.setColWidthA(i,value);
if ((i+1)<=ind) this._fake._correctSplit(Math.min(this._fake.objBox.offsetWidth,this._fake.obj.offsetWidth));
}
this.adjustColumnSizeA=this.adjustColumnSize;
this.setColumnLabelA=this.setColumnLabel;
this.setColumnLabel=function(a,b,c,d){
var that = this;
if (a<ind) that = this._fake;
return this.setColumnLabelA.apply(that,[a,b,c,d]);
}
this.adjustColumnSize=function(aind,c){
if (aind<ind) {
if (_isIE) this._fake.obj.style.tableLayout="";
this._fake.adjustColumnSize(aind,c);
if (_isIE) this._fake.obj.style.tableLayout="fixed";
this._fake._correctSplit();
}
else return this.adjustColumnSizeA(aind,c);
}
var zname="cells";
this._bfs_cells=this[zname];
this[zname]=function(){
if (arguments[1]<ind){
return this._fake.cells.apply(this._fake,arguments);
} else
return this._bfs_cells.apply(this,arguments);
}
this._bfs_isColumnHidden=this.isColumnHidden;
this.isColumnHidden=function(){
if (parseInt(arguments[0])<ind)
return this._fake.isColumnHidden.apply(this._fake,arguments);
else
return this._bfs_isColumnHidden.apply(this,arguments);
}
this._bfs_setColumnHidden=this.setColumnHidden;
this.setColumnHidden=function(){
if (parseInt(arguments[0])<ind){
this._fake.setColumnHidden.apply(this._fake,arguments);
return this._fake._correctSplit();
}
else
return this._bfs_setColumnHidden.apply(this,arguments);
}
var zname="cells2";
this._bfs_cells2=this[zname];
this[zname]=function(){
if (arguments[1]<ind)
return this._fake.cells2.apply(this._fake,arguments);
else
return this._bfs_cells2.apply(this,arguments);
}
var zname="cells3";
this._bfs_cells3=this[zname];
this[zname]=function(a,b){
if (arguments[1]<ind && this._fake.rowsAr[arguments[0].idd]){
//fall back for totally rowspanned row
if (this._fake.rowsAr[a.idd] && this._fake.rowsAr[a.idd].childNodes.length==0) return this._bfs_cells3.apply(this,arguments);
arguments[0]=arguments[0].idd;
return this._fake.cells.apply(this._fake,arguments);
}
else
return this._bfs_cells3.apply(this,arguments);
}
var zname="changeRowId";
this._bfs_changeRowId=this[zname];
this[zname]=function(){
this._bfs_changeRowId.apply(this,arguments);
if (this._fake.rowsAr[arguments[0]])
this._fake.changeRowId.apply(this._fake,arguments);
}
this._fake.getRowById=function(id){
var row = this.rowsAr[id];
if (!row && this._fake.rowsAr[id]) row=this._fake.getRowById(id);
if (row){
if (row.tagName != "TR"){
for (var i = 0; i < this.rowsBuffer.length; i++)
if (this.rowsBuffer[i] && this.rowsBuffer[i].idd == id)
return this.render_row(i);
if (this._h2) return this.render_row(null,row.idd);
}
return row;
}
return null;
}
if (this.collapseKids){
//tree grid
this._fake["_bfs_collapseKids"]=this.collapseKids;
this._fake["collapseKids"]=function(){
return this._fake["collapseKids"].apply(this._fake,[this._fake.rowsAr[arguments[0].idd]]);
}
this["_bfs_collapseKids"]=this.collapseKids;
this["collapseKids"]=function(){
var z=this["_bfs_collapseKids"].apply(this,arguments);
this._fake._h2syncModel();
if (!this._cssSP) this._fake._fixAlterCss();
}
this._fake["_bfs_expandKids"]=this.expandKids;
this._fake["expandKids"]=function(){
this._fake["expandKids"].apply(this._fake,[this._fake.rowsAr[arguments[0].idd]]);
if (!this._cssSP) this._fake._fixAlterCss();
}
this["_bfs_expandAll"]=this.expandAll;
this["expandAll"]=function(){
this._bfs_expandAll();
this._fake._h2syncModel();
if (!this._cssSP) this._fake._fixAlterCss();
}
this["_bfs_collapseAll"]=this.collapseAll;
this["collapseAll"]=function(){
this._bfs_collapseAll();
this._fake._h2syncModel();
if (!this._cssSP) this._fake._fixAlterCss();
}
this["_bfs_expandKids"]=this.expandKids;
this["expandKids"]=function(){
var z=this["_bfs_expandKids"].apply(this,arguments);
this._fake._h2syncModel();
if (!this._cssSP) this._fake._fixAlterCss();
}
this._fake._h2syncModel=function(){
if (this._fake.pagingOn) this._fake._renderSort();
else this._renderSort();
}
this._updateTGRState=function(a){
return this._fake._updateTGRState(a);
}
}
//split
if (this._elmnh){
this._setRowHoverA=this._fake._setRowHoverA=this._setRowHover;
this._unsetRowHoverA=this._fake._unsetRowHoverA=this._unsetRowHover;
this._setRowHover=this._fake._setRowHover=function(){
var that=this.grid;
that._setRowHoverA.apply(this,arguments);
var z=(_isIE?event.srcElement:arguments[0].target);
z=that._fake.rowsAr[that.getFirstParentOfType(z,'TD').parentNode.idd];
if (z){
that._fake._setRowHoverA.apply(that._fake.obj,[{target:z.childNodes[0]},arguments[1]]);
}
};
this._unsetRowHover=this._fake._unsetRowHover=function(){
if (arguments[1]) var that=this;
else var that=this.grid;
that._unsetRowHoverA.apply(this,arguments);
that._fake._unsetRowHoverA.apply(that._fake.obj,arguments);
};
this._fake.enableRowsHover(true,this._hvrCss);
this.enableRowsHover(false);
this.enableRowsHover(true,this._fake._hvrCss);
}
this._updateTGRState=function(z){
if (!z.update || z.id==0) return;
if (this.rowsAr[z.id].imgTag)
this.rowsAr[z.id].imgTag.src=this.imgURL+z.state+".gif";
if (this._fake.rowsAr[z.id] && this._fake.rowsAr[z.id].imgTag)
this._fake.rowsAr[z.id].imgTag.src=this.imgURL+z.state+".gif";
z.update=false;
}
this.copy_row=function(row){
var x=row.cloneNode(true);
x._skipInsert=row._skipInsert;
var r_ind=ind;
x._attrs={};
x._css = row._css;
if (this._ecspn){
r_ind=0;
for (var i=0; (r_ind<x.childNodes.length && i<ind); i+=(x.childNodes[r_ind].colSpan||1))
r_ind++;
}
while (x.childNodes.length>r_ind)
x.removeChild(x.childNodes[x.childNodes.length-1]);
var zm=r_ind;
for (var i=0; i<zm; i++){
if (this.dragAndDropOff)
this.dragger.addDraggableItem(x.childNodes[i], this);
x.childNodes[i].style.display=(this._fake._hrrar?(this._fake._hrrar[i]?"none":""):"");
x.childNodes[i]._cellIndex=i;
//TODO - more universal solution
x.childNodes[i].combo_value=arguments[0].childNodes[i].combo_value;
x.childNodes[i]._clearCell=arguments[0].childNodes[i]._clearCell;
x.childNodes[i]._cellType=arguments[0].childNodes[i]._cellType;
x.childNodes[i]._brval=arguments[0].childNodes[i]._brval;
x.childNodes[i]._attrs=arguments[0].childNodes[i]._attrs;
x.childNodes[i].chstate=arguments[0].childNodes[i].chstate;
if (row._attrs['style']) x.childNodes[i].style.cssText+=";"+row._attrs['style'];
if(x.childNodes[i].colSpan>1)
this._childIndexes=this._fake._childIndexes;
}
if (this._h2 && this._treeC < ind){
var trow=this._h2.get[arguments[0].idd];
x.imgTag=x.childNodes[this._treeC].childNodes[0].childNodes[trow.level];
x.valTag=x.childNodes[this._treeC].childNodes[0].childNodes[trow.level+2];
}
x.idd=row.idd;
x.grid=this._fake;
return x;
}
var zname="_insertRowAt";
this._bfs_insertRowAt=this[zname];
this[zname]=function(){
var r=this["_bfs_insertRowAt"].apply(this,arguments);
arguments[0]=this.copy_row(arguments[0]);
var r2=this._fake["_insertRowAt"].apply(this._fake,arguments);
if (r._fhd){
r2.parentNode.removeChild(r2);
this._fake.rowsCol._dhx_removeAt(this._fake.rowsCol._dhx_find(r2));
r._fhd=false;
}
return r;
}
/*
var quirks = (_isIE && document.compatMode=="BackCompat");
var isVScroll = this.parentGrid?false:(this.objBox.scrollHeight > this.objBox.offsetHeight);
var isHScroll = this.parentGrid?false:(this.objBox.scrollWidth > this.objBox.offsetWidth);
var scrfix = _isFF?20:18;
var outerBorder=(this.entBox.offsetWidth-this.entBox.clientWidth)/2;
var gridWidth=this.entBox.clientWidth;
var gridHeight=this.entBox.clientHeight;
*/
this._bfs_setSizes=this.setSizes;
this.setSizes=function(){
if (this._notresize) return;
this._bfs_setSizes(this,arguments);
this.sync_headers()
if (this.sync_scroll() && this._ahgr) this.setSizes(); //if scrolls was removed - check once more to correct auto-height
this._fake.entBox.style.height=this.entBox.style.height;
this._fake.objBox.style.height=this.objBox.style.height;
this._fake.hdrBox.style.height=this.hdrBox.style.height;
this._fake.objBox.scrollTop=this.objBox.scrollTop;
this._fake.setColumnSizes(this._fake.entBox.clientWidth);
this.globalBox.style.width=parseInt(this.entBox.style.width)+parseInt(this._fake.entBox.style.width);
this.globalBox.style.height=this.entBox.style.height;
}
this.sync_scroll=this._fake.sync_scroll=function(end){
var old=this.objBox.style.overflowX;
if (this.obj.offsetWidth<=this.objBox.offsetWidth)
{
if (!end) return this._fake.sync_scroll(true);
this.objBox.style.overflowX="hidden";
this._fake.objBox.style.overflowX="hidden";
}
else{
this.objBox.style.overflowX="scroll";
this._fake.objBox.style.overflowX="scroll";
}
return old!=this.objBox.style.overflowX;
}
this.sync_headers=this._fake.sync_headers=function(){
if (this.noHeader || (this._fake.hdr.scrollHeight==this.hdr.offsetHeight)) return;
// if (this.hdr.rows.length!=2){
for (var i=1; i<this.hdr.rows.length; i++){
var ha=this.hdr.rows[i].scrollHeight; var hb=this._fake.hdr.rows[i].scrollHeight;
if (ha!=hb)
this._fake.hdr.rows[i].style.height=this.hdr.rows[i].style.height=Math.max(ha,hb)+"px";
if (window._KHTMLrv)
this._fake.hdr.rows[i].childNodes[0].style.height=this.hdr.rows[i].childNodes[ind].style.height=Math.max(ha,hb)+"px";
}
this._fake.sync_headers;
// } else this._fake.hdr.style.height=this.hdr.offsetHeight+"px";
}
this._fake._bfs_setSizes=this._fake.setSizes;
this._fake.setSizes=function(){
if (this._fake._notresize) return;
this._fake.setSizes();
}
var zname="_doOnScroll";
this._bfs__doOnScroll=this[zname];
this[zname]=function(){
this._bfs__doOnScroll.apply(this,arguments);
this._fake.objBox.scrollTop=this.objBox.scrollTop;
this._fake["_doOnScroll"].apply(this._fake,arguments);
}
var zname="selectAll";
this._bfs__selectAll=this[zname];
this[zname]=function(){
this._bfs__selectAll.apply(this,arguments);
this._bfs__selectAll.apply(this._fake,arguments);
}
var zname="doClick";
this._bfs_doClick=this[zname];
this[zname]=function(){
this["_bfs_doClick"].apply(this,arguments);
if (arguments[0].tagName=="TD"){
var fl=(arguments[0]._cellIndex>=ind);
if (!arguments[0].parentNode.idd) return;
if (!fl)
arguments[0].className=arguments[0].className.replace(/cellselected/g,"");
//item selected but it left part not rendered yet
if (!this._fake.rowsAr[arguments[0].parentNode.idd])
this._fake.render_row(this.getRowIndex(arguments[0].parentNode.idd));
arguments[0]=this._fake.cells(arguments[0].parentNode.idd,(fl?0:arguments[0]._cellIndex)).cell;
if (fl) this._fake.cell=null;
this._fake["_bfs_doClick"].apply(this._fake,arguments);
if (fl) this._fake.cell=this.cell;
else this.cell=this._fake.cell;
if (this._fake.onRowSelectTime) clearTimeout(this._fake.onRowSelectTime)
if (fl) {
arguments[0].className=arguments[0].className.replace(/cellselected/g,"");
globalActiveDHTMLGridObject=this;
this._fake.cell=this.cell;
}
else{
this.objBox.scrollTop=this._fake.objBox.scrollTop;
}
}
}
this._fake._bfs_doClick=this._fake[zname];
this._fake[zname]=function(){
this["_bfs_doClick"].apply(this,arguments);
if (arguments[0].tagName=="TD"){
var fl=(arguments[0]._cellIndex<ind);
if (!arguments[0].parentNode.idd) return;
arguments[0]=this._fake._bfs_cells(arguments[0].parentNode.idd,(fl?ind:arguments[0]._cellIndex)).cell;
this._fake.cell=null;
this._fake["_bfs_doClick"].apply(this._fake,arguments);
this._fake.cell=this.cell;
if (this._fake.onRowSelectTime) clearTimeout(this._fake.onRowSelectTime)
if (fl) {
arguments[0].className=arguments[0].className.replace(/cellselected/g,"");
globalActiveDHTMLGridObject=this;
this._fake.cell=this.cell;
this._fake.objBox.scrollTop=this.objBox.scrollTop;
}
}
}
this.clearSelectionA = this.clearSelection;
this.clearSelection = function(mode){
if (mode) this._fake.clearSelection();
this.clearSelectionA();
}
this.moveRowUpA = this.moveRowUp;
this.moveRowUp = function(row_id){
if (!this._h2)
this._fake.moveRowUp(row_id);
this.moveRowUpA(row_id);
if (this._h2) this._fake._h2syncModel();
}
this.moveRowDownA = this.moveRowDown;
this.moveRowDown = function(row_id){
if (!this._h2)
this._fake.moveRowDown(row_id);
this.moveRowDownA(row_id);
if (this._h2) this._fake._h2syncModel();
}
this._fake.getUserData=function(){ return this._fake.getUserData.apply(this._fake,arguments); }
this._fake.setUserData=function(){ return this._fake.setUserData.apply(this._fake,arguments); }
this.getSortingStateA=this.getSortingState;
this.getSortingState = function(){
var z=this.getSortingStateA();
if (z.length!=0) return z;
return this._fake.getSortingState();
}
this.setSortImgStateA=this._fake.setSortImgStateA=this.setSortImgState;
this.setSortImgState = function(a,b,c,d){
this.setSortImgStateA(a,b,c,d);
if (b*1<ind) {
this._fake.setSortImgStateA(a,b,c,d);
this.setSortImgStateA(false);
} else
this._fake.setSortImgStateA(false);
}
this._fake.doColResizeA = this._fake.doColResize;
this._fake.doColResize = function(ev,el,startW,x,tabW){
var a=-1;
var z=0;
if (arguments[1]._cellIndex==(ind-1)){
a = this._initalSplR + (ev.clientX-x);
if (!this._initalSplF) this._initalSplF=arguments[3]+this.objBox.scrollWidth-this.objBox.offsetWidth;
if (this.objBox.scrollWidth==this.objBox.offsetWidth && (this._fake.alter_split_resize || (ev.clientX-x)>0 )){
arguments[3]=(this._initalSplF||arguments[3]);
z=this.doColResizeA.apply(this,arguments);
}
else
z=this.doColResizeA.apply(this,arguments);
}
else{
if (this.obj.offsetWidth<this.entBox.offsetWidth)
a=this.obj.offsetWidth;
z=this.doColResizeA.apply(this,arguments);
}
this._correctSplit(a);
this.resized=this._fake.resized=1;
return z;
}
this._fake.changeCursorState = function(ev){
var el = ev.target||ev.srcElement;
if(el.tagName!="TD")
el = this.getFirstParentOfType(el,"TD")
if ((el.tagName=="TD")&&(this._drsclmn)&&(!this._drsclmn[el._cellIndex])) return;
var check = (ev.layerX||0)+(((!_isIE)&&(ev.target.tagName=="DIV"))?el.offsetLeft:0);
var pos = parseInt(this.getPosition(el,this.hdrBox));
if(((el.offsetWidth - (ev.offsetX||(pos-check)*-1))<(_isOpera?20:10))||((this.entBox.offsetWidth - (ev.offsetX?(ev.offsetX+el.offsetLeft):check) + this.objBox.scrollLeft - 0)<(_isOpera?20:10))){
el.style.cursor = "E-resize";
}else
el.style.cursor = "default";
if (_isOpera) this.hdrBox.scrollLeft = this.objBox.scrollLeft;
}
this._fake.startColResizeA = this._fake.startColResize;
this._fake.startColResize = function(ev){
var z=this.startColResizeA(ev);
this._initalSplR=this.entBox.offsetWidth;
this._initalSplF=null;
if (this.entBox.onmousemove){
var m=this.entBox.parentNode;
if (m._aggrid) return z;
m._aggrid=m.grid; m.grid=this;
this.entBox.parentNode.onmousemove=this.entBox.onmousemove;
this.entBox.onmousemove=null;
}
return z;
}
this._fake.stopColResizeA = this._fake.stopColResize;
this._fake.stopColResize = function(ev){
if (this.entBox.parentNode.onmousemove){
var m=this.entBox.parentNode; m.grid=m._aggrid; m._aggrid=null;
this.entBox.onmousemove=this.entBox.parentNode.onmousemove;
this.entBox.parentNode.onmousemove=null;
if (this.obj.offsetWidth<this.entBox.offsetWidth)
this._correctSplit(this.obj.offsetWidth);
}
return this.stopColResizeA(ev);
}
this.doKeyA = this.doKey;
this._fake.doKeyA = this._fake.doKey;
this._fake.doKey=this.doKey=function(ev){
if (!ev) return true;
if (this._htkebl) return true;
if ((ev.target||ev.srcElement).value !== window.undefined){
var zx = (ev.target||ev.srcElement);
if ((!zx.parentNode)||(zx.parentNode.className.indexOf("editable") == -1))
return true;
}
switch (ev.keyCode){
case 9:
if (!ev.shiftKey){
if (this._realfake){
if ((this.cell)&&(this.cell._cellIndex==(ind-1))){
if (ev.preventDefault)
ev.preventDefault();
var ind_t=ind;
while (this._fake._hrrar && this._fake._hrrar[ind_t]) ind_t++;
this._fake.selectCell(this._fake.getRowIndex(this.cell.parentNode.idd),ind_t,false,false,true);
return false;
}
else
var z=this.doKeyA(ev);
globalActiveDHTMLGridObject=this;
return z;
}
else{
if (this.cell){
var ind_t=this.cell._cellIndex+1;
while (this.rowsCol[0].childNodes[ind_t] && this.rowsCol[0].childNodes[ind_t].style.display=="none") ind_t++;
if (ind_t == this.rowsCol[0].childNodes.length){
if (ev.preventDefault)
ev.preventDefault();
var z=this.rowsBuffer[this.getRowIndex(this.cell.parentNode.idd)+1];
if (z) {
this.showRow(z.idd);
this._fake.selectCell(this._fake.getRowIndex(z.idd),0,false,false,true);
return false;
}
}
}
return this.doKeyA(ev);
}
}
else{
if (this._realfake){
if ((this.cell)&&(this.cell._cellIndex==0)){
if (ev.preventDefault)
ev.preventDefault();
var z=this._fake.rowsBuffer[this._fake.getRowIndex(this.cell.parentNode.idd)-1];
if (z) {
this._fake.showRow(z.idd);
var ind_t=this._fake._cCount-1;
while (z.childNodes[ind_t].style.display=="none")
ind_t--;
this._fake.selectCell(this._fake.getRowIndex(z.idd),ind_t,false,false,true);
}
return false;
}
else
return this.doKeyA(ev);
}
else{
if ((this.cell)&&(this.cell._cellIndex==ind)){
if (ev.preventDefault)
ev.preventDefault();
this._fake.selectCell(this.getRowIndex(this.cell.parentNode.idd),ind-1,false,false,true);
return false;
}
else
return this.doKeyA(ev);
}
}
break;
}
return this.doKeyA(ev);
}
this.editCellA=this.editCell;
this.editCell=function(){
if (this.cell && this.cell.parentNode.grid != this) return this._fake.editCell();
return this.editCellA();
}
this.deleteRowA = this.deleteRow;
this.deleteRow=function(row_id,node){
/* if (!this._realfake)
this._fake.loadedKidsHash=this.loadedKidsHash;*/
if (this.deleteRowA(row_id,node)===false) return false;
if (this._fake.rowsAr[row_id])
this._fake.deleteRow(row_id);
}
this.clearAllA = this.clearAll;
this.clearAll=function(){
this.clearAllA();
this._fake.clearAll();
}
this.editStopA = this.editStop;
this.editStop=function(){
if (this._fake.editor)
this._fake.editStop();
else
this.editStopA();
};
this.attachEvent("onAfterSorting",function(i,b,c){
if (i>=ind)
this._fake.setSortImgState(false)
});
this._fake.sortField = function(a,b,c){
this._fake.sortField.call(this._fake,a,b,this._fake.hdr.rows[0].cells[a]);
if (this.fldSort[a]!="na" && this._fake.fldSorted){
var mem = this._fake.getSortingState()[1];
this._fake.setSortImgState(false);
this.setSortImgState(true,arguments[0],mem)
}
}
this.sortTreeRowsA = this.sortTreeRows;
this._fake.sortTreeRowsA = this._fake.sortTreeRows;
this.sortTreeRows=this._fake.sortTreeRows=function(col,type,order,ar){
if (this._realfake) return this._fake.sortTreeRows(col,type,order,ar)
this.sortTreeRowsA(col,type,order,ar);
this._fake._h2syncModel();
this._fake.setSortImgStateA(false);
this._fake.fldSorted=null;
}
/* SRND mode */
this._fake._fillers=[];
this._fake.rowsBuffer=this.rowsBuffer;
this.attachEvent("onClearAll",function(){
this._fake.rowsBuffer=this.rowsBuffer;
})
this._add_filler_s=this._add_filler;
this._add_filler=function(a,b,c,e){
if (!this._fake._fillers) this._fake._fillers=[];
if (this._realfake || !e){
var d;
if (c || !this._fake._fillers.length){
if (c && c.idd) d=this._fake.rowsAr[c.idd];
else if (c && c.nextSibling) {
d = {};
d.nextSibling=this._fake.rowsAr[c.nextSibling.idd];
d.parentNode=d.nextSibling.parentNode;
}
this._fake._fillers.push(this._fake._add_filler(a,b,d));
}
}
return this._add_filler_s.apply(this,arguments);
}
this._add_from_buffer_s=this._add_from_buffer;
this._add_from_buffer=function() {
var res=this._add_from_buffer_s.apply(this,arguments);
if (res!=-1){
this._fake._add_from_buffer.apply(this._fake,arguments);
if (this.multiLine) this._correctRowHeight(this.rowsBuffer[arguments[0]].idd);
}
return res;
}
this._fake.render_row=function(ind){
var row=this._fake.render_row(ind);
if (row == -1) return -1;
if (row) {
return this.rowsAr[row.idd]=this.rowsAr[row.idd]||this._fake.copy_row(row);
}
return null;
}
this._reset_view_s=this._reset_view;
this._reset_view=function(){
this._fake._reset_view(true);
this._fake._fillers=[];
this._reset_view_s();
}
this.moveColumn_s=this.moveColumn;
this.moveColumn=function(a,b){
if (b>=ind) return this.moveColumn_s(a,b);
}
this.attachEvent("onCellChanged",function(id,i,val){
if (this._split_event && i<ind && this.rowsAr[id]){
var cell=this._fake.rowsAr[id];
if (!cell) return;
if (cell._childIndexes)
cell=cell.childNodes[cell._childIndexes[i]];
else
cell=cell.childNodes[i];
var tcell = this.rowsAr[id].childNodes[i];
if (tcell._treeCell && tcell.firstChild.lastChild)
tcell.firstChild.lastChild.innerHTML = val;
else
tcell.innerHTML=cell.innerHTML;
tcell._clearCell=false;
tcell.combo_value = cell.combo_value;
tcell.chstate=cell.chstate; //TODO - more universal solution
}
})
this._fake.combos=this.combos;
this.setSizes();
if (this.rowsBuffer[0]) this._reset_view();
this.attachEvent("onXLE",function(){this._fake._correctSplit()})
this._fake._correctSplit();
}
dhtmlXGridObject.prototype._correctSplit=function(a){
a=a||(this.obj.scrollWidth-this.objBox.scrollLeft);
a=Math.min(this.globalBox.offsetWidth, a);
if (a>-1){
this.entBox.style.width=a+"px";
this.objBox.style.width=a+"px";
var outerBorder=(this.globalBox.offsetWidth-this.globalBox.clientWidth)/2;
this._fake.entBox.style.left=a+"px";
this._fake.entBox.style.width=Math.max(0,this.globalBox.offsetWidth-a-(this.quirks?0:2)*outerBorder)+"px";
if (this._fake.ftr)
this._fake.ftr.parentNode.style.width=this._fake.entBox.style.width;
if (_isIE){
var quirks=_isIE && !window.xmlHttpRequest;
var outerBorder=(this.globalBox.offsetWidth-this.globalBox.clientWidth);
this._fake.hdrBox.style.width=this._fake.objBox.style.width=Math.max(0,this.globalBox.offsetWidth-(quirks?outerBorder:0)-a)+"px";
}
}
}
dhtmlXGridObject.prototype._correctRowHeight=function(id,ind){
if (!this.rowsAr[id] || !this._fake.rowsAr[id]) return;
var h=this.rowsAr[id].offsetHeight;
var h2=this._fake.rowsAr[id].offsetHeight;
var max = Math.max(h,h2);
if (!max) return;
this.rowsAr[id].style.height=this._fake.rowsAr[id].style.height=max+"px";
if (window._KHTMLrv) this.rowsAr[id].childNodes[this._fake._cCount].style.height=this._fake.rowsAr[id].firstChild.style.height=max+"px";
}
//(c)dhtmlx ltd. www.dhtmlx.com
| tottaz/yggdrasil | third_party/modules/dhtmlx/grid/ext/dhtmlxgrid_splt.js | JavaScript | mit | 42,780 |
angular.module('duScroll.scrollspy', ['duScroll.spyAPI'])
.directive('duScrollspy', function(spyAPI, $timeout, $rootScope) {
'use strict';
var Spy = function(targetElementOrId, $element, offset) {
if(angular.isElement(targetElementOrId)) {
this.target = targetElementOrId;
} else if(angular.isString(targetElementOrId)) {
this.targetId = targetElementOrId;
}
this.$element = $element;
this.offset = offset;
};
Spy.prototype.getTargetElement = function() {
if (!this.target && this.targetId) {
this.target = document.getElementById(this.targetId);
}
return this.target;
};
Spy.prototype.getTargetPosition = function() {
var target = this.getTargetElement();
if(target) {
return target.getBoundingClientRect();
}
};
Spy.prototype.flushTargetCache = function() {
if(this.targetId) {
this.target = undefined;
}
};
return {
link: function ($scope, $element, $attr) {
var href = $attr.ngHref || $attr.href;
var targetId;
if (href && href.indexOf('#') !== -1) {
targetId = href.replace(/.*(?=#[^\s]+$)/, '').substring(1);
} else if($attr.duScrollspy) {
targetId = $attr.duScrollspy;
}
if(!targetId) return;
// Run this in the next execution loop so that the scroll context has a chance
// to initialize
$timeout(function() {
var spy = new Spy(targetId, $element, -($attr.offset ? parseInt($attr.offset, 10) : 0));
spyAPI.addSpy(spy);
$scope.$on('$destroy', function() {
spyAPI.removeSpy(spy);
});
$scope.$on('$locationChangeSuccess', spy.flushTargetCache.bind(spy));
$rootScope.$on('$stateChangeSuccess', spy.flushTargetCache.bind(spy));
}, 0, false);
}
};
});
| 1wheel/angular-scroll | src/directives/scrollspy.js | JavaScript | mit | 1,808 |
/**
* This file is used specifically and only for development. It installs
* `electron-debug` & `vue-devtools`. There shouldn't be any need to
* modify this file, but it can be used to extend your development
* environment.
*/
/* eslint-disable no-console */
// Set environment for development
process.env.NODE_ENV = 'development'
/* // Install `electron-debug` with `devtron`
require('electron-debug')({ showDevTools: true })
// Install `vue-devtools`
require('electron').app.on('ready', () => {
let installExtension = require('electron-devtools-installer')
installExtension.default(installExtension.VUEJS_DEVTOOLS)
.then(() => {})
.catch(err => {
console.log('Unable to install `vue-devtools`: \n', err)
})
}) */
// Require `main` process to boot app
require('./index')
| deboyblog/model-maker-pro | src/main/index.dev.js | JavaScript | mit | 806 |
/* Duplex stream for Tellstick (Duo)
*/
var Duplex = require("stream").Duplex
var inherits = require("util").inherits
var tellsock = require("tellsock")
var through2 = require("through2")
function Tellstick() {
this._init()
Duplex.call(this, { objectMode: true })
}
inherits(Tellstick, Duplex)
Tellstick.prototype._init = function() {
this.events = new tellsock.TelldusEvents()
this.client = new tellsock.TelldusClient()
this.events.on("raw", this.push.bind(this))
this.events.on("end", function() {
console.log("Reconnecting")
setTimeout(this._init.bind(this), 3000)
}.bind(this))
}
Tellstick.prototype._read = function (size) {
}
// [ command, deviceId, arg1, ... ]
Tellstick.prototype._write = function (arr, enc, done) {
this.client[arr.splice(0,1)].apply(this.client, arr)
done()
}
Tellstick.dimmerEvents = function(source) {
/* Events from selflearning remotes come in the form of house, unit, method
* Map them to id, dimLevel events using the remotes.js config */
var buttonMap = require("../config/remotes")
return source.pipe(through2.obj(function(obj, enc, done) {
var house = buttonMap[obj.house] || {}
var tuple = house[obj.unit]
if (tuple) {
this.push({
id: "light" + tuple[0],
key: "dimLevel",
value: (obj.method == 'turnoff') ? 0 : tuple[1],
origin: [ "433mhz", obj.house, obj.unit ].join(":")
})
}
done()
}))
}
Tellstick.sensorEvents = function(source) {
return source.pipe(through2.obj(function(obj, enc, done) {
if (obj.temp || obj.humidity) {
var ev = { id: "rf" + obj.id }
if (obj.temp) ev.temperature = parseFloat(obj.temp);
if (obj.humidity) ev.humidity = parseFloat(obj.humidity);
this.push(ev)
}
done()
}))
}
module.exports = Tellstick | wittfeldt/smart-home | lib/Tellstick.js | JavaScript | mit | 1,977 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var JSONLocation = (function () {
function JSONLocation(segments) {
this.segments = segments;
}
JSONLocation.prototype.append = function (segment) {
return new JSONLocation(this.segments.concat(segment));
};
JSONLocation.prototype.getSegments = function () {
return this.segments;
};
JSONLocation.prototype.matches = function (segments) {
var k = 0;
for (var i = 0; k < segments.length && i < this.segments.length; i++) {
if (segments[k] === this.segments[i] || segments[k] === '*') {
k++;
}
else if (segments[k] !== '**') {
return false;
}
}
return k === segments.length;
};
JSONLocation.prototype.toString = function () {
return '[' + this.segments.join('][') + ']';
};
return JSONLocation;
}());
exports.JSONLocation = JSONLocation;
//# sourceMappingURL=jsonLocation.js.map | paulmarsy/Console | Libraries/Visual Studio Code/App/resources/app/extensions/json/server/out/jsonLocation.js | JavaScript | mit | 1,363 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Broad Institute
*
* 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.
*/
import $ from "../vendor/jquery-3.3.1.slim.js"
import {Alert} from '../../node_modules/igv-ui/dist/igv-ui.js'
import BamSource from "./bamSource.js"
import PairedAlignment from "./pairedAlignment.js"
import TrackBase from "../trackBase.js"
import IGVGraphics from "../igv-canvas.js"
import paintAxis from "../util/paintAxis.js"
import {createCheckbox} from "../igv-icons.js"
import MenuUtils from "../ui/menuUtils.js"
import {PaletteColorTable} from "../util/colorPalletes.js"
import {IGVColor, StringUtils} from "../../node_modules/igv-utils/src/index.js"
import {makePairedAlignmentChords, makeSupplementalAlignmentChords, sendChords} from "../jbrowse/circularViewUtils.js"
import {isSecureContext} from "../util/igvUtils.js"
import PairedEndStats from "./pairedEndStats.js"
const alignmentStartGap = 5
const downsampleRowHeight = 5
const DEFAULT_COVERAGE_TRACK_HEIGHT = 50
const DEFAULT_TRACK_HEIGHT = 300
const DEFAULT_ALIGNMENT_COLOR = "rgb(185, 185, 185)"
const DEFAULT_COVERAGE_COLOR = "rgb(150, 150, 150)"
const DEFAULT_CONNECTOR_COLOR = "rgb(200, 200, 200)"
class BAMTrack extends TrackBase {
constructor(config, browser) {
super(config, browser)
}
init(config) {
super.init(config)
this.type = "alignment"
if (config.alleleFreqThreshold === undefined) {
config.alleleFreqThreshold = 0.2
}
this.featureSource = new BamSource(config, this.browser)
this.showCoverage = config.showCoverage === undefined ? true : config.showCoverage
this.showAlignments = config.showAlignments === undefined ? true : config.showAlignments
this.coverageTrack = new CoverageTrack(config, this)
this.alignmentTrack = new AlignmentTrack(config, this)
this.alignmentTrack.setTop(this.coverageTrack, this.showCoverage)
this.visibilityWindow = config.visibilityWindow || 30000
this.viewAsPairs = config.viewAsPairs
this.pairsSupported = config.pairsSupported !== false
this.showSoftClips = config.showSoftClips
this.showAllBases = config.showAllBases
this.showInsertions = false !== config.showInsertions
this.showMismatches = false !== config.showMismatches
this.color = config.color
this.coverageColor = config.coverageColor
// The sort object can be an array in the case of multi-locus view, however if multiple sort positions
// are present for a given reference frame the last one will take precedence
if (config.sort) {
if (Array.isArray(config.sort)) {
// Legacy support
this.assignSort(config.sort[0])
} else {
this.assignSort(config.sort)
}
}
// Invoke height setter last to allocated to coverage and alignment tracks
this.height = (config.height !== undefined ? config.height : DEFAULT_TRACK_HEIGHT)
}
set height(h) {
this._height = h
if (this.coverageTrack && this.showAlignments) {
this.alignmentTrack.height = this.showCoverage ? h - this.coverageTrack.height : h
}
}
get height() {
return this._height
}
get minTemplateLength() {
const configMinTLEN = this.config.minTLEN !== undefined ? this.config.minTLEN : this.config.minFragmentLength
return (configMinTLEN !== undefined) ? configMinTLEN :
this._pairedEndStats ? this._pairedEndStats.minTLEN : 0
}
get maxTemplateLength() {
const configMaxTLEN = this.config.maxTLEN !== undefined ? this.config.maxTLEN : this.config.maxFragmentLength
return (configMaxTLEN !== undefined) ? configMaxTLEN :
this._pairedEndStats ? this._pairedEndStats.maxTLEN : 1000
}
sort(options) {
options = this.assignSort(options)
for (let vp of this.trackView.viewports) {
if (vp.containsPosition(options.chr, options.position)) {
const alignmentContainer = vp.cachedFeatures
if (alignmentContainer) {
sortAlignmentRows(options, alignmentContainer)
vp.repaint()
}
}
}
}
/**
* Fix syntax problems for sort options.
* @param options
*/
assignSort(options) {
// convert old syntax
if (options.locus) {
const range = StringUtils.parseLocusString(options.locus)
options.chr = range.chr
options.position = range.start
} else {
options.position--
}
options.direction = options.direction === "ASC" || options.direction === true
// chr aliasing
options.chr = this.browser.genome.getChromosomeName(options.chr)
this.sortObject = options
return this.sortObject
}
async getFeatures(chr, bpStart, bpEnd, bpPerPixel, viewport) {
const alignmentContainer = await this.featureSource.getAlignments(chr, bpStart, bpEnd)
if (alignmentContainer.paired && !this._pairedEndStats && !this.config.maxFragmentLength) {
const pairedEndStats = new PairedEndStats(alignmentContainer.alignments, this.config)
if (pairedEndStats.totalCount > 99) {
this._pairedEndStats = pairedEndStats
}
}
alignmentContainer.alignments = undefined // Don't need to hold onto these anymore
const sort = this.sortObject
if (sort) {
if (sort.chr === chr && sort.position >= bpStart && sort.position <= bpEnd) {
sortAlignmentRows(sort, alignmentContainer)
}
}
return alignmentContainer
}
/**
* Compute the pixel height required to display all content. This is not the same as the viewport height
* (track.height) which might include a scrollbar.
*
* @param alignmentContainer
* @returns {number}
*/
computePixelHeight(alignmentContainer) {
return (this.showCoverage ? this.coverageTrack.height : 0) +
(this.showAlignments ? this.alignmentTrack.computePixelHeight(alignmentContainer) : 0) +
15
}
draw(options) {
IGVGraphics.fillRect(options.context, 0, options.pixelTop, options.pixelWidth, options.pixelHeight, {'fillStyle': "rgb(255, 255, 255)"})
if (true === this.showCoverage && this.coverageTrack.height > 0) {
this.trackView.axisCanvas.style.display = 'block'
this.coverageTrack.draw(options)
} else {
this.trackView.axisCanvas.style.display = 'none'
}
if (true === this.showAlignments) {
this.alignmentTrack.setTop(this.coverageTrack, this.showCoverage)
this.alignmentTrack.draw(options)
}
}
paintAxis(ctx, pixelWidth, pixelHeight) {
this.coverageTrack.paintAxis(ctx, pixelWidth, this.coverageTrack.height)
// if (this.browser.isMultiLocusMode()) {
// ctx.clearRect(0, 0, pixelWidth, pixelHeight);
// } else {
// this.coverageTrack.paintAxis(ctx, pixelWidth, this.coverageTrack.height);
// }
}
contextMenuItemList(config) {
return this.alignmentTrack.contextMenuItemList(config)
}
popupData(clickState) {
if (true === this.showCoverage && clickState.y >= this.coverageTrack.top && clickState.y < this.coverageTrack.height) {
return this.coverageTrack.popupData(clickState)
} else {
return this.alignmentTrack.popupData(clickState)
}
}
/**
* Return the features (alignment, coverage, downsampled interval) clicked on. Needed for "onclick" event.
* @param clickState
* @param features
*/
clickedFeatures(clickState) {
if (true === this.showCoverage && clickState.y >= this.coverageTrack.top && clickState.y < this.coverageTrack.height) {
return [this.coverageTrack.getClickedObject(clickState)]
} else {
return [this.alignmentTrack.getClickedObject(clickState)]
}
}
menuItemList() {
// Start with overage track items
let menuItems = []
menuItems = menuItems.concat(MenuUtils.numericDataMenuItems(this.trackView))
// Color by items
menuItems.push('<hr/>')
const $e = $('<div class="igv-track-menu-category">')
$e.text('Color by:')
menuItems.push({name: undefined, object: $e, click: undefined, init: undefined})
const colorByMenuItems = [{key: 'strand', label: 'read strand'}]
if (this.alignmentTrack.hasPairs) {
colorByMenuItems.push({key: 'firstOfPairStrand', label: 'first-of-pair strand'})
colorByMenuItems.push({key: 'pairOrientation', label: 'pair orientation'})
colorByMenuItems.push({key: 'tlen', label: 'insert size (TLEN)'})
colorByMenuItems.push({key: 'unexpectedPair', label: 'pair orientation & insert size (TLEN)'})
}
const tagLabel = 'tag' + (this.alignmentTrack.colorByTag ? ' (' + this.alignmentTrack.colorByTag + ')' : '')
colorByMenuItems.push({key: 'tag', label: tagLabel})
for (let item of colorByMenuItems) {
const selected = (this.alignmentTrack.colorBy === item.key)
menuItems.push(this.colorByCB(item, selected))
}
// Show coverage / alignment options
const adjustTrackHeight = () => {
if (!this.autoHeight) {
const h = 15 +
(this.showCoverage ? this.coverageTrack.height : 0) +
(this.showAlignments ? this.alignmentTrack.height : 0)
this.trackView.setTrackHeight(h)
}
}
menuItems.push('<hr/>')
menuItems.push({
object: $(createCheckbox("Show Coverage", this.showCoverage)),
click: () => {
this.showCoverage = !this.showCoverage
adjustTrackHeight()
this.trackView.checkContentHeight()
this.trackView.repaintViews()
}
})
menuItems.push({
object: $(createCheckbox("Show Alignments", this.showAlignments)),
click: () => {
this.showAlignments = !this.showAlignments
adjustTrackHeight()
this.trackView.checkContentHeight()
this.trackView.repaintViews()
}
})
// Show all bases
menuItems.push('<hr/>')
menuItems.push({
object: $(createCheckbox("Show all bases", this.showAllBases)),
click: () => {
this.showAllBases = !this.showAllBases
this.config.showAllBases = this.showAllBases
this.trackView.repaintViews()
}
})
// Show mismatches
menuItems.push('<hr/>')
menuItems.push({
object: $(createCheckbox("Show mismatches", this.showMismatches)),
click: () => {
this.showMismatches = !this.showMismatches
this.config.showMismatches = this.showMismatches
this.trackView.repaintViews()
}
})
// Insertions
menuItems.push({
object: $(createCheckbox("Show insertions", this.showInsertions)),
click: () => {
this.showInsertions = !this.showInsertions
this.config.showInsertions = this.showInsertions
const alignmentContainers = this.getCachedAlignmentContainers()
this.trackView.repaintViews()
}
})
// Soft clips
menuItems.push({
object: $(createCheckbox("Show soft clips", this.showSoftClips)),
click: () => {
this.showSoftClips = !this.showSoftClips
this.config.showSoftClips = this.showSoftClips
this.featureSource.setShowSoftClips(this.showSoftClips)
const alignmentContainers = this.getCachedAlignmentContainers()
for (let ac of alignmentContainers) {
ac.setShowSoftClips(this.showSoftClips)
}
this.trackView.repaintViews()
}
})
// View as pairs
if (this.pairsSupported && this.alignmentTrack.hasPairs) {
menuItems.push('<hr/>')
menuItems.push({
object: $(createCheckbox("View as pairs", this.viewAsPairs)),
click: () => {
this.viewAsPairs = !this.viewAsPairs
this.config.viewAsPairs = this.viewAsPairs
this.featureSource.setViewAsPairs(this.viewAsPairs)
const alignmentContainers = this.getCachedAlignmentContainers()
for (let ac of alignmentContainers) {
ac.setViewAsPairs(this.viewAsPairs)
}
this.trackView.repaintViews()
}
})
}
// Add chords to JBrowse circular view, if present
if (this.browser.circularView && true === this.browser.circularViewVisible &&
(this.alignmentTrack.hasPairs || this.alignmentTrack.hasSupplemental)) {
menuItems.push('<hr/>')
if (this.alignmentTrack.hasPairs) {
menuItems.push({
label: 'Add discordant pairs to circular view',
click: () => {
for (let viewport of this.trackView.viewports) {
this.addPairedChordsForViewport(viewport)
}
}
})
}
if (this.alignmentTrack.hasSupplemental) {
menuItems.push({
label: 'Add split reads to circular view',
click: () => {
for (let viewport of this.trackView.viewports) {
this.addSplitChordsForViewport(viewport)
}
}
})
}
}
// Display mode
menuItems.push('<hr/>')
const $dml = $('<div class="igv-track-menu-category">')
$dml.text('Display mode:')
menuItems.push({name: undefined, object: $dml, click: undefined, init: undefined})
menuItems.push({
object: $(createCheckbox("expand", this.alignmentTrack.displayMode === "EXPANDED")),
click: () => {
this.alignmentTrack.displayMode = "EXPANDED"
this.config.displayMode = "EXPANDED"
this.trackView.checkContentHeight()
this.trackView.repaintViews()
}
})
menuItems.push({
object: $(createCheckbox("squish", this.alignmentTrack.displayMode === "SQUISHED")),
click: () => {
this.alignmentTrack.displayMode = "SQUISHED"
this.config.displayMode = "SQUISHED"
this.trackView.checkContentHeight()
this.trackView.repaintViews()
}
})
return menuItems
}
/**
* Create a "color by" checkbox menu item, optionally initially checked
* @param menuItem
* @param showCheck
* @returns {{init: undefined, name: undefined, click: clickHandler, object: (jQuery|HTMLElement|jQuery.fn.init)}}
*/
colorByCB(menuItem, showCheck) {
const $e = $(createCheckbox(menuItem.label, showCheck))
const clickHandler = (ev) => {
if (menuItem.key !== 'tag') {
if (menuItem.key === this.alignmentTrack.colorBy) {
this.alignmentTrack.colorBy = 'none'
this.config.colorBy = 'none'
this.trackView.repaintViews()
} else {
this.alignmentTrack.colorBy = menuItem.key
this.config.colorBy = menuItem.key
this.trackView.repaintViews()
}
} else {
this.browser.inputDialog.present({
label: 'Tag Name',
value: this.alignmentTrack.colorByTag ? this.alignmentTrack.colorByTag : '',
callback: (tag) => {
if (tag) {
this.alignmentTrack.colorBy = 'tag'
this.alignmentTrack.colorByTag = tag
if (!this.alignmentTrack.tagColors) {
this.alignmentTrack.tagColors = new PaletteColorTable("Set1")
}
} else {
this.alignmentTrack.colorBy = 'none'
this.alignmentTrack.colorByTag = ''
}
this.trackView.repaintViews()
}
}, ev)
}
}
return {name: undefined, object: $e, click: clickHandler, init: undefined}
}
/**
* Called when the track is removed. Do any needed cleanup here
*/
dispose() {
this.trackView = undefined
}
/**
* Return the current state of the track. Used to create sessions and bookmarks.
*
* @returns {*|{}}
*/
getState() {
const config = super.getState()
if (this.sortObject) {
config.sort = {
chr: this.sortObject.chr,
position: this.sortObject.position + 1,
option: this.sortObject.option,
direction: this.sortObject.direction ? "ASC" : "DESC"
}
}
return config
}
getCachedAlignmentContainers() {
return this.trackView.viewports.map(vp => vp.cachedFeatures)
}
get dataRange() {
return this.coverageTrack.dataRange
}
set dataRange(dataRange) {
this.coverageTrack.dataRange = dataRange
}
get logScale() {
return this.coverageTrack.logScale
}
set logScale(logScale) {
this.coverageTrack.logScale = logScale
}
get autoscale() {
return this.coverageTrack.autoscale
}
set autoscale(autoscale) {
this.coverageTrack.autoscale = autoscale
}
/**
* Add chords to the circular view for the given viewport, represented by its reference frame
* @param refFrame
*/
addPairedChordsForViewport(viewport) {
const maxTemplateLength = this.maxTemplateLength
const inView = []
const refFrame = viewport.referenceFrame
for (let a of viewport.cachedFeatures.allAlignments()) {
if (a.end >= refFrame.start
&& a.start <= refFrame.end
&& a.mate
&& a.mate.chr
&& (a.mate.chr !== a.chr || Math.max(a.fragmentLength) > maxTemplateLength)) {
inView.push(a)
}
}
const chords = makePairedAlignmentChords(inView)
sendChords(chords, this, refFrame, 0.02)
// const chordSetColor = IGVColor.addAlpha("all" === refFrame.chr ? this.color : getChrColor(refFrame.chr), 0.02)
// const trackColor = IGVColor.addAlpha(this.color || 'rgb(0,0,255)', 0.02)
//
// // name the chord set to include track name and locus
// const encodedName = this.name.replaceAll(' ', '%20')
// const chordSetName = "all" === refFrame.chr ? encodedName :
// `${encodedName} (${refFrame.chr}:${refFrame.start}-${refFrame.end}`
// this.browser.circularView.addChords(chords, {name: chordSetName, color: chordSetColor, trackColor: trackColor})
}
addSplitChordsForViewport(viewport) {
const inView = []
const refFrame = viewport.referenceFrame
for (let a of viewport.cachedFeatures.allAlignments()) {
const sa = a.hasTag('SA')
if (a.end >= refFrame.start && a.start <= refFrame.end && sa) {
inView.push(a)
}
}
const chords = makeSupplementalAlignmentChords(inView)
sendChords(chords, this, refFrame, 0.02)
// const chordSetColor = IGVColor.addAlpha("all" === refFrame.chr ? this.color : getChrColor(refFrame.chr), 0.02)
// const trackColor = IGVColor.addAlpha(this.color || 'rgb(0,0,255)', 0.02)
//
// // name the chord set to include track name and locus
// const encodedName = this.name.replaceAll(' ', '%20')
// const chordSetName = "all" === refFrame.chr ? encodedName :
// `${encodedName} (${refFrame.chr}:${refFrame.start}-${refFrame.end}`
// this.browser.circularView.addChords(chords, {name: chordSetName, color: chordSetColor, trackColor: trackColor})
}
}
class CoverageTrack {
constructor(config, parent) {
this.parent = parent
this.featureSource = parent.featureSource
this.height = config.coverageTrackHeight !== undefined ? config.coverageTrackHeight : DEFAULT_COVERAGE_TRACK_HEIGHT
this.paintAxis = paintAxis
this.top = 0
this.autoscale = config.autoscale || config.max === undefined
if (!this.autoscale) {
this.dataRange = {
min: config.min || 0,
max: config.max
}
}
}
draw(options) {
const pixelTop = options.pixelTop
const pixelBottom = pixelTop + options.pixelHeight
const nucleotideColors = this.parent.browser.nucleotideColors
if (pixelTop > this.height) {
return //scrolled out of view
}
const ctx = options.context
const alignmentContainer = options.features
const coverageMap = alignmentContainer.coverageMap
let sequence
if (coverageMap.refSeq) {
sequence = coverageMap.refSeq.toUpperCase()
}
const bpPerPixel = options.bpPerPixel
const bpStart = options.bpStart
const pixelWidth = options.pixelWidth
const bpEnd = bpStart + pixelWidth * bpPerPixel + 1
// paint for all coverage buckets
// If alignment track color is != default, use it
let color
if (this.parent.coverageColor) {
color = this.parent.coverageColor
} else if (this.parent.color !== undefined) {
color = IGVColor.darkenLighten(this.parent.color, -35)
} else {
color = DEFAULT_COVERAGE_COLOR
}
IGVGraphics.setProperties(ctx, {
fillStyle: color,
strokeStyle: color
})
const w = Math.max(1, Math.ceil(1.0 / bpPerPixel))
for (let i = 0, len = coverageMap.coverage.length; i < len; i++) {
const bp = (coverageMap.bpStart + i)
if (bp < bpStart) continue
if (bp > bpEnd) break
const item = coverageMap.coverage[i]
if (!item) continue
const h = Math.round((item.total / this.dataRange.max) * this.height)
const y = this.height - h
const x = Math.floor((bp - bpStart) / bpPerPixel)
// IGVGraphics.setProperties(ctx, {fillStyle: "rgba(0, 200, 0, 0.25)", strokeStyle: "rgba(0, 200, 0, 0.25)" });
IGVGraphics.fillRect(ctx, x, y, w, h)
}
// coverage mismatch coloring -- don't try to do this in above loop, color bar will be overwritten when w<1
if (sequence) {
for (let i = 0, len = coverageMap.coverage.length; i < len; i++) {
const bp = (coverageMap.bpStart + i)
if (bp < bpStart) continue
if (bp > bpEnd) break
const item = coverageMap.coverage[i]
if (!item) continue
const h = (item.total / this.dataRange.max) * this.height
let y = this.height - h
const x = Math.floor((bp - bpStart) / bpPerPixel)
const refBase = sequence[i]
if (item.isMismatch(refBase)) {
IGVGraphics.setProperties(ctx, {fillStyle: nucleotideColors[refBase]})
IGVGraphics.fillRect(ctx, x, y, w, h)
let accumulatedHeight = 0.0
for (let nucleotide of ["A", "C", "T", "G"]) {
const count = item["pos" + nucleotide] + item["neg" + nucleotide]
// non-logoritmic
const hh = (count / this.dataRange.max) * this.height
y = (this.height - hh) - accumulatedHeight
accumulatedHeight += hh
IGVGraphics.setProperties(ctx, {fillStyle: nucleotideColors[nucleotide]})
IGVGraphics.fillRect(ctx, x, y, w, hh)
}
}
}
}
}
getClickedObject(clickState) {
let features = clickState.viewport.cachedFeatures
if (!features || features.length === 0) return
const genomicLocation = Math.floor(clickState.genomicLocation)
const coverageMap = features.coverageMap
const coverageMapIndex = Math.floor(genomicLocation - coverageMap.bpStart)
return coverageMap.coverage[coverageMapIndex]
}
popupData(clickState) {
const nameValues = []
const coverage = this.getClickedObject(clickState)
if (coverage) {
const genomicLocation = Math.floor(clickState.genomicLocation)
const referenceFrame = clickState.viewport.referenceFrame
nameValues.push(referenceFrame.chr + ":" + StringUtils.numberFormatter(1 + genomicLocation))
nameValues.push({name: 'Total Count', value: coverage.total})
// A
let tmp = coverage.posA + coverage.negA
if (tmp > 0) tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage.posA + "+, " + coverage.negA + "- )"
nameValues.push({name: 'A', value: tmp})
// C
tmp = coverage.posC + coverage.negC
if (tmp > 0) tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage.posC + "+, " + coverage.negC + "- )"
nameValues.push({name: 'C', value: tmp})
// G
tmp = coverage.posG + coverage.negG
if (tmp > 0) tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage.posG + "+, " + coverage.negG + "- )"
nameValues.push({name: 'G', value: tmp})
// T
tmp = coverage.posT + coverage.negT
if (tmp > 0) tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage.posT + "+, " + coverage.negT + "- )"
nameValues.push({name: 'T', value: tmp})
// N
tmp = coverage.posN + coverage.negN
if (tmp > 0) tmp = tmp.toString() + " (" + Math.round((tmp / coverage.total) * 100.0) + "%, " + coverage.posN + "+, " + coverage.negN + "- )"
nameValues.push({name: 'N', value: tmp})
nameValues.push('<HR/>')
nameValues.push({name: 'DEL', value: coverage.del.toString()})
nameValues.push({name: 'INS', value: coverage.ins.toString()})
}
return nameValues
}
}
class AlignmentTrack {
constructor(config, parent) {
this.parent = parent
this.browser = parent.browser
this.featureSource = parent.featureSource
this.top = 0 === config.coverageTrackHeight ? 0 : config.coverageTrackHeight + 5
this.displayMode = config.displayMode || "EXPANDED"
this.alignmentRowHeight = config.alignmentRowHeight || 14
this.squishedRowHeight = config.squishedRowHeight || 3
this.negStrandColor = config.negStrandColor || "rgba(150, 150, 230, 0.75)"
this.posStrandColor = config.posStrandColor || "rgba(230, 150, 150, 0.75)"
this.insertionColor = config.insertionColor || "rgb(138, 94, 161)"
this.deletionColor = config.deletionColor || "black"
this.skippedColor = config.skippedColor || "rgb(150, 170, 170)"
this.pairConnectorColor = config.pairConnectorColor
this.smallTLENColor = config.smallTLENColor || config.smallFragmentLengthColor || "rgb(0, 0, 150)"
this.largeTLENColor = config.largeTLENColor || config.largeFragmentLengthColor || "rgb(200, 0, 0)"
this.pairOrientation = config.pairOrienation || 'fr'
this.pairColors = {}
this.pairColors["RL"] = config.rlColor || "rgb(0, 150, 0)"
this.pairColors["RR"] = config.rrColor || "rgb(20, 50, 200)"
this.pairColors["LL"] = config.llColor || "rgb(0, 150, 150)"
this.colorBy = config.colorBy || "unexpectedPair"
this.colorByTag = config.colorByTag ? config.colorByTag.toUpperCase() : undefined
this.bamColorTag = config.bamColorTag === undefined ? "YC" : config.bamColorTag
this.hideSmallIndels = config.hideSmallIndels
this.indelSizeThreshold = config.indelSizeThreshold || 1
this.hasPairs = false // Until proven otherwise
this.hasSupplemental = false
}
setTop(coverageTrack, showCoverage) {
this.top = (0 === coverageTrack.height || false === showCoverage) ? 0 : (5 + coverageTrack.height)
}
/**
* Compute the pixel height required to display all content.
*
* @param alignmentContainer
* @returns {number|*}
*/
computePixelHeight(alignmentContainer) {
if (alignmentContainer.packedAlignmentRows) {
const h = alignmentContainer.hasDownsampledIntervals() ? downsampleRowHeight + alignmentStartGap : 0
const alignmentRowHeight = this.displayMode === "SQUISHED" ?
this.squishedRowHeight :
this.alignmentRowHeight
return h + (alignmentRowHeight * alignmentContainer.packedAlignmentRows.length) + 5
} else {
return 0
}
}
draw(options) {
const alignmentContainer = options.features
const ctx = options.context
const bpPerPixel = options.bpPerPixel
const bpStart = options.bpStart
const pixelWidth = options.pixelWidth
const bpEnd = bpStart + pixelWidth * bpPerPixel + 1
const showSoftClips = this.parent.showSoftClips
const showAllBases = this.parent.showAllBases
const nucleotideColors = this.browser.nucleotideColors
//alignmentContainer.repack(bpPerPixel, showSoftClips);
const packedAlignmentRows = alignmentContainer.packedAlignmentRows
ctx.save()
let referenceSequence = alignmentContainer.sequence
if (referenceSequence) {
referenceSequence = referenceSequence.toUpperCase()
}
let alignmentRowYInset = 0
let pixelTop = options.pixelTop
if (this.top) {
ctx.translate(0, this.top)
}
const pixelBottom = pixelTop + options.pixelHeight
if (alignmentContainer.hasDownsampledIntervals()) {
alignmentRowYInset = downsampleRowHeight + alignmentStartGap
alignmentContainer.downsampledIntervals.forEach(function (interval) {
var xBlockStart = (interval.start - bpStart) / bpPerPixel,
xBlockEnd = (interval.end - bpStart) / bpPerPixel
if (xBlockEnd - xBlockStart > 5) {
xBlockStart += 1
xBlockEnd -= 1
}
IGVGraphics.fillRect(ctx, xBlockStart, 2, (xBlockEnd - xBlockStart), downsampleRowHeight - 2, {fillStyle: "black"})
})
} else {
alignmentRowYInset = 0
}
// Transient variable -- rewritten on every draw, used for click object selection
this.alignmentsYOffset = alignmentRowYInset
const alignmentRowHeight = this.displayMode === "SQUISHED" ?
this.squishedRowHeight :
this.alignmentRowHeight
if (packedAlignmentRows) {
const nRows = packedAlignmentRows.length
for (let rowIndex = 0; rowIndex < nRows; rowIndex++) {
const alignmentRow = packedAlignmentRows[rowIndex]
const alignmentY = alignmentRowYInset + (alignmentRowHeight * rowIndex)
const alignmentHeight = alignmentRowHeight <= 4 ? alignmentRowHeight : alignmentRowHeight - 2
if (alignmentY > pixelBottom) {
break
} else if (alignmentY + alignmentHeight < pixelTop) {
continue
}
for (let alignment of alignmentRow.alignments) {
this.hasPairs = this.hasPairs || alignment.isPaired()
if (this.browser.circularView && true === this.browser.circularViewVisible) {
// This is an expensive check, only do it if needed
this.hasSupplemental = this.hasSupplemental || alignment.hasTag('SA')
}
if ((alignment.start + alignment.lengthOnRef) < bpStart) continue
if (alignment.start > bpEnd) break
if (true === alignment.hidden) {
continue
}
if (alignment instanceof PairedAlignment) {
drawPairConnector.call(this, alignment, alignmentY, alignmentHeight)
drawSingleAlignment.call(this, alignment.firstAlignment, alignmentY, alignmentHeight)
if (alignment.secondAlignment) {
drawSingleAlignment.call(this, alignment.secondAlignment, alignmentY, alignmentHeight)
}
} else {
drawSingleAlignment.call(this, alignment, alignmentY, alignmentHeight)
}
}
}
}
ctx.restore()
// alignment is a PairedAlignment
function drawPairConnector(alignment, yRect, alignmentHeight) {
var connectorColor = this.getConnectorColor(alignment.firstAlignment),
xBlockStart = (alignment.connectingStart - bpStart) / bpPerPixel,
xBlockEnd = (alignment.connectingEnd - bpStart) / bpPerPixel,
yStrokedLine = yRect + alignmentHeight / 2
if ((alignment.connectingEnd) < bpStart || alignment.connectingStart > bpEnd) {
return
}
if (alignment.mq <= 0) {
connectorColor = IGVColor.addAlpha(connectorColor, 0.15)
}
IGVGraphics.setProperties(ctx, {fillStyle: connectorColor, strokeStyle: connectorColor})
IGVGraphics.strokeLine(ctx, xBlockStart, yStrokedLine, xBlockEnd, yStrokedLine)
}
function drawSingleAlignment(alignment, yRect, alignmentHeight) {
if ((alignment.start + alignment.lengthOnRef) < bpStart || alignment.start > bpEnd) {
return
}
const blocks = showSoftClips ? alignment.blocks : alignment.blocks.filter(b => 'S' !== b.type)
let alignmentColor = this.getAlignmentColor(alignment)
const outlineColor = alignmentColor
if (alignment.mq <= 0) {
alignmentColor = IGVColor.addAlpha(alignmentColor, 0.15)
}
IGVGraphics.setProperties(ctx, {fillStyle: alignmentColor, strokeStyle: outlineColor})
let lastBlockEnd
for (let b = 0; b < blocks.length; b++) { // Can't use forEach here -- we need ability to break
const block = blocks[b]
// Somewhat complex test, neccessary to insure gaps are drawn.
// If this is not the last block, and the next block starts before the orign (off screen to left) then skip.
if ((b !== blocks.length - 1) && blocks[b + 1].start < bpStart) continue
drawBlock.call(this, block, b)
if ((block.start + block.len) > bpEnd) {
// Do this after drawBlock to insure gaps are drawn
break
}
}
if (alignment.insertions && this.parent.showInsertions) {
let lastXBlockStart = -1
for (let insertionBlock of alignment.insertions) {
if (this.hideSmallIndels && insertionBlock.len <= this.indelSizeThreshold) {
continue
}
if (insertionBlock.start < bpStart) {
continue
}
if (insertionBlock.start > bpEnd) {
break
}
const refOffset = insertionBlock.start - bpStart
const xBlockStart = refOffset / bpPerPixel - 1
if ((xBlockStart - lastXBlockStart) > 2) {
const widthBlock = 3
IGVGraphics.fillRect(ctx, xBlockStart, yRect - 1, widthBlock, alignmentHeight + 2, {fillStyle: this.insertionColor})
lastXBlockStart = xBlockStart
}
}
}
if (alignment.gaps) {
const yStrokedLine = yRect + alignmentHeight / 2
for (let gap of alignment.gaps) {
const sPixel = (gap.start - bpStart) / bpPerPixel
const ePixel = ((gap.start + gap.len) - bpStart) / bpPerPixel
const color = ("D" === gap.type) ? this.deletionColor : this.skippedColor
IGVGraphics.strokeLine(ctx, sPixel, yStrokedLine, ePixel, yStrokedLine, {strokeStyle: color})
}
}
function drawBlock(block, b) {
const offsetBP = block.start - alignmentContainer.start
const blockStartPixel = (block.start - bpStart) / bpPerPixel
const blockEndPixel = ((block.start + block.len) - bpStart) / bpPerPixel
const blockWidthPixel = Math.max(1, blockEndPixel - blockStartPixel)
//const arrowHeadWidthPixel = alignmentRowHeight / 2.0;
const nomPixelWidthOnRef = 100 / bpPerPixel
const arrowHeadWidthPixel = Math.min(alignmentRowHeight / 2.0, nomPixelWidthOnRef / 6)
const isSoftClip = 'S' === block.type
const strokeOutline =
alignment.mq <= 0 ||
this.highlightedAlignmentReadNamed === alignment.readName ||
isSoftClip
let blockOutlineColor = outlineColor
if (this.highlightedAlignmentReadNamed === alignment.readName) blockOutlineColor = 'red'
else if (isSoftClip) blockOutlineColor = 'rgb(50,50,50)'
const lastBlockPositiveStrand = (true === alignment.strand && b === blocks.length - 1)
const lastBlockReverseStrand = (false === alignment.strand && b === 0)
const lastBlock = lastBlockPositiveStrand | lastBlockReverseStrand
if (lastBlock) {
let xListPixel
let yListPixel
if (lastBlockPositiveStrand) {
xListPixel = [
blockStartPixel,
blockEndPixel,
blockEndPixel + arrowHeadWidthPixel,
blockEndPixel,
blockStartPixel,
blockStartPixel]
yListPixel = [
yRect,
yRect,
yRect + (alignmentHeight / 2.0),
yRect + alignmentHeight,
yRect + alignmentHeight,
yRect]
}
// Last block on - strand ?
else if (lastBlockReverseStrand) {
xListPixel = [
blockEndPixel,
blockStartPixel,
blockStartPixel - arrowHeadWidthPixel,
blockStartPixel,
blockEndPixel,
blockEndPixel]
yListPixel = [
yRect,
yRect,
yRect + (alignmentHeight / 2.0),
yRect + alignmentHeight,
yRect + alignmentHeight,
yRect]
}
IGVGraphics.fillPolygon(ctx, xListPixel, yListPixel, {fillStyle: alignmentColor})
if (strokeOutline) {
IGVGraphics.strokePolygon(ctx, xListPixel, yListPixel, {strokeStyle: blockOutlineColor})
}
}
// Internal block
else {
IGVGraphics.fillRect(ctx, blockStartPixel, yRect, blockWidthPixel, alignmentHeight, {fillStyle: alignmentColor})
if (strokeOutline) {
ctx.save()
ctx.strokeStyle = blockOutlineColor
ctx.strokeRect(blockStartPixel, yRect, blockWidthPixel, alignmentHeight)
ctx.restore()
}
}
// Read base coloring coloring
if (isSoftClip ||
showAllBases ||
this.parent.showMismatches && (referenceSequence && alignment.seq && alignment.seq !== "*")) {
const seq = alignment.seq ? alignment.seq.toUpperCase() : undefined
const qual = alignment.qual
const seqOffset = block.seqOffset
for (let i = 0, len = block.len; i < len; i++) {
if (offsetBP + i < 0) continue
let readChar = seq ? seq.charAt(seqOffset + i) : ''
const refChar = referenceSequence.charAt(offsetBP + i)
if (readChar === "=") {
readChar = refChar
}
if (readChar === "X" || refChar !== readChar || isSoftClip || showAllBases) {
let baseColor
if (!isSoftClip && qual !== undefined && qual.length > seqOffset + i) {
const readQual = qual[seqOffset + i]
baseColor = shadedBaseColor(readQual, nucleotideColors[readChar])
} else {
baseColor = nucleotideColors[readChar]
}
if (baseColor) {
const xPixel = ((block.start + i) - bpStart) / bpPerPixel
const widthPixel = Math.max(1, 1 / bpPerPixel)
renderBlockOrReadChar(ctx, bpPerPixel, {
x: xPixel,
y: yRect,
width: widthPixel,
height: alignmentHeight
}, baseColor, readChar)
}
}
}
}
}
function renderBlockOrReadChar(context, bpp, bbox, color, char) {
var threshold,
center
threshold = 1.0 / 10.0
if (bpp <= threshold && bbox.height >= 8) {
// render letter
const fontHeight = Math.min(10, bbox.height)
context.font = '' + fontHeight + 'px sans-serif'
center = bbox.x + (bbox.width / 2.0)
IGVGraphics.strokeText(context, char, center - (context.measureText(char).width / 2), fontHeight - 1 + bbox.y, {strokeStyle: color})
} else {
// render colored block
IGVGraphics.fillRect(context, bbox.x, bbox.y, bbox.width, bbox.height, {fillStyle: color})
}
}
}
};
popupData(clickState) {
const clickedObject = this.getClickedObject(clickState)
return clickedObject ? clickedObject.popupData(clickState.genomicLocation) : undefined
};
contextMenuItemList(clickState) {
const viewport = clickState.viewport
const list = []
const sortByOption = (option) => {
const cs = this.parent.sortObject
const direction = (cs && cs.position === Math.floor(clickState.genomicLocation)) ? !cs.direction : true
const newSortObject = {
chr: viewport.referenceFrame.chr,
position: Math.floor(clickState.genomicLocation),
option: option,
direction: direction
}
this.parent.sortObject = newSortObject
sortAlignmentRows(newSortObject, viewport.cachedFeatures)
viewport.repaint()
}
list.push('<b>Sort by...</b>')
list.push({label: ' base', click: () => sortByOption("BASE")})
list.push({label: ' read strand', click: () => sortByOption("STRAND")})
list.push({label: ' insert size', click: () => sortByOption("INSERT_SIZE")})
list.push({label: ' gap size', click: () => sortByOption("GAP_SIZE")})
list.push({label: ' chromosome of mate', click: () => sortByOption("MATE_CHR")})
list.push({label: ' mapping quality', click: () => sortByOption("MQ")})
list.push({label: ' read name', click: () => sortByOption("READ_NAME")})
list.push({
label: ' tag', click: () => {
const cs = this.parent.sortObject
const direction = (cs && cs.position === Math.floor(clickState.genomicLocation)) ? !cs.direction : true
const config =
{
label: 'Tag Name',
value: this.sortByTag ? this.sortByTag : '',
callback: (tag) => {
if (tag) {
const newSortObject = {
chr: viewport.referenceFrame.chr,
position: Math.floor(clickState.genomicLocation),
option: "TAG",
tag: tag,
direction: direction
}
this.sortByTag = tag
this.parent.sortObject = newSortObject
sortAlignmentRows(newSortObject, viewport.cachedFeatures)
viewport.repaint()
}
}
}
this.browser.inputDialog.present(config, clickState.event)
}
})
list.push('<hr/>')
const clickedObject = this.getClickedObject(clickState)
if (clickedObject) {
const showSoftClips = this.parent.showSoftClips
const clickedAlignment = (typeof clickedObject.alignmentContaining === 'function') ?
clickedObject.alignmentContaining(clickState.genomicLocation, showSoftClips) :
clickedObject
if (clickedAlignment) {
if (clickedAlignment.isPaired() && clickedAlignment.isMateMapped()) {
list.push({
label: 'View mate in split screen',
click: () => {
if (clickedAlignment.mate) {
const referenceFrame = clickState.viewport.referenceFrame
if (this.browser.genome.getChromosome(clickedAlignment.mate.chr)) {
this.highlightedAlignmentReadNamed = clickedAlignment.readName
//this.browser.presentMultiLocusPanel(clickedAlignment, referenceFrame)
const bpWidth = referenceFrame.end - referenceFrame.start
const frameStart = clickedAlignment.mate.position - bpWidth / 2
const frameEnd = clickedAlignment.mate.position + bpWidth / 2
this.browser.addMultiLocusPanel(clickedAlignment.mate.chr, frameStart, frameEnd, referenceFrame)
} else {
Alert.presentAlert(`Reference does not contain chromosome: ${clickedAlignment.mate.chr}`)
}
}
},
init: undefined
})
}
list.push({
label: 'View read sequence',
click: () => {
const alignment = clickedAlignment
if (!alignment) return
const seqstring = alignment.seq //.map(b => String.fromCharCode(b)).join("");
if (!seqstring || "*" === seqstring) {
Alert.presentAlert("Read sequence: *")
} else {
Alert.presentAlert(seqstring)
}
}
})
if (isSecureContext()) {
list.push({
label: 'Copy read sequence',
click: () => {
const alignment = clickedAlignment
if (!alignment) return
const seqstring = alignment.seq //.map(b => String.fromCharCode(b)).join("");
navigator.clipboard.writeText(seqstring)
}
})
}
list.push('<hr/>')
}
}
// Experimental JBrowse feature
if (this.browser.circularView && true === this.browser.circularViewVisible
&& (this.hasPairs || this.hasSupplemental)) {
if (this.hasPairs) {
list.push({
label: 'Add discordant pairs to circular view',
click: () => {
this.parent.addPairedChordsForViewport(viewport)
}
})
}
if (this.hasSupplemental) {
list.push({
label: 'Add split reads to circular view',
click: () => {
this.parent.addSplitChordsForViewport(viewport)
}
})
}
list.push('<hr/>')
}
return list
}
getClickedObject(clickState) {
const viewport = clickState.viewport
const y = clickState.y
const genomicLocation = clickState.genomicLocation
const showSoftClips = this.parent.showSoftClips
let features = viewport.cachedFeatures
if (!features || features.length === 0) return
let packedAlignmentRows = features.packedAlignmentRows
let downsampledIntervals = features.downsampledIntervals
const alignmentRowHeight = this.displayMode === "SQUISHED" ?
this.squishedRowHeight :
this.alignmentRowHeight
let packedAlignmentsIndex = Math.floor((y - this.top - this.alignmentsYOffset) / alignmentRowHeight)
if (packedAlignmentsIndex < 0) {
for (let i = 0; i < downsampledIntervals.length; i++) {
if (downsampledIntervals[i].start <= genomicLocation && (downsampledIntervals[i].end >= genomicLocation)) {
return downsampledIntervals[i]
}
}
} else if (packedAlignmentsIndex < packedAlignmentRows.length) {
const alignmentRow = packedAlignmentRows[packedAlignmentsIndex]
const clicked = alignmentRow.alignments.filter(alignment => alignment.containsLocation(genomicLocation, showSoftClips))
if (clicked.length > 0) return clicked[0]
}
return undefined
};
/**
* Return the color for connectors in paired alignment view. If explicitly set return that, otherwise return
* the alignment color, unless the color option can result in split colors (separte color for each mate).
*
* @param alignment
* @returns {string}
*/
getConnectorColor(alignment) {
if (this.pairConnectorColor) {
return this.pairConnectorColor
}
switch (this.colorBy) {
case "strand":
case "firstOfPairStrand":
case "pairOrientation":
case "tag":
return this.parent.color || DEFAULT_CONNECTOR_COLOR
default:
return this.getAlignmentColor(alignment)
}
}
getAlignmentColor(alignment) {
let color = this.parent.color || DEFAULT_ALIGNMENT_COLOR // The default color if nothing else applies
const option = this.colorBy
switch (option) {
case "strand":
color = alignment.strand ? this.posStrandColor : this.negStrandColor
break
case "firstOfPairStrand":
if (alignment instanceof PairedAlignment) {
color = alignment.firstOfPairStrand() ? this.posStrandColor : this.negStrandColor
} else if (alignment.isPaired()) {
if (alignment.isFirstOfPair()) {
color = alignment.strand ? this.posStrandColor : this.negStrandColor
} else if (alignment.isSecondOfPair()) {
color = alignment.strand ? this.negStrandColor : this.posStrandColor
} else {
console.error("ERROR. Paired alignments are either first or second.")
}
}
break
case "unexpectedPair":
case "pairOrientation":
if (this.pairOrientation && alignment.pairOrientation) {
var oTypes = orientationTypes[this.pairOrientation]
if (oTypes) {
var pairColor = this.pairColors[oTypes[alignment.pairOrientation]]
if (pairColor) color = pairColor
}
}
if ("pairOrientation" === option) {
break
}
case "tlen":
case "fragmentLength":
if (alignment.mate && alignment.isMateMapped()) {
if (alignment.mate.chr !== alignment.chr) {
color = getChrColor(alignment.mate.chr)
} else if (this.parent.minTemplateLength && Math.abs(alignment.fragmentLength) < this.parent.minTemplateLength) {
color = this.smallTLENColor
} else if (this.parent.maxTemplateLength && Math.abs(alignment.fragmentLength) > this.parent.maxTemplateLength) {
color = this.largeTLENColor
}
}
break
case "tag":
const tagValue = alignment.tags()[this.colorByTag]
if (tagValue !== undefined) {
if (this.bamColorTag === this.colorByTag) {
// UCSC style color option
color = "rgb(" + tagValue + ")"
} else {
if (!this.tagColors) {
this.tagColors = new PaletteColorTable("Set1")
}
color = this.tagColors.getColor(tagValue)
}
}
break
default:
color = this.parent.color || DEFAULT_ALIGNMENT_COLOR
}
return color
}
}
function sortAlignmentRows(options, alignmentContainer) {
const direction = options.direction
for (let row of alignmentContainer.packedAlignmentRows) {
row.updateScore(options, alignmentContainer)
}
alignmentContainer.packedAlignmentRows.sort(function (rowA, rowB) {
const i = rowA.score > rowB.score ? 1 : (rowA.score < rowB.score ? -1 : 0)
return true === direction ? i : -i
})
}
function shadedBaseColor(qual, baseColor) {
const minQ = 5 //prefs.getAsInt(PreferenceManager.SAM_BASE_QUALITY_MIN),
const maxQ = 20 //prefs.getAsInt(PreferenceManager.SAM_BASE_QUALITY_MAX);
let alpha
if (qual < minQ) {
alpha = 0.1
} else {
alpha = Math.max(0.1, Math.min(1.0, 0.1 + 0.9 * (qual - minQ) / (maxQ - minQ)))
}
// Round alpha to nearest 0.1
alpha = Math.round(alpha * 10) / 10.0
if (alpha < 1) {
baseColor = IGVColor.addAlpha(baseColor, alpha)
}
return baseColor
}
const orientationTypes = {
"fr": {
"F1R2": "LR",
"F2R1": "LR",
"F1F2": "LL",
"F2F1": "LL",
"R1R2": "RR",
"R2R1": "RR",
"R1F2": "RL",
"R2F1": "RL"
},
"rf": {
"R1F2": "LR",
"R2F1": "LR",
"R1R2": "LL",
"R2R1": "LL",
"F1F2": "RR",
"F2F1": "RR",
"F1R2": "RL",
"F2R1": "RL"
},
"ff": {
"F2F1": "LR",
"R1R2": "LR",
"F2R1": "LL",
"R1F2": "LL",
"R2F1": "RR",
"F1R2": "RR",
"R2R1": "RL",
"F1F2": "RL"
}
}
export function getChrColor(chr) {
if (chrColorMap[chr]) {
return chrColorMap[chr]
} else if (chrColorMap["chr" + chr]) {
const color = chrColorMap["chr" + chr]
chrColorMap[chr] = color
return color
} else {
const color = IGVColor.randomRGB(0, 255)
chrColorMap[chr] = color
return color
}
}
const chrColorMap = {
"chrX": "rgb(204, 153, 0)",
"chrY": "rgb(153, 204, 0)",
"chrUn": "rgb(50, 50, 50)",
"chr1": "rgb(80, 80, 255)",
"chrI": "rgb(139, 155, 187)",
"chr2": "rgb(206, 61, 50)",
"chrII": "rgb(206, 61, 50)",
"chr2a": "rgb(216, 71, 60)",
"chr2b": "rgb(226, 81, 70)",
"chr3": "rgb(116, 155, 88)",
"chrIII": "rgb(116, 155, 88)",
"chr4": "rgb(240, 230, 133)",
"chrIV": "rgb(240, 230, 133)",
"chr5": "rgb(70, 105, 131)",
"chr6": "rgb(186, 99, 56)",
"chr7": "rgb(93, 177, 221)",
"chr8": "rgb(128, 34, 104)",
"chr9": "rgb(107, 215, 107)",
"chr10": "rgb(213, 149, 167)",
"chr11": "rgb(146, 72, 34)",
"chr12": "rgb(131, 123, 141)",
"chr13": "rgb(199, 81, 39)",
"chr14": "rgb(213, 143, 92)",
"chr15": "rgb(122, 101, 165)",
"chr16": "rgb(228, 175, 105)",
"chr17": "rgb(59, 27, 83)",
"chr18": "rgb(205, 222, 183)",
"chr19": "rgb(97, 42, 121)",
"chr20": "rgb(174, 31, 99)",
"chr21": "rgb(231, 199, 111)",
"chr22": "rgb(90, 101, 94)",
"chr23": "rgb(204, 153, 0)",
"chr24": "rgb(153, 204, 0)",
"chr25": "rgb(51, 204, 0)",
"chr26": "rgb(0, 204, 51)",
"chr27": "rgb(0, 204, 153)",
"chr28": "rgb(0, 153, 204)",
"chr29": "rgb(10, 71, 255)",
"chr30": "rgb(71, 117, 255)",
"chr31": "rgb(255, 194, 10)",
"chr32": "rgb(255, 209, 71)",
"chr33": "rgb(153, 0, 51)",
"chr34": "rgb(153, 26, 0)",
"chr35": "rgb(153, 102, 0)",
"chr36": "rgb(128, 153, 0)",
"chr37": "rgb(51, 153, 0)",
"chr38": "rgb(0, 153, 26)",
"chr39": "rgb(0, 153, 102)",
"chr40": "rgb(0, 128, 153)",
"chr41": "rgb(0, 51, 153)",
"chr42": "rgb(26, 0, 153)",
"chr43": "rgb(102, 0, 153)",
"chr44": "rgb(153, 0, 128)",
"chr45": "rgb(214, 0, 71)",
"chr46": "rgb(255, 20, 99)",
"chr47": "rgb(0, 214, 143)",
"chr48": "rgb(20, 255, 177)",
}
export default BAMTrack
| igvteam/igv.js | js/bam/bamTrack.js | JavaScript | mit | 61,578 |
import React from 'react';
import * as UU5 from 'uu5g03';
import {browserHistory} from 'react-router';
import Utils from "../../utils.js";
import './link-button.css';
const LinkButton = React.createClass({
//@@viewOn:mixins
mixins: [
UU5.Common.BaseMixin,
UU5.Common.ElementaryMixin,
UU5.Layout.FlcMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'Ucl.Itkpd.Configurator.Components.LinkButton',
classNames: {
main: 'ucl-itkpd-configurator-component-link'
},
defaults: {
}
},
//@@viewOff:statics
//@@viewOn:propTypes
propTypes: {
caption: React.PropTypes.string,
route: React.PropTypes.string,
componentId: React.PropTypes.string
},
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
getDefaultProps() {
return {
caption: "",
route: "",
componentId: ""
};
},
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
//@@viewOff:interface
//@@viewOn:overridingMethods
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
_onClick: function() {
browserHistory.push(Utils.getRouterBaseUri() + '/' + this.props.route + '?id=' + this.props.componentId + '&project=' + Utils.getParamValue("project"))
},
//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render() {
return (
<UU5.Bricks.Link onClick={() => this._onClick()} content={this.props.caption} />
);
}
//@@viewOn:render
});
export default LinkButton; | UnicornCollege/ucl.itkpd.configurator | client/src/component/common/link-button.js | JavaScript | mit | 1,724 |
import React, {Component,PropTypes} from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
} from 'react-native';
import Icon from './../mixins/icons';
import Colors from '../assets/Colors';
import BaseHeader from '../components/BaseHeader';
export default class Topbar extends BaseHeader {
static propTypes = {
isShowStatuBar:PropTypes.bool,
};
static defaultProps = {
isShowStatuBar:true
};
constructor(props) {
super(props);
this.state = {
};
}
render() {
var {color, backgroundColor,isShowStatuBar}=this.props;
var h_n = 50+(isShowStatuBar?this.statuBarHeight:0);
var back_iconcolor = this.props.color ? this.props.color : 'white';
var background_color = backgroundColor? backgroundColor : Colors.main;
this.getRenderHeader();
return (
<View style={[styles.topbar, { backgroundColor:background_color,height:h_n }, this.props.style]}>
<View style={[styles.left,{marginTop:isShowStatuBar?this.statuBarHeight:0}]}>
{this.props.navigator?<TouchableOpacity
onPress={this._onPress}
style={[styles.button, {paddingLeft: 12,}]}>
<Text style={styles.button_lable}>
<Icon name='common-fanhui' size={20} color={back_iconcolor}/>
</Text>
</TouchableOpacity>:null}
</View>
<TouchableOpacity
onPress={this._callBack}
style={[styles.middle,{marginTop:isShowStatuBar?this.statuBarHeight:0}]}>
<Text numberOfLines={1} style={[styles.title, {color: back_iconcolor}]}>{this.props.title}</Text>
</TouchableOpacity>
<View style={[styles.right,{marginTop:isShowStatuBar?this.statuBarHeight:0}]}/>
</View>
);
}
_callBack=()=>{
if(this.props._scollorTop){
this.props._scollorTop()
}
}
_onPress=()=>{
requestAnimationFrame(()=>{
this.props.navigator.pop();
})
}
}
const styles = StyleSheet.create({
topbar: {
height: 50,
borderBottomWidth: 1,
borderColor: 'rgba(0,0,0,.15)',
flexDirection: "row",
},
left: {
flex: 1,
},
middle: {
flex: 3,
justifyContent: 'center',
alignItems: 'center',
},
right: {
flex: 1,
},
button: {
flex: 1,
justifyContent: 'center',
},
button_lable: {
fontSize: 16,
color: '#999',
},
title: {
color: 'black',
fontSize: 18,
},
});
| 8088/react-native-live-demo | app/modules/Topbar.js | JavaScript | mit | 2,501 |
function initMap(){
'use strict';
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 22.282467, lng: 114.161573},
zoom: 12
});
function makeMarkerIcon(markerColor) {
var markerImage = new google.maps.MarkerImage(
'http://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|'+ markerColor +
'|40|_|%E2%80%A2',
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34),
new google.maps.Size(21,34));
return markerImage;
}
// Style the markers a bit. This will be our listing marker icon.
var defaultIcon = makeMarkerIcon('0091ff');
// Create a "highlighted location" marker color for when the user
// mouses over the marker.
var highlightedIcon = makeMarkerIcon('FFFF24');
var infowindow = new google.maps.InfoWindow();
var searchWikiAlertOnce = true;
var PlaceModel = function(place) {
var self = this;
// if this place display on the map
self.display = ko.observable(true);
// if this place is active
self.active = ko.observable(false);
self.title = place.title;
self.location = place.location;
self.latLng = new google.maps.LatLng(place.location)
self.contentHTML = '<h2>' + place.title + '</h2>' +
'<hr/>' +
'<p>loading data from wikipedia, please reopen later</p>';
self.marker = self.makeMarker(place);
self.display.subscribe(function(display) {
self.marker.setVisible(display);
});
self.active.subscribe(function(active){
if (active) {
infowindow.setContent(self.contentHTML);
infowindow.open(map, self.marker);
self.marker.setIcon(highlightedIcon);
} else {
infowindow.close();
self.marker.setIcon(defaultIcon);
}
});
self.searchWiki();
};
PlaceModel.prototype.makeMarker = function(place) {
var marker = new google.maps.Marker({
map: map,
position: place.location,
title: place.title,
icon: defaultIcon,
animation: google.maps.Animation.DROP
});
return marker;
};
PlaceModel.prototype.searchWiki = function() {
var place = this;
var apiUrl = 'https://en.wikipedia.org/w/api.php';
var contentHTML;
var jqXHR = $.ajax({
url: apiUrl,
data: {
format: 'json',
action: 'opensearch',
search: place.title,
limit: 5
},
dataType: 'jsonp',
type: 'POST',
headers: { 'Api-User-Agent': 'fend/1.0' },
});
jqXHR.done(function(d){
place.contentHTML = '<h2>' + place.title + '</h2>' +
'<hr/>' +
'<a href="' + (d[3][1] || d[3]) + '">' + (d[1][1] || d[1]) + '</a>' +
'<p>' + (d[2][1] || d[2]) + '</p>';
});
jqXHR.fail(function(d){
if ( searchWikiAlertOnce ) {
alert('unable to connect to wikipedia.');
searchWikiAlertOnce = false;
}
place.contentHTML = '<h2>' + place.title + '<h2>';
});
};
var NeighorhoodViewModel = function() {
var self = this;
self.isOpenSiderbar = ko.observable(false);
self.toggleMenu = function() {
self.isOpenSiderbar(!self.isOpenSiderbar());
};
self.places = ko.observableArray([]);
self.filterKeyword = ko.observable('');
self.displayPlaces = ko.computed(function(){
var places = self.places();
var filter = self.filterKeyword().toLowerCase();
if (!filter) {
places.forEach(function(place) {
place.display(true);
});
return places;
} else {
return ko.utils.arrayFilter(places, function(place) {
var isDisplay = place.title.toLowerCase().search(filter) !== -1;
place.display(isDisplay);
return isDisplay;
});
}
});
self.displayPlaces.subscribe(function(places){
infowindow.close();
self.deactiveAll();
self.resizeMap();
});
self.active = ko.observable(-1);
self.active.subscribe(function(id){
self.deactiveAll();
if (self.active() >= 0) {
self.displayPlaces()[id].active(true);
}
});
self.deactiveAll = function() {
var places = self.places();
for (var i = places.length - 1; i >= 0; i--) {
places[i].active(false);
}
};
self.activeThis = function() {
self.active(self.displayPlaces().indexOf(this));
};
// Load place datas
$.getJSON('data.json', function(d) {
var mappedPlaces = $.map(d.payload.places, function(place){
return new PlaceModel(place);
});
self.places(mappedPlaces);
var places = self.places()
for (var i = 0; i < places.length; i++) {
places[i].marker.addListener('click', function(place) {
return function() {
var id = self.displayPlaces().indexOf(place);
if ( self.active() !== id) {
self.active(self.displayPlaces().indexOf(place));
} else {
self.active(-1);
}
};
}(places[i]));
}
google.maps.event.addListener(infowindow,'closeclick',function(){
self.deactiveAll();
self.active(-1);
});
}).fail(function(){
alert("failed to load data.json");
});
};
NeighorhoodViewModel.prototype.resizeMap = function() {
var bounds = new google.maps.LatLngBounds();
this.displayPlaces().forEach(function(place){
bounds.extend(place.latLng);
});
map.fitBounds(bounds);
}
if (typeof google !== 'undefined') {
ko.applyBindings(new NeighorhoodViewModel());
} else {
googleError();
}
}
function googleError() {
$('#map').html('<h3>Ah... Error Occurred. Cannot connect to google maps api! Please check your network connection.<h3>');
}
| weiliy/fend-neighborhood-map | app.js | JavaScript | mit | 5,797 |
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var mongoose = require('mongoose');
var api = require('./controllers/api');
var router = require('./controllers/router');
mongoose.connect('mongodb://cyabansu:[email protected]:39504/cemurl', function (error) {
if (error) console.error(error);
else console.log('Connected to mongodb');
});
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, '/public')));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/', router.Index);
app.get('/add', api.AddUrl);
//will match paths with 6 chars like /ABCXYZ
app.use(/\/[a-zA-Z0-9]{6}/, api.GetUrl);
//If there is no proper response, show error page
app.get('*', router.Error);
var port = process.env.PORT || 8080;
app.listen(port);
| cemyabansu/cemurl | server.js | JavaScript | mit | 893 |
/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
this.Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
var ZebraBuilder = {
cmd: {},
FONTS: {
ARIAL: {
LOCATION: 'E',
NAME: 'ARI',
EXT: 'TTF',
NORMAL: '000',
BOLD: '001',
ITALIC: '002',
BOLD_ITALIC: '003',
},
HELVETICA: {
LOCATION: 'E',
NAME: 'HEL',
EXT: 'TTF',
NORMAL: '004',
BOLD: '009',
},
CONSOLAS: {
LOCATION: 'E',
NAME: 'CON',
EXT: 'TTF',
NORMAL: '005',
BOLD: '006',
ITALIC: '007',
BOLD_ITALIC: '008',
},
}
};
| dem4ply/zebra_builder | src/base.js | JavaScript | mit | 2,407 |
import React, {Component} from "react";
import ReactDOM from "react-dom";
import {connect} from "react-redux";
import {AddHost, SearchHosts, UpdateHost} from "../actions/uiactions";
import {Dropdown, Menu, Icon} from "semantic-ui-react";
import EditorModal from "./EditorModal";
const mapStateToProps = ({SideBar, Bus, Categories}) =>({SideBar, Categories, Bus});
const mapDispatchToProps = dispatch =>({
AddHost: (Host)=> dispatch(AddHost(Host)),
UpdateHost: (Host, Target)=> dispatch(UpdateHost(Host, Target)),
SearchHosts: (search)=> dispatch(SearchHosts(search))
});
class ToolBar extends Component {
state = {
modalOpen: false,
value: 1,
loadingForm: false,
errors: [],
options: this.props.Categories.map(category=> {
return {key: category.name, text: category.name, value: category.name}
})
};
showNewHostModal = (editHost) => this.setState({modalOpen: true, editHostData: editHost});
removeErrors = () => this.setState({errors: []});
search() {
let search_value = ReactDOM.findDOMNode(this.refs.searchinput).value;
this.props.SearchHosts(search_value.trim());
};
handleSubmit(e, {formData}) {
e.preventDefault();
//Validate input fields has some values
let errors = [];
formData.ip.trim() == "" ? errors.push("ip") : "";
formData.domain.trim() == "" ? errors.push("domain") : "";
formData.category.trim() == "" ? errors.push("category") : "";
if (errors.length != 0) {
this.setState({errors});
return;
}
//Set new host to active
formData.active = true;
//Dispatch AddHost Action with form data
this.props.AddHost(formData);
this.setState({modalOpen: false});
};
componentWillReceiveProps(nextProps) {
this.setState({
options: nextProps.Categories.map(category=> {
return {key: category.name, text: category.name, value: category.name}
})
})
}
componentDidUpdate() {
}
closeModal(e) {
e.preventDefault();
//this is required because button is inside form element or it will try to submit the form
this.setState({modalOpen: false})
}
render() {
let props = this.props;
return (<div>
<EditorModal
open={this.state.modalOpen}
onSubmit={this.handleSubmit.bind(this)}
close={this.closeModal.bind(this)}
errors={this.state.errors}
options={this.state.options}
removeErrors={this.removeErrors.bind(this)}
close={this.closeModal.bind(this)}
/>
<Menu attached='top' fluid className="m-t-0 toolbar">
<Menu.Item name='hamburger' onClick={props.sidebarToggle}>
<Icon name='sidebar'/>
</Menu.Item>
<Dropdown item icon='rocket' simple>
<Dropdown.Menu>
<Dropdown.Item onClick={this.showNewHostModal}>New Host</Dropdown.Item>
<Dropdown.Item>Save...</Dropdown.Item>
<Dropdown.Item>Edit Permissions</Dropdown.Item>
<Dropdown.Divider />
<Dropdown.Header>Export</Dropdown.Header>
<Dropdown.Item>Share</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Menu.Menu position='right'>
<div className='ui category search item'>
<div className='ui transparent icon input'>
<input ref="searchinput" onChange={this.search.bind(this)} className='prompt' type='text'
placeholder='Search Hosts...'/>
<i className='search link icon'/>
</div>
<div className='results'></div>
</div>
</Menu.Menu>
</Menu>
</div>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ToolBar);
| InvertedX/Dose-Host-Manager | src/components/toolbarmenu.js | JavaScript | mit | 3,771 |
import Ember from 'ember';
import ParentComponentSupport from 'ember-composability/mixins/parent-component-support';
import layout from '../templates/components/md-table';
const { A, Component, computed } = Ember;
export default Component.extend(ParentComponentSupport, {
tagName: 'table',
layout,
columns: null,
composableChildrenDebounceTime: 1,
init() {
this._super(...arguments);
this.set('columns', []);
},
columnComponents: computed('composableChildren', function() {
return new A(this.get('composableChildren'));
}).readOnly(),
registerChildComponent(childComponent) {
this.get('_childComponents').add(childComponent, childComponent.get('key'));
this._notifyComposableChildrenChanged();
},
unregisterChildComponent(childComponent) {
this.get('_childComponents').delete(childComponent, childComponent.get('key'));
this._notifyComposableChildrenChanged();
}
});
| dortort/ember-cli-materialize | addon/components/md-table.js | JavaScript | mit | 924 |
import React from 'react';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/styles';
const useStyles = makeStyles({
root: {
'&.root': {
height: 100,
width: 100,
backgroundColor: 'blue',
},
'& .child': {
height: 8,
backgroundColor: 'red',
},
},
});
function HybridCss() {
const classes = useStyles();
return (
<div className={clsx(classes.root, 'root')}>
<div className="child" />
</div>
);
}
export default HybridCss;
| allanalexandre/material-ui | docs/src/pages/styles/advanced/HybridGlobalCss.js | JavaScript | mit | 509 |
// Entry point for browser
import ReactDOM from 'react-dom';
import domready from 'domready';
import ga from 'google-analytics';
import App from './components';
function getRenderedProps(document) {
const props = {};
// Ensure the initial render is exactly the same
props.href = document.querySelector('link[rel="canonical"]').getAttribute('href');
props.styles = document.querySelector('link[rel="stylesheet"]').getAttribute('href');
const scriptProps = document.querySelectorAll('script[data-prop-name]');
for (let i = 0; i < scriptProps.length; i += 1) {
const elem = scriptProps[i];
let value = elem.text;
const elemType = elem.getAttribute('type') || '';
if (elemType === 'application/json' || elemType.slice(-5) === '+json') {
value = JSON.parse(value);
}
props[elem.getAttribute('data-prop-name')] = value;
}
return props;
}
function recordServerStats(serverStats, timingVar) {
// serverStats *_time are microsecond values...
Object.keys(serverStats).forEach((name) => {
if (name.indexOf('_time') === -1) return;
ga('send', 'timing', {
timingCategory: name,
timingVar,
timingValue: Math.round(serverStats[name] / 1000),
});
});
}
// Treat domready function as the entry point to the application.
// Inside this function, kick-off all initialization, everything up to this
// point should be definitions.
if (!window.TEST_RUNNER) {
domready(() => {
console.log('ready');
// Set <html> class depending on browser features
const props = getRenderedProps(document);
const serverStats = require('querystring').parse(window.stats_cookie);
recordServerStats(serverStats, 'html');
ReactDOM.hydrate(<App {...props} />, document);
});
}
| ENCODE-DCC/encoded | src/encoded/static/browser.js | JavaScript | mit | 1,858 |
const Loader = () => {
return (
<div className='flex justify-center items-center'>
<div className='loader h-32 w-32' />
</div>
)
}
export default Loader
| BanManagement/BanManager-WebUI | components/Loader.js | JavaScript | mit | 172 |
import {addDragHandler, setAttributes} from '../utils'
export default class text {
static argNames = ['text', 'x', 'y', 'affects'];
constructor(get_args, minimize_args){
this.minimize_args = minimize_args
this.get_args = get_args
}
mount(container){
this.container = container
this.el = document.createElementNS("http://www.w3.org/2000/svg", "text")
this.container.appendChild(this.el)
var dragstart = e => {
var {x, y} = this.get_args()
return (dx, dy) => {
var {affects} = this.get_args()
this.minimize_args(args => {
var drx = args.x - (x + dx)
var dry = args.y - (y + dy)
return drx*drx + dry*dry
}, affects)
}
}
addDragHandler(this.el, dragstart)
}
unmount() {
this.container.removeChild(this.el)
}
update() {
var args = this.get_args()
setAttributes(this.el, args)
this.el.innerHTML = args.text
}
} | bijection/g9 | src/shapes/text.js | JavaScript | mit | 1,090 |
import { getOptions } from './internal/options.js';
// the taskId to assign to the next task added via addTask()
let nextTaskId = 0;
// array of queued tasks sorted with highest priority task first
const tasks = [];
// array of web workers to dispatch decode tasks to
const webWorkers = [];
// The options for CornerstoneWADOImageLoader
const options = getOptions();
const defaultConfig = {
maxWebWorkers: navigator.hardwareConcurrency || 1,
startWebWorkersOnDemand: true,
webWorkerPath: '../../dist/cornerstoneWADOImageLoaderWebWorker.js',
webWorkerTaskPaths: [],
taskConfiguration: {
decodeTask: {
loadCodecsOnStartup: true,
initializeCodecsOnStartup: false,
codecsPath: '../dist/cornerstoneWADOImageLoaderCodecs.js',
usePDFJS: false,
strict: options.strict
}
}
};
let config;
const statistics = {
maxWebWorkers: 0,
numWebWorkers: 0,
numTasksQueued: 0,
numTasksExecuting: 0,
numTasksCompleted: 0,
totalTaskTimeInMS: 0,
totalTimeDelayedInMS: 0
};
/**
* Function to start a task on a web worker
*/
function startTaskOnWebWorker () {
// return immediately if no decode tasks to do
if (!tasks.length) {
return;
}
// look for a web worker that is ready
for (let i = 0; i < webWorkers.length; i++) {
if (webWorkers[i].status === 'ready') {
// mark it as busy so tasks are not assigned to it
webWorkers[i].status = 'busy';
// get the highest priority task
const task = tasks.shift();
task.start = new Date().getTime();
// update stats with how long this task was delayed (waiting in queue)
const end = new Date().getTime();
statistics.totalTimeDelayedInMS += end - task.added;
// assign this task to this web worker and send the web worker
// a message to execute it
webWorkers[i].task = task;
webWorkers[i].worker.postMessage({
taskType: task.taskType,
workerIndex: i,
data: task.data
}, task.transferList);
statistics.numTasksExecuting++;
return;
}
}
// if no available web workers and we haven't started max web workers, start a new one
if (webWorkers.length < config.maxWebWorkers) {
spawnWebWorker();
}
}
/**
* Function to handle a message from a web worker
* @param msg
*/
function handleMessageFromWorker (msg) {
// console.log('handleMessageFromWorker', msg.data);
if (msg.data.taskType === 'initialize') {
webWorkers[msg.data.workerIndex].status = 'ready';
startTaskOnWebWorker();
} else {
const start = webWorkers[msg.data.workerIndex].task.start;
webWorkers[msg.data.workerIndex].task.deferred.resolve(msg.data.result);
webWorkers[msg.data.workerIndex].task = undefined;
statistics.numTasksExecuting--;
webWorkers[msg.data.workerIndex].status = 'ready';
statistics.numTasksCompleted++;
const end = new Date().getTime();
statistics.totalTaskTimeInMS += end - start;
startTaskOnWebWorker();
}
}
/**
* Spawns a new web worker
*/
function spawnWebWorker () {
// prevent exceeding maxWebWorkers
if (webWorkers.length >= config.maxWebWorkers) {
return;
}
// spawn the webworker
const worker = new Worker(config.webWorkerPath);
webWorkers.push({
worker,
status: 'initializing'
});
worker.addEventListener('message', handleMessageFromWorker);
worker.postMessage({
taskType: 'initialize',
workerIndex: webWorkers.length - 1,
config
});
}
/**
* Initialization function for the web worker manager - spawns web workers
* @param configObject
*/
function initialize (configObject) {
configObject = configObject || defaultConfig;
// prevent being initialized more than once
if (config) {
throw new Error('WebWorkerManager already initialized');
}
config = configObject;
config.maxWebWorkers = config.maxWebWorkers || (navigator.hardwareConcurrency || 1);
// Spawn new web workers
if (!config.startWebWorkersOnDemand) {
for (let i = 0; i < config.maxWebWorkers; i++) {
spawnWebWorker();
}
}
}
/**
* dynamically loads a web worker task
* @param sourcePath
* @param taskConfig
*/
function loadWebWorkerTask (sourcePath, taskConfig) {
// add it to the list of web worker tasks paths so on demand web workers
// load this properly
config.webWorkerTaskPaths.push(sourcePath);
// if a task specific configuration is provided, merge it into the config
if (taskConfig) {
config.taskConfiguration = Object.assign(config.taskConfiguration, taskConfig);
}
// tell each spawned web worker to load this task
for (let i = 0; i < webWorkers.length; i++) {
webWorkers[i].worker.postMessage({
taskType: 'loadWebWorkerTask',
workerIndex: webWorkers.length - 1,
sourcePath,
config
});
}
}
/**
* Function to add a decode task to be performed
*
* @param taskType - the taskType for this task
* @param data - data specific to the task
* @param priority - optional priority of the task (defaults to 0), > 0 is higher, < 0 is lower
* @param transferList - optional array of data to transfer to web worker
* @returns {*}
*/
function addTask (taskType, data, priority = 0, transferList) {
if (!config) {
initialize();
}
let deferred = {};
const promise = new Promise((resolve, reject) => {
deferred = {
resolve,
reject
};
});
// find the right spot to insert this decode task (based on priority)
let i;
for (i = 0; i < tasks.length; i++) {
if (tasks[i].priority < priority) {
break;
}
}
const taskId = nextTaskId++;
// insert the decode task at position i
tasks.splice(i, 0, {
taskId,
taskType,
status: 'ready',
added: new Date().getTime(),
data,
deferred,
priority,
transferList
});
// try to start a task on the web worker since we just added a new task and a web worker may be available
startTaskOnWebWorker();
return {
taskId,
promise
};
}
/**
* Changes the priority of a queued task
* @param taskId - the taskId to change the priority of
* @param priority - priority of the task (defaults to 0), > 0 is higher, < 0 is lower
* @returns boolean - true on success, false if taskId not found
*/
function setTaskPriority (taskId, priority = 0) {
// search for this taskId
for (let i = 0; i < tasks.length; i++) {
if (tasks[i].taskId === taskId) {
// taskId found, remove it
const task = tasks.splice(i, 1)[0];
// set its priority
task.priority = priority;
// find the right spot to insert this decode task (based on priority)
for (i = 0; i < tasks.length; i++) {
if (tasks[i].priority < priority) {
break;
}
}
// insert the decode task at position i
tasks.splice(i, 0, task);
return true;
}
}
return false;
}
/**
* Cancels a queued task and rejects
* @param taskId - the taskId to cancel
* @param reason - optional reason the task was rejected
* @returns boolean - true on success, false if taskId not found
*/
function cancelTask (taskId, reason) {
// search for this taskId
for (let i = 0; i < tasks.length; i++) {
if (tasks[i].taskId === taskId) {
// taskId found, remove it
const task = tasks.splice(i, 1);
task.deferred.reject(reason);
return true;
}
}
return false;
}
/**
* Function to return the statistics on running web workers
* @returns object containing statistics
*/
function getStatistics () {
statistics.maxWebWorkers = config.maxWebWorkers;
statistics.numWebWorkers = webWorkers.length;
statistics.numTasksQueued = tasks.length;
return statistics;
}
export default {
initialize,
loadWebWorkerTask,
addTask,
getStatistics,
setTaskPriority,
cancelTask
};
| google/cornerstoneWADOImageLoader | src/imageLoader/webWorkerManager.js | JavaScript | mit | 7,794 |
"use strict";
var Crpyto = require("crypto");
var Util = require("util");
var DIGEST = "sha1";
var DIGEST_FORMAT = "hex";
var EVENT_HEADER = "x-github-event";
var SIGNATURE_HEADER = "x-hub-signature";
exports.DEFAULT_SECRET = "lurkersecret";
exports.register = function (plugin, options, done) {
var secret = options.secret;
function validateSignature (headers, validateOptions, done) {
var hmac = Crpyto.createHmac(DIGEST, secret);
var signature;
hmac.update(validateOptions.context.payload);
signature = Util.format("%s=%s", DIGEST, hmac.digest(DIGEST_FORMAT));
if (headers[SIGNATURE_HEADER] === signature) {
done(null, headers);
return;
}
else {
plugin.log(
[ "warning", "github" ],
"signature verification failed"
);
done(plugin.hapi.error.badRequest("checksum failure"));
return;
}
}
// Validate plugin options.
if (!secret) {
plugin.log(
[ "warning", "github" ],
"No GitHub secret found. Using default secret value."
);
secret = exports.DEFAULT_SECRET;
}
plugin.route({
config : {
auth : false,
payload : {
output : "data",
parse : false
},
validate : {
headers : validateSignature
}
},
handler : function (request, reply) {
var payload;
// Attempt to parse the request payload.
try {
payload = JSON.parse(request.payload.toString());
}
catch (error) {
plugin.log(
[ "error", "github" ],
"failed to parse request: %s", error.message
);
reply(plugin.hapi.error.badRequest("parse error", error));
return;
}
payload.event = request.headers[EVENT_HEADER];
plugin.plugins.outflux.point("github", payload);
reply(null);
},
method : "POST",
path : "/github"
});
done();
};
exports.register.attributes = {
name : "github"
};
| jagoda/lurker | lib/plugins/github.js | JavaScript | mit | 1,822 |
/*global m */
(function HomeView(n) {
'use strict';
var drawHeader = function (element) {
element.firstElementChild.innerHTML = "Listagram";
};
// declaring view
n.view = function (ctrl) {
return m('.full .scrollable', [
m('x-appbar#homeBar.redbar', {config: drawHeader}),
m('.snapped', [
m('#wall', [
m('#columns', [
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 1')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 2')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 3')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 4')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 5')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 6')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 7')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 8')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 9')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 10')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 11')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 12')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 13')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 14')]),
m('.pin', [m('img', {src: 'http://placehold.it/78x78'}), m('p', 'legenda 15')])
])
])
]),
m('.bt-pin', {onclick: ctrl.showForm}, [
m('i', {class: 'fa fa-camera'}, [])
])
]);
};
// exporting
window.listagram.home = n;
}(window.listagram.home || {}));
// loader
// http://codepen.io/NeekGerd/pen/jnkGy
//http://damien.antipa.at/2012/10/16/ios-pull-to-refresh-in-mobile-safari-with-native-scrolling/ | vinnylinck/listagram | www/js/views/home.js | JavaScript | mit | 2,409 |
/*!
* nodejs-express-mongoose-demo
* Copyright(c) 2013 Madhusudhan Srinivasa <[email protected]>
* MIT Licensed
*/
/**
* Module dependencies
*/
var fs = require('fs');
var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('config');
var app = express();
var port = process.env.PORT || 3000;
// Connect to mongodb
var connect = function () {
var options = { server: { socketOptions: { keepAlive: 1 } } };
mongoose.connect(config.db, options);
};
connect();
mongoose.connection.on('error', console.log);
mongoose.connection.on('disconnected', connect);
// Bootstrap models
fs.readdirSync(__dirname + '/app/models').forEach(function (file) {
if (~file.indexOf('.js')) require(__dirname + '/app/models/' + file);
});
// Bootstrap passport config
require('./config/passport')(passport, config);
// Bootstrap application settings
require('./config/express')(app, passport);
// Bootstrap routes
require('./config/routes')(app, passport);
// Bootstrap logger config
require('./config/winston');
app.listen(port);
console.log('Express app started on port ' + port);
/**
* Expose
*/
module.exports = app;
| wmzy/hiskyCrm | server.js | JavaScript | mit | 1,195 |
var express = require('express');
var fs = require('fs');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var partials = require('express-partials');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(path.join(__dirname, 'public/assets/ico', 'favicon.ico')));
app.use(partials());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// var rpath='./routes';
// fs.readdir(rpath,function(err,files){
// if(err)
// {
// console.log(err);
// }else{
// for(var i=0;i<files.length;i++){
// if(path.extname(files[i]) == '.js'){
// var filename=path.basename(files[i],'.js');
// app.use('/'+filename, require(rpath+'/'+filename));
// }
// }
// }
// });
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err,
layout:false
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
| kerryyao/mushroom | app.js | JavaScript | mit | 1,871 |
define([
'./demo.tpl.html'
], function (template) {
// @ngInject
function demoState ($stateProvider, $urlRouterProvider) {
$stateProvider.state('rb-deep-search', {
url: '/rb-deep-search',
controller: 'demo-rb-deep-search-ctrl as demoCtrl',
template: template
});
}
return demoState;
});
| rockabox/rbx_ui_components | src/rb-deep-search/demo/demo-state.js | JavaScript | mit | 361 |
'use strict';
let datafire = require('datafire');
let openapi = require('./openapi.json');
let aws = require('aws-sdk');
const INTEGRATION_ID = 'amazonaws_acm_pca';
const SDK_ID = 'ACMPCA';
let integ = module.exports = new datafire.Integration({
id: INTEGRATION_ID,
title: openapi.info.title,
description: openapi.info.description,
logo: openapi.info['x-logo'],
});
integ.security[INTEGRATION_ID]= {
integration: INTEGRATION_ID,
fields: {
accessKeyId: "",
secretAccessKey: "",
region: "AWS region (if applicable)",
}
}
function maybeCamelCase(str) {
return str.replace(/_(\w)/g, (match, char) => char.toUpperCase())
}
// We use this instance to make sure each action is available in the SDK at startup.
let dummyInstance = new aws[SDK_ID]({version: openapi.version, endpoint: 'foo'});
for (let path in openapi.paths) {
for (let method in openapi.paths[path]) {
if (method === 'parameters') continue;
let op = openapi.paths[path][method];
let actionID = op.operationId;
actionID = actionID.replace(/\d\d\d\d_\d\d_\d\d$/, '');
if (actionID.indexOf('_') !== -1) {
actionID = actionID.split('_')[1];
}
let functionID = actionID.charAt(0).toLowerCase() + actionID.substring(1);
if (!dummyInstance[functionID]) {
console.error("AWS SDK " + SDK_ID + ": Function " + functionID + " not found");
console.log(method, path, op.operationId, actionID);
continue;
}
let inputParam = (op.parameters || []).filter(p => p.in === 'body')[0] || {};
let response = (op.responses || {})[200] || {};
let inputSchema = {
type: 'object',
properties: {},
};
if (inputParam.schema) inputSchema.allOf = [inputParam.schema];
(op.parameters || []).forEach(p => {
if (p.name !== 'Action' && p.name !== 'Version' && p.name !== 'body' && !p.name.startsWith('X-')) {
inputSchema.properties[maybeCamelCase(p.name)] = {type: p.type};
if (p.required) {
inputSchema.required = inputSchema.required || [];
inputSchema.required.push(p.name);
}
}
})
function getSchema(schema) {
if (!schema) return;
return Object.assign({definitions: openapi.definitions}, schema);
}
integ.addAction(actionID, new datafire.Action({
inputSchema: getSchema(inputSchema),
outputSchema: getSchema(response.schema),
handler: (input, context) => {
let lib = new aws[SDK_ID](Object.assign({
version: openapi.info.version,
}, context.accounts[INTEGRATION_ID]));
return lib[functionID](input).promise()
.then(data => {
return JSON.parse(JSON.stringify(data));
})
}
}));
}
}
| DataFire/Integrations | integrations/generated/amazonaws_acm_pca/index.js | JavaScript | mit | 2,725 |
/*
* collection.js - Utilities for wrapping collection operations so that
* operations will not directly be applied to the server's
* underlying MongoDB database, but instead will be sent
* through the distributed database.
*/
Meteor.collections = {};
wrap_insert = function (collection, getUserId, onflict_resolution) {
Meteor.collections[collection._name] = collection;
if (Meteor.isServer) {
if (!conflict_resolution || !(conflict_resolution instanceof Function)) {
// Default conflict resolution is to take the object with the latest
// timestamp.
conflict_resolution = function (doc1, doc2) {
return (doc1._ts >= doc2._ts ? doc1 : doc2);
}
}
collection.localFindOne = collection.findOne;
collection._collection.localUpdate = collection._collection.update;
var localInsert = collection._collection.insert;
localInsert = Meteor._wrapAsync(Meteor.bindEnvironment(localInsert, Meteor._debug, collection._collection));
collection._collection.localPut = Meteor._wrapAsync(function (doc, callback) {
console.log(collection._name + ".localPut defined");
// If an object currently exists, find it, perform conflict
// resolution, and update the document.
// Otherwise, insert the new document.
var docCurrent = collection.localFindOne({_id: doc._id});
if (docCurrent) {
doc = conflict_resolution(docCurrent, doc);
return collection._collection.localUpdate(doc._id, doc, function (error) { return callback(error, doc._id); });
}
else {
return localInsert(doc, callback);
}
});
console.log(collection._name + ".localPut defined");
collection._collection.localRemove = collection._collection.remove;
collection._collection.remove = Meteor._wrapAsync(function (id, callback) {
console.log(collection._name + ".remove redefined");
// We need to keep track of deleted objects. So a remove is actually
// just overwriting the object with an empty object.
return collection._collection.insert({_id: id}, function (error) { return callback(error, 1); });
});
console.log(collection._name + ".remove redefined");
collection._collection.insert = Meteor._wrapAsync(function (doc, callback) {
console.log(collection._name + ".insert redefined");
// The server method that gets called by the client. Instead of
// inserting directly into MongoDB, call out to the distributed
// database. But first, give the object an _id (so that all replicas
// will get the same _id for this object) and a timestamp (for
// conflict resolution).
doc = _.clone(doc);
if (!doc._id) {
doc._id = Random.id();
}
doc._ts = new Date();
reply = CoordinatorPut(collection._name, getUserId(doc), doc._id, doc);
console.log("about to finish collection.insert with " + reply);
if ("OK" === reply) {
return collection._collection.localPut(doc, callback);
}
});
console.log(collection._name + ".insert redefined");
}
else if (Meteor.isClient) {
_.each(["update", "upsert"], function (name) {
collection[name] = function () {
throw new Meteor.Error(405, "Method Not Allowed",
collection._name+"."+name+"() not allowed. " +
"Instead call "+collection._name+".insert().");
}
});
}
};
wrap_insert(
Meteor.users,
function (doc) { return doc._id; },
function (doc1, doc2) {
// use the latest version, but always keep the certificate
var doc = _.clone(doc1._ts >= doc2._ts ? doc1 : doc2);
var other = (doc1._ts >= doc2._ts ? doc2 : doc1);
if (!doc._pubkey_cert) {
doc._pubkey_cert = other._pubkey_cert;
doc.emails[0].verified = other.emails[0].verified;
}
});
wrap_insert(Principals, function (doc) { return doc.name; });
// not WrappedKeys, Certs, PrincType PrincType doesn't need duplication (the
// objects are static for an application), and the others aren't supported.
| jmoldow/MylarDistributedDB | packages/mylar-distributed-db/collection.js | JavaScript | mit | 4,116 |
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View
} from 'react-native';
class HelloWorld extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
| edagarli/ReactNativeDayAndDay | Day01HelloWorld/index.android.js | JavaScript | mit | 1,016 |
import fs from 'fs';
import cluster from 'cluster'
import express from 'express';
import path from 'path';
import contentDisposition from 'content-disposition';
import onFinished from 'on-finished';
import destroy from 'destroy';
import scan from './scan';
import getPromisedZipFilePath from './zip';
const numCpus = require('os').cpus().length;
export default function(port, hostedDirectory) {
if (cluster.isMaster) {
for (let i = 0; i < numCpus; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} has died with code: ${code} and signal: ${signal}`);
});
}
else {
const pid = cluster.worker.process.pid;
const name = cluster.worker.id;
console.log(`Starting worker '${name}' with PID: ${pid}`)
let tree = scan(hostedDirectory, 'files');
let app = express();
app.use('/', express.static(path.join(__dirname, '../public')));
app.use('/files', express.static(hostedDirectory, {
index: false,
setHeaders: function(res, path) {
res.setHeader('Content-Disposition', contentDisposition(path));
}
}));
app.get('/zips/:folderpath', function(req, res) {
console.log('User is requesting zip from folderPath: ', req.params.folderpath);
let folderPath = req.params.folderpath;
getPromisedZipFilePath(folderPath).then((zipPath) => {
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', contentDisposition(zipPath));
res.attachment(zipPath);
let responseStream = fs.createReadStream(zipPath);
responseStream.pipe(res);
onFinished(res, () => {
destroy(responseStream);
res.status(200).end();
});
});
});
app.get('/scan', function(req, res) {
res.send(tree);
});
app.listen(port);
}
}
| theamazingfedex/socketshare | src/browser.js | JavaScript | mit | 1,892 |
let ASSERT = require('assert');
const HTTP = require('http');
describe('Hook Specification', function () {
let Acts = null;
beforeEach(function () {
Acts = require('./../index');
Acts.createServer(__dirname, {
server: {
address: 'localhost',
port: 8087
}
}, []);
});
afterEach(function () {
Acts.shutdown();
Acts = null;
});
after(function () {
setTimeout(process.exit, 2000);
});
it('can call hook', function (done) {
Acts.hook((req, res, next) => {
if (req.method === 'GET') {
res.statusCode = 200;
return res.end('test ok');
}
next();
});
Acts.start(function () {
let req = HTTP.request({
protocol: 'http:',
host: 'localhost',
port: 8087,
path: '/something',
method: 'GET'
});
req.on('response', resp => {
ASSERT.equal(resp.statusCode, 200, 'invalid status code on GET');
resp.on('data', d => {
let body = d.toString('utf8');
ASSERT.equal(body, 'test ok', 'invalid request body');
done();
});
});
req.on('abort', err => {
Acts.shutdown();
done(err);
});
req.end();
});
});
it('hook is not a function', function (done) {
Acts.hook({});
Acts.start(function () {
let req = HTTP.request({
protocol: 'http:',
host: 'localhost',
port: 8087,
path: '/something',
method: 'GET'
});
req.on('response', resp => {
ASSERT.equal(resp.statusCode, 200, 'invalid status code on GET');
done();
});
req.on('abort', err => {
Acts.shutdown();
done(err);
});
req.end();
});
});
});
| nodejayes/acts | spec/hook.spec.js | JavaScript | mit | 2,173 |
// RUN
function appInit(){
// load and add basemap
map = L.map('map', { zoomControl: false }).setView([50, 10], 4);
addBaseMap(map)
$('.loading').remove();
// add on click temp info
addOnClickInfo();
addOnAddRemoveInfo();
}
function updateApp(selYear, selMonth){
// disable select menu
disableMenu();
// make accesable
this.selYear = selYear
this.selMonth = selMonth
if(typeof this.contourMap !== 'undefined'){
map.removeLayer(this.contourMap);
this.contourMap = undefined;
}
if(typeof this.regioMap !== 'undefined'){
map.removeLayer(this.regioMap);
this.regioMap = undefined;
}
if(typeof this.indexData !== 'undefined'){
map.removeLayer(this.indexData);
this.indexData = undefined;
this.geojsonIdx = undefined;
}
if(typeof this.validationData !== 'undefined'){
map.removeLayer(this.validationData);
validationData = undefined;
}
if(typeof this.contourL !== 'undefined'){
map.removeLayer(this.contourL);
contourL = undefined;
}
if(typeof this.selectedEventIds !== 'undefined'){
this.selectedEventIds = undefined;
}
getRasterMap(map, selYear, selMonth, 'contourMap')
getDataPoints(map, selYear, selMonth, 1, 'indexData')
getDataPoints(map, selYear, selMonth, 1, 'validationData')
getRasterMap(map, selYear, selMonth, 'regionMap')
getContourLines(map, selYear, selMonth)
// load all data and wait till everything is done, than add controls
$.when(mapTemperature, pointVali, pointIdx, contourLines, regioMap).done(function(a1,a2,indexData, cdat){
mapTemperature = pointVali = pointIdx = contourLines = undefined;
// add temperature legend
if(cdat[0].features !== null){
geojsondat = cdat[0]
addTempLegend(map);
}
// add map controls
addControls(map);
// add map info with shorttext
addInfo(map, selYear, selMonth);
// add info table
var tableData = indexData[0];
addTable1(tableData['idxPDat'], tableData['cruStats'], tableData['stationStats'])
// re-enable select meanu:
enableMenu();
});
/*
// update short info
shortPointTxt = createShortTxt(geojson);
// populate info table
if(res['cruStats'] != '' && res['stationStats'] != ''){
addTable(geojson, res['cruStats'], res['stationStats']);
}
*/
}
//###############################################################################
function addBaseMap(map){
L.tileLayer('http://a.tiles.mapbox.com/v3/jcheng.map-5ebohr46/{z}/{x}/{y}.png', {
maxZoom: 8,
minZoom: 2
}).addTo(map);
// add zoom control
new L.Control.Zoom({ position: 'topright' }).addTo(map);
}
function addRasterMap(imageUrl, type, imageBounds, viewBounds){
// load map
this[type] = L.imageOverlay(imageUrl, imageBounds, {opacity:0.7});
// display map
this[type].addTo(map);
// set view to countor Image extent
if(typeof viewBounds !== 'undefined'){
map.fitBounds(viewBounds);
}
}
function addCircleMarker(map, geojson, type){
// add index marker
this[type] = L.geoJson(geojson, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, getMarkerOptions(feature, type));
},
onEachFeature: onEachFeature
});
if(type !== "validationData"){
this[type].addTo(map);
}
}
function addInfo(map, selYear, selMonth){
$('.info').remove();
var selMonthArr = new Array('NONE','January','February','March','April','May','June','July','August','September','October','November','December');
if(typeof this.geojsonIdx !== 'undefined'){
var shortPointTxt = createShortTxt(this.geojsonIdx);
} else {
var shortPointTxt = undefined;
}
//define info control
info = L.control({style:style, position: 'bottomleft'});
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
this.update();
return this._div;
};
info.update = function (props) {
if(typeof shortPointTxt === 'undefined'){
this._div.innerHTML = '<h4>'+selMonthArr[selMonth]+" "+selYear+'</h4>'
} else {
this._div.innerHTML = '<h4>'+selMonthArr[selMonth]+" "+selYear+'</h4>' + (props ?
'Temperature: ' + props.temp
: '<i>'+shortPointTxt+'</i>'
);
}
highlightInfoTable('NULL') ;
};
// show detail info to selected (hover) index point
info.updatePoint = function (props) {
var text = props.text;
var location = props.location;
highlightInfoTable(location);
text = replaceAll(text, '*', '');
if(text.length > 9000) text = text.substring(0,9000) +' [...]';
this._div.innerHTML = '<h4>'+selYear+" "+selMonthArr[selMonth]+'</h4>' + (props ?
'<b>Location: </b>' + props.location + '<br />'+
'<b>Event Id: </b>' + props.event_id + '<br />'+
'<b>Value: </b>' + props.idx + '<br />'+
'<b>Longitude: </b>' + parseFloat(props.lon_info).toFixed(2) + '<br />'+
'<b>Latitude: </b>' + parseFloat(props.lat_info).toFixed(2) + '<br />'+
'<b>Text: </b>' + text + '<br />'
: '');
};
info.addTo(map);
// modify info style
var width = $('.left').width()-10;
var height = $('#map').height();
height = (height/100) * 80;
$('.info').css({'max-width':width, 'max-height':height, 'overflow': 'hidden'});
}
function addControls(map){
var overlayPane = {};
if(typeof this.layerControl !== 'undefined'){
layerControl.removeFrom(map);
}
if(typeof this.contourMap !== 'undefined'){
overlayPane['reconstructed temperature map'] = this.contourMap;
}
if(typeof this.regioMap !== 'undefined'){
overlayPane['regionalised idices map'] = this.regioMap;
}
if(typeof this.indexData !== 'undefined'){
overlayPane['index points'] = this.indexData;
}
if(typeof this.validationData !== 'undefined'){
overlayPane['climate stations'] = this.validationData;
}
if(typeof this.contourL !== 'undefined'){
overlayPane['contour lines'] = this.contourL;
}
if(typeof this.selectMap !== 'undefined'){
overlayPane['reconstructed temperature map'] = this.selectMap;
}
// Add a layer control element to the map
layerControl = L.control.layers(null, overlayPane, {position: 'topleft'});
layerControl.addTo(map);
}
function addContourLines(map, geojson){
// contourL = L.geoJson(geojson, {style: style, onEachFeature: onEachFeature});
contourL = L.geoJson(geojson, {style: style});
// Lgeojson.addTo(map); // disabled by default
}
function updateAppBySelect(){
if(this.selectedEventIds[0] != null && this.selectedEventIds.length != this.allEventIds.length){
getRasterMap(map, selYear, selMonth, 'selectMap');
getRasterMap(map, selYear, selMonth, 'regionMap');
getDataPoints(map, selYear, selMonth, 1,'validationDataArea');
updateStats(selectedEventIds, selYear, selMonth);
// pointVali, pointIdx, contourLines,
$.when(selMap, regioMap, pointValiArea).done(function(a1,a2,a3){
// update text stats
// update controls with new layer info
addControls(map);
});
} else if(this.selectedEventIds.length === this.allEventIds.length) {
getRasterMap(map, selYear, selMonth, 'contourMap');
getRasterMap(map, selYear, selMonth, 'regionMap');
getDataPoints(map, selYear, selMonth, 1, 'validationData');
updateStats(selectedEventIds, selYear, selMonth);
// update text stats
$.when(mapTemperature, regioMap, pointVali).done(function(a1,a2,a3){
// update controls with new layer info
addControls(map);
});
} else {
if(typeof this.contourMap !== 'undefined'){
map.removeLayer(this.contourMap);
this.contourMap = undefined;
}
if(typeof this.selectMap !== 'undefined'){
map.removeLayer(this.selectMap);
this.selectMap = undefined;
}
}
}
function addOnClickInfo(){
map.on('click', function(e) {
//alert("Lat, Lon : " + e.latlng.lat + ", " + e.latlng.lng+" " + year +" "+month)
var lat = e.latlng.lat;
var lon = e.latlng.lng;
if(selectedEventIds.length === allEventIds.length){
var bbox = checkBoundingBox()[0]
$.getJSON(window.location+'rasterToPng.php?callback=?&year='+selYear+"&month="+selMonth+"&lat="+lat+"&lon="+lon+"&evid="+selectedEventIds.toString(),
function(res){
if(res != null){
var marker = L.circleMarker([e.latlng.lat,e.latlng.lng]).addTo(map)
.bindPopup(parseFloat(res).toFixed(2)+" °C" ).openPopup();
setTimeout(function(){ map.removeLayer(marker); }, 1000);
}
// define rectangle geographical bounds
// var bounds = [[e.latlng.lat, e.latlng.lng], [e.latlng.lat+1, e.latlng.lng+1]];
// create an orange rectangle
// L.rectangle(bounds, {color: "#ff7800", weight: 100}).addTo(map);
});
} else if(selectedEventIds[0] != null && selectedEventIds.length != allEventIds.length){
var sum = selectedEventIds.reduce(function(a, b) { return parseInt(a) + parseInt(b); });
var evHash = sum/selectedEventIds.length
$.getJSON(window.location+'rasterToPng.php?callback=?&year='+selYear+"&month="+selMonth+"&lat="+lat+"&lon="+lon+'&evid='+selectedEventIds.toString(),
function(res){
if(res != null){
console.log(res)
var marker = L.circleMarker([e.latlng.lat,e.latlng.lng]).addTo(map)
.bindPopup(parseFloat(res).toFixed(2)+" °C" ).openPopup();
setTimeout(function(){ map.removeLayer(marker); }, 1000);
}
});
}
});
}
function addOnAddRemoveInfo(){
map.on('overlayadd', function(e){
if(e.name==='regionalised idices map'){
addRegioLegend(map)
var tMpaControl = $('span:contains(reconstructed temperature map)').parent().children(':first-child')
if(tMpaControl.is(':checked')){
tMpaControl.click();
}
}
});
map.on('overlayremove', function(e){
if(e.name==='regionalised idices map'){
addTempLegend(map)
var tMpaControl = $('span:contains(reconstructed temperature map)').parent().children(':first-child')
if(!tMpaControl.is(':checked')){
tMpaControl.click();
}
}
});
};
//######################################################################################
// create default historical text from shortest historical comment
function createShortTxt(geojsonPoints){
for(var i = 0; i < geojsonPoints.features.length; i++){
var pointTxt = geojsonPoints.features[i].properties['text'];
if(i == 0){
shortPointTxt = pointTxt;
}
else if(shortPointTxt.length > pointTxt.length){
shortPointTxt = pointTxt;
}
}
// cut text to n chars and display selMonth selYear h4
shortPointTxt = replaceAll(shortPointTxt, '*', '');
if(shortPointTxt.length > 150) shortPointTxt = shortPointTxt.substring(0,150) +' [...]';
// $('.info').html('<h4>'+ this.selMonthArr[selMonth]+" "+selYear+'</h4><i>'+shortPointTxt+'</i>');
return shortPointTxt;
}
function checkSameLatLon(data){
// check if points exist on same location; make little offset if so
var checkLoc = [];
for(var i = 0; i < data.length; i++){
if($.inArray(data[i]['lon'], checkLoc) != -1){
// multiply offset for multiple same locations
var count = checkLoc.reduce(function(n, val) {
return n + (val === data[i]['lon']);
}, 0);
checkLoc.push(data[i]['lon'])
data[i]['lon'] = parseFloat(data[i]['lon'])+(0.3*count)
} else {
checkLoc.push(data[i]['lon'])
}
}
return data
}
function getDataPoints(map, selYear, selMonth, bbox, type){
if(type === 'indexData'){
// check if bounding box was defined and load data appropriate
var bbox = checkBoundingBox()[0]
// get data points overlay
pointIdx = $.getJSON(window.location+'postgresInt.php?callback=?&mode=3&year='+selYear+'&month='+selMonth+'&areaView='+bbox,
function(res){
// check if view is available in db
if(res['idxPDat'] != ''){
var data = res['idxPDat'];
// check if points exist on same location; make little offset if so
data = checkSameLatLon(data)
// make geojson object from data
geojsonIdx = GeoJSON.parse(data, {Point: ['lat', 'lon']});
// store all available event ids for select
getAllEventIds(geojsonIdx)
// add index marker
addCircleMarker(map, geojsonIdx, type)
// populate instant stats
updateStats(allEventIds, selYear, selMonth)
}
});
} else if(type === 'validationData'){
if(typeof this.validationData !== 'undefined'){
map.removeLayer(this.validationData);
validationData = undefined;
}
var bbox = checkBoundingBox()[0]
pointVali = $.getJSON(window.location+'valiPoints.php?callback=?&mode=0&year='+selYear+'&month='+selMonth+'&areaView='+bbox,
function(res){
// check if view is available in db
if(res['idxPDat'] != ''){
console.log('vali0')
// make geojson object from data
geojson = GeoJSON.parse(res['idxPDat'], {Point: ['lat', 'lon']});
// create station marker overlay
addCircleMarker(map, geojson, type) // display station marker overlay
}
});
} else if(type === 'validationDataArea'){
if(typeof this.validationData !== 'undefined'){
map.removeLayer(this.validationData);
validationData = undefined;
}
pointValiArea = $.getJSON(window.location+'valiPoints.php?callback=?&mode=3&year='+selYear+'&month='+selMonth+'&evid='+selectedEventIds.toString(),
function(res){
// check if view is available in db
if(res['idxPDat'] != ''){
// make geojson object from data
geojson = GeoJSON.parse(res['idxPDat'], {Point: ['lat', 'lon']});
// create station marker overlay
addCircleMarker(map, geojson, 'validationData') // display station marker overlay
//geojsonValiPoints.addTo(map);
// display station offset (eg: -1 means that the reconstructed data are at the station locations by
// average 1 C colder than the station data)
/*
if(res['idxPDatMean'] != "null") {
$('#stationTextMean').text((res['idxPDatMean']).toFixed(2));
$('#mapStats').show();
} else {
$('#mapStats').hide();
}
*/
}
});
}
}
function getContourLines(map, selYear, selMonth){
// load contour data
contourLines = $.getJSON(window.location+'test.php?year='+selYear+'&month='+selMonth,
function(res){
if(res.features !== null){
addContourLines(map, res)
}
});
}
function getRasterMap(map, selYear, selMonth, type){
if(type === 'contourMap'){
if(typeof this.contourMap !== 'undefined'){
map.removeLayer(this.contourMap);
this.contourMap = undefined;
}
if(typeof this.selectMap !== 'undefined'){
map.removeLayer(this.selectMap);
this.selectMap = undefined;
}
var bbox = checkBoundingBox()[0]
mapTemperature = $.getJSON(window.location+'rasterToPng.php?callback=?&extent=1&year='+selYear+'&month='+selMonth,
function(res){
// check if view is available in db else show cru selMonth mean map
if(res === 'no data'){
var imageUrl = 'rasterToPng.php?crumean=1&month='+selMonth;
// place map like corner coordinates
var imageBounds = [[70,50],[30, -30]]; // ymax, xmax, ymin, xmin
var viewBounds = [[70,50],[30, -30]]; // ymax, xmax, ymin, xmin
} else {
var dim = res['idxPDat'];
var imageUrl = 'rasterToPng.php?year='+selYear+'&month='+selMonth+'&areaView='+bbox;
// place map like corner coordinates
var viewBounds = [[dim['ymax'], dim['xmax']], [dim['ymin'], dim['xmin']]]; // ymax, xmax, ymin, xmin
var imageBounds = [[70,50],[30, -30]]; // ymax, xmax, ymin, xmin
}
addRasterMap(imageUrl, type, imageBounds, viewBounds)
}
)
} else if(type == 'regionMap'){
// set bbox map url
var bbox = checkBoundingBox()[0]
if(typeof this.selectedEventIds !== 'undefined'){
var imageUrl = 'rasterToPng.php?regiomax=1&evid='+this.selectedEventIds.toString();
}else {
var imageUrl = 'rasterToPng.php?regiomax=1&year='+selYear+'&month='+selMonth+'&areaView='+bbox;
}
// load map and display
var imageBounds = [[70,50],[30,-30]]; // ymax, xmax, ymin, xmin
regioMap = L.imageOverlay(imageUrl, imageBounds, {opacity:0.9});
// regioImage.addTo(map);
} else if(type === 'selectMap'){
if(typeof this.selectMap !== 'undefined'){
map.removeLayer(this.selectMap);
this.selectMap = undefined;
}
if(typeof this.contourMap !== 'undefined'){
map.removeLayer(this.contourMap);
this.contourMap = undefined;
}
selMap = $.getJSON(window.location+'rasterToPng.php?callback=?&live=2&year='+this.selYear+'&month='+this.selMonth+'&evid='+this.selectedEventIds.toString(),
function(res){
var imageUrl = 'rasterToPng.php?live=1&evid='+selectedEventIds.toString();
var imageBounds = [[70,50],[30, -30]]; // ymax, xmax, ymin, xmin
addRasterMap(imageUrl, type, imageBounds)
});
}
}
function getPythonRasterMap(){
// rework if available get extend and then load like getRaster map but with evHASH if not get extend -> calc data -> get data like before
var imageUrl = 'rasterToPng.php?year='+selYear+'&month='+selMonth+'&evid='+selectedEventIds.toString()+'&evidHash='+evHash;
var imageBounds = [[70, 50], [30, -30]]; // ymax, xmax, ymin, xmin
//var imageBounds = [[41.6932432432432, -3.30367647058824], [59.2932432432432, 29.7963235294118]]; // ymax, xmax, ymin, xmin
map.removeLayer(contourImage);
contourImage = new L.imageOverlay(imageUrl, imageBounds, {opacity:0.7});
contourImage.addTo(map);
}
//######################################################################################################
// UTILS
function clacEventHash(selectedEventIds){
var sum = selectedEventIds.reduce(function(a, b) { return parseInt(a) + parseInt(b); });
var evHash = sum/selectedEventIds.length
return evHash
}
function updateEvidsSelected(layerId, selectedEventIds){
// this has to be persistent in some way
if(jQuery.inArray( layerId, selectedEventIds ) == -1){
selectedEventIds.push(layerId);
} else {
var idx = jQuery.inArray( layerId, selectedEventIds )
selectedEventIds.splice(idx, 1);
}
}
function getAllEventIds(geojson){
//get all event_id's for this selYear selMonth combi
allEventIds = [];
selectedEventIds = [];
for(var i = 0; i < geojson.features.length; i++){
allEventIds.push(geojson.features[i].properties['event_id']);
// make deep copy cause a = b is just a reference ...
selectedEventIds = deepCopy(allEventIds);
}
}
function disableMenu(){
$('#century').css({'pointerEvents':'none'});
$('#decade').css({'pointerEvents':'none'});
$('#year').css({'pointerEvents':'none'});
$('#month').css({'pointerEvents':'none'});
}
function enableMenu(){
$('#century').css({'pointerEvents':'auto'});
$('#decade').css({'pointerEvents':'auto'});
$('#year').css({'pointerEvents':'auto'});
$('#month').css({'pointerEvents':'auto'});
}
//######################################################################################################
// Animation
function toggleFeature(e){
var layer = e.target;
// only index points are clickable
if(layer.feature.properties.text){
var layerId = layer.feature.properties['event_id'];
updateEvidsSelected(layerId, selectedEventIds)
// animate point
if(layer.options.color != '#FFFFFF') {
layer.setStyle({
weight: 1,
color: '#FFFFFF',
dashArray: '',
fillOpacity: 0.7
})
} else {
layer.setStyle({
weight: 1,
color: '#000',
dashArray: '',
fillOpacity: 0.7
})
}
// update displayd stats for selected layers
updateStats(selectedEventIds, this.selYear, this.selMonth);
// update map
updateAppBySelect()
}
}
function getMarkerOptions(feature, type) {
if(type !== "validationData"){
return {
radius: 6,
fillColor: getColor(feature.properties.idx),
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
}
}
else {
return {
radius: 5,
fillColor: getColor(feature.properties.stdOff),
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
}
}
};
// style for point layer
function getColor(d) {
return d == '-3' ? '#4575b4' :
d == '-2' ? '#91bfdb' :
d == '-1' ? '#e0f3f8' :
d == '0' ? '#ffffbf' :
d == '1' ? '#fee090' :
d == '2' ? '#fc8d59' :
d == '3' ? '#d73027' :
'#9F0000';
}
// CONTOUR DATA
function style(feature) {
return {
// fillColor: getColor(parseInt(feature.properties.level)),
weight: 1,
opacity: 1,
color: 'white',//getColor(parseInt(feature.properties.level)),
dashArray: '0',
fillOpacity: 0.7
};
}
// add map Interaction
function highlightFeature(e) {
var layer = e.target;
// if indexpoint or vali point
if(layer.feature.properties.text){
// check if contour layer or point layer
if(!layer['_radius']){
layer.setStyle({
weight: 2,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
}
if (!L.Browser.ie && !L.Browser.opera) {
layer.bringToFront();
}
// populate info appropriate to layer feature
(!layer['_radius']) ? info.update(layer.feature.properties) : info.updatePoint(layer.feature.properties);
}else {
// popup for vali point
layer.bindPopup('<b>Location: </b>'+layer.feature.properties.name+'<br><b>Station Temperature: </b>'+layer.feature.properties.temperature+'<br><b>Recon Temperature: </b>'+parseFloat(layer.feature.properties.temp_recon).toFixed(2))
layer.openPopup();
}
}
function resetHighlight(e) {
var layer = e.target;
if(layer.feature.properties.text){
if(!e.target['_radius']) Lgeojson.resetStyle(e.target);
info.update();
} else {
setTimeout(function(){ layer.closePopup(); }, 2000);
}
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: toggleFeature
})
};
| ElenorFrisbee/MSC | regmod/js/mapView_opti.js | JavaScript | mit | 25,418 |
Oskari.registerLocalization(
{
"lang": "sq",
"key": "FeatureData",
"value": {
"title": "Objekt i të dhënave",
"desc": "",
"loading": "Ngarkim",
"showmore": "Paraqit",
"nodata": "Shtresat e hartës së përzgjedhur nuk përmbajnë tipare të të dhënave",
"featureNameAll": "Lloji i të dhënave",
"errorscale": "Të dhënat nuk mund të paraqiten në këtë nivel të shkallës I Ju lutem ndryshoni nivelin e shkallës",
"errordata": "Të dhënat e ofruara nga serveri përmbajnë gabime I Ju lutem lëvizeni pak hartën për ta azhurnuar atë",
"columnSelectorTooltip": "Paraqit kolonat",
"popup": {
"title": "Zgjedh tiparet në hartë",
"instructions": "NOT TRANSLATED",
"link": {
"title": "Zgjedh më shumë"
},
"button": {
"cancel": "Anulo",
"show": "Shih vendet",
"close": "Mbyll",
"edit": "Ndrysho"
},
"tools": {
"point": {
"tooltip": "Shto pikën"
},
"line": {
"tooltip": "Shto linjën"
},
"polygon": {
"tooltip": "Shto shumëkëndëshin"
},
"square": {
"tooltip": "Shto drejtëkëndëshin"
},
"circle": {
"tooltip": "Shto rrethin"
},
"select": {
"tooltip": "NOT TRANSLATED"
}
}
}
}
}
); | uhef/Oskari-Routing-frontend | bundles/framework/bundle/featuredata/locale/sq.js | JavaScript | mit | 1,689 |
import Label, {textLayoutToJSON} from './label';
import Vector from '../utils/vector';
import OBB from '../utils/obb';
const STOPS = [0, 0.33, 0.66, 0.99]; // zoom levels for curved label snapshot data (offsets and angles)
const LINE_EXCEED_STRAIGHT = 1.5; // minimal ratio for straight labels (label length) / (line length)
const LINE_EXCEED_STRAIGHT_NO_CURVE = 1.8; // minimal ratio for straight labels that have no curved option (like Arabic)
const LINE_EXCEED_STAIGHT_LOOSE = 2.3; // 2nd pass minimal ratio for straight labels
const STRAIGHT_ANGLE_TOLERANCE = 0.1; // multiple "almost straight" segments within this angle tolerance can be considered one straight segment (in radians)
const CURVE_MIN_TOTAL_COST = 1.3; // curved line total curvature tolerance (sum in radians)
const CURVE_MIN_AVG_COST = 0.4; // curved line average curvature tolerance (mean)
const CURVE_MAX_ANGLE = 1; // curved line singular curvature tolerance (value in radians)
const ORIENTED_LABEL_OFFSET_FACTOR = 1.2; // multiply offset by this amount to avoid linked label collision
const VERTICAL_ANGLE_TOLERANCE = 0.01; // nearly vertical lines considered vertical within this angle tolerance
let LabelLine = {
// Given a label's bounding box size and size of broken up individual segments
// return a label that fits along the line geometry that is either straight (preferred) or curved (if straight tolerances aren't met)
create : function(segment_sizes, total_size, line, layout){
// The passes done for fitting a label, and provided tolerances for each pass
// First straight is chosen with a low tolerance. Then curved. Then straight with a higher tolerance.
const passes = [
{ type: 'straight', tolerance : (layout.no_curving) ? LINE_EXCEED_STRAIGHT_NO_CURVE : LINE_EXCEED_STRAIGHT },
{ type: 'curved' },
{ type: 'straight', tolerance : LINE_EXCEED_STAIGHT_LOOSE }
];
// loop through passes. first label found wins.
for (let i = 0; i < passes.length; i++){
let check = passes[i];
let label;
if (check.type === 'straight'){
label = new LabelLineStraight(total_size, line, layout, check.tolerance);
}
else if (check.type === 'curved' && !layout.no_curving && line.length > 2){
label = new LabelLineCurved(segment_sizes, line, layout);
}
if (label && !label.throw_away) {
return label;
}
}
return false;
}
};
export default LabelLine;
// Base class for a labels.
export class LabelLineBase {
constructor (layout) {
this.id = Label.nextLabelId();
this.layout = layout;
this.position = [];
this.angle = 0;
this.offset = layout.offset.slice();
this.unit_scale = this.layout.units_per_pixel;
this.obbs = [];
this.aabbs = [];
this.type = ''; // "curved" or "straight" to be set by child class
this.throw_away = false; // boolean that determines if label should be discarded
}
// Minimal representation of label
toJSON () {
return {
id: this.id,
type: this.type,
position: this.position,
size: this.size,
offset: this.offset,
angle: this.angle,
breach: this.breach,
may_repeat_across_tiles: this.may_repeat_across_tiles,
layout: textLayoutToJSON(this.layout)
};
}
// Given a line, find the longest series of segments that maintains a constant orientation in the x-direction.
// This assures us that the line has no orientation flip, so text would not appear upside-down.
// If the line's orientation is reversed, the flip return value will be true, otherwise false
static splitLineByOrientation(line){
let current_line = [line[0]];
let current_length = 0;
let max_length = 0;
let orientation = 0;
let longest_line = current_line;
let flip = false;
for (let i = 1; i < line.length; i++) {
let pt = line[i];
let prev_pt = line[i - 1];
let length = Vector.length(Vector.sub(pt, prev_pt));
if (pt[0] > prev_pt[0]){
// positive orientation
if (orientation === 1){
current_line.push(pt);
current_length += length;
if (current_length > max_length){
longest_line = current_line;
max_length = current_length;
flip = false;
}
}
else {
current_line = [prev_pt, pt];
current_length = length;
if (current_length > max_length){
longest_line = current_line;
max_length = current_length;
flip = false;
}
orientation = 1;
}
}
else if (pt[0] < prev_pt[0]) {
// negative orientation
if (orientation === -1){
current_line.unshift(pt);
current_length += length;
if (current_length > max_length){
longest_line = current_line;
max_length = current_length;
flip = true;
}
}
else {
// prepend points (reverse order)
current_line = [pt, prev_pt];
current_length = length;
if (current_length > max_length){
longest_line = current_line;
max_length = current_length;
flip = true;
}
orientation = -1;
}
}
else {
// vertical line (doesn't change previous orientation)
if (orientation === -1){
current_line.unshift(pt);
}
else {
current_line.push(pt);
orientation = 1;
}
current_length += length;
if (current_length > max_length){
longest_line = current_line;
max_length = current_length;
flip = (orientation === -1);
}
}
}
return [longest_line, flip];
}
// Checks each segment to see if it should be discarded (via collision). If any segment fails this test, they all fail.
discard(bboxes, exclude = null) {
if (this.throw_away) {
return true;
}
for (let i = 0; i < this.obbs.length; i++){
let aabb = this.aabbs[i];
let obb = this.obbs[i];
let obj = { aabb, obb };
let shouldDiscard = Label.prototype.occluded.call(obj, bboxes, exclude);
if (shouldDiscard) {
return true;
}
}
return false;
}
// Checks each segment to see if it is within the tile. If any segment fails this test, they all fail.
inTileBounds() {
for (let i = 0; i < this.aabbs.length; i++) {
let aabb = this.aabbs[i];
let obj = { aabb };
let in_bounds = Label.prototype.inTileBounds.call(obj);
if (!in_bounds) {
return false;
}
}
return true;
}
// Method to calculate oriented bounding box
// "angle" is the angle of the text segment, "angle_offset" is the angle applied to the offset.
// Offset angle is constant for the entire label, while segment angles are not.
static createOBB (position, width, height, angle, angle_offset, offset, upp) {
let p0 = position[0];
let p1 = position[1];
// apply offset, x positive, y pointing down
if (offset && (offset[0] !== 0 || offset[1] !== 0)) {
offset = Vector.rot(offset, angle_offset);
p0 += offset[0] * upp;
p1 -= offset[1] * upp;
}
// the angle of the obb is negative since it's the tile system y axis is pointing down
return new OBB(p0, p1, -angle, width, height);
}
}
// Class for straight labels.
// Extends base LabelLine class.
export class LabelLineStraight extends LabelLineBase {
constructor (size, line, layout, tolerance){
super(layout);
this.type = 'straight';
this.size = size;
this.throw_away = !this.fit(size, line, layout, tolerance);
}
// Determine if the label can fit the geometry within provided tolerance
// A straight label is generally placed at segment midpoints, but can "look ahead" to further segments
// if they are within an angle bound given by STRAIGHT_ANGLE_TOLERANCE and place at the midpoint between non-consecutive segments
fit (size, line, layout, tolerance){
let upp = this.unit_scale;
let flipped; // boolean indicating if orientation of line is changed
// Make new copy of line, with consistent orientation
[line, flipped] = LabelLineBase.splitLineByOrientation(line);
// matches for "left" or "right" labels where the offset angle is dependent on the geometry
if (typeof layout.orientation === 'number'){
this.offset[1] += ORIENTED_LABEL_OFFSET_FACTOR * (size[1] - layout.vertical_buffer);
// if line is flipped, or the orientation is "left" (-1), flip the offset's y-axis
if (flipped){
this.offset[1] *= -1;
}
if (layout.orientation === -1){
this.offset[1] *= -1;
}
}
let line_lengths = getLineLengths(line);
let label_length = size[0] * upp;
// loop through line looking for a placement for the label
for (let i = 0; i < line.length - 1; i++){
let curr = line[i];
let curve_tolerance = 0;
let length = 0;
let ahead_index = i + 1;
let prev_angle;
// look ahead to further line segments within an angle tolerance
while (ahead_index < line.length){
let ahead_curr = line[ahead_index - 1];
let ahead_next = line[ahead_index];
let next_angle = getAngleForSegment(ahead_curr, ahead_next);
if (ahead_index !== i + 1){
curve_tolerance += getAbsAngleDiff(next_angle, prev_angle);
}
// if curve tolerance is exceeded, break out of loop
if (Math.abs(curve_tolerance) > STRAIGHT_ANGLE_TOLERANCE){
break;
}
length += line_lengths[ahead_index - 1];
// check if label fits geometry
if (calcFitness(length, label_length) < tolerance){
let curr_midpt = Vector.mult(Vector.add(curr, ahead_next), 0.5);
// TODO: modify angle if line chosen within curve_angle_tolerance
// Currently line angle is the same as the starting angle, perhaps it should average across segments?
this.angle = -next_angle;
// ensure that all vertical labels point up (not down) by snapping angles close to pi/2 to -pi/2
if (Math.abs(this.angle - Math.PI/2) < VERTICAL_ANGLE_TOLERANCE) {
// flip angle and offset
this.angle = -Math.PI/2;
if (typeof layout.orientation === 'number'){
this.offset[1] *= -1;
}
}
this.position = curr_midpt;
this.updateBBoxes(this.position, size, this.angle, this.angle, this.offset);
return true; // use this placement
}
prev_angle = next_angle;
ahead_index++;
}
}
return false;
}
// Calculate bounding boxes
updateBBoxes(position, size, angle, angle_offset, offset) {
let upp = this.unit_scale;
// reset bounding boxes
this.obbs = [];
this.aabbs = [];
let width = (size[0] + 2 * this.layout.buffer[0]) * upp * Label.epsilon;
let height = (size[1] + 2 * this.layout.buffer[1]) * upp * Label.epsilon;
let obb = LabelLineBase.createOBB(position, width, height, angle, angle_offset, offset, upp);
let aabb = obb.getExtent();
this.obbs.push(obb);
this.aabbs.push(aabb);
if (this.inTileBounds) {
this.breach = !this.inTileBounds();
}
if (this.mayRepeatAcrossTiles) {
this.may_repeat_across_tiles = this.mayRepeatAcrossTiles();
}
}
}
// Class for curved labels
// Extends base LabelLine class to support angles, pre_angles, offsets as arrays for each segment
class LabelLineCurved extends LabelLineBase {
constructor (segment_sizes, line, layout) {
super(layout);
this.type = 'curved';
// extra data for curved labels
this.angles = [];
this.pre_angles = [];
this.offsets = [];
this.num_segments = segment_sizes.length;
this.sizes = segment_sizes;
this.throw_away = !this.fit(this.sizes, line, layout);
}
// Minimal representation of label
toJSON () {
return {
id: this.id,
type: this.type,
obbs: this.obbs.map(o => o.toJSON()),
position: this.position,
breach: this.breach,
may_repeat_across_tiles: this.may_repeat_across_tiles,
layout: textLayoutToJSON(this.layout)
};
}
// Determine if the curved label can fit the geometry.
// No tolerance is provided because the label must fit entirely within the line geometry.
fit (size, line, layout){
let upp = this.unit_scale;
let flipped; // boolean determining if the line orientation is reversed
let height_px = Math.max(...size.map(s => s[1])); // use max segment height
let height = height_px * upp;
// Make new copy of line, with consistent orientation
[line, flipped] = LabelLineBase.splitLineByOrientation(line);
// matches for "left" or "right" labels where the offset angle is dependent on the geometry
if (typeof layout.orientation === 'number'){
this.offset[1] += ORIENTED_LABEL_OFFSET_FACTOR * (height_px - layout.vertical_buffer);
// if line is flipped, or the orientation is "left" (-1), flip the offset's y-axis
if (flipped){
this.offset[1] *= -1;
}
if (layout.orientation === -1){
this.offset[1] *= -1;
}
}
let line_lengths = getLineLengths(line);
let label_lengths = size.map(size => size[0] * upp);
let total_line_length = line_lengths.reduce((prev, next) => prev + next, 0);
let total_label_length = label_lengths.reduce((prev, next) => prev + next, 0);
// if label displacement is longer than the line, no fit can be possible
if (total_label_length > total_line_length){
return false;
}
// need two line segments for a curved label
// NB: single segment lines should still be labeled if possible during straight label placement pass
let start_index = 0, end_index = line.length-1;
if (end_index - start_index < 2){
return false;
}
// all positional offsets of the label are relative to the anchor
let anchor_index = LabelLineCurved.curvaturePlacement(line, total_line_length, line_lengths, total_label_length, start_index, end_index);
let anchor = line[anchor_index];
// if anchor not found, or greater than the end_index, no fit possible
if (anchor_index === -1 || end_index - anchor_index < 2){
return false;
}
// set start position at anchor position
this.position = anchor;
// Loop through labels at each zoom level stop
// TODO: Can be made faster since we are computing every segment for every zoom stop
// We can skip a segment's calculation once a segment's angle equals its fully zoomed angle
for (var i = 0; i < label_lengths.length; i++){
this.offsets[i] = [];
this.angles[i] = [];
this.pre_angles[i] = [];
// loop through stops (z = [0, .33, .66, .99] + base zoom)
for (var j = 0; j < STOPS.length; j++){
let stop = STOPS[j];
// scale the line geometry by the zoom magnification
let [new_line, line_lengths] = LabelLineCurved.scaleLine(stop, line);
anchor = new_line[anchor_index];
// calculate label data relative to anchor position
let {positions, offsets, angles, pre_angles} = LabelLineCurved.placeAtIndex(anchor_index, new_line, line_lengths, label_lengths);
// translate 2D offsets into "polar coordinates"" (1D distances with angles)
let offsets1d = offsets.map(offset => {
return Math.sqrt(offset[0] * offset[0] + offset[1] * offset[1]) / upp;
});
// Calculate everything that is independent of zoom level (angle for offset, bounding boxes, etc)
if (stop === 0){
// use average angle for a global label offset (if offset is specified)
this.angle = 1 / angles.length * angles.reduce((prev, next) => prev + next);
// calculate bounding boxes for collision at zoom level 0
for (let i = 0; i < positions.length; i++){
let position = positions[i];
let pre_angle = pre_angles[i];
let width = label_lengths[i];
let angle_segment = pre_angle + angles[i];
let angle_offset = this.angle;
let obb = LabelLineBase.createOBB(position, width, height, angle_segment, angle_offset, this.offset, upp);
let aabb = obb.getExtent();
this.obbs.push(obb);
this.aabbs.push(aabb);
}
}
// push offsets/angles/pre_angles for each zoom and for each label segment
this.offsets[i].push(offsets1d[i]);
this.angles[i].push(angles[i]);
this.pre_angles[i].push(pre_angles[i]);
}
}
return true;
}
// Find optimal starting segment for placing a curved label along a line within provided tolerances
// This is determined by calculating the curvature at each interior vertex of a line
// then construct a "window" whose breadth is the length of the label. Place this label at each vertex
// and add the curvatures of each vertex within the window. The vertex mimimizing this value is the "best" placement.
// Return -1 is no placement found.
static curvaturePlacement(line, total_line_length, line_lengths, label_length, start_index, end_index){
start_index = start_index || 0;
end_index = end_index || line.length - 1;
var curvatures = []; // array of curvature values per line vertex
// calculate curvature values
for (let i = start_index + 1; i < end_index; i++){
var prev = line[i - 1];
var curr = line[i];
var next = line[i + 1];
var norm_1 = Vector.perp(curr, prev);
var norm_2 = Vector.perp(next, curr);
var curvature = Vector.angleBetween(norm_1, norm_2);
// If curvature at a vertex is greater than the tolerance, remove it from consideration
// by giving it an infinite penalty
if (curvature > CURVE_MAX_ANGLE) {
curvature = Infinity;
}
curvatures.push(curvature);
}
curvatures.push(Infinity); // Infinite penalty for going off end of line
// calculate curvature costs
var total_costs = [];
var avg_costs = [];
var line_index = start_index;
var position = 0;
for (let i = 0; i < start_index; i++){
position += line_lengths[i];
}
// move window along line, starting at first vertex
while (position + label_length < total_line_length){
// define window breadth
var window_start = position;
var window_end = window_start + label_length;
var line_position = window_start;
var ahead_index = line_index;
var cost = 0;
// iterate through points on line intersecting window
while (ahead_index < end_index && line_position + line_lengths[ahead_index] < window_end){
cost += curvatures[ahead_index];
if (cost === Infinity) {
break; // no further progress can be made
}
line_position += line_lengths[ahead_index];
ahead_index++;
}
// if optimal cost, break out
if (cost === 0) {
return line_index;
}
var avg_cost = cost / (ahead_index - line_index);
total_costs.push(cost);
avg_costs.push(avg_cost);
position += line_lengths[line_index];
line_index++;
}
if (total_costs.length === 0) {
return -1;
}
// calculate min cost and avg cost to determine if label can fit within curvatures tolerances
var min_total_cost = Math.min.apply(null, total_costs);
var min_index = total_costs.indexOf(min_total_cost);
var min_avg_cost = avg_costs[min_index];
if (min_total_cost < CURVE_MIN_TOTAL_COST && min_avg_cost < CURVE_MIN_AVG_COST){
// return index with best placement (least curvature)
return total_costs.indexOf(min_total_cost);
}
else {
// if tolerances aren't satisfied, throw away tile
return -1;
}
}
// Scale the line by a scale factor (used for computing the angles and offsets at fractional zoom levels)
// Return the new line positions and their lengths
static scaleLine(scale, line){
var new_line = [line[0]];
var line_lengths = [];
line.forEach((pt, i) => {
if (i === line.length - 1) {
return;
}
var v = Vector.sub(line[i+1], line[i]);
var delta = Vector.mult(v, 1 + scale);
new_line.push(Vector.add(new_line[i], delta));
line_lengths.push(Vector.length(delta));
});
return [new_line, line_lengths];
}
// Place a label at a given line index
static placeAtIndex(anchor_index, line, line_lengths, label_lengths){
let anchor = line[anchor_index];
// Use flat coordinates. Get nearest line vertex index, and offset from the vertex for all labels.
let [indices, relative_offsets] = LabelLineCurved.getIndicesAndOffsets(anchor_index, line_lengths, label_lengths);
// get 2D positions based on "flat" indices and offsets
let positions = LabelLineCurved.getPositionsFromIndicesAndOffsets(line, indices, relative_offsets);
// get 2d offsets, angles and pre_angles relative to anchor
let [offsets, angles, pre_angles] = LabelLineCurved.getAnglesFromIndicesAndOffsets(anchor, indices, line, positions);
return {positions, offsets, angles, pre_angles};
}
// Given label lengths to place along a line broken into several lengths, computer what indices and at which offsets
// the labels will appear on the line. Assume the line is straight, as it is not necessary to consider angles.
//
// Label lengths:
// |-----|----|-----|-----------------|-------------|
//
// Line Lengths;
// |---------|---------|-------------|------------|----------|-------|
//
// Result: indices: [0,0,1,1,3,4]
static getIndicesAndOffsets(line_index, line_lengths, label_lengths){
let num_labels = label_lengths.length;
let indices = [];
let offsets = [];
let label_index = 0;
let label_offset = 0;
let line_offset = 0;
// iterate along line
while (label_index < num_labels){
let label_length = label_lengths[label_index];
// iterate along labels within the line segment
while (label_index < num_labels && label_offset + 0.5 * label_length <= line_offset + line_lengths[line_index]){
let offset = label_offset - line_offset + 0.5 * label_length;
offsets.push(offset);
indices.push(line_index);
label_offset += label_length;
label_index++;
label_length = label_lengths[label_index];
}
line_offset += line_lengths[line_index];
line_index++;
}
return [indices, offsets];
}
// Given indices and 1D offsets on a line, compute their 2D positions
static getPositionsFromIndicesAndOffsets(line, indices, offsets){
let positions = [];
for (let i = 0; i < indices.length; i++){
let index = indices[i];
let offset = offsets[i];
let angle = getAngleForSegment(line[index], line[index + 1]);
let offset2d = Vector.rot([offset, 0], angle);
let position = Vector.add(line[index], offset2d);
positions.push(position);
}
return positions;
}
// Given indices and 1D offsets on a line, compute their angles and pre-angles from a reference anchor point
static getAnglesFromIndicesAndOffsets(anchor, indices, line, positions){
let angles = [];
let pre_angles = [];
let offsets = [];
for (let i = 0; i < positions.length; i++){
let position = positions[i];
let index = indices[i];
let offset = Vector.sub(position, anchor);
let offset_angle = -Vector.angle(offset);
let angle = getTextAngleForSegment(line[index], line[index + 1]);
let pre_angle = angle - offset_angle;
if (i > 0){
let prev_angle = angles[i - 1];
let prev_pre_angle = pre_angles[i - 1];
if (Math.abs(offset_angle - prev_angle) > Math.PI) {
offset_angle += (offset_angle > prev_angle) ? -2 * Math.PI : 2 * Math.PI;
}
if (Math.abs(prev_pre_angle - pre_angle) > Math.PI) {
pre_angle += (pre_angle > prev_pre_angle) ? -2 * Math.PI : 2 * Math.PI;
}
}
angles.push(offset_angle);
pre_angles.push(pre_angle);
offsets.push(offset);
}
return [offsets, angles, pre_angles];
}
}
// Fitness function (label length / line length)
function calcFitness(line_length, label_length) {
return label_length / line_length;
}
function getAngleForSegment(p, q){
let pq = Vector.sub(q,p);
return Vector.angle(pq);
}
function getTextAngleForSegment(pt1, pt2) {
return -getAngleForSegment(pt1, pt2);
}
function getLineLengths(line){
let lengths = [];
for (let i = 0; i < line.length - 1; i++){
let p = line[i];
let q = line[i+1];
let length = Math.hypot(p[0] - q[0], p[1] - q[1]);
lengths.push(length);
}
return lengths;
}
function getAbsAngleDiff(angle1, angle2){
let small, big;
if (angle1 > angle2){
small = angle2;
big = angle1;
}
else {
small = angle1;
big = angle2;
}
while (big - small > Math.PI){
small += 2 * Math.PI;
}
return Math.abs(big - small);
}
| tangrams/tangram | src/labels/label_line.js | JavaScript | mit | 28,485 |
var express = require('express');
var router = express.Router();
router.get('/', function(req,res){
//get data from JSON file
var data = req.app.get('appData');
var pagePhotos = [];
var pageSpeakers = data.speakers;
data.speakers.forEach(function(item){
pagePhotos = pagePhotos.concat(item.artwork);
});
res.render('index', {
pageTitle: 'Home',
artwork: pagePhotos,
speakers: pageSpeakers,
pageID: 'home'
});
});
module.exports = router;
| neep305/jtown | app/routes/index.js | JavaScript | mit | 479 |
'use strict';
/**
*Module dependies
**/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Question Schema
**/
var QuestionSchema = new Schema({
created: {
type: String,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Question', QuestionSchema); | dtytomi/NaijaMusic | app/models/question.server.model.js | JavaScript | mit | 460 |
import * as route from './faq.route';
import './faq.scss';
const pageModule = angular.module('faqPage', [
'ui.router',
'ngScrollSpy'
]);
pageModule.config(route);
export default pageModule;
| secretgspot/sanjosepintor | src/app/pages/faq/faq.module.js | JavaScript | mit | 197 |
import { createStore,compose,applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import { routerMiddleware } from 'react-router-redux'
import {persistState} from 'redux-devtools'
import createLogger from 'redux-logger'
import {Iterable} from 'immutable'
import promiseMiddleware from '../api/promiseMiddleware'
import DevTools from '../components/DevTools'
import rootReducer from '../reducers'
export default function configureStore(initialState, history) {
const stateTransformer = (state) => {
let newSate = {}
Object.keys(state).forEach(x=>{
if(Iterable.isIterable(state[x])){
newSate[x] = state[x].toJS()
}else{
newSate[x] = state[x]
}
})
return newSate
}
let middleware = [ thunkMiddleware, promiseMiddleware, routerMiddleware(history) ]
let finalCreateStore
if (__DEVCLIENT__) {
if(__DEVLOGGER__){
middleware.push(createLogger({stateTransformer}))
}
finalCreateStore = compose(
applyMiddleware(...middleware),
window.devToolsExtension ? window.devToolsExtension() : __DEVTOOLS__?DevTools.instrument():f => f,
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
)
} else {
finalCreateStore = compose(applyMiddleware(...middleware))
}
const store = finalCreateStore(createStore)(rootReducer, initialState)
if (module.hot) {
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers')
store.replaceReducer(nextReducer)
})
}
return store
}
| icezeros/ice-react | src/store/configureStore.js | JavaScript | mit | 1,547 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
/* eslint-disable react-internal/warning-and-invariant-args */
'use strict';
import type {
ReactNativeBaseComponentViewConfig,
ViewConfigGetter,
} from './ReactNativeTypes';
const invariant = require('invariant');
// Event configs
const customBubblingEventTypes = {};
const customDirectEventTypes = {};
exports.customBubblingEventTypes = customBubblingEventTypes;
exports.customDirectEventTypes = customDirectEventTypes;
const viewConfigCallbacks = new Map();
const viewConfigs = new Map();
function processEventTypes(
viewConfig: ReactNativeBaseComponentViewConfig<>,
): void {
const {bubblingEventTypes, directEventTypes} = viewConfig;
if (__DEV__) {
if (bubblingEventTypes != null && directEventTypes != null) {
for (const topLevelType in directEventTypes) {
invariant(
bubblingEventTypes[topLevelType] == null,
'Event cannot be both direct and bubbling: %s',
topLevelType,
);
}
}
}
if (bubblingEventTypes != null) {
for (const topLevelType in bubblingEventTypes) {
if (customBubblingEventTypes[topLevelType] == null) {
customBubblingEventTypes[topLevelType] =
bubblingEventTypes[topLevelType];
}
}
}
if (directEventTypes != null) {
for (const topLevelType in directEventTypes) {
if (customDirectEventTypes[topLevelType] == null) {
customDirectEventTypes[topLevelType] = directEventTypes[topLevelType];
}
}
}
}
/**
* Registers a native view/component by name.
* A callback is provided to load the view config from UIManager.
* The callback is deferred until the view is actually rendered.
*/
exports.register = function(name: string, callback: ViewConfigGetter): string {
invariant(
!viewConfigCallbacks.has(name),
'Tried to register two views with the same name %s',
name,
);
viewConfigCallbacks.set(name, callback);
return name;
};
/**
* Retrieves a config for the specified view.
* If this is the first time the view has been used,
* This configuration will be lazy-loaded from UIManager.
*/
exports.get = function(name: string): ReactNativeBaseComponentViewConfig<> {
let viewConfig;
if (!viewConfigs.has(name)) {
const callback = viewConfigCallbacks.get(name);
if (typeof callback !== 'function') {
invariant(
false,
'View config not found for name %s.%s',
name,
typeof name[0] === 'string' && /[a-z]/.test(name[0])
? ' Make sure to start component names with a capital letter.'
: '',
);
}
viewConfigCallbacks.set(name, null);
viewConfig = callback();
processEventTypes(viewConfig);
viewConfigs.set(name, viewConfig);
} else {
viewConfig = viewConfigs.get(name);
}
invariant(viewConfig, 'View config not found for name %s', name);
return viewConfig;
};
| yiminghe/react | scripts/rollup/shims/react-native/ReactNativeViewConfigRegistry.js | JavaScript | mit | 3,087 |
$(document).ready(function() {
var addEditor, changePosition, commenting, moderate, refreshLineno, reorderPages, setLineno, showStar, stars, voting;
commenting = false;
$("#form_comment").submit(function() {
var button, form, loader, values;
if (!commenting) {
commenting = true;
button = $("#form_comment button");
loader = $("#form_comment .ajax-loader");
button.addClass("disabled");
values = {};
form = $(this);
$.each(form.serializeArray(), function(i, field) {
return values[field.name] = field.value;
});
loader.css("visibility", "visible");
$.post(form.attr("action"), values, function(html) {
commenting = false;
button.removeClass("disabled");
$("#comment_message").val("");
loader.css("visibility", "hidden");
return form.before(html);
});
}
return false;
});
showStar = function() {
return $(".meta .icon-star").css({
display: "inline-block"
});
};
stars = $(".star-rating li a");
if (stars.length) {
voting = false;
$(".star-rating li a").click(function() {
var form, loader, values;
if (!voting) {
voting = true;
loader = $(".meta .ajax-loader");
form = $("#form_vote");
values = {};
loader.css("visibility", "visible");
$.each(form.serializeArray(), function(i, field) {
return values[field.name] = field.value;
});
values["vote[value]"] = $(this).html();
$.post(form.attr("action"), values, function(rating) {
voting = false;
loader.css("visibility", "hidden");
$(".rating-value").html(rating);
$(".meta .star-rating").hide();
return showStar();
});
}
return false;
});
} else {
showStar();
}
setLineno = function(page, lineno) {
var buttons, title;
page.attr("data-page", lineno);
buttons = $("button", page);
if (lineno <= 2) {
title = lineno === 1 ? "Write summary" : "Create Story";
buttons.hide();
} else {
title = "Create story " + (lineno - 1);
buttons.show();
}
$(".page-number", page).html(title);
return $($("input", page)[0]).val(lineno);
};
refreshLineno = function() {
return $("#story_Pages li").each(function(i, li) {
return setLineno($(this), i + 1);
});
};
reorderPages = function() {
var cont, newOrder, page, _i, _len, _results;
newOrder = [];
$("#story_Pages li").each(function(i, li) {
return newOrder[parseInt($(li).attr("data-page"))] = li;
});
cont = $("#story_Pages");
_results = [];
for (_i = 0, _len = newOrder.length; _i < _len; _i++) {
page = newOrder[_i];
_results.push(cont.append(page));
}
return _results;
};
refreshLineno();
$(document).delegate(".story-page-header .page-number", "click", function() {
var pageData;
pageData = $(this).parent().siblings(".story-page-data");
if (pageData.is(":visible")) {
return pageData.slideUp();
} else {
return pageData.slideDown();
}
});
$(document).delegate(".story-page-header .page-delete", "click", function() {
$(this).parents("li").slideUp(function() {
$(this).remove();
return refreshLineno();
});
return false;
});
changePosition = function(page, delta) {
var curLineno, toLineno;
curLineno = parseInt(page.attr("data-page"));
toLineno = curLineno + delta;
if ((delta === -1 && curLineno === 1) || (delta === 1 && curLineno === page.siblings().length + 1)) {
return;
}
setLineno($("li[data-page=" + toLineno + "]"), curLineno);
setLineno(page, toLineno);
return reorderPages();
};
$(document).delegate(".story-page-header .page-up", "click", function() {
changePosition($(this).parents("li"), -1);
return false;
});
$(document).delegate(".story-page-header .page-down", "click", function() {
changePosition($(this).parents("li"), +1);
return false;
});
addEditor = function(id) {
var edEl, placeholder, textarea;
textarea = $("#" + id);
placeholder = textarea.attr("placeholder");
new nicEditor({
fullPanel: true
}).panelInstance(id);
if (placeholder) {
return edEl = textarea.siblings().children(".niceditor-elm").focus(function() {
var text;
text = edEl.html();
if (text === textarea.attr("placeholder")) {
return edEl.html("");
}
}).blur(function() {
return !edEl.html() && edEl.html(textarea.attr("placeholder"));
}).html(placeholder);
}
};
$(".add-page").click(function() {
var pages, placeholder;
placeholder = $($("#story_Pages textarea")[1]).attr("placeholder");
$($("#story_Pages textarea")[1]).attr("placeholder", "");
if ($($("#story_Pages .niceditor-elm")[1]).html() === placeholder) {
$($("#story_Pages .niceditor-elm")[1]).html("");
}
pages = $("#story_Pages");
pages.append(pages.attr("data-prototype").split("$$name$$").join(pages.children().length));
addEditor("story_Pages_" + (pages.children().length - 1) + "_body");
refreshLineno();
return false;
});
$(".add-video").click(function() {
$("#video-upload").modal();
return false;
});
$("#video-upload button").click(function() {
var bar, progress, progressHelp;
progress = $("#video-upload .progress").css({
display: "block"
});
progressHelp = $("#video-upload .progress-help").css({
display: "block"
});
bar = progress.children().css({
width: "0%"
});
progress.removeClass("progress-info").addClass("progress-success");
progressHelp.html("Uploading...");
$("#video-upload form").ajaxSubmit({
uploadProgress: function(e, position, total, percent) {
if (percent > 98) {
percent = 100;
progressHelp.html("Sending to youtube...");
progress.removeClass("progress-success").addClass("progress-info");
}
return bar.css({
width: percent + "%"
});
},
success: function(data) {
progress.css({
display: "none"
});
progressHelp.css({
display: "none"
});
try {
data = $.parseJSON(data);
$(".videos").append('<li data-player="' + data.player + '"><a href="' + data.url + '"><img src="' + data.thumbnail + '"/></a></li>');
return $("#video-upload").modal("hide");
} catch (error) {
alert("Upload error!");
console.log(data);
return console.log(error);
}
}
});
return false;
});
$("#story_Pages textarea").each(function() {
return addEditor(this.id);
});
$(".publish-request").click(function() {
var button;
button = $(this);
button.addClass("disabled").attr("disabled", "disabled");
button.hide().siblings().removeClass("status-blocked").removeClass("status-unpublished").addClass("status-moderated").html("Moderated");
$.post(button.attr("data-url"), function(ok) {
if (ok) {
return console.log(ok);
}
});
return false;
});
$(".teller-request").click(function() {
var button;
button = $(this);
button.addClass("disabled").attr("disabled", "disabled");
button.hide().siblings().removeClass("hide");
$.post(button.attr("data-url"), function(ok) {
if (ok) {
return console.log(ok);
}
});
return false;
});
moderate = function(button, status) {
button.addClass("disabled").attr("disabled", "disabled");
return $.post(button.attr("data-url"), function(ok) {
if (ok) {
console.log(ok);
button.parents("tr").remove();
}
return false;
});
};
$("button.block").click(function() {
return moderate($(this), 4);
});
$("button.publish").click(function() {
return moderate($(this), 2);
});
$("button.promote").click(function() {
return moderate($(this), 1);
});
$("button.decline").click(function() {
return moderate($(this), 0);
});
$("#myCarousel").carousel({
interval: $(".tags-cloud").length > 0 ? 10000 : 32600000
}).carousel("next");
// $("#story_date").datepicker({
// changeMonth: true,
// changeYear: true
// });
return true
});
| limitium/pds | web/js/pds.js | JavaScript | mit | 8,372 |
{
render(component, write, context, done);
}
| stas-vilchik/bdd-ml | data/11630.js | JavaScript | mit | 47 |
function getMovie() {
var url = '';
var searchType = getSearchType();
if (searchType == 'name') {
url = getMovieByNameURL(document.getElementById('titleText').value, document.getElementById('yearText').value);
}
else if (searchType == 'id') {
url = getMovieByIdURL(document.getElementById('movieIdText').value);
}
search(url, searchType);
}
function getSearchType() {
var e = document.getElementById('searchTypeList');
return e.options[e.selectedIndex].value;
}
function search(url, searchType) {
console.log('Search type is by:', searchType);
document.getElementById("searchResults").style.display = 'none';
clearFields();
setSearchButton(true, searchType);
getJSON(url,
function(err, data) {
if (err !== null) {
document.getElementById('descriptionText').value = err;
}
else {
console.log('Found ' + data.length + ' movies matching the search criteria!');
var movie = searchType == 'name' ? data[0] : data;
console.log(movie);
if (movie) {
setFields(movie);
}
else {
document.getElementById('descriptionText').value = 'Movie not found!';
}
if (searchType == 'name') {
createFullList(data);
}
setSearchButton(false, searchType);
}
document.getElementById('searchResults').style.display = 'block';
});
}
function clearFields() {
document.getElementById('movieTitle').innerHTML = '';
document.getElementById('moviesFound').innerHTML = '';
document.getElementById('movieLink').innerHTML = '';
document.getElementById('descriptionText').value = '';
document.getElementById('posterImg').src = '';
var ul = document.getElementById('fullList');
while (ul.firstChild) ul.removeChild(ul.firstChild);
}
function setFields(movie) {
document.getElementById('movieTitle').innerHTML = movie.title + '(' + movie.year + ')';
document.getElementById('movieLink').href = movie.url.url;
document.getElementById('movieLink').innerHTML = movie.imdb_id;
document.getElementById('descriptionText').value = movie.description;
document.getElementById('posterImg').src = movie.poster.thumb;
}
function setSearchButton(wait, searchType) {
var buttonName = searchType == 'name' ? 'searchButton' : 'searchIdButton';
document.getElementById(buttonName).disabled = wait;
document.getElementById(buttonName).value = wait ? 'Wait...' : 'Search';
}
function createFullList(movies) {
document.getElementById('moviesFound').innerHTML = movies.length > 0 ? 'More movies found with this search criteria: ' : '';
var ul = document.getElementById('fullList');
for (var i = 0, l = movies.length; i < l; ++i) {
var li = document.createElement('li');
var nodeText = movies[i].title + ' (' + movies[i].year + ') ';
nodeText = nodeText + ' - ' + movies[i].url.url;
li.appendChild(document.createTextNode(nodeText));
ul.appendChild(li);
}
}
function selectSearchType() {
var searchType = getSearchType();
if (searchType == 'name') {
document.getElementById('searchByName').style.display = 'block';
document.getElementById('searchById').style.display = 'none';
document.getElementById("searchResults").style.display = 'none';
}
else if (searchType == 'id') {
document.getElementById('searchByName').style.display = 'none';
document.getElementById('searchById').style.display = 'block';
document.getElementById("searchResults").style.display = 'none';
}
}
| RodolfoDiaz/codelibrary | web/js/movies/ui.js | JavaScript | mit | 3,785 |
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const gemsPerMinute = 0.1;
const ChestSchema = new Schema({
name: {
type: String,
enum: [
'Wooden Chest',
'Silver Chest',
'Golden Chest',
'Crown Chest',
'Magical Chest',
'Giant Chest',
'Super Magical Chest',
'Epic Chest',
'Legendary Chest',
'Season Reward Chest',
'Lightning Chest',
'Fortune Chest',
"King's Chest",
"Legendary King's Chest",
],
require: true,
},
idName: {
type: String,
unique: true,
require: true,
},
arena: {
type: Number,
default: 0,
require: true,
},
league: {
type: Number,
},
description: {
type: String,
},
information: {
type: String,
},
numberOfChoices: {
type: Number,
},
cards: {
number: { type: Number, require: true },
minRare: { type: Number, default: 0, require: true },
minEpic: { type: Number, default: 0, require: true },
minLegendary: { type: Number, default: 0, require: true },
},
gold: {
min: { type: Number, require: true },
max: { type: Number, require: true },
},
gemCost: {
type: Number,
default: 0,
require: true,
},
unlock: {
time: { type: Number, require: true },
gemCost: { type: Number },
},
order: {
type: Number,
require: true,
},
});
ChestSchema.index({ name: 1, arena: 1, league: 1 }, { unique: true });
// @TODO Change function to arrow function.
ChestSchema.pre('save', function preSave(next) {
if (!this.unlock.gemCost) {
this.unlock.gemCost = this.unlock.time * gemsPerMinute;
}
if (!this.idName) {
this.idName = JSON.parse(JSON.stringify(this.name.toLowerCase()));
this.idName = this.idName.replace(/ /g, '-');
this.idName = this.idName.replace(/\./g, '');
this.idName = this.idName.concat('-', this.arena);
if (this.league) {
this.idName = this.idName.concat('-', this.league);
}
}
next();
});
module.exports = mongoose.model('Chest', ChestSchema);
| martincarrera/clash-royale-api | src/schemas/chest-schema.js | JavaScript | mit | 2,077 |
import createReactClass from 'create-react-class';
import React from 'react';
import ReactDOM from 'react-dom';
import { connect, Provider } from 'react-redux';
import { applyMiddleware, createStore } from 'redux';
import createSagaMiddleware from 'redux-saga';
import { call, fork, put, select, spawn, take, takeEvery, takeLatest } from 'redux-saga/effects';
//============
// Reducer
//============
const defaultState = {
color0: 'yellow',
color1: 'red',
color2: 'blue',
count: 0,
};
const reducer = (state = defaultState, action) => {
console.info(action.type);
switch (action.type) {
case 'SET_COLOR':
let colorPos = 'color' + action.payload.pos;
let newState = { ...state };
newState[colorPos] = action.payload.color;
return newState;
case 'BUTTON_COUNT':
return {
...state,
count: state.count + 1
};
default:
return { ...state };
}
};
//============
// Actions
//============
function setColor(color, pos) {
return {
type: 'SET_COLOR',
payload: { color, pos }
};
}
function buttonCount(pos) {
return {
type: 'BUTTON_COUNT',
payload: pos
}
}
function cancel() {
return {
type: 'CANCEL',
payload: ''
}
}
//============
// APIs
//============
const colors = ['red', 'blue', 'green', 'orange', 'gray', 'black', 'coffee', 'purple', 'pink'];
function getColorApi() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let randomColor = colors[Math.floor(Math.random() * colors.length)];
resolve(randomColor);
}, 1500);
});
}
//================
// Saga (Monitor)
//================
function* rootFlow(){
// yield takeEvery('BUTTON_COUNT', colorFlow);
yield takeLatest('BUTTON_COUNT', colorFlow);
/*
const { response, cancel } = yield race({
response: takeEvery('BUTTON_COUNT', colorFlow),
cancel: take('CANCEL')
});
console.log('如果response 为 undefined 即表示被取消', response)
*/
console.log('流程完成')
}
function* colorFlow(action) {
let pos = action.payload;
console.log("pos=", pos);
let lastColor = yield select(state => state['color' + pos]);
console.log(pos, '当前颜色是', lastColor);
let color = yield getColorApi();
console.log(pos, '修改后的颜色是', color);
yield put(setColor(color, pos));
}
//============
// Components
//============
const mapStateToProps = (state = {}) => {
return { ...state };
};
let Container = connect(mapStateToProps)(createReactClass({
render: function () {
const { count, dispatch, color0, color1, color2 } = this.props;
return (
<div>
<div style={{backgroundColor:color0, width:'50px', height:'50px'}}>
</div>
<button onClick={()=>dispatch(buttonCount(0))}>按钮0</button>
<div style={{backgroundColor:color1, width:'50px', height:'50px'}}>
</div>
<button onClick={()=>dispatch(buttonCount(1))}>按钮1</button>
<div style={{backgroundColor:color2, width:'50px', height:'50px'}}>
</div>
<button onClick={()=>dispatch(buttonCount(2))}>按钮2</button>
<button onClick={()=>dispatch(cancel())}>取消</button>
<h2>{count}</h2>
</div>
);
}
}));
//============
// Store
//============
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
);
sagaMiddleware.run(rootFlow);
//============
// Output
//============
ReactDOM.render(
<Provider store={store}>
<Container />
</Provider>,
document.getElementById('root')
); | wefine/reactjs-guide | redux-saga/redux-saga-starter/src/index.js | JavaScript | mit | 3,887 |
import destroyApp from '../../helpers/destroy-app';
import {
module,
test
} from 'qunit';
import startApp from 'ilios/tests/helpers/start-app';
import setupAuthentication from 'ilios/tests/helpers/setup-authentication';
import Ember from 'ember';
var application;
var fixtures = {};
var url = '/courses/1?details=true&courseObjectiveDetails=true';
module('Acceptance: Course - Objective Create', {
beforeEach: function() {
application = startApp();
setupAuthentication(application);
server.create('school');
server.create('academicYear', {id: 2013});
server.createList('program', 2);
server.createList('programYear', 2);
server.createList('cohort', 2);
fixtures.objective = server.create('objective', {
courses: [1],
});
fixtures.course = server.create('course', {
year: 2013,
school: 1,
objectives: [1]
});
},
afterEach: function() {
destroyApp(application);
}
});
test('save new objective', function(assert) {
assert.expect(8);
visit(url);
var newObjectiveTitle = 'Test junk 123';
andThen(function() {
let objectiveRows = find('.detail-objectives .course-objective-list tbody tr');
assert.equal(objectiveRows.length, fixtures.course.objectives.length);
click('.detail-objectives .detail-objectives-actions button');
//wait for the editor to load
Ember.run.later(()=>{
find('.detail-objectives .newobjective .froalaEditor').froalaEditor('html.set', newObjectiveTitle);
find('.detail-objectives .newobjective .froalaEditor').froalaEditor('events.trigger', 'contentChanged');
Ember.run.later(()=>{
click('.detail-objectives .newobjective button.done');
andThen(function(){
let objectiveRows = find('.detail-objectives .course-objective-list tbody tr');
assert.equal(objectiveRows.length, fixtures.course.objectives.length + 1);
let tds = find('td', objectiveRows.eq(0));
assert.equal(getElementText(tds.eq(0)), getText(fixtures.objective.title));
assert.equal(getElementText(tds.eq(1)), getText('Add New'));
assert.equal(getElementText(tds.eq(2)), getText('Add New'));
tds = find('td', objectiveRows.eq(1));
assert.equal(getElementText(tds.eq(0)), getText(newObjectiveTitle));
assert.equal(getElementText(tds.eq(1)), getText('Add New'));
assert.equal(getElementText(tds.eq(2)), getText('Add New'));
});
}, 100);
}, 100);
});
});
test('cancel new objective', function(assert) {
assert.expect(5);
visit(url);
andThen(function() {
let objectiveRows = find('.detail-objectives .course-objective-list tbody tr');
assert.equal(objectiveRows.length, fixtures.course.objectives.length);
click('.detail-objectives .detail-objectives-actions button');
click('.detail-objectives .newobjective button.cancel');
});
andThen(function(){
let objectiveRows = find('.detail-objectives .course-objective-list tbody tr');
assert.equal(objectiveRows.length, fixtures.course.objectives.length);
let tds = find('td', objectiveRows.eq(0));
assert.equal(getElementText(tds.eq(0)), getText(fixtures.objective.title));
assert.equal(getElementText(tds.eq(1)), getText('Add New'));
assert.equal(getElementText(tds.eq(2)), getText('Add New'));
});
});
test('empty objective title can not be created', function(assert) {
assert.expect(3);
const container = '.detail-objectives:eq(0)';
const expandNewObjective = `${container} .detail-objectives-actions button`;
const newObjective = `${container} .newobjective`;
const editor = `${newObjective} .froalaEditor`;
const save = `${newObjective} .done`;
const errorMessage = `${newObjective} .validation-error-message`;
visit(url);
click(expandNewObjective);
andThen(function() {
//wait for the editor to load
Ember.run.later(()=>{
let editorContents = find(editor).data('froala.editor').$el.text();
assert.equal(getText(editorContents), '');
find(editor).froalaEditor('html.set', '<p> </p><div></div><span> </span>');
find(editor).froalaEditor('events.trigger', 'contentChanged');
Ember.run.later(()=>{
assert.equal(getElementText(errorMessage), getText('This field cannot be blank'));
assert.ok(find(save).is(':disabled'));
}, 100);
}, 100);
});
});
| stopfstedt/frontend | tests/acceptance/course/objectivecreate-test.js | JavaScript | mit | 4,383 |
/*
* jQuery Joyride Plugin 1.0.5
* www.ZURB.com/playground
* Copyright 2011, ZURB
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
$.fn.joyride = function(options) {
// +++++++++++++++++++
// Defaults
// +++++++++++++++++++
var settings = {
'tipLocation': 'bottom', // 'top' or 'bottom' in relation to parent
'scrollSpeed': 300, // Page scrolling speed in milliseconds
'timer': 0, // 0 = no timer, all other numbers = timer in milliseconds
'startTimerOnClick': false, // true or false - true requires clicking the first button start the timer
'nextButton': true, // true or false to control whether a next button is used
'tipAnimation': 'pop', // 'pop' or 'fade' in each tip
'tipAnimationFadeSpeed': 300, // when tipAnimation = 'fade' this is speed in milliseconds for the transition
'cookieMonster': false, // true or false to control whether cookies are used
'cookieName': 'JoyRide', // Name the cookie you'll use
'cookieDomain': false, // Will this cookie be attached to a domain, ie. '.notableapp.com'
'tipContainer': 'body', // Where will the tip be attached if not inline
'inline': false, // true or false, if true the tip will be attached after the element
'tipContent': '#joyRideTipContent', // What is the ID of the <ol> you put the content in
'postRideCallback': $.noop, // A method to call once the tour closes (canceled or complete)
'postStepCallback': $.noop // A method to call after each step
};
var options = $.extend(settings, options);
return this.each(function() {
if ($(options.tipContent).length === 0) return;
$(options.tipContent).hide();
var bodyOffset = $(options.tipContainer).children('*').first().position(),
tipContent = $(options.tipContent + ' li'),
count = skipCount = 0,
prevCount = -1,
end = false,
timerIndicatorInstance,
timerIndicatorTemplate = '<div class="joyride-timer-indicator-wrap"><span class="joyride-timer-indicator"></span></div>';
var tipTemplate = function(tipClass, index, buttonText, self) {
return '<div class="joyride-tip-guide ' +
tipClass + '" id="joyRidePopup' + index + '"><span class="joyride-nub"></span><div class="joyride-content-wrapper">' +
$(self).html() + buttonText + '<a href="#close" class="joyride-close-tip">X</a>' +
timerIndicatorInstance + '</div></div>';
};
var tipLayout = function(tipClass, index, buttonText, self) {
if (index == 0 && settings.startTimerOnClick && settings.timer > 0 || settings.timer == 0) {
timerIndicatorInstance = '';
} else {
timerIndicatorInstance = timerIndicatorTemplate;
}
if (!tipClass) {
tipClass = '';
}
if (buttonText) {
buttonText = '<a href="#" class="joyride-next-tip small nice radius yellow button">' + buttonText + '</a>'
} else {
buttonText = '';
}
if (settings.inline) {
$(tipTemplate(tipClass, index, buttonText, self)).insertAfter('#' + $(self).data('id'));
} else {
$(options.tipContainer).append(tipTemplate(tipClass, index, buttonText, self));
}
};
if(!settings.cookieMonster || !$.cookie(settings.cookieName)) {
tipContent.each(function(index) {
var buttonText = $(this).data('text'),
tipClass = $(this).attr('class'),
self = this;
if (settings.nextButton && !buttonText) {
buttonText = 'Next';
}
if (settings.nextButton || !settings.nextButton && settings.startTimerOnClick) {
if ($(this).attr('class')) {
tipLayout(tipClass, index, buttonText, self);
} else {
tipLayout(false, index, buttonText, self);
}
} else if (!settings.nextButton) {
if ($(this).attr('class')) {
tipLayout(tipClass, index, '', self);
} else {
tipLayout(false, index, '', self);
}
}
$('#joyRidePopup' + index).hide();
});
}
showNextTip = function() {
if (end) {
return;
}
var parentElementID = $(tipContent[count]).data('id'),
parentElement = $('#' + parentElementID),
opt = {};
// Parse the options string
$.each(($(tipContent[count]).data('options') || ':').split(';'),
function (i, s) {
var p = s.split(':');
if (p.length == 2) {
opt[$.trim(p[0])] = $.trim(p[1]);
}
}
);
var tipSettings = $.extend({}, settings, opt);
while (parentElement.offset() === null) {
count++;
skipCount++;
if ((tipContent.length - 1) > prevCount) {
prevCount++;
}
parentElementID = $(tipContent[count]).data('id'),
parentElement = $('#' + parentElementID);
if ($(tipContent).length < count) {
break;
}
}
var windowHalf = Math.ceil($(window).height() / 2),
currentTip = $('#joyRidePopup' + count),
currentTipPosition = parentElement.offset(),
currentParentHeight = parentElement.outerHeight(),
currentTipHeight = currentTip.outerHeight(),
nubHeight = Math.ceil($('.joyride-nub').outerHeight() / 2),
tipOffset = 0;
if (currentTip.length === 0) {
return;
}
if (count < tipContent.length) {
if (settings.tipAnimation == "pop") {
$('.joyride-timer-indicator').width(0);
if (settings.timer > 0) {
currentTip.show().children('.joyride-timer-indicator-wrap')
.children('.joyride-timer-indicator')
.animate({width: $('.joyride-timer-indicator-wrap')
.width()}, settings.timer);
} else {
currentTip.show();
}
} else if (settings.tipAnimation == "fade") {
$('.joyride-timer-indicator').width(0);
if (settings.timer > 0) {
currentTip.fadeIn(settings.tipAnimationFadeSpeed)
.children('.joyride-timer-indicator-wrap')
.children('.joyride-timer-indicator')
.animate({width: $('.joyride-timer-indicator-wrap')
.width()}, settings.timer);
} else {
currentTip.fadeIn(settings.tipAnimationFadeSpeed);
}
}
// ++++++++++++++++++
// Tip Location
// ++++++++++++++++++
var nub = currentTip.children('.joyride-nub');
var left = currentTipPosition.left - bodyOffset.left;
nub.removeClass('bottom')
.removeClass('top')
.removeClass('right');
// Update the tip position so it is in the same position
// but the nub is right aligned.
if ($(window).scrollLeft() + $(window).width() < left + currentTip.width()) {
left -= (currentTip.width() - nub.offset().left * 2);
nub.addClass("right");
}
if (Modernizr.mq('only screen and (max-width: 769px)')) {
//If the user is "mobile"
if (tipSettings.tipLocation.indexOf("top") != -1 ) {
if (currentTipHeight >= currentTipPosition.top) {
currentTip.offset({top: ((currentTipPosition.top + currentParentHeight + nubHeight) - bodyOffset.top)});
nub.addClass('top').css({ left: left });
} else {
currentTip.offset({top: ((currentTipPosition.top) - (currentTipHeight + bodyOffset.top + nubHeight))});
nub.addClass('bottom').css({ left: left });
}
} else {
// Default is bottom alignment.
currentTip.offset({top: (currentTipPosition.top + currentParentHeight + nubHeight)});
nub.addClass('top').css({ left: left });
}
} else {
if (tipSettings.tipLocation == "top") {
if (currentTipHeight >= currentTipPosition.top) {
currentTip.offset({
top: ((currentTipPosition.top + currentParentHeight + nubHeight) - bodyOffset.top),
left: left
});
nub.addClass('top');
} else {
currentTip.offset({
top: ((currentTipPosition.top) - (currentTipHeight + bodyOffset.top + nubHeight)),
left: left
});
nub.addClass('bottom');
}
} else {
// Default is bottom alignment.
currentTip.offset({
top: (currentTipPosition.top + currentParentHeight + nubHeight),
left: left
});
nub.addClass('top');
}
}
// Default is left alignment.
if (tipSettings.tipLocation.indexOf("right") != -1) {
// Here we ignore the viewport alignment.
currentTip.offset({left: (currentTipPosition.left - bodyOffset.left - currentTip.width() + parentElement.width())});
currentTip.children('.joyride-nub').addClass('right');
};
// Animate Scrolling when tip is off screen
tipOffset = Math.ceil(currentTip.offset().top - windowHalf);
$("html, body").animate({
scrollTop: tipOffset
}, settings.scrollSpeed);
if (count > 0) {
if (skipCount > 0) {
var hideCount = prevCount - skipCount;
skipCount = 0;
} else {
var hideCount = prevCount;
}
if (settings.tipAnimation == "pop") {
$('#joyRidePopup' + hideCount).hide();
} else if (settings.tipAnimation == "fade") {
$('#joyRidePopup' + hideCount).fadeOut(settings.tipAnimationFadeSpeed);
}
}
// Hide the last tip when clicked
} else if ((tipContent.length - 1) < count) {
var hideCnt;
if (skipCount > 0) {
hideCount = prevCount - skipCount;
skipCount = 0;
} else {
hideCount = prevCount;
}
if (settings.cookieMonster == true) {
$.cookie(settings.cookieName, 'ridden', { expires: 365, domain: settings.cookieDomain });
}
if (settings.tipAnimation == "pop") {
$('#joyRidePopup' + hideCount).fadeTo(0, 0);
} else if (settings.tipAnimation == "fade") {
$('#joyRidePopup' + hideCount).fadeTo(settings.tipAnimationFadeSpeed, 0);
}
}
count++;
if (prevCount < 0) {
prevCount = 0;
} else if ((tipContent.length - 1) > prevCount) {
prevCount++;
}
if (settings.postStepCallback != $.noop) {
var parentElementID = $(tipContent[prevCount]).data('id');
var parentElement = $('#' + parentElementID);
var previousIndex = (prevCount < tipContent.length ) ? (prevCount - 1 ) : (tipContent.length - 1) ;
if (prevCount === 0){
previousIndex = (tipContent.length - 1) ;
}
var previousElementID = $(tipContent[previousIndex]).data('id');
var previousElement = $('#' + previousElementID);
settings.postStepCallback(prevCount, parentElement, previousElement);
}
};
if (!settings.inline || !settings.cookieMonster || !$.cookie(settings.cookieName)) {
$(window).resize(function () {
var parentElementID = $(tipContent[prevCount]).data('id'),
currentTipPosition = $('#' + parentElementID).offset(),
currentParentHeight = $('#' + parentElementID).outerHeight(),
currentTipHeight = $('#joyRidePopup' + prevCount).outerHeight(),
nubHeight = Math.ceil($('.joyride-nub').outerHeight() / 2);
if (Modernizr.mq('only screen and (max-width: 769px)')) {
if (settings.tipLocation == "bottom") {
$('#joyRidePopup' + prevCount).offset({
top: (currentTipPosition.top + currentParentHeight + nubHeight),
left: 0
});
$('#joyRidePopup' + prevCount).children('.joyride-nub').addClass('top').removeClass('bottom').css({ left: (currentTipPosition.left - bodyOffset.left) });
} else if (settings.tipLocation == "top") {
if (currentTipPosition.top <= currentTipHeight) {
$('#joyRidePopup' + prevCount).offset({
top: (currentTipPosition.top + nubHeight + currentParentHeight),
left: 0
});
$('#joyRidePopup' + prevCount).children('.joyride-nub').addClass('top').removeClass('bottom').css({ left: (currentTipPosition.left - bodyOffset.left) });
} else {
$('#joyRidePopup' + prevCount).offset({
top: ((currentTipPosition.top) - (currentTipHeight + nubHeight)),
left: 0
});
$('#joyRidePopup' + prevCount).children('.joyride-nub').addClass('bottom').removeClass('top').css({ left: (currentTipPosition.left - bodyOffset.left) });
}
}
} else {
if (settings.tipLocation == "bottom") {
$('#joyRidePopup' + prevCount).offset({
top: (currentTipPosition.top + currentParentHeight + nubHeight),
left: currentTipPosition.left
});
$('#joyRidePopup' + prevCount).children('.joyride-nub').addClass('top').removeClass('bottom').css({ left: '' });
} else if (settings.tipLocation == "top") {
if (currentTipPosition.top <= currentTipHeight) {
$('#joyRidePopup' + prevCount).offset({
top: (currentTipPosition.top + nubHeight + currentParentHeight),
left: currentTipPosition.left
});
$('#joyRidePopup' + prevCount).children('.joyride-nub').addClass('top').removeClass('bottom').css({ left: '' });
}
else {
$('#joyRidePopup' + prevCount).offset({
top: ((currentTipPosition.top) - (currentTipHeight + nubHeight)),
left: currentTipPosition.left
});
$('#joyRidePopup' + prevCount).children('.joyride-nub').addClass('bottom').removeClass('top').css({ left: '' });
}
}
}
});
}
// +++++++++++++++
// Timer
// +++++++++++++++
var interval_id = null,
showTimerState = false;
if (!settings.startTimerOnClick && settings.timer > 0){
showNextTip();
interval_id = setInterval(function() {showNextTip()}, settings.timer);
} else {
showNextTip();
}
var endTip = function(e, interval_id, cookie, self) {
e.preventDefault();
clearInterval(interval_id);
if (cookie) {
$.cookie(settings.cookieName, 'ridden', { expires: 365, domain: settings.cookieDomain });
}
$(self).parent().parent().hide();
if (settings.postRideCallback != $.noop) {
var parentElementID = $(tipContent[prevCount]).data('id');
var $current = $('#' + parentElementID);
settings.postRideCallback($current);
count = 0;
prevCount = -1;
end = true;
}
};
$('.joyride-close-tip').click(function(e) {
endTip(e, interval_id, settings.cookieMonster, this);
});
// When the next button is clicked, show the next tip, only when cookie isn't present
$('.joyride-next-tip').click(function(e) {
e.preventDefault();
if (count >= tipContent.length) {
endTip(e, interval_id, settings.cookieMonster, this);
}
if (settings.timer > 0 && settings.startTimerOnClick) {
showNextTip();
clearInterval(interval_id);
interval_id = setInterval(function() {showNextTip()}, settings.timer);
} else if (settings.timer > 0 && !settings.startTimerOnClick){
clearInterval(interval_id);
interval_id = setInterval(function() {showNextTip()}, settings.timer);
} else {
showNextTip();
}
});
});
};
})(jQuery);
| houssemFat/MeeM-Dev | static/js/vender/guiders/jquery.joyride-1.0.5.js | JavaScript | mit | 16,535 |
/* Copyright 2015, Yahoo Inc.
Copyrights licensed under the MIT License.
See the accompanying LICENSE file for terms. */
var React = require('react');
var ReactDOM = require('react-dom');
var Scroller = require('../../src/scroller');
var ScrollItem = require('../../src/scroll-item');
var TopBar = require('./top');
var BotBar = require('./bot');
var Lorem = require('../lorem');
var Hammer = require('hammerjs');
var ConsumptionMode = React.createClass({
render: function () {
return (
<div className="consumption">
<Scroller viewport scrollingX={false} scrollingY={true}
getContentSize={this.getContentSize} ref="scroller">
<ScrollItem ref="topbar" name="topbar" scrollHandler={consumptionBars}>
<TopBar />
</ScrollItem>
<ScrollItem name="content" scrollHandler={contentHandler}>
<div ref="swipeArea">
<Lorem />
</div>
</ScrollItem>
<ScrollItem name="botbar" scrollHandler={consumptionBars}>
<BotBar />
</ScrollItem>
</Scroller>
</div>
);
},
getContentSize: function (items, scroller) {
/*
This is a very generic contentSize implementation, accounting for all
items regardless of semantics of each item. It's not a coincidence that a
regular for loop is used. map/reduce/forEach creates functions in runtime.
If you scrape each piece of performance, you can probably run this example
on iPhone 3GS or older Androids.
*/
var height = 0, width = 0;
for (var item in items) {
height += items[item].rect.height;
width = Math.max(width, items[item].rect.width);
}
return {
height: height,
width: width,
};
},
componentDidMount: function() {
this.refs.scroller.consuming = true;
this.refs.scroller.origin = 0;
var hammer = (this.hammer = new Hammer(this.refs.swipeArea));
hammer.get('swipe').set({
direction: Hammer.DIRECTION_DOWN,
velocity: 0.3,
threshold: 7,
});
hammer.on('swipe', this.swipeDown);
},
componentWillUnmount: function() {
this.hammer.off('swipe');
},
swipeDown: function() {
var scroller = this.refs.scroller;
if (!scroller.consuming) {
scroller.consuming = true;
scroller.origin = scroller._scroller._scroller.getValues().top - this.refs.topbar.rect.height;
}
},
});
/*
Notice: It's a Scrollable best practice to use plain functions instead
of React bound methods. Read more about why on the minimal example.
*/
function consumptionBars(x, y, self, items, scroller) {
// All calculations are made for top handler, then inverted in the end
// if this call refers to the bottom handler
// If we are in the middle of the content and scrolled past the swipe origin
// keeps reseting origin until user scrolls down. Effectively this means the
// first time user scrolls down starts hiding the bars again.
if (y > 0 && y < scroller.origin && scroller.consuming) {
scroller.origin = y;
}
// if we are near the top, force topBar to show
if (y <= self.rect.height && !scroller.consuming) {
scroller.consuming = true;
scroller.origin = 0;
}
var pos;
if (scroller.consuming) {
pos = Math.min(scroller.origin - y, 0);
} else {
pos = -self.rect.height; // offscreen
}
// As the top bar moves offscreen, it should be locked offscreen
if (pos <= -self.rect.height) {
scroller.consuming = false;
}
// If this was called from botbar, make it work from bottom of the viewport.
if (self === items.botbar) {
pos = scroller.rect.height - self.rect.height - pos;
}
return {
y: pos,
zIndex: 5,
};
}
function contentHandler(x, y, self, items, scroller) {
return {
y: items.topbar.rect.bottom - y,
};
}
module.exports = ConsumptionMode;
| yahoo/scrollable | examples/consumption/index.js | JavaScript | mit | 3,897 |
import EventEmitter from "wolfy87-eventemitter";
export default class Object3D extends EventEmitter
{
mesh = null;
loadFromObj(url, onProcess)
{
const loader = new THREE.OBJLoader();
return new Promise((resolve, reject) => {
loader.load(
url,
obj => {
resolve(obj);
},
onProcess,
reject
);
});
}
}
| MagicCube/mx3d | src/mx3d/obj/Object3D.js | JavaScript | mit | 458 |
/* global Store:true */
/* global localStorage */
Store = {
isAvailable: function checkLocalStorageStatus() {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
},
dataEncode: function keyEncode(data) {
return JSON.stringify(data);
},
dataDecode: function keyDecode(data) {
try {
data = JSON.parse(data);
}
catch (error) {
data = null;
}
return data;
},
set: function setStoreKey(key, data, type) {
if (Store.isAvailable) {
return localStorage.setItem(key, Store.dataEncode({
type: type || 'settings',
data: data
}));
}
},
get: function getStoreKey(key) {
if (Store.isAvailable) {
var lsValue = Store.dataDecode(localStorage.getItem(key));
if (lsValue !== null && lsValue.hasOwnProperty('data')) {
return lsValue.data;
}
return null;
}
},
reset: function removeStoreKey(key) {
if (Store.isAvailable) {
return localStorage.removeItem(key);
}
}
};
Store.readSettings = function storeReadSettings(key) {
return Store.get(key);
};
Store.writeSettings = function storeWriteSettings(key, data) {
return Store.set(key, data);
}; | komogortev/AD-tech-challenge | assets/js/store.js | JavaScript | mit | 1,321 |
/**
* @venus-library jasmine
* @venus-include ../../src/functions.js
* @venus-code ../../src/ServiceContainer/Reference.js
*/
describe('servcie container reference', function () {
it('should return the original service id', function () {
var r = new Sy.ServiceContainer.Reference('foo');
expect(r.toString()).toEqual('foo');
});
});
| Baptouuuu/Sy | tests/servicecontainer/referencce.js | JavaScript | mit | 365 |
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.7-6-a-41
description: >
Object.defineProperties - type of desc.value is different from
type of P.value (8.12.9 step 6)
includes: [propertyHelper.js]
---*/
var obj = {};
obj.foo = 101; // default value of attributes: writable: true, configurable: true, enumerable: true
Object.defineProperties(obj, {
foo: {
value: "102"
}
});
verifyEqualTo(obj, "foo", "102");
verifyWritable(obj, "foo");
verifyEnumerable(obj, "foo");
verifyConfigurable(obj, "foo");
| PiotrDabkowski/Js2Py | tests/test_cases/built-ins/Object/defineProperties/15.2.3.7-6-a-41.js | JavaScript | mit | 870 |
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Text from 'components/input/text';
import './textlist.scss';
class TextList extends Component {
static propTypes = {
className: PropTypes.string,
onChange: PropTypes.func.isRequired,
value: ImmutablePropTypes.list.isRequired,
placeholder: PropTypes.string,
};
static defaultProps = {
className: '',
placeholder: '',
};
constructor(props) {
super(props);
this.onDelete = ::this.onDelete;
this.onKeyPress = ::this.onKeyPress;
this.onTextChange = ::this.onTextChange;
this.state = {
suggestions: [],
text: '',
};
}
onTextChange(text) {
this.setState({ text });
}
onDelete(index) {
const { onChange, value } = this.props;
onChange(value.delete(index));
}
onKeyPress(e) {
if (e.key === 'Enter') {
const { onChange, value } = this.props;
const { text } = this.state;
onChange(value.push(text));
this.setState({ text: '' });
}
}
render() {
const { className, placeholder, value } = this.props;
const { text } = this.state;
return (
<div className={`TextList ${className}`}>
<Text
placeholder={placeholder}
value={text}
onChange={this.onTextChange}
onKeyPress={this.onKeyPress}
/>
<ul className="TextList__Elements">
{value.map((elt, i) => (
<li className="TextList__Element" key={elt}>
<span>{elt}</span>
<button
className="fa fa-times"
onClick={() => { this.onDelete(i); }}
/>
</li>
))}
</ul>
</div>
);
}
}
export default TextList;
| bobinette/papernet-front | src/components/input/textlist/index.js | JavaScript | mit | 1,835 |
/* @flow */
import Node from './Node';
import SimpleSelector from './SimpleSelector';
import type Identifier from './Identifier';
import type NamespacePrefix from './NamespacePrefix';
import type StringLiteral from './StringLiteral';
import type { DefaultTraverser } from '../../traverser';
// @TODO Generalize with tokenizer
export type AttributeSelectorMatcherValue = '=' | '~=' | '|=' | '^=' | '$=' | '*=';
export default class AttributeSelector extends SimpleSelector {
attribute: AttributeSelectorAttribute;
constructor(attribute: AttributeSelectorAttribute) {
super('AttributeSelector');
this.attribute = attribute;
}
accept(traverser: DefaultTraverser): void {
traverser.visit(this.attribute);
}
}
export class AttributeSelectorWithMatcher extends AttributeSelector {
matcher: AttributeSelectorMatcher;
value: AttributeSelectorValue;
caseSensitive: boolean;
constructor(
attribute: AttributeSelectorAttribute,
matcher: AttributeSelectorMatcher,
value: AttributeSelectorValue,
caseSensitive: boolean,
) {
super(attribute);
this.matcher = matcher;
this.value = value;
this.caseSensitive = caseSensitive;
}
accept(traverser: DefaultTraverser): void {
super.accept(traverser);
traverser.visit(this.matcher);
traverser.visit(this.value);
}
}
export class AttributeSelectorAttribute extends Node {
namespacePrefix: ?NamespacePrefix;
value: Identifier;
constructor(value: Identifier, namespacePrefix: ?NamespacePrefix) {
super('AttributeSelectorAttribute');
this.namespacePrefix = namespacePrefix;
this.value = value;
}
accept(traverser: DefaultTraverser): void {
traverser.visit(this.value);
if (this.namespacePrefix) {
traverser.visit(this.namespacePrefix);
}
}
}
export class AttributeSelectorMatcher extends Node {
value: AttributeSelectorMatcherValue;
constructor(value: AttributeSelectorMatcherValue) {
super('AttributeSelectorMatcher');
this.value = value;
}
}
export class AttributeSelectorValue extends Node {
value: Identifier|StringLiteral;
constructor(value: Identifier|StringLiteral) {
super('AttributeSelectorValue');
this.value = value;
}
accept(traverser: DefaultTraverser): void {
traverser.visit(this.value);
}
}
| clentfort/another-selector-parser | src/util/nodes/AttributeSelector.js | JavaScript | mit | 2,307 |
import gulp from 'gulp';
import browserSync from 'browser-sync';
import {dirs, files} from '../config';
export const serve = 'serve';
gulp.task(serve, (callback) =>
browserSync
.create('devServer')
.init({
port: 8004,
ui: false,
ghostMode: false,
server: [dirs.base],
files: [
files.css,
files.indexHtml,
files.js
]
}, callback)
);
| bverbist/chrono-race | gulp/dev/serve.js | JavaScript | mit | 482 |
import Immutable, { List } from 'immutable';
import * as l from '../core/index';
import * as c from '../field/index';
import { dataFns } from '../utils/data_utils';
import { emailDomain, emailLocalPart } from '../field/email';
import { setUsername } from '../field/username';
import { getFieldValue } from '../field/index';
import { isEmail } from '../field/email';
import { isSSOEnabled, matchesEnterpriseConnection } from '../engine/classic';
import { databaseUsernameValue } from './database/index';
import { swap, updateEntity } from '../store/index';
const { get, initNS, tget, tremove, tset } = dataFns(['enterprise']);
const { tremove: tremoveCore, tset: tsetCore, tget: tgetCore } = dataFns(['core']);
// TODO: Android version also has "google-opendid" in the list, but we
// consider it to be a social connection. See
// https://github.com/auth0/Lock.Android/blob/98262cb7110e5d1c8a97e1129faf2621c1d8d111/lock/src/main/java/com/auth0/android/lock/utils/Strategies.java
export const STRATEGIES = {
ad: 'AD / LDAP',
adfs: 'ADFS',
'auth0-adldap': 'AD/LDAP',
custom: 'Custom Auth',
'google-apps': 'Google Apps',
ip: 'IP Address',
mscrm: 'Dynamics CRM',
office365: 'Office365',
pingfederate: 'Ping Federate',
samlp: 'SAML',
sharepoint: 'SharePoint Apps',
waad: 'Windows Azure AD'
};
export function initEnterprise(m, opts) {
return initNS(m, Immutable.fromJS(processOptions(opts)));
}
function processOptions(opts) {
let { defaultEnterpriseConnection } = opts;
if (defaultEnterpriseConnection != undefined && typeof defaultEnterpriseConnection !== 'string') {
l.warn(
options,
'The `defaultEnterpriseConnection` option will be ignored, because it is not a string.'
);
defaultEnterpriseConnection = undefined;
}
return defaultEnterpriseConnection === undefined
? {}
: { defaultConnectionName: defaultEnterpriseConnection };
}
export function defaultEnterpriseConnection(m) {
const name = defaultEnterpriseConnectionName(m);
return name && findADConnectionWithoutDomain(m, name);
}
export function defaultEnterpriseConnectionName(m) {
return get(m, 'defaultConnectionName');
}
export function enterpriseActiveFlowConnection(m) {
if (isHRDActive(m)) {
// HRD is active when an email matched or there is only one
// connection and it is enterprise
const email = tget(m, 'hrdEmail', '');
return matchConnection(m, email) || findActiveFlowConnection(m);
} else {
return defaultEnterpriseConnection(m) || findADConnectionWithoutDomain(m);
}
}
export function matchConnection(m, email, strategies = []) {
const target = emailDomain(email);
if (!target) return false;
return l.connections(m, 'enterprise', ...strategies).find(x => {
return x.get('domains').contains(target);
});
}
export function isEnterpriseDomain(m, email, strategies = []) {
return !!matchConnection(m, email, strategies);
}
export function enterpriseDomain(m) {
return isSingleHRDConnection(m)
? l.connections(m, 'enterprise').getIn([0, 'domains', 0])
: emailDomain(tget(m, 'hrdEmail'));
}
export function quickAuthConnection(m) {
return !isADEnabled(m) && l.hasOneConnection(m, 'enterprise')
? l.connections(m, 'enterprise').get(0)
: null;
}
// ad / adldap
// https://github.com/auth0/Lock.Android/blob/0145b6853a8de0df5e63ef22e4e2bc40be97ad9e/lock/src/main/java/com/auth0/android/lock/utils/Strategy.java#L67
export function isADEnabled(m) {
return l.hasSomeConnections(m, 'enterprise', 'ad', 'auth0-adldap');
}
export function findADConnectionWithoutDomain(m, name = undefined) {
return l.connections(m, 'enterprise', 'ad', 'auth0-adldap').find(x => {
return x.get('domains').isEmpty() && (!name || x.get('name') === name);
});
}
function findActiveFlowConnection(m, name = undefined) {
return l.connections(m, 'enterprise', 'ad', 'auth0-adldap').find(x => {
return !name || x.get('name') === name;
});
}
// kerberos
export function isInCorpNetwork(m) {
return corpNetworkConnection(m) !== undefined;
}
export function corpNetworkConnection(m) {
// Information about connection is stored in to flat properties connection and strategy.
// If connection is present, strategy will always be present as defined by the server.
const name = m.getIn(['sso', 'connection']);
const strategy = m.getIn(['sso', 'strategy']);
return name && strategy && Immutable.Map({ name, strategy });
}
// hrd
export function isSingleHRDConnection(m) {
return isADEnabled(m) && l.connections(m).count() === 1;
}
export function isHRDDomain(m, email) {
return isEnterpriseDomain(m, email, ['ad', 'auth0-adldap']);
}
export function toggleHRD(m, email) {
if (email) {
const username = l.defaultADUsernameFromEmailPrefix(m) ? emailLocalPart(email) : email;
m = setUsername(m, username, 'username', false);
m = tset(m, 'hrdEmail', email);
} else {
m = tremove(m, 'hrdEmail');
}
return tset(m, 'hrd', !!email);
}
export function isHRDActive(m) {
return tget(m, 'hrd', isSingleHRDConnection(m));
}
export function isHRDEmailValid(m, str) {
if (
isEmail(str) &&
!l.hasSomeConnections(m, 'database') &&
!findADConnectionWithoutDomain(m) &&
!matchesEnterpriseConnection(m, str)
) {
return false;
}
return true;
}
| jkennedy3161/flixview | client/bower_components/auth0-lock/src/connection/enterprise.js | JavaScript | mit | 5,299 |
/**
* @author Ivaylo Ivanov
* @public
* @description Address book route
* @requires ember
* @requires ../mixins/api
* @requires ../mixins/notifier
*/
import Ember from 'ember';
import api from '../mixins/api';
import notifier from '../mixins/notifier';
export default Ember.Route.extend(api, notifier, {
actions: {
/**
* @public
* @description Fired when the error bubble to the application route.
* Makes a request to the server in order to log the error
*/
error(error) {
this.failNoty('Oops. Something went wrong..');
let host = this.get('host');
Ember.$.post(host + '/client-errors?error=' + error.toString());
}
}
});
| seen-stack/front-end | app/routes/application.js | JavaScript | mit | 685 |
var transitionKey = 'transition';
var bodyStyle = document.documentElement.style;
if (!(transitionKey in bodyStyle)) {
if ('mozTransition' in bodyStyle) transitionKey = 'mozTransition';
else if ('webkitTransition' in bodyStyle) {
transitionKey = 'webkitTransition';
}
else if ('msTransition' in bodyStyle) {
transitionKey = 'msTransition';
} else {
transitionKey = '';
}
}
function transition(target, isLeave, _initialStyle = target.initialStyle || target.enterStyle || target.leavingStyle || target.leaveStyle) {
if (!target) return;
if (typeof isLeave === "string") {
isLeave = parseKV(isLeave, ';', ":");
}
if (isObject(isLeave) && (_initialStyle === true || !_initialStyle)) {
_initialStyle = isLeave;
isLeave = arguments[2];
}
if (isLeave) {
_initialStyle = target.leavingStyle || target.leaveStyle || _initialStyle;
}
if (target instanceof Array) {
target.forEach(function (target) {
transition(target, isLeave, _initialStyle);
});
return;
}
if (!target.style) return;
var initialStyle = _initialStyle || target.initialStyle;
var { recoverStyle, transitionTimerStart, transitionTimerEnd } = target;
clearTimeout(transitionTimerStart);
clearTimeout(transitionTimerEnd);
if (isString(initialStyle)) {
initialStyle = parseKV(initialStyle, ";", ":");
}
if (isObject(initialStyle)) {
let transitionDuration = 100;
if (!initialStyle.transition) {
initialStyle.transition = "all .3s ease";
}
if (transitionKey.length > 10) initialStyle[transitionKey] = initialStyle.transition;
String(initialStyle.transition).replace(/([\.\d]+)(m?)s/gi, function (m, d, t) {
if (t) transitionDuration = Math.max(+d, transitionDuration);
else transitionDuration = Math.max(d * 1000, transitionDuration);
return m;
});
transitionDuration = transitionKey ? transitionDuration || 260 : 0;
if (!recoverStyle) {
recoverStyle = {};
}
let savedStyle = {};
{
let originalStyle = target.style;
for (let k in initialStyle) {
savedStyle[k] = originalStyle[k];
}
}
extendIfNeeded(recoverStyle, savedStyle);
if (isLeave) {
transitionTimerStart = setTimeout(function () {
extend(target.style, initialStyle);
});
transitionTimerEnd = setTimeout(function () {
if (transitionKey) target.style[transitionKey] = recoverStyle.transition;
}, transitionDuration + 2);
} else {
extend(target.style, initialStyle);
if (transitionKey) target.style[transitionKey] = "none";
var waitPaint = 20;
transitionTimerStart = setTimeout(function () {
delete recoverStyle.transition;
if (transitionKey) target.style[transitionKey] = initialStyle.transition;
target.transitionTimerStart = setTimeout(function () {
extend(target.style, recoverStyle);
}, waitPaint);
});
transitionTimerEnd = setTimeout(function (transition) {
return function () {
if (transitionKey) target.style[transitionKey] = transition;
};
}(recoverStyle.transition || ''), transitionDuration + waitPaint);
}
target.transitionTimerStart = transitionTimerStart;
target.transitionTimerEnd = transitionTimerEnd;
target.recoverStyle = recoverStyle;
if (target.with) {
transition(target.with, isLeave, _initialStyle);
}
return transitionDuration;
}
}
| yunxu1019/efront | coms/zimoli/transition.js | JavaScript | mit | 3,858 |
import React, { Component } from 'react'
import { Input, Label, Menu } from 'semantic-ui-react'
export default class SizeLargeMassive extends Component {
state = { activeItem: 'inbox' }
handleItemClick = (e, { name }) => this.setState({ activeItem: name })
render() {
const { activeItem } = this.state
return (
<Menu size='massive' vertical>
<Menu.Item name='inbox' active={activeItem === 'inbox'} onClick={this.handleItemClick}>
<Label color='teal'>1</Label>
Inbox
</Menu.Item>
<Menu.Item name='spam' active={activeItem === 'spam'} onClick={this.handleItemClick}>
<Label>51</Label>
Spam
</Menu.Item>
<Menu.Item name='updates' active={activeItem === 'updates'} onClick={this.handleItemClick}>
<Label>1</Label>
Updates
</Menu.Item>
<Menu.Item>
<Input icon='search' placeholder='Search mail...' />
</Menu.Item>
</Menu>
)
}
}
| ben174/Semantic-UI-React | docs/app/Examples/collections/Menu/Variations/SizeVerticalMassive.js | JavaScript | mit | 995 |
/* Test DOM
**
** Prepares a virtual DOM using jsdom, allowing for React testing
*/
var jsdom = require('jsdom');
// Setup the simplest document possible
var doc = jsdom.jsdom('<!doctype html><html><body></body></html>');
// Get the window object out of the document
var win = doc.defaultView;
// Set globals for Mocha for a more natural access to document and window
global.document = doc;
global.window = win;
// From mocha-jsdom https://github.com/rstacruz/mocha-jsdom/blob/master/index.js#L80
function propagateToGlobal(obj) {
for(var key in obj) {
if(obj.hasOwnProperty(key) && key in global) {
global[key] = obj[key];
}
}
}
// Attach properties of the window object to the Mocha global object
propagateToGlobal(win);
| Fourwinged/react-quizz | src/scripts/test/test-dom.js | JavaScript | mit | 766 |
msg:"",
dashboardSlug: "{{ dashboard_slug }}",
views: [],
activeView: "", | synw/django-chartflo | chartflo/templates/chartflo/vues/data.js | JavaScript | mit | 73 |
var Class = require('ee-class')
, log = require('ee-log')
, assert = require('assert');
var asyncMethod = require('../')
var MyClass = new Class({
exec: asyncMethod(function(a, b, callback) {
process.nextTick(function() {
callback(null, a*b);
});
})
});
describe('Async Methods', function(){
it('should work with callbacks', function(done) {
new MyClass().exec(4, 5, function(err, result) {
assert.equal(result, 20);
done();
});
});
it('should work with promises', function(done) {
new MyClass().exec(4, 5).then(function(result) {
assert.equal(result, 20);
done();
}).catch(done);
});
});
| eventEmitter/async-method | test/default.js | JavaScript | mit | 676 |
(function($) {
var options = {
mask: true,
width: '100%',
height: 'auto',
scrollMove: true,
url: "http://livechat.ly.com/out/guest/touch?p=",
desc: '',
memberid: '',
telnum: '4007-555-555',
lineproperty: '自助',
getProperty: function() {
if (this.lineproperty === "自助") {
this.url = this.url + "2&c=2" ;
} else {
this.url = this.url + "7";
}
}
};
var tpl = {
mask: '<div class="ui-share-bg"></div>',
wrap: '<div class="ui-share"><div class="ui-share-c"><div class="share-open-con"><ul><li class="share-collect">电话咨询:{{telnum}}</li><li class="share-share">在线客服</li></ul><a class="share-cancel" title="取消" >取消</a></div></div></div>'
};
function Tel(param) {
this._options = this._options || {};
$.extend(this._options, options);
$.extend(this._options, param);
this._options.memberid = TelLogInit();
this._options.getProperty();
this.init();
this.initEvent();
}
Tel.prototype.init = function() {
// body...
var self = this,
opts = self._options;
var status = self.checkstatus();
opts._container = $(document.body);
if (0 === status) {
opts._mask = $(".ui-share-bg");
opts._wrap = $(".ui-share");
} else {
tpl.wrap = tpl.wrap.replace('{{telnum}}', opts.telnum)
opts._mask = opts.mask ? $(tpl.mask).appendTo(opts._container) : null;
opts._wrap = $(tpl.wrap).appendTo(opts._container);
}
opts._mask.fadeIn("200");
opts._mask.css({
display: "block",
opacity: 0.7
});
opts._wrap.animate({
display: "block",
visibility: "visible",
height: opts.height,
bottom: "10px"
}, 200, 'ease');
self.bottomEvent(status);
};
Tel.prototype.close = function() {
var self = this._options,
status = this.checkstatus();
if (status === 1) {
self._mask.fadeOut("400")
self._wrap.animate({
display: "block",
visibility: "hidden",
height: self.height,
bottom: "-260px"
}, 200, 'ease');
this.bottomEvent(status);
}
};
Tel.prototype.checkstatus = function() {
//var _opts = this._options;
var mask = $(".ui-share-bg")[0],
wrap = $(".ui-share")[0];
if (!mask && !wrap) {
//不存在
return -1;
} else if ($(mask).css("display") === "none" && $(wrap).css("visibility") === "hidden") {
//存在但是都被隐藏
return 0;
} else if ($(mask).css("display") === "block" && $(wrap).css("visibility") === "visible") {
return 1;
}
};
Tel.prototype.bottomEvent = function(ex) {
var elem = $(".ctrl-box-wrap");
if (elem[0]) {
if (elem.css("display") === "block" && (ex === -1 || ex === 0)) {
elem.css("display", "none");
} else {
elem.css("display", "block");
}
}
};
Tel.prototype.initEvent = function() {
var me = this;
$(document).on("tap", ".share-open-con li", function() {
var self = $(this);
// console.log(self.index())
if (self.index() === 0) {
//跳转
window.location.href = "tel:" + me._options.telnum;
} else {
window.location.href = me._options.url + "&memberid=" +
me._options.memberid;
}
});
//取消的事件
$(document).on("tap", ".share-cancel", function() {
me.close();
});
};
function TelLogInit() {
//初始化会员ID
return (/userid=([^&$]*)/.exec(!$.cookie("cnUser") ? "userid=0" : $.cookie("cnUser"))[1]);
};
module.exports = Tel;
})(Zepto);
| spheee/tz-fantasy | app/modules/async/tel/index.js | JavaScript | mit | 4,326 |
var searchData=
[
['defaultrealmmodule',['DefaultRealmModule',['../classio_1_1realm_1_1_default_realm_module.html',1,'io::realm']]],
['defaultrealmmodulemediator',['DefaultRealmModuleMediator',['../classio_1_1realm_1_1_default_realm_module_mediator.html',1,'io::realm']]],
['detailsactivity',['DetailsActivity',['../classpl_1_1komunikator_1_1komunikator_1_1activity_1_1_details_activity.html',1,'pl::komunikator::komunikator::activity']]],
['dimen',['dimen',['../classandroid_1_1support_1_1v7_1_1recyclerview_1_1_r_1_1dimen.html',1,'android.support.v7.recyclerview.R.dimen'],['../classandroid_1_1support_1_1design_1_1_r_1_1dimen.html',1,'android.support.design.R.dimen'],['../classpl_1_1komunikator_1_1komunikator_1_1_r_1_1dimen.html',1,'pl.komunikator.komunikator.R.dimen'],['../classandroid_1_1support_1_1v7_1_1appcompat_1_1_r_1_1dimen.html',1,'android.support.v7.appcompat.R.dimen']]],
['drawable',['drawable',['../classandroid_1_1support_1_1design_1_1_r_1_1drawable.html',1,'android.support.design.R.drawable'],['../classpl_1_1komunikator_1_1komunikator_1_1_r_1_1drawable.html',1,'pl.komunikator.komunikator.R.drawable'],['../classandroid_1_1support_1_1v7_1_1appcompat_1_1_r_1_1drawable.html',1,'android.support.v7.appcompat.R.drawable']]]
];
| teneusz/aplikacja_mobilna_komunikator | docs/zalacznik 3 - Dokumentacja Klas/html/search/classes_3.js | JavaScript | mit | 1,257 |
'use strict';
const request = require('../support/client');
const getSetup = require('../support/setup');
describe('request', () => {
let setup;
let base;
before(async () => {
setup = await getSetup();
base = setup.uri;
});
describe('not modified', () => {
let ts;
it('should start with 200', (done) => {
request.get(`${base}/if-mod`).end((error, res) => {
res.should.have.status(200);
res.text.should.match(/^\d+$/);
ts = Number(res.text);
done();
});
});
it('should then be 304', (done) => {
request
.get(`${base}/if-mod`)
.set('If-Modified-Since', new Date(ts).toUTCString())
.end((error, res) => {
res.should.have.status(304);
// res.text.should.be.empty
done();
});
});
});
});
| visionmedia/superagent | test/node/not-modified.js | JavaScript | mit | 839 |
/**
* The Sea.js plugin to provide log function
*/
define(function() {
var data = seajs.data
// The safe wrapper for `console.xxx` functions
// log("message") ==> console.log("message")
// log("message", "warn") ==> console.warn("message")
seajs.log = function(msg, type) {
window.console &&
// Do NOT print `log(msg)` in non-debug mode
(type || data.debug) &&
// Set the default value of type
(console[type || (type = "log")]) &&
// Call native method of console
console[type](msg)
}
}); | panxuepeng/hioogo | seajslib/seajs/src/seajs-log.js | JavaScript | mit | 549 |
// import './ReactotronConfig'
import { AppRegistry } from 'react-native';
import setup from './js/setup';
AppRegistry.registerComponent('NativeStarterKit', setup);
| lemol/diario-escola-sabatina | react-native/nativebase/index.android.js | JavaScript | mit | 167 |
'use strict';
var Lib = require('../../lib');
var attributes = require('./attributes');
var Color = require('../../components/color');
var handleDomainDefaults = require('../../plots/domain').defaults;
var handleText = require('../bar/defaults').handleText;
var TEXTPAD = require('../bar/constants').TEXTPAD;
var Colorscale = require('../../components/colorscale');
var hasColorscale = Colorscale.hasColorscale;
var colorscaleDefaults = Colorscale.handleDefaults;
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var labels = coerce('labels');
var parents = coerce('parents');
if(!labels || !labels.length || !parents || !parents.length) {
traceOut.visible = false;
return;
}
var vals = coerce('values');
if(vals && vals.length) {
coerce('branchvalues');
} else {
coerce('count');
}
coerce('level');
coerce('maxdepth');
var packing = coerce('tiling.packing');
if(packing === 'squarify') {
coerce('tiling.squarifyratio');
}
coerce('tiling.flip');
coerce('tiling.pad');
var text = coerce('text');
coerce('texttemplate');
if(!traceOut.texttemplate) coerce('textinfo', Array.isArray(text) ? 'text+label' : 'label');
coerce('hovertext');
coerce('hovertemplate');
var hasPathbar = coerce('pathbar.visible');
var textposition = 'auto';
handleText(traceIn, traceOut, layout, coerce, textposition, {
hasPathbar: hasPathbar,
moduleHasSelected: false,
moduleHasUnselected: false,
moduleHasConstrain: false,
moduleHasCliponaxis: false,
moduleHasTextangle: false,
moduleHasInsideanchor: false
});
coerce('textposition');
var bottomText = traceOut.textposition.indexOf('bottom') !== -1;
var lineWidth = coerce('marker.line.width');
if(lineWidth) coerce('marker.line.color', layout.paper_bgcolor);
var colors = coerce('marker.colors');
var withColorscale = traceOut._hasColorscale = (
hasColorscale(traceIn, 'marker', 'colors') ||
(traceIn.marker || {}).coloraxis // N.B. special logic to consider "values" colorscales
);
if(withColorscale) {
colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'});
} else {
coerce('marker.depthfade', !(colors || []).length);
}
var headerSize = traceOut.textfont.size * 2;
coerce('marker.pad.t', bottomText ? headerSize / 4 : headerSize);
coerce('marker.pad.l', headerSize / 4);
coerce('marker.pad.r', headerSize / 4);
coerce('marker.pad.b', bottomText ? headerSize : headerSize / 4);
traceOut._hovered = {
marker: {
line: {
width: 2,
color: Color.contrast(layout.paper_bgcolor)
}
}
};
if(hasPathbar) {
// This works even for multi-line labels as treemap pathbar trim out line breaks
coerce('pathbar.thickness', traceOut.pathbar.textfont.size + 2 * TEXTPAD);
coerce('pathbar.side');
coerce('pathbar.edgeshape');
}
coerce('sort');
coerce('root.color');
handleDomainDefaults(traceOut, layout, coerce);
// do not support transforms for now
traceOut._length = null;
};
| plotly/plotly.js | src/traces/treemap/defaults.js | JavaScript | mit | 3,411 |
import { combineReducers, createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension';
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import todos from '../redux/todo-redux'
const middleware = [thunkMiddleware];
// if (process.env.NODE_ENV === 'dev') {
// middleware.push(createLogger())
// }
const store = createStore(
combineReducers({
todos
}),
composeWithDevTools(
applyMiddleware(...middleware)
)
)
export default store
| Cwright017/electron-boilerplate | app/store/index.js | JavaScript | mit | 533 |
/*! loadCSS: load a CSS file asynchronously. [c]2016 @scottjehl, Filament Group, Inc. Licensed MIT */
import {doc, win, html} from '../globals'
export default function( href, before, media,callback ){
// Arguments explained:
// `href` [REQUIRED] is the URL for your CSS file.
// `before` [OPTIONAL] is the element the script should use as a reference for injecting our stylesheet <link> before
// By default, loadCSS attempts to inject the link after the last stylesheet or script in the DOM. However, you might desire a more specific location in your document.
// `media` [OPTIONAL] is the media type or query of the stylesheet. By default it will be 'all'
var called;
var ss = doc.createElement( "link" );
var ref;
if( before ){
ref = before;
}
else {
var refs = ( doc.body || doc.getElementsByTagName( "head" )[ 0 ] ).childNodes;
ref = refs[ refs.length - 1];
}
var sheets = doc.styleSheets;
ss.rel = "stylesheet";
ss.href = href;
// temporarily set media to something inapplicable to ensure it'll fetch without blocking render
ss.media = "only x";
// wait until body is defined before injecting link. This ensures a non-blocking load in IE11.
function ready( cb ){
if( doc.body ){
return cb();
}
setTimeout(function(){
ready( cb );
});
}
// Inject link
// Note: the ternary preserves the existing behavior of "before" argument, but we could choose to change the argument to "after" in a later release and standardize on ref.nextSibling for all refs
// Note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
ready( function(){
ref.parentNode.insertBefore( ss, ( before ? ref : ref.nextSibling ) );
});
// A method (exposed on return object for external use) that mimics onload by polling until document.styleSheets until it includes the new sheet.
var onloadcssdefined = function( cb ){
var resolvedHref = ss.href;
var i = sheets.length;
while( i-- ){
if( sheets[ i ].href === resolvedHref ){
return cb();
}
}
setTimeout(function() {
onloadcssdefined( cb );
});
};
function loadCB(){
if (!called) {
called = 1;
if (ss.addEventListener) {
ss.removeEventListener("load", loadCB);
}
ss.media = media || "all";
if (callback)
callback.call(ss);
}
}
// once loaded, set link's media back to `all` so that the stylesheet applies once it loads
if( ss.addEventListener ){
ss.addEventListener( "load", loadCB);
}
ss.onloadcssdefined = onloadcssdefined;
onloadcssdefined( loadCB );
return ss;
};
| oliver-eifler/theater-pur | src/js/util/loadCSS.js | JavaScript | mit | 2,736 |
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
const { Route } = Ember;
export default Route.extend(AuthenticatedRouteMixin, {
setupController() {
this._super(...arguments);
this.controllerFor('application').set('pageTitleTranslation', 'general.admin');
}
});
| stopfstedt/frontend | app/routes/admin-dashboard.js | JavaScript | mit | 345 |
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
pluginName: 'archaeopteri',
watch: {
options: {
livereload: true
},
css: {
files: 'scss/*',
tasks: ['sass']
},
html: {
files: ['demo/*.html', 'demo/*.php']
},
images: {
files: 'demo/imgs/*'
}
},
sass: {
dist: {
files: {
'demo/css/<%= pluginName %>.css': 'scss/demo.scss'
}
}
},
connect: {
server: {
options: {
hostname: 'localhost',
base: 'demo/',
livereload: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.registerTask('default', ['sass', 'connect','watch']);
grunt.registerTask('build', ['sass']);
}; | keeleycarrigan/archaeopteri.css | Gruntfile.js | JavaScript | mit | 1,196 |
import R from 'ramda'
import { defaultMemoize } from 'reselect'
export const
allKeys = defaultMemoize(R.pipe(
R.values,
R.map(R.keys),
R.flatten,
R.uniq,
R.sort(R.ascend(R.identity))
)),
allEntries = defaultMemoize(R.pipe(
// R.filter(R.complement(R.prop("@@__hidden__"))),
allKeys,
R.filter(k => k.indexOf("@@__") != 0)
)),
subEnvEntries = (envsWithMeta, subEnvId)=> allEntries({
[subEnvId]: findSubEnv(subEnvId, envsWithMeta)
}),
allSubEnvsSorted = defaultMemoize(R.pipe(
R.values,
R.map(R.pipe(
R.propOr({},"@@__sub__"),
R.keys
)),
R.flatten,
R.uniq,
R.sort(R.ascend(R.identity))
)),
allEntriesWithSubEnvs = defaultMemoize(envsWithMeta => {
return R.pipe(
allSubEnvsSorted,
R.pipe(
R.map(subEnvId => (findSubEnv(subEnvId, envsWithMeta))),
allEntries
),
R.flatten,
R.concat(allEntries(envsWithMeta)),
R.sort(R.ascend(R.identity))
)(envsWithMeta)
}),
serverSubEnvOptsByRole = defaultMemoize(envsWithMeta => {
return R.pipe(
R.map(role => ({
[role]: R.sortBy(
R.pipe(R.prop('name'), R.toLower),
allSubEnvsSorted(R.pick([role], (envsWithMeta || {}))).map(
subEnvId => {
const {"@@__name__": name} = findSubEnv(subEnvId, envsWithMeta)
return {name, id: subEnvId}
}
)
)
})),
R.mergeAll
)(["development", "staging", "production"])
}),
hasAnyVal = defaultMemoize(R.pipe(
R.values,
R.map(R.values),
R.flatten,
R.filter(R.identity),
R.any(R.prop('val'))
)),
subEnvPath = (subEnvId, envsWithMeta)=>{
for (let environment in envsWithMeta){
let path = [environment, "@@__sub__", subEnvId]
if (R.path(path, envsWithMeta)){
return path
}
}
return []
},
findSubEnv = (subEnvId, envsWithMeta)=>{
const path = subEnvPath(subEnvId, envsWithMeta)
return R.isEmpty(path) ? null : R.path(path, envsWithMeta)
}
| envkey/envkey-app | envkey-react/src/lib/env/query.js | JavaScript | mit | 2,072 |
/*globals JSDOC, Opt */
/**
@overview
@date $Date: 2008-06-08 22:57:25 +0100 (Sun, 08 Jun 2008) $
@version $Revision: 638 $
@location $HeadURL: https://jsdoc-toolkit.googlecode.com/svn/tags/jsdoc_toolkit-2.0.1/jsdoc-toolkit/app/lib/JSDOC.js $
*/
/**
This is the main container for the JSDOC application.
@namespace
*/
JSDOC = {
};
/**
@requires Opt
*/
//if (typeof arguments == "undefined") arguments = [];
JSDOC.opt = Opt.get(
[],
{
d: "directory",
c: "conf",
t: "template",
r: "recurse",
x: "ext",
p: "private",
a: "allfunctions",
e: "encoding",
n: "nocode",
o: "out",
s: "suppress",
T: "testmode",
h: "help",
v: "verbose",
"D[]": "define",
"H[]": "handler"
}
);
/** The current version string of this application. */
JSDOC.VERSION = "2.0.3";
/** Print out usage information and quit. */
JSDOC.usage = function() {
print("USAGE: java -jar jsrun.jar app/run.js [OPTIONS] <SRC_DIR> <SRC_FILE> ...");
print("");
print("OPTIONS:");
print(" -a or --allfunctions\n Include all functions, even undocumented ones.\n");
print(" -c or --conf\n Load a configuration file.\n");
print(" -d=<PATH> or --directory=<PATH>\n Output to this directory (defaults to \"out\").\n");
print(" -D=\"myVar:My value\" or --define=\"myVar:My value\"\n Multiple. Define a variable, available in JsDoc as JSDOC.opt.D.myVar\n");
print(" -e=<ENCODING> or --encoding=<ENCODING>\n Use this encoding to read and write files.\n");
print(" -h or --help\n Show this message and exit.\n");
//print(" -H=ext:handler or --handler=ext:handler\n Multiple. Load handlers/handler.js to handle files with .ext names.\n");
print(" -n or --nocode\n Ignore all code, only document comments with @name tags.\n");
print(" -o=<PATH> or --out=<PATH>\n Print log messages to a file (defaults to stdout).\n");
print(" -p or --private\n Include symbols tagged as private, underscored and inner symbols.\n");
print(" -r=<DEPTH> or --recurse=<DEPTH>\n Descend into src directories.\n");
print(" -s or --suppress\n Suppress source code output.\n");
print(" -t=<PATH> or --template=<PATH>\n Required. Use this template to format the output.\n");
print(" -T or --test\n Run all unit tests and exit.\n");
print(" -v or --verbose\n Provide verbose feedback about what is happening.\n");
print(" -x=<EXT>[,EXT]... or --ext=<EXT>[,EXT]...\n Scan source files with the given extension/s (defaults to js).\n");
// quit();
};
/*t:
plan(4, "Testing JSDOC namespace.");
is(
typeof JSDOC,
"object",
"JSDOC.usage is a function."
);
is(
typeof JSDOC.VERSION,
"string",
"JSDOC.VERSION is a string."
);
is(
typeof JSDOC.usage,
"function",
"JSDOC.usage is a function."
);
is(
typeof JSDOC.opt,
"object",
"JSDOC.opt is a object."
);
*/
// if (this.IO) IO.includeDir("lib/JSDOC/"); | hankly/frizione | Frizione/modules/frizione/third-party/jsdoc-toolkit/lib/JSDOC.js | JavaScript | mit | 2,980 |
var Sequelize = require("sequelize");
var db = require('../libs/db');
var model_decl = ["taskrecords", {
// GUID
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
// 任务表主键
task_id: { type: Sequelize.INTEGER, allowNull: false },
// 任务名称
name: {type: Sequelize.STRING, allowNull: false},
// 任务描述
detail: {type: Sequelize.STRING, allowNull: false, defaultValue: ''},
// 任务描述
param: {type: Sequelize.STRING, allowNull: false, defaultValue: ''},
// 触发器标识
trigger_code: {type: Sequelize.STRING, allowNull: false},
// 任务类型:0-MQ类型任务 1-RESTful类型任务(暂不支持)
type: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0},
// 任务目标。MQ类型的任务taget标识任务MQ key,以后支持的RESTful类型任务target标识URL(多个URL可用;分隔)
target: { type: Sequelize.STRING, allowNull: false, defaultValue: ''},
// 开始时间
stime: { type: Sequelize.BIGINT(13)},
// 结束时间
etime: { type: Sequelize.BIGINT(13)},
// 进度
progress: { type: Sequelize.INTEGER },
// 状态:0-未开始 1-执行中 2-执行成功 3-执行失败 4-执行超时(暂不支持)
status: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0}
}];
module.exports = {
define: function() {
var sequelize = db.sequelize();
return sequelize.define(model_decl[0], model_decl[1], {
freezeTableName: true // Model tableName will be the same as the model name
});
},
model: function() {
var sequelize = db.sequelize();
return sequelize.model(model_decl[0]);
}
}
| alfredking12/hp-scheduler | dcenter/src/models/taskrecords.js | JavaScript | mit | 1,739 |
MugenRoleActionsController = MeteorisController.extend({
/* get subscribtion from server with parameter criteria, and sort/limit */
subscriptions: function() {
var sort = MeteorisGridView.getSorting();
sort.limit = this.limit();
this.subs.subscribe('mugenRoleGroups', {});
this.subs.subscribe('mugenRoleCollections', {});
this.subs.subscribe('mugenRoleActions', this.getCriteriaManage(), sort);
this.subscription = this.subs.subscribe('mugenRoleActions', this.getCriteria(), sort);
},
/* event searching data by user input with parameter */
search: function(t) {
Router.go(Router.current().route.getName(), {limit: this.limit()}, {
query: "q=" + t.find('#search').value +
"&mugenRoleCollectionId=" + t.find('#mugenRoleCollectionId').value +
"&mugenRoleGroupId=" + t.find('#mugenRoleGroupId').value
});
},
/* event searching data by user input with parameter */
searchManage: function(t) {
var mugenRoleCollectionId = t.find('#mugenRoleCollectionId').value;
var mugenRoleGroupId = t.find('#mugenRoleGroupId').value;
if (!mugenRoleCollectionId || !mugenRoleGroupId) {
var errMessage = "Porfavor escoger un colleccion y grupo";
MeteorisFlash.set('danger', errMessage);
throw new Meteor.Error(errMessage);
}
Router.go(Router.current().route.getName(), {limit: this.limit()}, {
query: "mugenRoleCollectionId=" + mugenRoleCollectionId +
"&mugenRoleGroupId=" + mugenRoleGroupId
});
},
/* @override getCriteria */
getCriteria: function() {
var search = this.params.query.q ? this.params.query.q : "";
var mugenRoleCollectionId = this.params.query.mugenRoleCollectionId ? this.params.query.mugenRoleCollectionId : "";
var mugenRoleGroupId = this.params.query.mugenRoleGroupId ? this.params.query.mugenRoleGroupId : "";
return {
$or: [
{name: {$regex: search, $options: 'i'}},
{mugenRoleGroupId: {$regex: mugenRoleGroupId, $options: 'i'}},
{mugenRoleCollectionId: {$regex: mugenRoleCollectionId, $options: 'i'}},
]
};
},
/* @override getCriteria */
getCriteriaManage: function() {
var mugenRoleCollectionId = this.params.query.mugenRoleCollectionId;
var mugenRoleGroupId = this.params.query.mugenRoleGroupId;
return {
mugenRoleGroupId: mugenRoleGroupId == '*' ? {$exists: false} : mugenRoleGroupId,
mugenRoleCollectionId: mugenRoleCollectionId,
};
},
index: function() {
var sort = MeteorisGridView.getSorting();
sort.limit = this.limit();
var models = MugenRoleActions.find(this.getCriteria(), sort);
return this.render('mugenRoleActionsIndex', {
data: {
ready: this.subscription.ready,
isEmpty: models.count() === 0 ? true : false,
models: models,
hasMore: this.limit() == models.fetch().length ? this.route.path({limit: this.limit() + this.increment}) : null,
}
});
},
manage: function() {
var sort = MeteorisGridView.getSorting();
sort.limit = this.limit();
var models = MugenRoleActions.find(this.getCriteriaManage(), sort);
return this.render('mugenRoleActionsManage', {
data: {
ready: this.subscription.ready,
isEmpty: models.count() === 0 ? true : false,
models: models,
hasMore: this.limit() == models.fetch().length ? this.route.path({limit: this.limit() + this.increment}) : null,
}
});
},
view: function() {
return this.render('mugenRoleActionsView', {
data: {
model: this._loadModel(this.getId()),
}
});
},
/* private get user input docs */
_getDoc: function(t) {
var doc = {
name: t.find('#name').value,
mugenRoleCollectionId: t.find('#mugenRoleCollectionId').value,
};
var mugenRoleGroupId = t.find('#mugenRoleGroupId').value;
if (mugenRoleGroupId != "*" && mugenRoleGroupId)
doc.mugenRoleGroupId = mugenRoleGroupId;
return doc;
},
/* uploading file using cfs:fileSystem package + cfs:ejson */
_uploadImage: function() {
var imageId = null;
var file = $('#image').get(0).files[0];
if (file) {
var image = Images.insert(file, function(err) {
if (err) {
MeteorisFlash.set('danger', err.message);
throw new Meteor.Error(err);
}
});
imageId = image._id;
}
return imageId;
},
/* event inserting data */
insert: function(t) {
if (this._post) {
//uploading file using cfs:fileSystem package + cfs:ejson
//var imageId = this._uploadImage();
//set inserted doc
var doc = this._getDoc(t);
//doc.imageId = imageId;
//mugenRoleActions must be unique
var mugenRoleActions = MugenRoleActions.findOne(doc);
if (mugenRoleActions) {
var errMessage = "Las accion de roles deben ser unicas";
MeteorisFlash.set('danger', errMessage);
throw new Meteor.Error(errMessage);
} else {
MugenRoleActions.insert(doc, function(err, _id) {
if (err) {
MeteorisFlash.set('danger', err.message);
throw new Meteor.Error(err);
}
MeteorisFlash.set('success', "Exito Insertando MugenRoleActions");
Router.go('mugenRoleActionsView', {_id: _id});
});
}
}
return this.render('mugenRoleActionsInsert', {});
},
insertManage: function(t) {
var doc = this._getDoc(t);
var mugenRoleActions = MugenRoleActions.findOne(doc);
if (mugenRoleActions) {
var errMessage = "Mugen Role Actions name must be unique";
MeteorisFlash.set('danger', errMessage);
throw new Meteor.Error(errMessage);
} else {
MugenRoleActions.insert(doc, function(err, _id) {
if (err) {
MeteorisFlash.set('danger', err.message);
throw new Meteor.Error(err);
}
MeteorisFlash.set('success', "Exito Insertando MugenRoleActions");
});
}
t.find('#name').value = "";
t.find('#name').focus();
},
/* event updating data */
update: function(t) {
var _id = this.getId();
var model = this._loadModel(_id);
if (this._post) {
//uploading file using cfs:fileSystem package + cfs:ejson
//var imageId = this._uploadImage();
//remove old image if user inputting new image
//if (imageId && model.imageId)
//Images.remove(model.imageId);
//set updated doc
var doc = this._getDoc(t);
//doc.imageId = imageId ? imageId : model.imageId;
MugenRoleActions.update(_id, {$set: doc}, function(err) {
if (err) {
MeteorisFlash.set('danger', err.message);
throw new Meteor.Error(err);
}
MeteorisFlash.set('success', "Exito Actualizando MugenRoleActions");
});
Router.go('mugenRoleActionsView', {_id: _id});
}
return this.render('mugenRoleActionsUpdate', {
data: {
model: model,
}
});
},
/* event removing data by id */
remove: function(_id) {
MugenRoleActions.remove(_id, function(err) {
if (err) {
MeteorisFlash.set('danger', err.message);
throw new Meteor.Error(err);
}
MeteorisFlash.set('success', "Exito Removiendo MugenRoleActions");
});
},
_loadModel: function(_id) {
return MugenRoleActions.findOne(_id);
},
}); | MindBlowStudio/portal | mugen/lib/controllers/MugenRoleActionsController.js | JavaScript | mit | 8,385 |
var fs = require('fs');
var path = require('path');
var docopt = require('docopt').docopt;
var Client = require('../../index');
// Parse command line options.
var opts = docopt(fs.readFileSync(__dirname + '/docopt.txt', 'utf8'), {
version : require('../../package').version
});
module.exports = function() {
// Determine which command to perform.
var cmd = process.argv.slice(2).filter((arg) => {
return arg[0] !== '-';
})[0];
// Load command module.
try {
var mod = require('./commands/' + cmd);
} catch(e) {
console.error('Unknown or unimplemented command `%s`', cmd);
process.exit(1);
}
// Set and check required parameters.
var params = {
serialNumber : opts['--serial'] || process.env.NEFIT_SERIAL_NUMBER,
accessKey : opts['--access-key'] || process.env.NEFIT_ACCESS_KEY,
password : opts['--password'] || process.env.NEFIT_PASSWORD,
};
var error = null;
if (! params.serialNumber) error = 'missing serial number';
if (! params.accessKey) error = 'missing access key';
if (! params.password) error = 'missing password';
if (error) {
console.error('Error: %s', error);
process.exit(1);
}
// Instantiate client.
const client = Client(params);
// Perform command.
return client.connect().then(() => mod(client, opts)).then((r) => {
if (typeof r === 'string') {
console.log(r);
} else if (opts['--pretty']) {
console.log(JSON.stringify(r, null, 2));
} else {
console.log('%j', r);
}
}).catch((err) => {
console.error(err);
if (opts['--verbose'] && err.stack) {
console.error(err.stack);
}
process.exit(1);
}).finally(() => {
client.end();
});
};
| robertklep/nefit-easy-client | lib/cli/index.js | JavaScript | mit | 1,722 |
(function (){
'use strict';
function labelCase (){
return function (input) {
if (input === null || input === undefined || input === ''){
input = ' ';
}
input = (input + '').replace(/([A-Z])/g, ' $1');
return input[0].toUpperCase() + input.slice(1);
};
}
angular.module('sds-angular-controls').filter('labelCase', labelCase);
})();
| SMARTDATASYSTEMSLLC/sds-angular-controls | src/filters/label-case.js | JavaScript | mit | 384 |
/**
* Includes all models into one place
*/
module.exports = {
User: require('./user'),
};
| Borodutch/hello-bot-telekit | models/index.js | JavaScript | mit | 96 |
const mongoose = require('mongoose'),
ObjectId = mongoose.Schema.Types.ObjectId
const localeEnum = ['frFR', 'deDE', 'enGB', 'enUS', 'itIT', 'koKR', 'zhCN', 'zhTW', 'ruRU', 'esES', 'esMX', 'ptBR']
const Schema = new mongoose.Schema({
wagoID: {type: String, index: true},
locale: {type: String, index: true, enum: localeEnum },
key : {type: String, index: true},
term : String,
active: {type: Boolean, index: true},
submissions : [{
user: { type: ObjectId, ref: 'Users', index: true},
term: String,
fuzzy: Date,
date: Date,
accepted: Boolean}]
})
Schema.statics.getTranslations = async function(wagoID) {
var terms = {}
var keys = await this.find({wagoID: wagoID, active: true}).distinct('key').exec()
if (!keys.length) return false
keys = keys.slice(0, 100)
var t = await this.find({wagoID: wagoID, key: keys}).populate("submissions.user").exec()
t.forEach(t => {
if (t.active) {
terms[t.locale] = terms[t.locale] || {}
var submissions = []
t.submissions.forEach(sub => {
submissions.push({name: sub.user.account.username, roleclass: sub.user.roleclass, locale: sub.locale, date: sub.date, accepted: sub.accepted })
})
submissions.sort((a, b) => {
if (a.date > b.sort) return 1
if (a.date < b.sort) return -1
return 0
})
terms[t.locale][t.key] = {term: t.term, submissions: submissions}
}
})
// fill in empty missing term structure
localeEnum.forEach(loc => {
terms[loc] = terms[loc] || {}
keys.forEach(k => {
terms[loc][k] = terms[loc][k] || {}
})
})
return terms
}
Schema.statics.setTranslation = async function (wagoID, locale, key, term, approveUser) {
var t = await this.findOne({wagoID: wagoID, locale: locale, key: key}).exec()
if (!t) {
return this.newTranslation(wagoID, locale, key, term)
}
else if (approveUser) {
t.term = term
for (let i = 0; i < t.submissions.length; i++) {
if (t.submissions[i].user.equals(approveUser)) {
t.submissions[i].accepted = true
}
}
await t.save()
}
else if (t.term !== term) {
t.term = term
for (let i = 0; i < t.submissions.length; i++) {
t.submissions[i].fuzzy = new Date()
}
await t.save()
}
}
Schema.statics.newTranslation = async function (wagoID, locale, key, term) {
await this.create({wagoID: wagoID, locale: locale, key: key, term: term, active: true})
}
const Translations = mongoose.model('WagoTranslations', Schema)
module.exports = Translations | oratory/wago.io | backend/api/models/WagoTranslation.js | JavaScript | mit | 2,546 |
import React from 'react'
import PropTypes from 'prop-types'
import {animateScroll as scroller} from 'react-scroll'
import injectSheet from '../../utils/jss'
import {scrollDuration as duration} from '../../constants/animations'
const styles = {
scroll: {
display: 'inline-block',
verticalAlign: 'middle',
boxShadow: 'none',
appearance: 'none',
border: 'none',
outline: 'none',
padding: 0,
margin: 0,
background: 'transparent',
cursor: 'pointer',
color: 'currentColor',
fill: 'currentColor',
},
}
const scroll = (containerId = null) =>
scroller.scrollTo(window.outerHeight, {
smooth: true,
containerId,
duration,
})
/**
* Scroll down by screen size
*/
const ScrollDown = ({classes, children, containerId}) => (
<button className={classes.scroll} onClick={() => scroll(containerId)}>
{children}
</button>
)
ScrollDown.propTypes = {
classes: PropTypes.objectOf(PropTypes.string).isRequired,
children: PropTypes.node.isRequired,
containerId: PropTypes.string,
}
ScrollDown.defaultProps = {
containerId: false,
}
export default injectSheet(styles)(ScrollDown)
| typical000/paveldavydov | src/components/ScrollDown/ScrollDown.js | JavaScript | mit | 1,147 |
function graphs(id) {
switch (id) {
case 'qtd-titulacao':
var url = "/IFLattes/Relatorios/getQTDTitulacao";
var id = 'graph_titulacao';
break;
case 'areas_atuacao':
var url = "/IFLattes/Relatorios/getAreas";
var id = 'graph_areas';
break;
}
$.ajax({
url: url,
dataType: "json",
success: function (data) {
console.log(data);
var result = Array();
for (var i = 0; i < data.length; i++) {
result[i] = {Name: data[i].nivel, Spent: data[i].qtd};
}
//console.log(result);
}
}
);
}
/*
*
var data1 = [
{Name: 'Mr A', Spent: 40, Year: 2011},
{Name: 'Mr B', Spent: 10, Year: 2011},
{Name: 'Mr C', Spent: 40, Year: 2011},
{Name: 'Mr A', Spent: 70, Year: 2012},
{Name: 'Mr B', Spent: 20, Year: 2012},
{Name: 'Mr B', Spent: 50, Year: 2013},
{Name: 'Mr C', Spent: 30, Year: 2013}
];
var data2 = [
{Name: 'Mr A', Spent: 10, Year: 2011},
{Name: 'Mr B', Spent: 20, Year: 2011},
{Name: 'Mr C', Spent: 50, Year: 2011},
{Name: 'Mr A', Spent: 20, Year: 2012},
{Name: 'Mr B', Spent: 40, Year: 2012},
{Name: 'Mr B', Spent: 50, Year: 2013},
{Name: 'Mr C', Spent: 50, Year: 2013}
];
// data reset function (adapted)
function resetData(ndx, dimensions) {
dimensions.forEach(function (dim) {
dim.filter(null);
});
ndx.remove();
}
// set crossfilter with first dataset
var ndx = crossfilter(data1),
yearDim = ndx.dimension(function (d) {
return +d.Year;
}),
spendDim = ndx.dimension(function (d) {
return Math.floor(d.Spent / 10);
}),
nameDim = ndx.dimension(function (d) {
return d.Name;
}),
spendPerYear = yearDim.group().reduceSum(function (d) {
return +d.Spent;
}),
spendPerName = nameDim.group().reduceSum(function (d) {
return +d.Spent;
}),
spendHist = spendDim.group().reduceCount();
function render_plots() {
yearRingChart
.width(200).height(200)
.dimension(yearDim)
.group(spendPerYear)
.innerRadius(50);
spenderRowChart
.width(250).height(200)
.dimension(nameDim)
.group(spendPerName)
.elasticX(true);
dc.renderAll();
}
render_plots();
*/ | luanhsd/IFLattes | assets/js/relatorios/graphs.js | JavaScript | mit | 2,313 |
import {application, application1, func, future} from './future.js';
export function forkCatch(f){
var context1 = application1(forkCatch, func, arguments);
return function forkCatch(g){
var context2 = application(2, forkCatch, func, arguments, context1);
return function forkCatch(h){
var context3 = application(3, forkCatch, func, arguments, context2);
return function forkCatch(m){
application(4, forkCatch, future, arguments, context3);
return m._interpret(f, g, h);
};
};
};
}
| fluture-js/Fluture | src/fork-catch.js | JavaScript | mit | 534 |
/**
* Created by ashani on 6/28/2017.
*/
angular.module("myApp").controller('drugController',['$scope','$http','$routeParams','$location',function ($scope,$http,$routeParams,$location) {
$scope.insertdrugdata=function () {
$http({
method: 'POST',
url: 'http://localhost:3000/newdrug',
headers: {
'Content-Type': 'application/json'
},
data: {
'itemName': $scope.itemName,
'batchNo': $scope.batchNo,
'packingType': $scope.packingType,
'manufacturer': $scope.manufacturer,
'quantity': $scope.quantity,
'addedDate': $scope.addedDate,
'expiryDate': $scope.expiryDate,
'sellingPrice': $scope.sellingPrice
}
}).then(function (success) {
console.log($scope.drug);
$scope.drug = success.data;
$scope.getdrugsucessmsg ='Successfully';
$scope.showAlert();
}, function (error) {
$scope.getdrugsucessmsg ='Something Went Wrong!!!!';
$scope.showAlert();
});
};
$scope.showAlert = function(){
$scope.mytrue = false;
$scope.myfalse = false;
console.log($scope.getdrugsucessmsg);
if($scope.getdrugsucessmsg=="Successfully")
$scope.mytrue = true;
else if($scope.getdrugsucessmsg=="Something Went Wrong!!!!")
$scope.myfalse = true;
};
$http({
method: 'GET',
url: 'http://localhost:3000/newdrug'
}).then(function (success){
$scope.drugdata=success.data;
},function (error){
});
// $http({
// method: 'GET',
// url: 'http://localhost:3000/newsup'
// }).then(function (success){
// $scope.supplierdata=success.data;
// },function (error){
//
// });
$http({
method: 'GET',
url: 'http://localhost:3000/newdrug/'+$routeParams.id
}).then(function (success) {
$scope.drugdataspecific = success.data[0];
}, function (error) {
});
$scope.updatedata=function () {
$http({
method: 'PUT',
url: 'http://localhost:3000/newdrug/'+$routeParams.id,
headers: {
'Content-Type': 'application/json'
},
data: {
'itemName': $scope.drugdataspecific.itemName,
'batchNo': $scope.drugdataspecific.batchNo,
'packingType': $scope.drugdataspecific.packingType,
'manufacturer': $scope.drugdataspecific.manufacturer,
'quantity': $scope.drugdataspecific.quantity,
'addedDate': $scope.drugdataspecific.addedDate,
'expiryDate': $scope.drugdataspecific.expiryDate,
'sellingPrice': $scope.drugdataspecific.sellingPrice
}
}).then(function (success) {
$scope.drug = success.data[0];
$scope.getdrugsucessmsg ='Successfully';
$scope.showAlert();
}, function (error) {
$scope.getdrugsucessmsg ='Something went wrong';
$scope.showAlert();
});
};
$scope.deletedata=function () {
$http({
method: 'DELETE',
url: 'http://localhost:3000/newdrug/'+$routeParams.id,
headers: {
'Content-Type': 'application/json'
},
data: {
'itemName': $scope.itemName,
'batchNo': $scope.batchNo,
'packingType': $scope.packingType,
'manufacturer': $scope.manufacturer,
'quantity': $scope.quantity,
'addedDate': $scope.addedDate,
'expiryDate': $scope.expiryDate,
'sellingPrice': $scope.sellingPrice
}
}).then(function (success) {
$scope.supplier = success.data[0];
$scope.getdrugsucessmsg ='Successfully';
$scope.showAlert();
$location.path('/viewdrug');
}, function (error) {
$scope.getdrugsucessmsg ='Something Went Wrong!!!!';
$scope.showAlert();
});
};
}]);
| ashi9422/Chumps | public/controllers/drug/drugController.js | JavaScript | mit | 4,256 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.